query
stringlengths
7
3.85k
document
stringlengths
11
430k
metadata
dict
negatives
sequencelengths
0
101
negative_scores
sequencelengths
0
101
document_score
stringlengths
3
10
document_rank
stringclasses
102 values
EndpointConfig indicates an expected call of EndpointConfig
func (mr *MockProvidersMockRecorder) EndpointConfig() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "EndpointConfig", reflect.TypeOf((*MockProviders)(nil).EndpointConfig)) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (mr *MockClientMockRecorder) EndpointConfig() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"EndpointConfig\", reflect.TypeOf((*MockClient)(nil).EndpointConfig))\n}", "func (m *MockClient) EndpointConfig() fab.EndpointConfig {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"EndpointConfig\")\n\tret0, _ := ret[0].(fab.EndpointConfig)\n\treturn ret0\n}", "func (m *MockProviders) EndpointConfig() fab.EndpointConfig {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"EndpointConfig\")\n\tret0, _ := ret[0].(fab.EndpointConfig)\n\treturn ret0\n}", "func (c *Provider) EndpointConfig() fab.EndpointConfig {\n\treturn c.endpointConfig\n}", "func TestInvalidConfiguration(t *testing.T) {\n\tt.Parallel()\n\t// Start a test gRPC server.\n\t_ = mock.NewBase64Plugin(t, newEndpoint().path)\n\n\tctx := testContext(t)\n\n\tinvalidConfigs := []struct {\n\t\tname string\n\t\tendpoint string\n\t}{\n\t\t{\"emptyConfiguration\", \"\"},\n\t\t{\"invalidScheme\", \"tcp://localhost:6060\"},\n\t}\n\n\tfor _, testCase := range invalidConfigs {\n\t\tt.Run(testCase.name, func(t *testing.T) {\n\t\t\t_, err := NewGRPCService(ctx, testCase.endpoint, 1*time.Second)\n\t\t\tif err == nil {\n\t\t\t\tt.Fatalf(\"should fail to create envelope service for %s.\", testCase.name)\n\t\t\t}\n\t\t})\n\t}\n}", "func WithEndpoint(endpoint string) {\n\tcfg.endpoint = strings.TrimRight(endpoint, \"/\")\n}", "func TestEndpointCase1(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"ap-east-1\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(false),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis.ap-east-1.amazonaws.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func (h Handler) TestEndpoint() error {\n\tr, err := http.Get(h.url)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif r.StatusCode != 200 {\n\t\treturn errors.New(\"Endpoint not replying typical 200 answer on ping\")\n\t}\n\n\treturn nil\n}", "func TestEndpointCase0(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"af-south-1\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(false),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis.af-south-1.amazonaws.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func TestEndpointCase46(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"us-east-1\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(true),\n\t\tEndpoint: ptr.String(\"https://example.com\"),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err == nil {\n\t\tt.Fatalf(\"expect error, got none\")\n\t}\n\tif e, a := \"Invalid Configuration: FIPS and custom endpoint are not supported\", err.Error(); !strings.Contains(a, e) {\n\t\tt.Errorf(\"expect %v error in %v\", e, a)\n\t}\n}", "func (c *ServerConfig) getConfigEndpoint() string {\n\tnurl := *c.ParsedEndpoint\n\tnurl.Path = path.Join(nurl.Path, c.APIPaths.Config)\n\treturn nurl.String()\n}", "func TestEndpointCase47(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"us-east-1\"),\n\t\tUseDualStack: ptr.Bool(true),\n\t\tUseFIPS: ptr.Bool(false),\n\t\tEndpoint: ptr.String(\"https://example.com\"),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err == nil {\n\t\tt.Fatalf(\"expect error, got none\")\n\t}\n\tif e, a := \"Invalid Configuration: Dualstack and custom endpoint are not supported\", err.Error(); !strings.Contains(a, e) {\n\t\tt.Errorf(\"expect %v error in %v\", e, a)\n\t}\n}", "func TestEndpointCase5(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"ap-south-1\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(false),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis.ap-south-1.amazonaws.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func TestEndpointCase44(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"us-east-1\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(false),\n\t\tEndpoint: ptr.String(\"https://example.com\"),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://example.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func validateAdapterEndpoint(endpoint string, adapterName string, errs []error) []error {\n\tif endpoint == \"\" {\n\t\treturn append(errs, fmt.Errorf(\"There's no default endpoint available for %s. Calls to this bidder/exchange will fail. \"+\n\t\t\t\"Please set adapters.%s.endpoint in your app config\", adapterName, adapterName))\n\t}\n\n\t// Create endpoint template\n\tendpointTemplate, err := template.New(\"endpointTemplate\").Parse(endpoint)\n\tif err != nil {\n\t\treturn append(errs, fmt.Errorf(\"Invalid endpoint template: %s for adapter: %s. %v\", endpoint, adapterName, err))\n\t}\n\t// Resolve macros (if any) in the endpoint URL\n\tresolvedEndpoint, err := macros.ResolveMacros(*endpointTemplate, macros.EndpointTemplateParams{\n\t\tHost: dummyHost,\n\t\tPublisherID: dummyPublisherID,\n\t\tAccountID: dummyAccountID,\n\t})\n\tif err != nil {\n\t\treturn append(errs, fmt.Errorf(\"Unable to resolve endpoint: %s for adapter: %s. %v\", endpoint, adapterName, err))\n\t}\n\t// Validate the resolved endpoint\n\t//\n\t// Validating using both IsURL and IsRequestURL because IsURL allows relative paths\n\t// whereas IsRequestURL requires absolute path but fails to check other valid URL\n\t// format constraints.\n\t//\n\t// For example: IsURL will allow \"abcd.com\" but IsRequestURL won't\n\t// IsRequestURL will allow \"http://http://abcd.com\" but IsURL won't\n\tif !validator.IsURL(resolvedEndpoint) || !validator.IsRequestURL(resolvedEndpoint) {\n\t\terrs = append(errs, fmt.Errorf(\"The endpoint: %s for %s is not a valid URL\", resolvedEndpoint, adapterName))\n\t}\n\treturn errs\n}", "func (nse ErrNoSuchEndpoint) NotFound() {}", "func (mr *MockConfigurationMockRecorder) IntrospectionEndpoint() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"IntrospectionEndpoint\", reflect.TypeOf((*MockConfiguration)(nil).IntrospectionEndpoint))\n}", "func (m *MockConfiguration) IntrospectionEndpoint() op.Endpoint {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"IntrospectionEndpoint\")\n\tret0, _ := ret[0].(op.Endpoint)\n\treturn ret0\n}", "func (o ClusterOutput) ConfigurationEndpoint() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Cluster) pulumi.StringOutput { return v.ConfigurationEndpoint }).(pulumi.StringOutput)\n}", "func TestEndpointCase45(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(false),\n\t\tEndpoint: ptr.String(\"https://example.com\"),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://example.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func EndpointForCondition(predicate predicate.Predicate, configFunc func()) {\n\touterCurrentMockHandler := currentMockHandler\n\tconfigFunc()\n\tcurrentMockery.HandleForCondition(DefaultPriority, predicate, currentMockHandler)\n\tcurrentMockHandler = outerCurrentMockHandler\n}", "func Test_convertEndpointsConfig(t *testing.T) {\n\ttype args struct {\n\t\txdsEndpoint *xdsendpoint.LocalityLbEndpoints\n\t}\n\ttests := []struct {\n\t\tname string\n\t\targs args\n\t\twant []v2.Host\n\t}{\n\t\t{\n\t\t\tname: \"case1\",\n\t\t\targs: args{\n\t\t\t\txdsEndpoint: &xdsendpoint.LocalityLbEndpoints{\n\t\t\t\t\tPriority: 1,\n\t\t\t\t},\n\t\t\t},\n\t\t\twant: []v2.Host{},\n\t\t},\n\t\t{\n\t\t\tname: \"case2\",\n\t\t\targs: args{\n\t\t\t\txdsEndpoint: &xdsendpoint.LocalityLbEndpoints{\n\t\t\t\t\tLbEndpoints: []*xdsendpoint.LbEndpoint{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tHostIdentifier: &xdsendpoint.LbEndpoint_Endpoint{\n\t\t\t\t\t\t\t\tEndpoint: &xdsendpoint.Endpoint{\n\t\t\t\t\t\t\t\t\tAddress: &core.Address{\n\t\t\t\t\t\t\t\t\t\tAddress: &core.Address_SocketAddress{\n\t\t\t\t\t\t\t\t\t\t\tSocketAddress: &core.SocketAddress{\n\t\t\t\t\t\t\t\t\t\t\t\tAddress: \"192.168.0.1\",\n\t\t\t\t\t\t\t\t\t\t\t\tProtocol: core.SocketAddress_TCP,\n\t\t\t\t\t\t\t\t\t\t\t\tPortSpecifier: &core.SocketAddress_PortValue{PortValue: 8080},\n\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tLoadBalancingWeight: &wrappers.UInt32Value{Value: 20},\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tHostIdentifier: &xdsendpoint.LbEndpoint_Endpoint{\n\t\t\t\t\t\t\t\tEndpoint: &xdsendpoint.Endpoint{\n\t\t\t\t\t\t\t\t\tAddress: &core.Address{\n\t\t\t\t\t\t\t\t\t\tAddress: &core.Address_SocketAddress{\n\t\t\t\t\t\t\t\t\t\t\tSocketAddress: &core.SocketAddress{\n\t\t\t\t\t\t\t\t\t\t\t\tAddress: \"192.168.0.2\",\n\t\t\t\t\t\t\t\t\t\t\t\tProtocol: core.SocketAddress_TCP,\n\t\t\t\t\t\t\t\t\t\t\t\tPortSpecifier: &core.SocketAddress_PortValue{PortValue: 8080},\n\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tLoadBalancingWeight: &wrappers.UInt32Value{Value: 0},\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tHostIdentifier: &xdsendpoint.LbEndpoint_Endpoint{\n\t\t\t\t\t\t\t\tEndpoint: &xdsendpoint.Endpoint{\n\t\t\t\t\t\t\t\t\tAddress: &core.Address{\n\t\t\t\t\t\t\t\t\t\tAddress: &core.Address_SocketAddress{\n\t\t\t\t\t\t\t\t\t\t\tSocketAddress: &core.SocketAddress{\n\t\t\t\t\t\t\t\t\t\t\t\tAddress: \"192.168.0.3\",\n\t\t\t\t\t\t\t\t\t\t\t\tProtocol: core.SocketAddress_TCP,\n\t\t\t\t\t\t\t\t\t\t\t\tPortSpecifier: &core.SocketAddress_PortValue{PortValue: 8080},\n\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tLoadBalancingWeight: &wrappers.UInt32Value{Value: 200},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\twant: []v2.Host{\n\t\t\t\t{\n\t\t\t\t\tHostConfig: v2.HostConfig{\n\t\t\t\t\t\tAddress: \"192.168.0.1:8080\",\n\t\t\t\t\t\tWeight: 20,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tHostConfig: v2.HostConfig{\n\t\t\t\t\t\tAddress: \"192.168.0.2:8080\",\n\t\t\t\t\t\tWeight: configmanager.MinHostWeight,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tHostConfig: v2.HostConfig{\n\t\t\t\t\t\tAddress: \"192.168.0.3:8080\",\n\t\t\t\t\t\tWeight: configmanager.MaxHostWeight,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tif got := ConvertEndpointsConfig(tt.args.xdsEndpoint); !reflect.DeepEqual(got, tt.want) {\n\t\t\t\tt.Errorf(\"convertEndpointsConfig() = %v, want %v\", got, tt.want)\n\t\t\t}\n\t\t})\n\t}\n}", "func TestEndpointCase2(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"ap-northeast-1\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(false),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis.ap-northeast-1.amazonaws.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func TestFailedEndpoint1(t *testing.T) {\n\tisTesting = true\n\tvar request = Request{\n\t\tPath: \"/api/device\",\n\t\tHTTPMethod: \"GET\",\n\t}\n\tvar response, _ = Handler(request)\n\tif response.StatusCode != 404 {\n\t\tt.Errorf(\"response status code has to be 404 but is %d\", response.StatusCode)\n\t}\n\tif response.Body != `{\"message\":\"requested endpoint not found\"}` {\n\t\tt.Errorf(\"body is: %s\", response.Body)\n\t}\n}", "func TestEndpointCase4(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"ap-northeast-3\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(false),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis.ap-northeast-3.amazonaws.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func assertEqualEndpoints(t *testing.T, expected, actual *Endpoint) {\n\tif !reflect.DeepEqual(*expected, *actual) {\n\t\tt.Errorf(\"Expected endpoint: %v, Actual %v\", expected, actual)\n\t}\n}", "func (h *HeaderfileWriter) WriteEndpointConfig(w io.Writer, e datapath.EndpointConfiguration) error {\n\tfw := bufio.NewWriter(w)\n\n\twriteIncludes(w)\n\th.writeStaticData(fw, e)\n\n\treturn h.writeTemplateConfig(fw, e)\n}", "func TestEndpointCase25(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"us-west-2\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(true),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis-fips.us-west-2.amazonaws.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func TestEndpointCase84(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"us-iso-west-1\"),\n\t\tUseFIPS: ptr.Bool(true),\n\t\tUseDualStack: ptr.Bool(true),\n\t\tConsumerARN: ptr.String(\"arn:aws-iso:kinesis:us-iso-west-1:123456789012:stream/testStream/consumer/test-consumer:1525898737\"),\n\t\tOperationType: ptr.String(\"control\"),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err == nil {\n\t\tt.Fatalf(\"expect error, got none\")\n\t}\n\tif e, a := \"FIPS and DualStack are enabled, but this partition does not support one or both\", err.Error(); !strings.Contains(a, e) {\n\t\tt.Errorf(\"expect %v error in %v\", e, a)\n\t}\n}", "func (o ServiceOutput) EndpointSpec() ServiceEndpointSpecOutput {\n\treturn o.ApplyT(func(v *Service) ServiceEndpointSpecOutput { return v.EndpointSpec }).(ServiceEndpointSpecOutput)\n}", "func TestEndpointCase6(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"ap-southeast-1\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(false),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis.ap-southeast-1.amazonaws.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func TestEndpointCase27(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"us-east-1\"),\n\t\tUseDualStack: ptr.Bool(true),\n\t\tUseFIPS: ptr.Bool(false),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis.us-east-1.api.aws\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func customSetupEndpoints(pprofActive bool, mgr manager.Manager) error {\n\tif pprofActive {\n\t\tif err := debug.RegisterEndpoint(mgr.AddMetricsExtraHandler, nil); err != nil {\n\t\t\tsetupLog.Error(err, \"Unable to register pprof endpoint\")\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func TestEndpointCase10(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"eu-central-1\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(false),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis.eu-central-1.amazonaws.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func TestEndpointCase12(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"eu-south-1\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(false),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis.eu-south-1.amazonaws.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func TestEndpointCase15(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"eu-west-3\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(false),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis.eu-west-3.amazonaws.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func TestEndpointCase40(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"us-iso-west-1\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(false),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis.us-iso-west-1.c2s.ic.gov\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func TestEndpointCase75(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"us-east-1\"),\n\t\tUseFIPS: ptr.Bool(false),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tConsumerARN: ptr.String(\"arn\"),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err == nil {\n\t\tt.Fatalf(\"expect error, got none\")\n\t}\n\tif e, a := \"Invalid ARN: Failed to parse ARN.\", err.Error(); !strings.Contains(a, e) {\n\t\tt.Errorf(\"expect %v error in %v\", e, a)\n\t}\n}", "func TestEndpointCase18(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"us-east-1\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(false),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis.us-east-1.amazonaws.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func (c *MockRemoteWriteClient) Endpoint() string { return \"\" }", "func TestFailedEndpoint0(t *testing.T) {\n\tisTesting = true\n\tvar request = Request{\n\t\tPath: \"/api/devices\",\n\t\tHTTPMethod: \"PUT\",\n\t}\n\tvar response, _ = Handler(request)\n\tif response.StatusCode != 404 {\n\t\tt.Errorf(\"response status code has to be 404 but is %d\", response.StatusCode)\n\t}\n\tif response.Body != `{\"message\":\"requested endpoint not found\"}` {\n\t\tt.Errorf(\"body is: %s\", response.Body)\n\t}\n}", "func TestEndpointCase34(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"us-gov-east-1\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(true),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis.us-gov-east-1.amazonaws.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func TestEndpointCase24(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"us-west-2\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(false),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis.us-west-2.amazonaws.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func IsEndpointDisabled(err error) bool {\n\treturn unwrapError(err) == ErrEndpointDisabled\n}", "func TestEndpointCase48(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"us-east-1\"),\n\t\tUseFIPS: ptr.Bool(false),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tStreamARN: ptr.String(\"arn\"),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err == nil {\n\t\tt.Fatalf(\"expect error, got none\")\n\t}\n\tif e, a := \"Invalid ARN: Failed to parse ARN.\", err.Error(); !strings.Contains(a, e) {\n\t\tt.Errorf(\"expect %v error in %v\", e, a)\n\t}\n}", "func TestEndpointCase80(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"us-east-1\"),\n\t\tUseFIPS: ptr.Bool(false),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tConsumerARN: ptr.String(\"arn:aws:kinesis: :123456789012:stream/testStream/consumer/test-consumer:1525898737\"),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err == nil {\n\t\tt.Fatalf(\"expect error, got none\")\n\t}\n\tif e, a := \"Invalid ARN: Invalid region.\", err.Error(); !strings.Contains(a, e) {\n\t\tt.Errorf(\"expect %v error in %v\", e, a)\n\t}\n}", "func (p *EscalationConfig) EndPoint() string {\n\treturn \"/api/escalation/config/{id}\"\n}", "func TestEndpointCase20(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"us-east-2\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(false),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis.us-east-2.amazonaws.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func TestEndpointCase55(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"us-east-1\"),\n\t\tUseFIPS: ptr.Bool(false),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tStreamARN: ptr.String(\"arn:aws:kinesis:us-east-1: :stream/testStream\"),\n\t\tOperationType: ptr.String(\"control\"),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err == nil {\n\t\tt.Fatalf(\"expect error, got none\")\n\t}\n\tif e, a := \"Invalid ARN: Invalid account id.\", err.Error(); !strings.Contains(a, e) {\n\t\tt.Errorf(\"expect %v error in %v\", e, a)\n\t}\n}", "func TestEndpointCase22(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"us-west-1\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(false),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis.us-west-1.amazonaws.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func TestEndpointCase3(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"ap-northeast-2\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(false),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis.ap-northeast-2.amazonaws.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func TestEndpointCase16(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"me-south-1\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(false),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis.me-south-1.amazonaws.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func (c *Client) CustomEndpoint(e string) {\n\tc.Endpoint = e\n}", "func TestEndpointCase56(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"us-east-1\"),\n\t\tUseFIPS: ptr.Bool(false),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tStreamARN: ptr.String(\"arn:aws:kinesis:us-east-1:123:accesspoint/testStream\"),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err == nil {\n\t\tt.Fatalf(\"expect error, got none\")\n\t}\n\tif e, a := \"Invalid ARN: Kinesis ARNs don't support `accesspoint` arn types.\", err.Error(); !strings.Contains(a, e) {\n\t\tt.Errorf(\"expect %v error in %v\", e, a)\n\t}\n}", "func TestEndpointCase28(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"cn-north-1\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(false),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis.cn-north-1.amazonaws.com.cn\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func TestEndpointCase14(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"eu-west-2\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(false),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis.eu-west-2.amazonaws.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func TestEndpointCase42(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"us-isob-east-1\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(false),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis.us-isob-east-1.sc2s.sgov.gov\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func editEndpointInConfig(t *testing.T, configFilePath, endpoint string) {\n\tvar config cli.Config\n\tb, err := ioutil.ReadFile(configFilePath)\n\trequire.NoError(t, err)\n\n\terr = yaml.Unmarshal(b, &config)\n\trequire.NoError(t, err)\n\n\tconfig.Endpoint = endpoint\n\n\tb, err = yaml.Marshal(&config)\n\trequire.NoError(t, err)\n\n\terr = ioutil.WriteFile(configFilePath, b, 0655)\n\trequire.NoError(t, err)\n\n}", "func (mr *MockConfigurationMockRecorder) KeysEndpoint() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"KeysEndpoint\", reflect.TypeOf((*MockConfiguration)(nil).KeysEndpoint))\n}", "func (r mockEndpointResolver) EndpointFor(service, region string, opts ...func(*endpoints.Options)) (endpoints.ResolvedEndpoint, error) {\n\treturn r.resolvedEndpoint, r.err\n}", "func IngressEndpoint() string {\n\treturn grpcCfg.IngressEndpoint\n}", "func TestEndpointCase8(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"ap-southeast-3\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(false),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis.ap-southeast-3.amazonaws.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func TestEndpointCase13(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"eu-west-1\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(false),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis.eu-west-1.amazonaws.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func validateOutpostEndpoint(req *request.Request, resource arn.Resource) error {\n\tif err := validateEndpointRequestResource(req, resource); err != nil {\n\t\treturn err\n\t}\n\n\t// DualStack not supported\n\tif isUseDualStackEndpoint(req) {\n\t\treturn s3shared.NewClientConfiguredForDualStackError(resource,\n\t\t\treq.ClientInfo.PartitionID, aws.StringValue(req.Config.Region), nil)\n\t}\n\n\treturn nil\n}", "func TestEndpointCase37(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"us-gov-east-1\"),\n\t\tUseDualStack: ptr.Bool(true),\n\t\tUseFIPS: ptr.Bool(true),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis-fips.us-gov-east-1.api.aws\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func TestEndpointCase17(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"sa-east-1\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(false),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis.sa-east-1.amazonaws.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func TestEndpointCase35(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"us-gov-west-1\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(false),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis.us-gov-west-1.amazonaws.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func TestEndpointCase26(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"us-east-1\"),\n\t\tUseDualStack: ptr.Bool(true),\n\t\tUseFIPS: ptr.Bool(true),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis-fips.us-east-1.api.aws\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func (r *DomainName) EndpointConfiguration() pulumi.Output {\n\treturn r.s.State[\"endpointConfiguration\"]\n}", "func TestEndpointCase29(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"cn-northwest-1\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(false),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis.cn-northwest-1.amazonaws.com.cn\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func (policy *PolicySvc) augmentEndpoint(endpoint *common.Endpoint) error {\n\ttenantSvcUrl, err := policy.client.GetServiceUrl(\"tenant\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tif endpoint.Peer == common.Wildcard {\n\t\t// If a wildcard is specfied, there is nothing to augment\n\t\treturn nil\n\t}\n\tlog.Printf(\"Policy: Augmenting %#v\", endpoint)\n\n\t// Code below tries to resolve tenant name into tenant_network_id if possible.\n\t//\n\t// TODO this will have to be changed once we implement\n\t// https://paninetworks.kanbanize.com/ctrl_board/3/cards/319/details\n\tten := &tenant.Tenant{}\n\tif endpoint.TenantNetworkID == nil {\n\t\tif endpoint.TenantID != 0 {\n\t\t\ttenantIDToUse := strconv.FormatUint(endpoint.TenantID, 10)\n\t\t\ttenantsUrl := fmt.Sprintf(\"%s/tenants/%s\", tenantSvcUrl, tenantIDToUse)\n\t\t\tlog.Printf(\"Policy: Looking tenant up at %s\", tenantsUrl)\n\t\t\terr = policy.client.Get(tenantsUrl, ten)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tendpoint.TenantNetworkID = &ten.NetworkID\n\n\t\t} else if endpoint.TenantExternalID != \"\" || endpoint.TenantName != \"\" {\n\t\t\tif endpoint.TenantExternalID != \"\" {\n\t\t\t\tten.ExternalID = endpoint.TenantExternalID\n\t\t\t}\n\t\t\tif endpoint.TenantName != \"\" {\n\t\t\t\tten.Name = endpoint.TenantName\n\t\t\t}\n\t\t\terr = policy.client.Find(ten, common.FindLast)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tendpoint.TenantNetworkID = &ten.NetworkID\n\t\t}\n\t}\n\n\tif endpoint.SegmentNetworkID == nil {\n\t\tif ten == nil && (endpoint.SegmentID != 0 || endpoint.SegmentExternalID != \"\" || endpoint.SegmentName != \"\") {\n\t\t\treturn common.NewError400(\"No tenant information specified, cannot look up segment.\")\n\t\t}\n\t\tsegment := &tenant.Segment{}\n\t\tif endpoint.SegmentID != 0 {\n\t\t\tsegmentIDToUse := strconv.FormatUint(endpoint.SegmentID, 10)\n\t\t\tsegmentsUrl := fmt.Sprintf(\"%s/tenants/%d/segments/%s\", tenantSvcUrl, ten.ID, segmentIDToUse)\n\t\t\tlog.Printf(\"Policy: Looking segment up at %s for %#v\", segmentsUrl, endpoint)\n\t\t\terr = policy.client.Get(segmentsUrl, &segment)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tendpoint.SegmentNetworkID = &segment.NetworkID\n\t\t} else if endpoint.SegmentExternalID != \"\" || endpoint.SegmentName != \"\" {\n\t\t\tsegmentsUrl := fmt.Sprintf(\"%s/findLast/segments?tenant_id=%d&\", tenantSvcUrl, ten.ID)\n\t\t\tif endpoint.SegmentExternalID != \"\" {\n\t\t\t\tsegmentsUrl += \"external_id=\" + endpoint.TenantExternalID + \"&\"\n\t\t\t}\n\t\t\tif endpoint.SegmentName != \"\" {\n\t\t\t\tsegmentsUrl += \"name=\" + endpoint.SegmentName\n\t\t\t}\n\t\t\tlog.Printf(\"Policy: Finding segments at %s for %#v (Tenant %#v %t)\", segmentsUrl, endpoint, ten, ten == nil)\n\t\t\terr = policy.client.Get(segmentsUrl, &segment)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tendpoint.SegmentNetworkID = &segment.NetworkID\n\t\t}\n\t}\n\treturn nil\n}", "func TestEndpointCase86(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"us-east-1\"),\n\t\tUseFIPS: ptr.Bool(false),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tOperationType: ptr.String(\"control\"),\n\t\tConsumerARN: ptr.String(\"arn:aws:kinesis:us-east-1:123:stream/test-stream/consumer/test-consumer:1525898737\"),\n\t\tEndpoint: ptr.String(\"https://example.com\"),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://example.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func TestEndpointCase11(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"eu-north-1\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(false),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis.eu-north-1.amazonaws.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func TestEndpointCase87(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"us-east-1\"),\n\t\tUseFIPS: ptr.Bool(false),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tOperationType: ptr.String(\"control\"),\n\t\tConsumerARN: ptr.String(\"arn:aws:kinesis:us-east-1:123:stream/test-stream/consumer/test-consumer:1525898737\"),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://123.control-kinesis.us-east-1.amazonaws.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func TestEndpointCase88(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"us-east-1\"),\n\t\tUseFIPS: ptr.Bool(false),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tOperationType: ptr.String(\"data\"),\n\t\tConsumerARN: ptr.String(\"arn:aws:kinesis:us-east-1:123:stream/test-stream/consumer/test-consumer:1525898737\"),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://123.data-kinesis.us-east-1.amazonaws.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func (uee *UnknownEndpointError) NotFound() {}", "func TestValidate1(t *testing.T) {\n\tendpoints := make(map[string]map[string]*Endpoint)\n\tendpoints[\"/test\"] = map[string]*Endpoint{\n\t\t\"get\": {\n\t\t\tParams: &Parameters{\n\t\t\t\tQuery: map[string]*ParamEntry{\"test\": {Type: \"string\", Required: true}},\n\t\t\t\tPath: map[string]*ParamEntry{\"test\": {Type: \"boolean\", Required: true}},\n\t\t\t},\n\t\t\tRecieves: &Recieves{\n\t\t\t\tHeaders: map[string]string{\"foo\": \"bar\"},\n\t\t\t\tBody: map[string]string{\"example_array.0.foo\": \"string\"},\n\t\t\t},\n\t\t\tResponses: map[int]*Response{\n\t\t\t\t200: {\n\t\t\t\t\tHeaders: map[string]string{\"foo\": \"bar\"},\n\t\t\t\t\tBody: map[string]interface{}{\"bar\": \"foo\"},\n\t\t\t\t\tWeight: 100,\n\t\t\t\t\tActions: []map[string]interface{}{\n\t\t\t\t\t\t{\"delay\": 10},\n\t\t\t\t\t\t{\"request\": map[interface{}]interface{}{\"target\": \"testService\", \"id\": \"testRequest\"}},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tActions: []map[string]interface{}{\n\t\t\t\t{\"delay\": 10},\n\t\t\t\t{\"request\": map[interface{}]interface{}{\"target\": \"testService\", \"id\": \"testRequest\"}},\n\t\t\t},\n\t\t},\n\t}\n\n\tcfg := &Config{\n\t\tVersion: 1.0,\n\t\tServices: map[string]*Service{\n\t\t\t\"testService\": {Hostname: \"localhost\", Port: 8080},\n\t\t},\n\t\tStartupActions: []map[string]interface{}{\n\t\t\t{\"delay\": 10},\n\t\t\t{\"request\": map[interface{}]interface{}{\"target\": \"testService\", \"id\": \"testRequest\"}},\n\t\t},\n\t\tRequests: map[string]*Request{\n\t\t\t\"testRequest\": {\n\t\t\t\tURL: \"/test\",\n\t\t\t\tProtocol: \"http\",\n\t\t\t\tMethod: \"get\",\n\t\t\t\tHeaders: map[string]string{\"foo\": \"bar\"},\n\t\t\t\tBody: nil,\n\t\t\t\tExpectedResponse: &Response{\n\t\t\t\t\tStatusCode: 200,\n\t\t\t\t\tBody: map[string]interface{}{\"foo.bar\": \"string\"},\n\t\t\t\t\tHeaders: nil,\n\t\t\t\t\tWeight: 100,\n\t\t\t\t\tActions: []map[string]interface{}{\n\t\t\t\t\t\t{\"delay\": 10},\n\t\t\t\t\t\t{\"request\": map[interface{}]interface{}{\"target\": \"testService\", \"id\": \"testRequest\"}},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tEndpoints: endpoints,\n\t}\n\n\tif err := Validate(cfg); err != nil {\n\t\tt.Errorf(\"Validation Failed: %s\", err.Error())\n\t}\n}", "func TestEndpointCase33(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"us-gov-east-1\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(false),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis.us-gov-east-1.amazonaws.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func TestEndpointCase76(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"us-east-1\"),\n\t\tUseFIPS: ptr.Bool(false),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tConsumerARN: ptr.String(\"arn::kinesis:us-west-2:123456789012:stream/testStream/consumer/test-consumer:1525898737\"),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err == nil {\n\t\tt.Fatalf(\"expect error, got none\")\n\t}\n\tif e, a := \"Invalid ARN: Failed to parse ARN.\", err.Error(); !strings.Contains(a, e) {\n\t\tt.Errorf(\"expect %v error in %v\", e, a)\n\t}\n}", "func (c *Config) Endpoint() string {\n\turi := *c.exporterURL\n\n\tif uri.Scheme == \"file\" {\n\t\turi.RawQuery = \"\"\n\t}\n\turi.Scheme = \"\"\n\n\ts := uri.String()\n\tif strings.HasPrefix(s, \"//\") {\n\t\treturn s[2:]\n\t}\n\treturn s\n}", "func (e Endpoint) GetEndpoint() string {\n\treturn \"someendpoint\"\n}", "func TestEndpointCase101(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"us-isob-east-1\"),\n\t\tUseFIPS: ptr.Bool(true),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tOperationType: ptr.String(\"data\"),\n\t\tConsumerARN: ptr.String(\"arn:aws-iso-b:kinesis:us-isob-east-1:123:stream/test-stream/consumer/test-consumer:1525898737\"),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis-fips.us-isob-east-1.sc2s.sgov.gov\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func TestEndpointCase31(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"cn-north-1\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(true),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis-fips.cn-north-1.amazonaws.com.cn\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func TestEndpointCase21(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"us-east-2\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(true),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis-fips.us-east-2.amazonaws.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func TestEndpointCase43(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"us-isob-east-1\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(true),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis-fips.us-isob-east-1.sc2s.sgov.gov\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func TestEndpointCase7(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"ap-southeast-2\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(false),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis.ap-southeast-2.amazonaws.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func MustNewEndpoints(c Configuration, alternate func() (Endpoints, error)) Endpoints {\n\t// nolint:govet\n\te, err := NewEndpoints(c, alternate)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn e\n}", "func TestEndpointCase9(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"ca-central-1\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(false),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis.ca-central-1.amazonaws.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func TestEndpointCase38(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"us-gov-east-1\"),\n\t\tUseDualStack: ptr.Bool(true),\n\t\tUseFIPS: ptr.Bool(false),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis.us-gov-east-1.api.aws\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func (a *DefaultApiService) ShowEndpoint(ctx _context.Context, id string) ApiShowEndpointRequest {\n\treturn ApiShowEndpointRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t\tid: id,\n\t}\n}", "func TestEndpointCase94(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"us-east-1\"),\n\t\tUseFIPS: ptr.Bool(false),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tOperationType: ptr.String(\"data\"),\n\t\tConsumerARN: ptr.String(\"arn:aws:kinesis:us-west-1:123:stream/testStream/consumer/test-consumer:1525898737\"),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://123.data-kinesis.us-east-1.amazonaws.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func TestEndpointCase103(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"us-east-1\"),\n\t\tUseFIPS: ptr.Bool(false),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tOperationType: ptr.String(\"data\"),\n\t\tStreamARN: ptr.String(\"arn:aws:kinesis:us-east-1:123:stream/foobar\"),\n\t\tConsumerARN: ptr.String(\"arn:aws:kinesis:us-east-1:123456789123:stream/foobar/consumer/test-consumer:1525898737\"),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://123.data-kinesis.us-east-1.amazonaws.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func (o NotificationEndpointGrpcSettingsResponseOutput) Endpoint() pulumi.StringOutput {\n\treturn o.ApplyT(func(v NotificationEndpointGrpcSettingsResponse) string { return v.Endpoint }).(pulumi.StringOutput)\n}", "func (mr *MockConfigurationMockRecorder) TokenEndpoint() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"TokenEndpoint\", reflect.TypeOf((*MockConfiguration)(nil).TokenEndpoint))\n}", "func Endpoint(url string, configureFunc func()) {\n\touterCurrentMockHandler := currentMockHandler\n\tSwitch(extractor.ExtractMethod(), configureFunc)\n\tcurrentMockery.Handle(url, currentMockHandler)\n\tcurrentMockHandler = outerCurrentMockHandler\n}", "func TestEndpointCase57(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"us-iso-west-1\"),\n\t\tUseFIPS: ptr.Bool(true),\n\t\tUseDualStack: ptr.Bool(true),\n\t\tStreamARN: ptr.String(\"arn:aws-iso:kinesis:us-iso-west-1:123456789012:stream/testStream\"),\n\t\tOperationType: ptr.String(\"control\"),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err == nil {\n\t\tt.Fatalf(\"expect error, got none\")\n\t}\n\tif e, a := \"FIPS and DualStack are enabled, but this partition does not support one or both\", err.Error(); !strings.Contains(a, e) {\n\t\tt.Errorf(\"expect %v error in %v\", e, a)\n\t}\n}", "func EndpointFactory(args *endpoint.Arg, stats *stats.Stats, workerCount uint) (endpoint.EndPoint, error) {\n\tif FailSetup {\n\t\treturn nil, errors.New(\"Forced Error\")\n\t}\n\treturn &fakeEndpoint{}, nil\n}", "func WithEndpoint(endpoint string) Option {\n\treturn wrappedOption{oconf.WithEndpoint(endpoint)}\n}", "func TestEndpointCase66(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"us-west-1\"),\n\t\tUseFIPS: ptr.Bool(false),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tOperationType: ptr.String(\"control\"),\n\t\tStreamARN: ptr.String(\"arn:aws:kinesis:us-west-1:123:stream/test-stream\"),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://123.control-kinesis.us-west-1.amazonaws.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func TestEndpointCase30(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"cn-north-1\"),\n\t\tUseDualStack: ptr.Bool(true),\n\t\tUseFIPS: ptr.Bool(true),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis-fips.cn-north-1.api.amazonwebservices.com.cn\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}" ]
[ "0.7167553", "0.6726208", "0.67124325", "0.66572237", "0.5858098", "0.58116376", "0.5778302", "0.57659733", "0.5761034", "0.5759742", "0.57112086", "0.5677339", "0.5649133", "0.5614298", "0.56138974", "0.55987", "0.5568511", "0.5566935", "0.5559191", "0.5552176", "0.55307144", "0.5530202", "0.55239594", "0.55195445", "0.5501351", "0.5498651", "0.54890525", "0.548284", "0.546585", "0.5455927", "0.54555684", "0.5452213", "0.5443767", "0.543083", "0.54294497", "0.5426947", "0.54107386", "0.54104775", "0.5406895", "0.5405905", "0.53882754", "0.53735405", "0.5361897", "0.5361724", "0.5350386", "0.53447735", "0.53439796", "0.5341854", "0.5335686", "0.532988", "0.53236586", "0.5312715", "0.53046393", "0.5303447", "0.5298489", "0.5297415", "0.529137", "0.529021", "0.52874875", "0.52860785", "0.5285997", "0.5281335", "0.52773154", "0.5271595", "0.52701735", "0.526812", "0.52664346", "0.5258766", "0.52549344", "0.5254028", "0.5238508", "0.5229367", "0.5213746", "0.52128613", "0.5207596", "0.5206577", "0.52064025", "0.5206069", "0.52056694", "0.5203943", "0.52020794", "0.52018875", "0.5195881", "0.5194564", "0.51937133", "0.5187734", "0.5185406", "0.5169066", "0.5168827", "0.5166771", "0.5166375", "0.5152772", "0.51495486", "0.51428574", "0.51375234", "0.51321006", "0.5130912", "0.5130253", "0.51192397", "0.51191497" ]
0.7092974
1
GetMetrics mocks base method
func (m *MockProviders) GetMetrics() *metrics.ClientMetrics { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetMetrics") ret0, _ := ret[0].(*metrics.ClientMetrics) return ret0 }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (m *MockTaskManager) GetMetrics() handler.Metric {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetMetrics\")\n\tret0, _ := ret[0].(handler.Metric)\n\treturn ret0\n}", "func MockMetrics() []telegraf.Metric {\n\tmetrics := make([]telegraf.Metric, 0)\n\t// Create a new point batch\n\tmetrics = append(metrics, TestMetric(1.0))\n\treturn metrics\n}", "func TestGetMetrics(t *testing.T) {\n\n\t//\t\tCreating mock request with custom params\n\t//\t\tand checking for error\n\trequest, err := http.NewRequest(\"GET\", \"/fizzbuzz-metrics\", nil)\n\tif err != nil {\n\t\tt.Errorf(\"GetMetrics() failed because of bad request: %v\", err)\n\t}\n\n\t//\t\tCreating a HTTP recorder for the test\n\trecorder := httptest.NewRecorder()\n\n\t//\t\tHitting endpoint\n\trouter := httprouter.New()\n\trouter.GET(\"/fizzbuzz-metrics\", GetMetrics)\n\trouter.ServeHTTP(recorder, request)\n\n\t//\t\tCheck status code\n\tif recorder.Code != http.StatusOK {\n\t\tt.Errorf(\"GetMetrics() failed because of status code: got %v instead of %v\", recorder.Code, http.StatusOK)\n\t}\n\n\t//\t\tCheck body\n\tgot := recorder.Body.String()\n\tif got == \"\" {\n\t\tt.Error(\"GetMetrics() failed because of empty body.\")\n\t}\n}", "func MockMetrics() []optic.Metric {\n\tmetricsEvents := make([]optic.Metric, 0)\n\tmetricsEvents = append(metricsEvents, TestMetric(1.0))\n\treturn metricsEvents\n}", "func MockGetMetricStatistics(t *testing.T, mockMatcher *sdk.MockCloudWatchAPI, metric float64, statistic string, numberOfMetrics int) {\n\tlog.Logger.Warningf(\"Mocking AWS iface: GetMetricStatistics\")\n\tif numberOfMetrics == 0 {\n\t\tnumberOfMetrics = 1\n\t}\n\n\tresult := &cloudwatch.GetMetricStatisticsOutput{}\n\tresult.Label = aws.String(\"fake\")\n\tresult.Datapoints = make([]*cloudwatch.Datapoint, numberOfMetrics)\n\tfor i := 0; i < numberOfMetrics; i++ {\n\t\td := &cloudwatch.Datapoint{}\n\n\t\tswitch statistic {\n\t\tcase cloudwatch.StatisticMaximum:\n\t\t\td.Maximum = aws.Float64(metric)\n\t\tcase cloudwatch.StatisticMinimum:\n\t\t\td.Minimum = aws.Float64(metric)\n\t\tcase cloudwatch.StatisticSum:\n\t\t\td.Sum = aws.Float64(metric)\n\t\tcase cloudwatch.StatisticSampleCount:\n\t\t\td.SampleCount = aws.Float64(metric)\n\t\tcase cloudwatch.StatisticAverage:\n\t\t\td.Average = aws.Float64(metric)\n\t\tdefault:\n\t\t\tt.Fatalf(\"Wrong metric statistic: %s\", statistic)\n\t\t}\n\t\td.Timestamp = aws.Time(time.Now().UTC())\n\t\td.Unit = aws.String(cloudwatch.StandardUnitPercent)\n\t\tresult.Datapoints[i] = d\n\t}\n\n\t// Mock as expected with our result\n\tmockMatcher.EXPECT().GetMetricStatistics(gomock.Any()).Do(func(input interface{}) {\n\t\tgotInput := input.(*cloudwatch.GetMetricStatisticsInput)\n\t\t// Check API received parameters are fine\n\t\tif aws.StringValue(gotInput.Namespace) == \"\" {\n\t\t\tt.Fatalf(\"Expected namespace, got nothing\")\n\t\t}\n\n\t\tif aws.StringValue(gotInput.MetricName) == \"\" {\n\t\t\tt.Fatalf(\"Expected metric name, got nothing\")\n\t\t}\n\n\t\tif aws.StringValue(gotInput.Unit) == \"\" {\n\t\t\tt.Fatalf(\"Expected unit, got nothing\")\n\t\t}\n\n\t\tif len(gotInput.Statistics) != 1 {\n\t\t\tt.Fatalf(\"Wrong statistics name\")\n\t\t}\n\n\t}).AnyTimes().Return(result, nil)\n\n}", "func TestGetMetrics(t *testing.T) {\n\t// set up test server and mocked LogStore\n\tmockLogStore := new(MockedLogStore)\n\tserver := newTestServer(mockLogStore)\n\ttestServer := httptest.NewServer(server.server.Handler)\n\tdefer testServer.Close()\n\tclient := testServer.Client()\n\n\t// Make a first call to a resource to make metrics middleware record some\n\t// stats. Prior to that, no stats will have been saved.\n\tresp, _ := client.Get(testServer.URL + \"/metrics\")\n\trequire.Equalf(t, http.StatusOK, resp.StatusCode, \"unexpected status code\")\n\trequire.Equalf(t, \"\", readBody(t, resp), \"expected first /metrics call to be empty\")\n\n\tresp, _ = client.Get(testServer.URL + \"/metrics\")\n\trequire.Equalf(t, http.StatusOK, resp.StatusCode, \"unexpected status code\")\n\trequire.Containsf(t, readBody(t, resp), `total_requests{method=\"GET\",path=\"/metrics\",statusCode=\"200\"} 1`, \"missing expected metric\")\n}", "func (m *MockClient) GetMetrics() *metrics.ClientMetrics {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetMetrics\")\n\tret0, _ := ret[0].(*metrics.ClientMetrics)\n\treturn ret0\n}", "func (_e *MockDataCoord_Expecter) GetMetrics(ctx interface{}, req interface{}) *MockDataCoord_GetMetrics_Call {\n\treturn &MockDataCoord_GetMetrics_Call{Call: _e.mock.On(\"GetMetrics\", ctx, req)}\n}", "func (_e *MockQueryCoord_Expecter) GetMetrics(ctx interface{}, req interface{}) *MockQueryCoord_GetMetrics_Call {\n\treturn &MockQueryCoord_GetMetrics_Call{Call: _e.mock.On(\"GetMetrics\", ctx, req)}\n}", "func (m *MockKairosDBClient) QueryMetrics(ctx context.Context, dsInfo *datasource.DatasourceInfo, request *remote.MetricQueryRequest) ([]*remote.MetricQueryResults, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"QueryMetrics\", ctx, dsInfo, request)\n\tret0, _ := ret[0].([]*remote.MetricQueryResults)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockFlowAggregatorQuerier) GetRecordMetrics() querier.Metrics {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetRecordMetrics\")\n\tret0, _ := ret[0].(querier.Metrics)\n\treturn ret0\n}", "func (_m *MockStatusStoreIface) GetMetric() (map[string]float64, error) {\n\tret := _m.Called()\n\n\tvar r0 map[string]float64\n\tif rf, ok := ret.Get(0).(func() map[string]float64); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(map[string]float64)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func() error); ok {\n\t\tr1 = rf()\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func TestMetrics(t *testing.T) {\n\tctx := context.Background()\n\tvar err error\n\n\t// Check metrics-server deployment is ready.\n\terr = checkReadyDeployment(ctx)\n\tif err != nil {\n\t\tt.Fatalf(\"could not get metrics: %v\", err)\n\t}\n\n\t// Check metrics availability.\n\terr = checkMetricsAvailability(ctx)\n\tif err != nil {\n\t\tt.Fatalf(\"could not get metrics: %v\", err)\n\t}\n}", "func (m *MockMetrics) InitMetrics() {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"InitMetrics\")\n}", "func NewMock() *MockMetrics {\n\treturn &MockMetrics{}\n}", "func (_m *MockDataCoord) GetMetrics(ctx context.Context, req *milvuspb.GetMetricsRequest) (*milvuspb.GetMetricsResponse, error) {\n\tret := _m.Called(ctx, req)\n\n\tvar r0 *milvuspb.GetMetricsResponse\n\tvar r1 error\n\tif rf, ok := ret.Get(0).(func(context.Context, *milvuspb.GetMetricsRequest) (*milvuspb.GetMetricsResponse, error)); ok {\n\t\treturn rf(ctx, req)\n\t}\n\tif rf, ok := ret.Get(0).(func(context.Context, *milvuspb.GetMetricsRequest) *milvuspb.GetMetricsResponse); ok {\n\t\tr0 = rf(ctx, req)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*milvuspb.GetMetricsResponse)\n\t\t}\n\t}\n\n\tif rf, ok := ret.Get(1).(func(context.Context, *milvuspb.GetMetricsRequest) error); ok {\n\t\tr1 = rf(ctx, req)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (_m *MockQueryCoord) GetMetrics(ctx context.Context, req *milvuspb.GetMetricsRequest) (*milvuspb.GetMetricsResponse, error) {\n\tret := _m.Called(ctx, req)\n\n\tvar r0 *milvuspb.GetMetricsResponse\n\tvar r1 error\n\tif rf, ok := ret.Get(0).(func(context.Context, *milvuspb.GetMetricsRequest) (*milvuspb.GetMetricsResponse, error)); ok {\n\t\treturn rf(ctx, req)\n\t}\n\tif rf, ok := ret.Get(0).(func(context.Context, *milvuspb.GetMetricsRequest) *milvuspb.GetMetricsResponse); ok {\n\t\tr0 = rf(ctx, req)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*milvuspb.GetMetricsResponse)\n\t\t}\n\t}\n\n\tif rf, ok := ret.Get(1).(func(context.Context, *milvuspb.GetMetricsRequest) error); ok {\n\t\tr1 = rf(ctx, req)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (m *MockIApi) MetricsRetrieveAll(arg0 *chartmogul.MetricsFilter) (*chartmogul.MetricsResult, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"MetricsRetrieveAll\", arg0)\n\tret0, _ := ret[0].(*chartmogul.MetricsResult)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (e Entry) GetMetrics(timeout time.Duration, h heimdall.Doer, debug bool) (Metrics, error) {\n\tvar m Metrics\n\n\t// Let's set the stuff we know already.\n\tm.Address = e.Address\n\tm.Regexp = e.Regexp\n\tm.CapturedAt = time.Now().UTC()\n\n\t// Set a timeout.\n\tctx, cancel := context.WithTimeout(context.Background(), timeout)\n\tdefer cancel()\n\n\t// Setup the request.\n\treq, err := http.NewRequestWithContext(ctx, http.MethodGet, e.Address, nil)\n\tif err != nil {\n\t\treturn m, err\n\t}\n\n\tif debug {\n\t\tfmt.Printf(\"%#v\\n\", req)\n\t}\n\n\t// Let's do the request.\n\tstart := time.Now()\n\tres, err := h.Do(req)\n\tif err != nil {\n\t\treturn m, err\n\t}\n\n\t// We don't need the body unless we've got a regexp.\n\tif e.Regexp != \"\" {\n\t\tbody, err := ioutil.ReadAll(res.Body)\n\t\tif err != nil {\n\t\t\treturn m, err\n\t\t}\n\t\t// Do the regexp here and assign the value.\n\t\tmatch, _ := regexp.MatchString(e.Regexp, string(body))\n\t\tm.RegexpStatus = match\n\t}\n\ttook := time.Since(start)\n\n\t// Set the last few values\n\tm.StatusCode = res.StatusCode\n\tm.ResponseTime = took\n\n\tif debug {\n\t\tfmt.Printf(\"Result: %#v\\n\", res)\n\t\tfmt.Printf(\"Time Taken: %s\\n\", took)\n\t\tfmt.Printf(\"Metrics: %#v\\n\", m)\n\t}\n\n\tif ctx.Err() != nil {\n\t\treturn m, errors.New(\"context deadline exceeded\")\n\t}\n\treturn m, nil\n}", "func (h *singleLhcNodeHarness) getMetrics() *metrics {\n\treturn &metrics{\n\t\ttimeSinceLastCommitMillis: h.metricRegistry.Get(\"ConsensusAlgo.LeanHelix.TimeSinceLastCommit.Millis\").(*metric.Histogram),\n\t\ttimeSinceLastElectionMillis: h.metricRegistry.Get(\"ConsensusAlgo.LeanHelix.TimeSinceLastElection.Millis\").(*metric.Histogram),\n\t\tcurrentElectionCount: h.metricRegistry.Get(\"ConsensusAlgo.LeanHelix.CurrentElection.Number\").(*metric.Gauge),\n\t\tcurrentLeaderMemberId: h.metricRegistry.Get(\"ConsensusAlgo.LeanHelix.CurrentLeaderMemberId.Number\").(*metric.Text),\n\t\tlastCommittedTime: h.metricRegistry.Get(\"ConsensusAlgo.LeanHelix.LastCommitted.TimeNano\").(*metric.Gauge),\n\t}\n}", "func (m *MockDataServiceServer) CalculateMetrics(arg0 context.Context, arg1 *dataservice.MetricsRequest) (*dataservice.FeedbackMetrics, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"CalculateMetrics\", arg0, arg1)\n\tret0, _ := ret[0].(*dataservice.FeedbackMetrics)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func setupMetrics() *Metrics {\n\t// Requests duration\n\tduration := prometheus.NewHistogramVec(prometheus.HistogramOpts{\n\t\tName: \"http_request_duration\",\n\t\tHelp: \"Duration of the http requests processed.\",\n\t},\n\t\t[]string{\"status\", \"method\", \"path\"},\n\t)\n\tprometheus.MustRegister(duration)\n\n\treturn &Metrics{\n\t\tduration: duration,\n\t}\n}", "func (m *MockProduct) ListMetricsForAggregation(arg0 context.Context, arg1 string) ([]string, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ListMetricsForAggregation\", arg0, arg1)\n\tret0, _ := ret[0].([]string)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockConnectionTracer) UpdatedMetrics(arg0 *utils.RTTStats, arg1, arg2 protocol.ByteCount, arg3 int) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"UpdatedMetrics\", arg0, arg1, arg2, arg3)\n}", "func Test_CollectMetrics21(t *testing.T) {\n\tassert := assert.New(t)\n\tconfig := getTestConfig(2, 1)\n\tconfig.DataFunc = config.GetTestData1\n\n\tres := config.CollectMetrics()\n\tfmt.Println(\"21: \", res)\n\tfmt.Println(\"21: \", []cmd.MetricData{{Name: \"m1\", Help: \"h1\", MetricType: \"gauge\", Stats: []cmd.MetricRecord{{Value: 999, Labels: []string{\"l00\"}, LabelValues: []string{\"lv00\"}}}}, {Name: \"m2\", Help: \"h2\", MetricType: \"gauge\", Stats: []cmd.MetricRecord{{Value: 999, Labels: []string{\"l10\"}, LabelValues: []string{\"lv10\"}}}}})\n\tassert.Equal(true, cmp.Equal(res, []cmd.MetricData{{Name: \"m1\", Help: \"h1\", MetricType: \"gauge\", Stats: []cmd.MetricRecord{{Value: 999, Labels: []string{\"l00\"}, LabelValues: []string{\"lv00\"}}}}, {Name: \"m2\", Help: \"h2\", MetricType: \"gauge\", Stats: []cmd.MetricRecord{{Value: 999, Labels: []string{\"l10\"}, LabelValues: []string{\"lv10\"}}}}}))\n}", "func (m *MockMetrics) DestroyMetrics() {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"DestroyMetrics\")\n}", "func (ds *dockServer) GetMetrics(context.Context, *pb.GetMetricsOpts) (*pb.GenericResponse, error) {\n\treturn nil, &model.NotImplementError{\"method GetMetrics has not been implemented yet\"}\n}", "func (m *MockDataServiceClient) CalculateMetrics(ctx context.Context, in *dataservice.MetricsRequest, opts ...grpc.CallOption) (*dataservice.FeedbackMetrics, error) {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{ctx, in}\n\tfor _, a := range opts {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"CalculateMetrics\", varargs...)\n\tret0, _ := ret[0].(*dataservice.FeedbackMetrics)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockQueryer) MetricMeta(arg0 i18n.LanguageCodes, arg1, arg2 string, arg3 ...string) ([]*pb.MetricMeta, error) {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{arg0, arg1, arg2}\n\tfor _, a := range arg3 {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"MetricMeta\", varargs...)\n\tret0, _ := ret[0].([]*pb.MetricMeta)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func Test_CollectMetrics01(t *testing.T) {\n\tassert := assert.New(t)\n\tconfig := getTestConfig(0, 1)\n\tconfig.DataFunc = config.GetTestData1\n\n\tres := config.CollectMetrics()\n\tassert.Nil(res)\n}", "func Test_CollectMetrics10(t *testing.T) {\n\tassert := assert.New(t)\n\tconfig := getTestConfig(1, 0)\n\tconfig.DataFunc = config.GetTestData1\n\n\tres := config.CollectMetrics()\n\tassert.Nil(res)\n}", "func TestPrometheusMetrics(t *testing.T) {\n\tbytesProcessedMetric.WithLabelValues(\"x\")\n\tcacheHitMetric.WithLabelValues(\"x\")\n\tuploadedBytesMetric.WithLabelValues(\"x\")\n\tqueryTotalMetric.WithLabelValues(\"x\")\n\tqueryProcessedMetric.WithLabelValues(\"x\")\n\tinFlightUploadsHistogram.WithLabelValues(\"x\")\n\tuploadQueueSizeHistogram.WithLabelValues(\"x\")\n\n\tpromtest.LintMetrics(t)\n}", "func (m *MockContext) GetMetricsClient() metrics.Client {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetMetricsClient\")\n\tret0, _ := ret[0].(metrics.Client)\n\treturn ret0\n}", "func Test_CollectMetrics12(t *testing.T) {\n\tassert := assert.New(t)\n\tconfig := getTestConfig(1, 2)\n\tconfig.DataFunc = config.GetTestData1\n\n\tres := config.CollectMetrics()\n\tfmt.Println(\"12: \", res)\n\tfmt.Println(\"12: \", []cmd.MetricData{{Name: \"m1\", Help: \"h1\", MetricType: \"gauge\", Stats: []cmd.MetricRecord{{Value: 999, Labels: []string{\"l01\"}, LabelValues: []string{\"lv01\"}}, {Value: 999, Labels: []string{\"l00\"}, LabelValues: []string{\"lv00\"}}}}})\n\tassert.Equal(true, cmp.Equal(res, []cmd.MetricData{{Name: \"m1\", Help: \"h1\", MetricType: \"gauge\", Stats: []cmd.MetricRecord{{Value: 999, Labels: []string{\"l01\"}, LabelValues: []string{\"lv01\"}}, {Value: 999, Labels: []string{\"l00\"}, LabelValues: []string{\"lv00\"}}}}}))\n}", "func (h *testMetricsHandler) GetRawMetrics(apiClient kubernetes.Interface, namespace, functionName string) ([]byte, error) {\n\tsvc, err := apiClient.CoreV1().Services(namespace).Get(functionName, metav1.GetOptions{})\n\tif err != nil {\n\t\treturn []byte{}, err\n\t}\n\tb, err := http.Get(svc.SelfLink)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer b.Body.Close()\n\treturn ioutil.ReadAll(b.Body)\n}", "func NewMetrics(reg *prometheus.Registry, namespace, subsystem string, methodsFrom interface{}) (metric Metrics) {\n\tmetric.callErrTotal = prometheus.NewCounterVec(\n\t\tprometheus.CounterOpts{\n\t\t\tNamespace: namespace,\n\t\t\tSubsystem: subsystem,\n\t\t\tName: \"errors_total\",\n\t\t\tHelp: \"Amount of DAL errors.\",\n\t\t},\n\t\t[]string{methodLabel},\n\t)\n\treg.MustRegister(metric.callErrTotal)\n\tmetric.callDuration = prometheus.NewHistogramVec(\n\t\tprometheus.HistogramOpts{\n\t\t\tNamespace: namespace,\n\t\t\tSubsystem: subsystem,\n\t\t\tName: \"call_duration_seconds\",\n\t\t\tHelp: \"DAL call latency.\",\n\t\t},\n\t\t[]string{methodLabel},\n\t)\n\treg.MustRegister(metric.callDuration)\n\n\tfor _, methodName := range reflectx.MethodsOf(methodsFrom) {\n\t\tl := prometheus.Labels{\n\t\t\tmethodLabel: methodName,\n\t\t}\n\t\tmetric.callErrTotal.With(l)\n\t\tmetric.callDuration.With(l)\n\t}\n\n\treturn metric\n}", "func (m *MockServicer) CalculateStats() *service.Stats {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"CalculateStats\")\n\tret0, _ := ret[0].(*service.Stats)\n\treturn ret0\n}", "func (m *MockQueryer) GetSingleMetricsMeta(arg0 i18n.LanguageCodes, arg1, arg2, arg3 string) (*pb.MetricMeta, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetSingleMetricsMeta\", arg0, arg1, arg2, arg3)\n\tret0, _ := ret[0].(*pb.MetricMeta)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockArgusdClient) RecordMetrics(arg0 context.Context, arg1 *golang.Empty, arg2 ...grpc.CallOption) (golang.Argusd_RecordMetricsClient, error) {\n\tvarargs := []interface{}{arg0, arg1}\n\tfor _, a := range arg2 {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"RecordMetrics\", varargs...)\n\tret0, _ := ret[0].(golang.Argusd_RecordMetricsClient)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockIApi) MetricsRetrieveMRRChurnRate(arg0 *chartmogul.MetricsFilter) (*chartmogul.MRRChurnRateResult, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"MetricsRetrieveMRRChurnRate\", arg0)\n\tret0, _ := ret[0].(*chartmogul.MRRChurnRateResult)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (c *Client) GetMetrics(ctx context.Context, req *milvuspb.GetMetricsRequest) (*milvuspb.GetMetricsResponse, error) {\n\treq = typeutil.Clone(req)\n\tcommonpbutil.UpdateMsgBase(\n\t\treq.GetBase(),\n\t\tcommonpbutil.FillMsgBaseFromClient(paramtable.GetNodeID()))\n\treturn wrapGrpcCall(ctx, c, func(client querypb.QueryNodeClient) (*milvuspb.GetMetricsResponse, error) {\n\t\treturn client.GetMetrics(ctx, req)\n\t})\n}", "func (_m *Client) GetMetricValues(ctx context.Context, resourceURI string, interval string, metricnames []string, aggregations []string, logger log.Logger) (map[string]insights.MetricValue, error) {\n\tret := _m.Called(ctx, resourceURI, interval, metricnames, aggregations, logger)\n\n\tvar r0 map[string]insights.MetricValue\n\tif rf, ok := ret.Get(0).(func(context.Context, string, string, []string, []string, log.Logger) map[string]insights.MetricValue); ok {\n\t\tr0 = rf(ctx, resourceURI, interval, metricnames, aggregations, logger)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(map[string]insights.MetricValue)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(context.Context, string, string, []string, []string, log.Logger) error); ok {\n\t\tr1 = rf(ctx, resourceURI, interval, metricnames, aggregations, logger)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func NewMetrics(consume ConsumeMetricsFunc, options ...Option) (Metrics, error) {\n\tif consume == nil {\n\t\treturn nil, errNilFunc\n\t}\n\treturn &baseMetrics{\n\t\tbaseImpl: newBaseImpl(options...),\n\t\tConsumeMetricsFunc: consume,\n\t}, nil\n}", "func (_m *MockBackend) PrometheusMetrics() string {\n\tret := _m.Called()\n\n\tvar r0 string\n\tif rf, ok := ret.Get(0).(func() string); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tr0 = ret.Get(0).(string)\n\t}\n\n\treturn r0\n}", "func getMetrics() []Metric {\n\tms := make([]Metric, 0)\n\treturn append(ms, &SimpleEapMetric{})\n}", "func NewMetrics(scope tally.Scope) *Metrics {\n\tsuccessScope := scope.Tagged(map[string]string{\"result\": \"success\"})\n\tfailScope := scope.Tagged(map[string]string{\"result\": \"fail\"})\n\ttimeoutScope := scope.Tagged(map[string]string{\"result\": \"timeout\"})\n\tapiScope := scope.SubScope(\"api\")\n\tserverScope := scope.SubScope(\"server\")\n\tplacement := scope.SubScope(\"placement\")\n\trecovery := scope.SubScope(\"recovery\")\n\n\treturn &Metrics{\n\t\tAPIEnqueueGangs: apiScope.Counter(\"enqueue_gangs\"),\n\t\tEnqueueGangSuccess: successScope.Counter(\"enqueue_gang\"),\n\t\tEnqueueGangFail: failScope.Counter(\"enqueue_gang\"),\n\n\t\tAPIDequeueGangs: apiScope.Counter(\"dequeue_gangs\"),\n\t\tDequeueGangSuccess: successScope.Counter(\"dequeue_gangs\"),\n\t\tDequeueGangTimeout: timeoutScope.Counter(\"dequeue_gangs\"),\n\n\t\tAPIGetPreemptibleTasks: apiScope.Counter(\"get_preemptible_tasks\"),\n\t\tGetPreemptibleTasksSuccess: successScope.Counter(\"get_preemptible_tasks\"),\n\t\tGetPreemptibleTasksTimeout: timeoutScope.Counter(\"get_preemptible_tasks\"),\n\n\t\tAPISetPlacements: apiScope.Counter(\"set_placements\"),\n\t\tSetPlacementSuccess: successScope.Counter(\"set_placements\"),\n\t\tSetPlacementFail: failScope.Counter(\"set_placements\"),\n\n\t\tAPIGetPlacements: apiScope.Counter(\"get_placements\"),\n\t\tGetPlacementSuccess: successScope.Counter(\"get_placements\"),\n\t\tGetPlacementFail: failScope.Counter(\"get_placements\"),\n\n\t\tAPILaunchedTasks: apiScope.Counter(\"launched_tasks\"),\n\n\t\tRecoverySuccess: successScope.Counter(\"recovery\"),\n\t\tRecoveryFail: failScope.Counter(\"recovery\"),\n\t\tRecoveryRunningSuccessCount: successScope.Counter(\"task_count\"),\n\t\tRecoveryRunningFailCount: failScope.Counter(\"task_count\"),\n\t\tRecoveryEnqueueFailedCount: failScope.Counter(\"enqueue_task_count\"),\n\t\tRecoveryEnqueueSuccessCount: successScope.Counter(\"enqueue_task_count\"),\n\t\tRecoveryTimer: recovery.Timer(\"running_tasks\"),\n\n\t\tPlacementQueueLen: placement.Gauge(\"placement_queue_length\"),\n\t\tPlacementFailed: placement.Counter(\"fail\"),\n\n\t\tElected: serverScope.Gauge(\"elected\"),\n\t}\n}", "func setupMetrics() Metrics {\n\tm := Metrics{}\n\tm.LastBackupDuration = prometheus.NewGauge(prometheus.GaugeOpts{\n\t\tNamespace: \"clickhouse_backup\",\n\t\tName: \"last_backup_duration\",\n\t\tHelp: \"Backup duration in nanoseconds.\",\n\t})\n\tm.LastBackupSuccess = prometheus.NewGauge(prometheus.GaugeOpts{\n\t\tNamespace: \"clickhouse_backup\",\n\t\tName: \"last_backup_success\",\n\t\tHelp: \"Last backup success boolean: 0=failed, 1=success, 2=unknown.\",\n\t})\n\tm.LastBackupStart = prometheus.NewGauge(prometheus.GaugeOpts{\n\t\tNamespace: \"clickhouse_backup\",\n\t\tName: \"last_backup_start\",\n\t\tHelp: \"Last backup start timestamp.\",\n\t})\n\tm.LastBackupEnd = prometheus.NewGauge(prometheus.GaugeOpts{\n\t\tNamespace: \"clickhouse_backup\",\n\t\tName: \"last_backup_end\",\n\t\tHelp: \"Last backup end timestamp.\",\n\t})\n\tm.SuccessfulBackups = prometheus.NewCounter(prometheus.CounterOpts{\n\t\tNamespace: \"clickhouse_backup\",\n\t\tName: \"successful_backups\",\n\t\tHelp: \"Number of Successful Backups.\",\n\t})\n\tm.FailedBackups = prometheus.NewCounter(prometheus.CounterOpts{\n\t\tNamespace: \"clickhouse_backup\",\n\t\tName: \"failed_backups\",\n\t\tHelp: \"Number of Failed Backups.\",\n\t})\n\tprometheus.MustRegister(\n\t\tm.LastBackupDuration,\n\t\tm.LastBackupStart,\n\t\tm.LastBackupEnd,\n\t\tm.LastBackupSuccess,\n\t\tm.SuccessfulBackups,\n\t\tm.FailedBackups,\n\t)\n\tm.LastBackupSuccess.Set(2) // 0=failed, 1=success, 2=unknown\n\treturn m\n}", "func (f FakeContainerImpl) GetContainerMetrics(containerID string) (*metrics.ContainerMetrics, error) {\n\treturn nil, nil\n}", "func TestMetricsEndpoint(t *testing.T) {\n\tc := newKubeClient(t)\n\n\tlistOptions := metav1.ListOptions{LabelSelector: \"app=olm-operator\"}\n\tpodList, err := c.KubernetesInterface().CoreV1().Pods(operatorNamespace).List(listOptions)\n\tif err != nil {\n\t\tlog.Infof(\"Error %v\\n\", err)\n\t\tt.Fatalf(\"Listing pods failed: %v\\n\", err)\n\t}\n\tif len(podList.Items) > 1 {\n\t\tt.Fatalf(\"Expected only 1 olm-operator pod, got %v\", len(podList.Items))\n\t}\n\n\tpodName := podList.Items[0].GetName()\n\n\trawOutput, err := getMetricsFromPod(t, c, podName, operatorNamespace, 8080)\n\tif err != nil {\n\t\tt.Fatalf(\"Metrics test failed: %v\\n\", err)\n\t}\n\n\tlog.Debugf(\"Metrics:\\n%v\", rawOutput)\n}", "func (p *StatsDParser) GetMetrics() pdata.Metrics {\n\tmetrics := pdata.NewMetrics()\n\trm := metrics.ResourceMetrics().AppendEmpty()\n\n\tfor _, metric := range p.gauges {\n\t\trm.InstrumentationLibraryMetrics().Append(metric)\n\t}\n\n\tfor _, metric := range p.counters {\n\t\trm.InstrumentationLibraryMetrics().Append(metric)\n\t}\n\n\tfor _, metric := range p.timersAndDistributions {\n\t\trm.InstrumentationLibraryMetrics().Append(metric)\n\t}\n\n\tfor _, summaryMetric := range p.summaries {\n\t\tmetrics.ResourceMetrics().At(0).InstrumentationLibraryMetrics().Append(buildSummaryMetric(summaryMetric))\n\t}\n\n\tp.gauges = make(map[statsDMetricdescription]pdata.InstrumentationLibraryMetrics)\n\tp.counters = make(map[statsDMetricdescription]pdata.InstrumentationLibraryMetrics)\n\tp.timersAndDistributions = make([]pdata.InstrumentationLibraryMetrics, 0)\n\tp.summaries = make(map[statsDMetricdescription]summaryMetric)\n\treturn metrics\n}", "func (m *MockQueryer) MetricNames(arg0 i18n.LanguageCodes, arg1, arg2 string) ([]*pb.NameDefine, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"MetricNames\", arg0, arg1, arg2)\n\tret0, _ := ret[0].([]*pb.NameDefine)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (sb ServiceBase) Metrics() metrics.Exposer {\n\treturn sb.options.Metrics\n}", "func newMetrics() *metrics {\n\treturn new(metrics)\n}", "func (c *Client) GetMetrics(ctx context.Context, req *milvuspb.GetMetricsRequest) (*milvuspb.GetMetricsResponse, error) {\n\treq = typeutil.Clone(req)\n\tcommonpbutil.UpdateMsgBase(\n\t\treq.GetBase(),\n\t\tcommonpbutil.FillMsgBaseFromClient(paramtable.GetNodeID(), commonpbutil.WithTargetID(c.grpcClient.GetNodeID())),\n\t)\n\treturn wrapGrpcCall(ctx, c, func(client querypb.QueryCoordClient) (*milvuspb.GetMetricsResponse, error) {\n\t\treturn client.GetMetrics(ctx, req)\n\t})\n}", "func (m *MockMetricsFactory) Create() metrics.Metrics {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Create\")\n\tret0, _ := ret[0].(metrics.Metrics)\n\treturn ret0\n}", "func Test_CollectMetrics11(t *testing.T) {\n\tassert := assert.New(t)\n\tconfig := getTestConfig(1, 1)\n\tconfig.DataFunc = config.GetTestData1\n\n\tres := config.CollectMetrics()\n\t// assert.Nil(res)\n\tassert.Equal(res, []cmd.MetricData{{Name: \"m1\", Help: \"h1\", MetricType: \"gauge\", Stats: []cmd.MetricRecord{{Value: 999, Labels: []string{\"l00\"}, LabelValues: []string{\"lv00\"}}}}})\n}", "func newMetrics() *Metrics {\n\treturn newMetricsFrom(DefaultMetricsOpts)\n}", "func (m *MockIApi) MetricsRetrieveARR(arg0 *chartmogul.MetricsFilter) (*chartmogul.ARRResult, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"MetricsRetrieveARR\", arg0)\n\tret0, _ := ret[0].(*chartmogul.ARRResult)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func callMetrics(metricsAPI *metricsAPI, clock func() time.Time, timingMetrics bool) callrules.Rule {\n\ttimed := metricsAPI.callLatency\n\tif !timingMetrics {\n\t\ttimed = nil\n\t}\n\tharness := xmetrics.NewHarness(metricsAPI.callCount, metricsAPI.callErrorCount, timed, clock)\n\treturn callrules.Metrics(harness, nil)\n}", "func NewMetrics() *Metrics {\n\tm := &Metrics{}\n\tm.Reset()\n\treturn m\n}", "func (_class PIFClass) GetMetrics(sessionID SessionRef, self PIFRef) (_retval PIFMetricsRef, _err error) {\n\t_method := \"PIF.get_metrics\"\n\t_sessionIDArg, _err := convertSessionRefToXen(fmt.Sprintf(\"%s(%s)\", _method, \"session_id\"), sessionID)\n\tif _err != nil {\n\t\treturn\n\t}\n\t_selfArg, _err := convertPIFRefToXen(fmt.Sprintf(\"%s(%s)\", _method, \"self\"), self)\n\tif _err != nil {\n\t\treturn\n\t}\n\t_result, _err := _class.client.APICall(_method, _sessionIDArg, _selfArg)\n\tif _err != nil {\n\t\treturn\n\t}\n\t_retval, _err = convertPIFMetricsRefToGo(_method + \" -> \", _result.Value)\n\treturn\n}", "func NewMetrics() *Metrics {\n\treturn &Metrics{\n\t\tInputBytesTotal: promauto.NewCounterVec(\n\t\t\tprometheus.CounterOpts{\n\t\t\t\tName: \"router_input_bytes_total\",\n\t\t\t\tHelp: \"Total number of bytes received\",\n\t\t\t},\n\t\t\t[]string{\"interface\", \"isd_as\", \"neighbor_isd_as\"},\n\t\t),\n\t\tOutputBytesTotal: promauto.NewCounterVec(\n\t\t\tprometheus.CounterOpts{\n\t\t\t\tName: \"router_output_bytes_total\",\n\t\t\t\tHelp: \"Total number of bytes sent.\",\n\t\t\t},\n\t\t\t[]string{\"interface\", \"isd_as\", \"neighbor_isd_as\"},\n\t\t),\n\t\tInputPacketsTotal: promauto.NewCounterVec(\n\t\t\tprometheus.CounterOpts{\n\t\t\t\tName: \"router_input_pkts_total\",\n\t\t\t\tHelp: \"Total number of packets received\",\n\t\t\t},\n\t\t\t[]string{\"interface\", \"isd_as\", \"neighbor_isd_as\"},\n\t\t),\n\t\tOutputPacketsTotal: promauto.NewCounterVec(\n\t\t\tprometheus.CounterOpts{\n\t\t\t\tName: \"router_output_pkts_total\",\n\t\t\t\tHelp: \"Total number of packets sent.\",\n\t\t\t},\n\t\t\t[]string{\"interface\", \"isd_as\", \"neighbor_isd_as\"},\n\t\t),\n\t\tDroppedPacketsTotal: promauto.NewCounterVec(\n\t\t\tprometheus.CounterOpts{\n\t\t\t\tName: \"router_dropped_pkts_total\",\n\t\t\t\tHelp: \"Total number of packets dropped by the router. This metric reports \" +\n\t\t\t\t\t\"the number of packets that were dropped because of errors.\",\n\t\t\t},\n\t\t\t[]string{\"interface\", \"isd_as\", \"neighbor_isd_as\"},\n\t\t),\n\t\tInterfaceUp: promauto.NewGaugeVec(\n\t\t\tprometheus.GaugeOpts{\n\t\t\t\tName: \"router_interface_up\",\n\t\t\t\tHelp: \"Either zero or one depending on whether the interface is up.\",\n\t\t\t},\n\t\t\t[]string{\"interface\", \"isd_as\", \"neighbor_isd_as\"},\n\t\t),\n\t\tBFDInterfaceStateChanges: promauto.NewCounterVec(\n\t\t\tprometheus.CounterOpts{\n\t\t\t\tName: \"router_bfd_state_changes_total\",\n\t\t\t\tHelp: \"Total number of BFD state changes.\",\n\t\t\t},\n\t\t\t[]string{\"interface\", \"isd_as\", \"neighbor_isd_as\"},\n\t\t),\n\t\tBFDPacketsSent: promauto.NewCounterVec(\n\t\t\tprometheus.CounterOpts{\n\t\t\t\tName: \"router_bfd_sent_packets_total\",\n\t\t\t\tHelp: \"Number of BFD packets sent.\",\n\t\t\t},\n\t\t\t[]string{\"interface\", \"isd_as\", \"neighbor_isd_as\"},\n\t\t),\n\t\tBFDPacketsReceived: promauto.NewCounterVec(\n\t\t\tprometheus.CounterOpts{\n\t\t\t\tName: \"router_bfd_received_packets_total\",\n\t\t\t\tHelp: \"Number of BFD packets received.\",\n\t\t\t},\n\t\t\t[]string{\"interface\", \"isd_as\", \"neighbor_isd_as\"},\n\t\t),\n\t\tServiceInstanceCount: promauto.NewGaugeVec(\n\t\t\tprometheus.GaugeOpts{\n\t\t\t\tName: \"router_service_instance_count\",\n\t\t\t\tHelp: \"Number of service instances known by the data plane.\",\n\t\t\t},\n\t\t\t[]string{\"service\", \"isd_as\"},\n\t\t),\n\t\tServiceInstanceChanges: promauto.NewCounterVec(\n\t\t\tprometheus.CounterOpts{\n\t\t\t\tName: \"router_service_instance_changes_total\",\n\t\t\t\tHelp: \"Number of total service instance changes. Both addition and removal of a \" +\n\t\t\t\t\t\"service instance is accumulated.\",\n\t\t\t},\n\t\t\t[]string{\"service\", \"isd_as\"},\n\t\t),\n\t\tSiblingReachable: promauto.NewGaugeVec(\n\t\t\tprometheus.GaugeOpts{\n\t\t\t\tName: \"router_sibling_reachable\",\n\t\t\t\tHelp: \"Either zero or one depending on whether a sibling router \" +\n\t\t\t\t\t\"instance is reachable.\",\n\t\t\t},\n\t\t\t[]string{\"sibling\", \"isd_as\"},\n\t\t),\n\t\tSiblingBFDPacketsSent: promauto.NewCounterVec(\n\t\t\tprometheus.CounterOpts{\n\t\t\t\tName: \"router_bfd_sent_sibling_packets_total\",\n\t\t\t\tHelp: \"Number of BFD packets sent to sibling router instance.\",\n\t\t\t},\n\t\t\t[]string{\"sibling\", \"isd_as\"},\n\t\t),\n\t\tSiblingBFDPacketsReceived: promauto.NewCounterVec(\n\t\t\tprometheus.CounterOpts{\n\t\t\t\tName: \"router_bfd_received_sibling_packets_total\",\n\t\t\t\tHelp: \"Number of BFD packets received from sibling router instance.\",\n\t\t\t},\n\t\t\t[]string{\"sibling\", \"isd_as\"},\n\t\t),\n\t\tSiblingBFDStateChanges: promauto.NewCounterVec(\n\t\t\tprometheus.CounterOpts{\n\t\t\t\tName: \"router_bfd_sibling_state_changes_total\",\n\t\t\t\tHelp: \"Total number of BFD state changes for sibling router instances\",\n\t\t\t},\n\t\t\t[]string{\"sibling\", \"isd_as\"},\n\t\t),\n\t}\n}", "func LoadExpectedMetrics(t *testing.T, model string) []string {\n\tt.Helper()\n\tdcgmNameToMetricNameMap := map[string]string{\n\t\t\"DCGM_FI_DEV_GPU_UTIL\": \"dcgm.gpu.utilization\",\n\t\t\"DCGM_FI_DEV_FB_USED\": \"dcgm.gpu.memory.bytes_used\",\n\t\t\"DCGM_FI_DEV_FB_FREE\": \"dcgm.gpu.memory.bytes_free\",\n\t\t\"DCGM_FI_PROF_SM_ACTIVE\": \"dcgm.gpu.profiling.sm_utilization\",\n\t\t\"DCGM_FI_PROF_SM_OCCUPANCY\": \"dcgm.gpu.profiling.sm_occupancy\",\n\t\t\"DCGM_FI_PROF_PIPE_TENSOR_ACTIVE\": \"dcgm.gpu.profiling.tensor_utilization\",\n\t\t\"DCGM_FI_PROF_DRAM_ACTIVE\": \"dcgm.gpu.profiling.dram_utilization\",\n\t\t\"DCGM_FI_PROF_PIPE_FP64_ACTIVE\": \"dcgm.gpu.profiling.fp64_utilization\",\n\t\t\"DCGM_FI_PROF_PIPE_FP32_ACTIVE\": \"dcgm.gpu.profiling.fp32_utilization\",\n\t\t\"DCGM_FI_PROF_PIPE_FP16_ACTIVE\": \"dcgm.gpu.profiling.fp16_utilization\",\n\t\t\"DCGM_FI_PROF_PCIE_TX_BYTES\": \"dcgm.gpu.profiling.pcie_sent_bytes\",\n\t\t\"DCGM_FI_PROF_PCIE_RX_BYTES\": \"dcgm.gpu.profiling.pcie_received_bytes\",\n\t\t\"DCGM_FI_PROF_NVLINK_TX_BYTES\": \"dcgm.gpu.profiling.nvlink_sent_bytes\",\n\t\t\"DCGM_FI_PROF_NVLINK_RX_BYTES\": \"dcgm.gpu.profiling.nvlink_received_bytes\",\n\t}\n\tgoldenPath := getModelGoldenFilePath(t, model)\n\tgoldenFile, err := ioutil.ReadFile(goldenPath)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tvar m modelSupportedFields\n\terr = yaml.Unmarshal(goldenFile, &m)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tvar expectedMetrics []string\n\tfor _, supported := range m.SupportedFields {\n\t\texpectedMetrics = append(expectedMetrics, dcgmNameToMetricNameMap[supported])\n\t}\n\treturn expectedMetrics\n}", "func (m *MockMetrics) MeasureSince(arg0 []string, arg1 time.Time) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"MeasureSince\", arg0, arg1)\n}", "func (_m *SysProbeUtil) GetStats() (map[string]interface{}, error) {\n\tret := _m.Called()\n\n\tvar r0 map[string]interface{}\n\tvar r1 error\n\tif rf, ok := ret.Get(0).(func() (map[string]interface{}, error)); ok {\n\t\treturn rf()\n\t}\n\tif rf, ok := ret.Get(0).(func() map[string]interface{}); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(map[string]interface{})\n\t\t}\n\t}\n\n\tif rf, ok := ret.Get(1).(func() error); ok {\n\t\tr1 = rf()\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func NewMockedMetrics() *MockedMetrics {\n\treturn &MockedMetrics{}\n}", "func NewMockedMetrics() *MockedMetrics {\n\treturn &MockedMetrics{}\n}", "func (m *MockContract) GetUserStats(arg0, arg1, arg2 string) (*services.UserResponseContract, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUserStats\", arg0, arg1, arg2)\n\tret0, _ := ret[0].(*services.UserResponseContract)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (y *YarnMetrics) getMetrics() *NMMetrics {\n\tjmxResp := &JmxResp{}\n\terr := y.requestUrl(metricsSuffix, jmxResp)\n\tif err != nil {\n\t\tklog.V(5).Infof(\"request nodemanager metrics err: %v\", err)\n\t\treturn nil\n\t}\n\tif len(jmxResp.Beans) == 0 {\n\t\tklog.V(5).Infof(\"request nodemanager metrics, empty beans\")\n\t\treturn nil\n\t}\n\treturn &jmxResp.Beans[0]\n}", "func TestMetrics(t *testing.T) {\n\tmetrics, err := NewMetrics()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tmetrics.Send(&influxdb.Series{\n\t\tName: \"testing\",\n\t\tColumns: []string{\n\t\t\t\"foo\",\n\t\t},\n\t\tPoints: [][]interface{}{\n\t\t\t{\n\t\t\t\t\"bar\",\n\t\t\t},\n\t\t},\n\t})\n}", "func initMetrics() *metrics.Manager {\n\treturn metrics.New(\"calert\")\n}", "func (a *Client) GetMetrics(params *GetMetricsParams, authInfo runtime.ClientAuthInfoWriter) (*GetMetricsOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewGetMetricsParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"GetMetrics\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/cdn/v1/stacks/{stack_id}/metrics\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"https\"},\n\t\tParams: params,\n\t\tReader: &GetMetricsReader{formats: a.formats},\n\t\tAuthInfo: authInfo,\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn result.(*GetMetricsOK), nil\n\n}", "func (_m *Client) GetDefinitionMetrics(_a0 context.Context, _a1 build.GetDefinitionMetricsArgs) (*[]build.BuildMetric, error) {\n\tret := _m.Called(_a0, _a1)\n\n\tvar r0 *[]build.BuildMetric\n\tif rf, ok := ret.Get(0).(func(context.Context, build.GetDefinitionMetricsArgs) *[]build.BuildMetric); ok {\n\t\tr0 = rf(_a0, _a1)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*[]build.BuildMetric)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(context.Context, build.GetDefinitionMetricsArgs) error); ok {\n\t\tr1 = rf(_a0, _a1)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (m *MockIApi) MetricsListActivities(arg0 *chartmogul.MetricsListActivitiesParams) (*chartmogul.MetricsActivities, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"MetricsListActivities\", arg0)\n\tret0, _ := ret[0].(*chartmogul.MetricsActivities)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (c *PromMetricsClient) GetMetrics() ([]*Metric, error) {\n\tres, err := http.Get(c.URL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif res.StatusCode != 200 {\n\t\treturn nil, ErrUnexpectedHTTPStatusCode\n\t}\n\n\tdefer res.Body.Close()\n\treturn Parse(res.Body)\n}", "func (m *MockIApi) MetricsRetrieveMRR(arg0 *chartmogul.MetricsFilter) (*chartmogul.MRRResult, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"MetricsRetrieveMRR\", arg0)\n\tret0, _ := ret[0].(*chartmogul.MRRResult)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func NewMetrics(component string, sampleRate float64, client metrics.Client) BaseMetrics {\n\treturn BaseMetrics{\n\t\tcomponent: component,\n\t\trate: sampleRate,\n\t\tmetrics: client,\n\t\tmetMap: map[string]string{\n\t\t\t\"latency\": \"comp.\" + component + \".requests.latency\",\n\t\t\t\"request\": \"comp.\" + component + \".requests.%d\",\n\t\t\t\"mLatency\": \"comp.\" + component + \".requests.%s.latency\",\n\t\t\t\"mRequest\": \"comp.\" + component + \".requests.%s.%d\",\n\t\t},\n\t}\n}", "func mustGetClientMetrics() *grpc_prometheus.ClientMetrics {\n\tclientMetricsOnce.Do(func() {\n\t\tclientMetrics = grpc_prometheus.NewRegisteredClientMetrics(prometheus.DefaultRegisterer,\n\t\t\tgrpc_prometheus.WithClientCounterOptions(setCounterNamespace),\n\t\t\tgrpc_prometheus.WithClientHandlingTimeHistogram(setHistogramNamespace), // record the overall request latency for a gRPC request\n\t\t\tgrpc_prometheus.WithClientStreamRecvHistogram(setHistogramNamespace), // record how long it takes for a client to receive a message during a streaming RPC\n\t\t\tgrpc_prometheus.WithClientStreamSendHistogram(setHistogramNamespace), // record how long it takes for a client to send a message during a streaming RPC\n\t\t)\n\t})\n\n\treturn clientMetrics\n}", "func (m *MockScheduler) GetClassLoadPercents() (map[string]int32, error) {\n\tret := m.ctrl.Call(m, \"GetClassLoadPercents\")\n\tret0, _ := ret[0].(map[string]int32)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func NewMockMetrics(ctrl *gomock.Controller) *MockMetrics {\n\tmock := &MockMetrics{ctrl: ctrl}\n\tmock.recorder = &MockMetricsMockRecorder{mock}\n\treturn mock\n}", "func NewMockMetrics(ctrl *gomock.Controller) *MockMetrics {\n\tmock := &MockMetrics{ctrl: ctrl}\n\tmock.recorder = &MockMetricsMockRecorder{mock}\n\treturn mock\n}", "func NewMockMetrics(ctrl *gomock.Controller) *MockMetrics {\n\tmock := &MockMetrics{ctrl: ctrl}\n\tmock.recorder = &MockMetricsMockRecorder{mock}\n\treturn mock\n}", "func NewMockMetrics(ctrl *gomock.Controller) *MockMetrics {\n\tmock := &MockMetrics{ctrl: ctrl}\n\tmock.recorder = &MockMetricsMockRecorder{mock}\n\treturn mock\n}", "func NewMockMetrics(ctrl *gomock.Controller) *MockMetrics {\n\tmock := &MockMetrics{ctrl: ctrl}\n\tmock.recorder = &MockMetricsMockRecorder{mock}\n\treturn mock\n}", "func (m *MockMetrics) CountStart() {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"CountStart\")\n}", "func (c *CAdvisor) GetMetrics() (*Metrics, error) {\n\tlog.Printf(\"[DEBUG] [cadvisor] Get metrics\")\n\tnodeSpec, err := c.Client.MachineInfo()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlog.Printf(\"[DEBUG] [cadvisor] Receive machine info : %#v\",\n\t\tnodeSpec)\n\tnodeInfo, err := c.Client.ContainerInfo(\"/\", c.Query)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlog.Printf(\"[DEBUG] [cadvisor] Receive container info : %#v\",\n\t\tnodeInfo)\n\tcontainersInfo, err := c.Client.AllDockerContainers(c.Query)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlog.Printf(\"[DEBUG] [cadvisor] Receive all docker containers : %#v\",\n\t\tcontainersInfo)\n\tmetrics := &Metrics{\n\t\tNodeSpec: nodeSpec,\n\t\tNodeInfo: nodeInfo,\n\t\tContainersInfo: containersInfo,\n\t}\n\t//log.Printf(\"[INFO] [cadvisor] Metrics: %#v\", metrics)\n\treturn metrics, nil\n}", "func (m *MockStatsReader) GetGlobalStats() GlobalStats {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetGlobalStats\")\n\tret0, _ := ret[0].(GlobalStats)\n\treturn ret0\n}", "func (c *client) getAllTicketMetrics(endpoint string, in interface{}) ([]TicketMetric, error) {\n\tresult := make([]TicketMetric, 0)\n\tpayload, err := marshall(in)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\theaders := map[string]string{}\n\tif in != nil {\n\t\theaders[\"Content-Type\"] = \"application/json\"\n\t}\n\n\tres, err := c.request(\"GET\", endpoint, headers, bytes.NewReader(payload))\n\tdataPerPage := new(APIPayload)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tapiV2 := \"/api/v2/\"\n\tfieldName := strings.Split(endpoint[len(apiV2):], \".\")[0]\n\tdefer res.Body.Close()\n\n\terr = unmarshall(res, dataPerPage)\n\n\tapiStartIndex := strings.Index(dataPerPage.NextPage, apiV2)\n\tcurrentPage := endpoint\n\n\tvar totalWaitTime int64\n\tfor currentPage != \"\" {\n\t\t// if too many requests(res.StatusCode == 429), delay sending request\n\t\tif res.StatusCode == 429 {\n\t\t\tafter, err := strconv.ParseInt(res.Header.Get(\"Retry-After\"), 10, 64)\n\t\t\tlog.Printf(\"[zd_ticket_metrics_service][getAllTicketMetrics] too many requests. Wait for %v seconds\\n\", after)\n\t\t\ttotalWaitTime += after\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\ttime.Sleep(time.Duration(after) * time.Second)\n\t\t} else {\n\t\t\tif fieldName == \"ticket_metrics\" {\n\t\t\t\tresult = append(result, dataPerPage.TicketMetrics...)\n\t\t\t}\n\t\t\tcurrentPage = dataPerPage.NextPage\n\t\t}\n\t\tres, _ = c.request(\"GET\", dataPerPage.NextPage[apiStartIndex:], headers, bytes.NewReader(payload))\n\t\tdataPerPage = new(APIPayload)\n\t\terr = unmarshall(res, dataPerPage)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tlog.Printf(\"[zd_ticket_metrics_service][getAllTicketMetrics] number of records pulled: %v\\n\", len(result))\n\tlog.Printf(\"[zd_ticket_metrics_service][getAllTicketMetrics] total waiting time due to rate limit: %v\\n\", totalWaitTime)\n\n\treturn result, err\n}", "func TestMetrics(t *testing.T) {\n\t// Notes that ReadPairsExamined, ReadPairDups, and\n\t// ReadPairOpticalDups below are doubled because they are halved\n\t// when written to the metrics file.\n\ttests := []struct {\n\t\trecords []*sam.Record\n\t\tmetrics *MetricsCollection\n\t}{\n\t\t{\n\t\t\t[]*sam.Record{\n\t\t\t\tNewRecord(\"A:::1:10:1:1\", chr1, 0, r1F, 10, chr1, cigar0),\n\t\t\t\tNewRecord(\"A:::1:10:1:1\", chr1, 10, r2R, 0, chr1, cigar0),\n\t\t\t},\n\t\t\t&MetricsCollection{\n\t\t\t\tLibraryMetrics: map[string]*Metrics{\n\t\t\t\t\t\"Unknown Library\": &Metrics{\n\t\t\t\t\t\tUnpairedReads: 0,\n\t\t\t\t\t\tReadPairsExamined: 2,\n\t\t\t\t\t\tSecondarySupplementary: 0,\n\t\t\t\t\t\tUnmappedReads: 0,\n\t\t\t\t\t\tUnpairedDups: 0,\n\t\t\t\t\t\tReadPairDups: 0,\n\t\t\t\t\t\tReadPairOpticalDups: 0,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t[]*sam.Record{\n\t\t\t\tNewRecord(\"A:::1:10:1:1\", chr1, 0, r1F, 10, chr1, cigar0),\n\t\t\t\tNewRecord(\"B:::2:10:1:1\", chr1, 0, r1F, 10, chr1, cigar0),\n\t\t\t\tNewRecord(\"A:::1:10:1:1\", chr1, 10, r2R, 0, chr1, cigar0),\n\t\t\t\tNewRecord(\"B:::2:10:1:1\", chr1, 10, r2R, 0, chr1, cigar0),\n\t\t\t},\n\t\t\t&MetricsCollection{\n\t\t\t\tLibraryMetrics: map[string]*Metrics{\n\t\t\t\t\t\"Unknown Library\": &Metrics{\n\t\t\t\t\t\tUnpairedReads: 0,\n\t\t\t\t\t\tReadPairsExamined: 4,\n\t\t\t\t\t\tSecondarySupplementary: 0,\n\t\t\t\t\t\tUnmappedReads: 0,\n\t\t\t\t\t\tUnpairedDups: 0,\n\t\t\t\t\t\tReadPairDups: 2,\n\t\t\t\t\t\tReadPairOpticalDups: 0,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t[]*sam.Record{\n\t\t\t\tNewRecord(\"A:::1:10:1:1\", chr1, 0, r1F, 10, chr1, cigar0),\n\t\t\t\tNewRecord(\"B:::2:11:1:1\", chr1, 0, r1F, 10, chr1, cigar0),\n\t\t\t\tNewRecord(\"C:::2:11:1:1\", chr1, 0, r1F, 10, chr1, cigar0),\n\t\t\t\tNewRecord(\"A:::1:10:1:1\", chr1, 10, r2R, 0, chr1, cigar0),\n\t\t\t\tNewRecord(\"B:::2:11:1:1\", chr1, 10, r2R, 0, chr1, cigar0),\n\t\t\t\tNewRecord(\"C:::2:11:1:1\", chr1, 10, r2R, 0, chr1, cigar0),\n\t\t\t},\n\t\t\t&MetricsCollection{\n\t\t\t\tLibraryMetrics: map[string]*Metrics{\n\t\t\t\t\t\"Unknown Library\": &Metrics{\n\t\t\t\t\t\tUnpairedReads: 0,\n\t\t\t\t\t\tReadPairsExamined: 6,\n\t\t\t\t\t\tSecondarySupplementary: 0,\n\t\t\t\t\t\tUnmappedReads: 0,\n\t\t\t\t\t\tUnpairedDups: 0,\n\t\t\t\t\t\tReadPairDups: 4,\n\t\t\t\t\t\tReadPairOpticalDups: 2,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t[]*sam.Record{\n\t\t\t\tNewRecord(\"A:::1:10:1:1\", chr1, 0, s1F, 0, nil, cigar0),\n\t\t\t\tNewRecord(\"A:::1:10:1:1\", chr1, 0, u2, 0, nil, cigar0),\n\t\t\t\tNewRecord(\"B:::2:10:1:1\", chr1, 0, s1F, 0, nil, cigar0),\n\t\t\t\tNewRecord(\"B:::2:10:1:1\", chr1, 0, u2, 0, nil, cigar0),\n\t\t\t},\n\t\t\t&MetricsCollection{\n\t\t\t\tLibraryMetrics: map[string]*Metrics{\n\t\t\t\t\t\"Unknown Library\": &Metrics{\n\t\t\t\t\t\tUnpairedReads: 2,\n\t\t\t\t\t\tReadPairsExamined: 0,\n\t\t\t\t\t\tSecondarySupplementary: 0,\n\t\t\t\t\t\tUnmappedReads: 2,\n\t\t\t\t\t\tUnpairedDups: 1,\n\t\t\t\t\t\tReadPairDups: 0,\n\t\t\t\t\t\tReadPairOpticalDups: 0,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t// Cross-shard pairs\n\t\t\t[]*sam.Record{\n\t\t\t\tNewRecord(\"A:::1:10:1:1\", chr1, 0, r1F, 105, chr1, cigar0),\n\t\t\t\tNewRecord(\"B:::1:10:1:1\", chr1, 0, r1F, 105, chr1, cigar0),\n\t\t\t\tNewRecord(\"A:::1:10:1:1\", chr1, 105, r2R, 0, chr1, cigar0),\n\t\t\t\tNewRecord(\"B:::1:10:1:1\", chr1, 105, r2R, 0, chr1, cigar0),\n\t\t\t},\n\t\t\t&MetricsCollection{\n\t\t\t\tLibraryMetrics: map[string]*Metrics{\n\t\t\t\t\t\"Unknown Library\": &Metrics{\n\t\t\t\t\t\tUnpairedReads: 0,\n\t\t\t\t\t\tReadPairsExamined: 4,\n\t\t\t\t\t\tSecondarySupplementary: 0,\n\t\t\t\t\t\tUnmappedReads: 0,\n\t\t\t\t\t\tUnpairedDups: 0,\n\t\t\t\t\t\tReadPairDups: 2,\n\t\t\t\t\t\tReadPairOpticalDups: 2,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t// Secondary alignments.\n\t\t\t[]*sam.Record{\n\t\t\t\tNewRecord(\"A:::1:10:1:1\", chr1, 0, r1F, 105, chr1, cigar0),\n\t\t\t\tNewRecord(\"A:::1:10:1:1\", chr1, 105, r2R, 0, chr1, cigar0),\n\t\t\t\tNewRecord(\"A:::1:10:1:1\", chr2, 12, sec, 105, chr1, cigar0),\n\t\t\t},\n\t\t\t&MetricsCollection{\n\t\t\t\tLibraryMetrics: map[string]*Metrics{\n\t\t\t\t\t\"Unknown Library\": &Metrics{\n\t\t\t\t\t\tUnpairedReads: 0,\n\t\t\t\t\t\tReadPairsExamined: 2,\n\t\t\t\t\t\tSecondarySupplementary: 1,\n\t\t\t\t\t\tUnmappedReads: 0,\n\t\t\t\t\t\tUnpairedDups: 0,\n\t\t\t\t\t\tReadPairDups: 0,\n\t\t\t\t\t\tReadPairOpticalDups: 0,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t// Verify that we're counting dual-unmapped pairs\n\t\t\t[]*sam.Record{\n\t\t\t\tNewRecord(\"A:::1:10:1:1\", chr1, 0, r1F, 105, chr1, cigar0),\n\t\t\t\tNewRecord(\"A:::1:10:1:1\", chr1, 105, r2R, 0, chr1, cigar0),\n\t\t\t\tNewRecord(\"U:::2:11:1:1\", nil, -1, up1, -1, nil, cigar0),\n\t\t\t\tNewRecord(\"U:::2:11:1:1\", nil, -1, up2, -1, nil, cigar0),\n\t\t\t},\n\t\t\t&MetricsCollection{\n\t\t\t\tLibraryMetrics: map[string]*Metrics{\n\t\t\t\t\t\"Unknown Library\": &Metrics{\n\t\t\t\t\t\tUnpairedReads: 0,\n\t\t\t\t\t\tReadPairsExamined: 2,\n\t\t\t\t\t\tSecondarySupplementary: 0,\n\t\t\t\t\t\tUnmappedReads: 2,\n\t\t\t\t\t\tUnpairedDups: 0,\n\t\t\t\t\t\tReadPairDups: 0,\n\t\t\t\t\t\tReadPairOpticalDups: 0,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\ttempDir, cleanup := testutil.TempDir(t, \"\", \"\")\n\tdefer cleanup()\n\tfor testIdx, test := range tests {\n\t\tfor _, tagDups := range []bool{true, false} {\n\t\t\tfor _, format := range []string{\"bam\", \"pam\"} {\n\t\t\t\tt.Logf(\"---- starting tests[%d, %v] ----\", testIdx, tagDups)\n\t\t\t\tprovider := bamprovider.NewFakeProvider(header, test.records)\n\t\t\t\toutputPath := NewTestOutput(tempDir, testIdx, format)\n\t\t\t\topts := Opts{\n\t\t\t\t\tShardSize: 100,\n\t\t\t\t\tPadding: 10,\n\t\t\t\t\tParallelism: 1,\n\t\t\t\t\tQueueLength: 10,\n\t\t\t\t\tClearExisting: false,\n\t\t\t\t\tRemoveDups: false,\n\t\t\t\t\tTagDups: tagDups,\n\t\t\t\t\tEmitUnmodifiedFields: true,\n\t\t\t\t\tOutputPath: outputPath,\n\t\t\t\t\tFormat: format,\n\t\t\t\t\tOpticalDetector: &TileOpticalDetector{\n\t\t\t\t\t\tOpticalDistance: 2500,\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t\tmarkDuplicates := &MarkDuplicates{\n\t\t\t\t\tProvider: provider,\n\t\t\t\t\tOpts: &opts,\n\t\t\t\t}\n\t\t\t\tactualMetrics, err := markDuplicates.Mark(nil)\n\t\t\t\tassert.NoError(t, err)\n\n\t\t\t\tfor i, r := range ReadRecords(t, outputPath) {\n\t\t\t\t\tt.Logf(\"output[%v]: %v\", i, r)\n\t\t\t\t}\n\t\t\t\tassert.Equal(t, len(test.metrics.LibraryMetrics), len(actualMetrics.LibraryMetrics))\n\t\t\t\tfor k, m := range actualMetrics.LibraryMetrics {\n\t\t\t\t\tassert.Equal(t, *(test.metrics.LibraryMetrics[k]), *m)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func (s *GrpcServer) GetMetrics(ctx context.Context, in *api.ScaledObjectRef) (*v1beta1.ExternalMetricValueList, error) {\n\tv1beta1ExtMetrics := &v1beta1.ExternalMetricValueList{}\n\textMetrics, err := (*s.scalerHandler).GetScaledObjectMetrics(ctx, in.Name, in.Namespace, in.MetricName)\n\tif err != nil {\n\t\treturn v1beta1ExtMetrics, fmt.Errorf(\"error when getting metric values %w\", err)\n\t}\n\n\terr = v1beta1.Convert_external_metrics_ExternalMetricValueList_To_v1beta1_ExternalMetricValueList(extMetrics, v1beta1ExtMetrics, nil)\n\tif err != nil {\n\t\treturn v1beta1ExtMetrics, fmt.Errorf(\"error when converting metric values %w\", err)\n\t}\n\n\tlog.V(1).WithValues(\"scaledObjectName\", in.Name, \"scaledObjectNamespace\", in.Namespace, \"metrics\", v1beta1ExtMetrics).Info(\"Providing metrics\")\n\n\treturn v1beta1ExtMetrics, nil\n}", "func TestMetricTooMany(t *testing.T) { //nolint:maintidx\n\thelper := newHelper(t)\n\tdefer helper.Close()\n\n\thelper.preregisterAgent(t)\n\thelper.initSynchronizer(t)\n\n\tmetricResource, _ := helper.api.resources[mockAPIResourceMetric].(*genericResource)\n\tdefaultPatchHook := metricResource.PatchHook\n\n\t// API always reject more than 3 active metrics\n\tmetricResource.PatchHook = func(r *http.Request, body []byte, valuePtr interface{}, oldValue interface{}) error {\n\t\tif defaultPatchHook != nil {\n\t\t\terr := defaultPatchHook(r, body, valuePtr, oldValue)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\tmetric, _ := valuePtr.(*metricPayload)\n\n\t\tif metric.DeactivatedAt.IsZero() {\n\t\t\tmetrics := helper.MetricsFromAPI()\n\t\t\tcountActive := 0\n\n\t\t\tfor _, m := range metrics {\n\t\t\t\tif m.DeactivatedAt.IsZero() && m.ID != metric.ID {\n\t\t\t\t\tcountActive++\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif countActive >= 3 {\n\t\t\t\treturn clientError{\n\t\t\t\t\tbody: `{\"label\":[\"Too many non standard metrics\"]}`,\n\t\t\t\t\tstatusCode: http.StatusBadRequest,\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn nil\n\t}\n\n\tmetricResource.CreateHook = func(r *http.Request, body []byte, valuePtr interface{}) error {\n\t\treturn metricResource.PatchHook(r, body, valuePtr, nil)\n\t}\n\n\thelper.AddTime(time.Minute)\n\thelper.pushPoints(t, []labels.Labels{\n\t\tlabels.New(\n\t\t\tlabels.Label{Name: types.LabelName, Value: \"metric1\"},\n\t\t),\n\t\tlabels.New(\n\t\t\tlabels.Label{Name: types.LabelName, Value: \"metric2\"},\n\t\t),\n\t})\n\n\tif err := helper.runOnceWithResult(t).CheckMethodWithFull(syncMethodMetric); err != nil {\n\t\tt.Error(err)\n\t}\n\n\t// list active metrics, register agent_status + 2x metrics to register\n\thelper.api.AssertCallPerResource(t, mockAPIResourceMetric, 6)\n\n\tmetrics := helper.MetricsFromAPI()\n\tif len(metrics) != 3 { // 2 + agent_status\n\t\tt.Errorf(\"len(metrics) = %d, want 3\", len(metrics))\n\t}\n\n\thelper.AddTime(5 * time.Minute)\n\thelper.pushPoints(t, []labels.Labels{\n\t\tlabels.New(\n\t\t\tlabels.Label{Name: types.LabelName, Value: \"metric3\"},\n\t\t),\n\t\tlabels.New(\n\t\t\tlabels.Label{Name: types.LabelName, Value: \"metric4\"},\n\t\t),\n\t})\n\n\tif err := helper.runOnceWithResult(t).CheckMethodWithoutFull(syncMethodMetric); err != nil {\n\t\tt.Error(err)\n\t}\n\n\tif helper.api.ClientErrorCount == 0 {\n\t\tt.Errorf(\"We should have some client error, had %d\", helper.api.ClientErrorCount)\n\t}\n\n\t// list active metrics + 2x metrics to register\n\thelper.api.AssertCallPerResource(t, mockAPIResourceMetric, 5)\n\n\tmetrics = helper.MetricsFromAPI()\n\tif len(metrics) != 3 { // 2 + agent_status\n\t\tt.Errorf(\"len(metrics) = %d, want 3\", len(metrics))\n\t}\n\n\thelper.AddTime(5 * time.Minute)\n\n\tif err := helper.runOnceWithResult(t).CheckMethodNotRun(syncMethodMetric); err != nil {\n\t\tt.Error(err)\n\t}\n\n\thelper.SetTimeToNextFullSync()\n\t// drop all because normally store drop inactive metrics and\n\t// metric1 don't emitted for 70 minutes\n\thelper.store.DropAllMetrics()\n\thelper.pushPoints(t, []labels.Labels{\n\t\tlabels.New(\n\t\t\tlabels.Label{Name: types.LabelName, Value: \"metric2\"},\n\t\t),\n\t\tlabels.New(\n\t\t\tlabels.Label{Name: types.LabelName, Value: \"metric3\"},\n\t\t),\n\t\tlabels.New(\n\t\t\tlabels.Label{Name: types.LabelName, Value: \"metric4\"},\n\t\t),\n\t})\n\n\tif err := helper.runOnceWithResult(t).CheckMethodWithFull(syncMethodMetric); err != nil {\n\t\tt.Error(err)\n\t}\n\n\t// We need two sync: one to deactivate the metric, one to regsiter another one\n\thelper.AddTime(15 * time.Second)\n\n\tif err := helper.runOnceWithResult(t).CheckMethodWithoutFull(syncMethodMetric); err != nil {\n\t\tt.Error(err)\n\t}\n\n\tmetrics = helper.MetricsFromAPI()\n\tif len(metrics) != 4 { // metric1 is now disabled, another get registered\n\t\tt.Errorf(\"len(metrics) = %d, want 4\", len(metrics))\n\t}\n\n\tfor _, m := range metrics {\n\t\tif !m.DeactivatedAt.IsZero() && m.Name != \"metric1\" {\n\t\t\tt.Errorf(\"metric %s is deactivated, want active\", m.Name)\n\t\t}\n\n\t\tif m.DeactivatedAt.IsZero() && m.Name == \"metric1\" {\n\t\t\tt.Errorf(\"metric %s is active, want deactivated\", m.Name)\n\t\t}\n\t}\n\n\thelper.AddTime(5 * time.Minute)\n\thelper.pushPoints(t, []labels.Labels{\n\t\tlabels.New(\n\t\t\tlabels.Label{Name: types.LabelName, Value: \"metric1\"},\n\t\t),\n\t})\n\n\tif err := helper.runOnceWithResult(t).CheckMethodWithoutFull(syncMethodMetric); err != nil {\n\t\tt.Error(err)\n\t}\n\n\tif helper.api.ClientErrorCount == 0 {\n\t\tt.Errorf(\"We should have some client error, had %d\", helper.api.ClientErrorCount)\n\t}\n\n\tmetrics = helper.MetricsFromAPI()\n\tif len(metrics) != 4 { // metric1 is still disabled and no newly registered\n\t\tt.Errorf(\"len(metrics) = %d, want 4\", len(metrics))\n\t}\n\n\tfor _, m := range metrics {\n\t\tif !m.DeactivatedAt.IsZero() && m.Name != \"metric1\" {\n\t\t\tt.Errorf(\"metric %s is deactivated, want active\", m.Name)\n\t\t}\n\n\t\tif m.DeactivatedAt.IsZero() && m.Name == \"metric1\" {\n\t\t\tt.Errorf(\"metric %s is active, want deactivated\", m.Name)\n\t\t}\n\t}\n\n\t// We do not retry to register them\n\thelper.AddTime(5 * time.Minute)\n\n\tif err := helper.runOnceWithResult(t).CheckMethodNotRun(syncMethodMetric); err != nil {\n\t\tt.Error(err)\n\t}\n\n\t// Excepted ONE per full-sync\n\thelper.SetTimeToNextFullSync()\n\thelper.pushPoints(t, []labels.Labels{\n\t\tlabels.New(\n\t\t\tlabels.Label{Name: types.LabelName, Value: \"metric2\"},\n\t\t),\n\t\tlabels.New(\n\t\t\tlabels.Label{Name: types.LabelName, Value: \"metric3\"},\n\t\t),\n\t\tlabels.New(\n\t\t\tlabels.Label{Name: types.LabelName, Value: \"metric4\"},\n\t\t),\n\t})\n\n\tif err := helper.runOnceWithResult(t).CheckMethodWithFull(syncMethodMetric); err != nil {\n\t\tt.Error(err)\n\t}\n\n\tif helper.api.ClientErrorCount != 1 {\n\t\tt.Errorf(\"had %d client error, want 1\", helper.api.ClientErrorCount)\n\t}\n\n\tmetrics = helper.MetricsFromAPI()\n\tif len(metrics) != 4 {\n\t\tt.Errorf(\"len(metrics) = %d, want 4\", len(metrics))\n\t}\n\n\tfor _, m := range metrics {\n\t\tif !m.DeactivatedAt.IsZero() && m.Name != \"metric1\" {\n\t\t\tt.Errorf(\"metric %s is deactivated, want active\", m.Name)\n\t\t}\n\n\t\tif m.DeactivatedAt.IsZero() && m.Name == \"metric1\" {\n\t\t\tt.Errorf(\"metric %s is active, want deactivated\", m.Name)\n\t\t}\n\t}\n\n\t// list active metrics + check existence of the metric we want to reg +\n\t// retry to register\n\thelper.api.AssertCallPerResource(t, mockAPIResourceMetric, 3)\n}", "func (m *MockGeneralRepository) GetStats(network types.Network) (map[string]*models.NetworkStats, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetStats\", network)\n\tret0, _ := ret[0].(map[string]*models.NetworkStats)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (_m *MockBackend) Stats() (int, int, int) {\n\tret := _m.Called()\n\n\tvar r0 int\n\tif rf, ok := ret.Get(0).(func() int); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tr0 = ret.Get(0).(int)\n\t}\n\n\tvar r1 int\n\tif rf, ok := ret.Get(1).(func() int); ok {\n\t\tr1 = rf()\n\t} else {\n\t\tr1 = ret.Get(1).(int)\n\t}\n\n\tvar r2 int\n\tif rf, ok := ret.Get(2).(func() int); ok {\n\t\tr2 = rf()\n\t} else {\n\t\tr2 = ret.Get(2).(int)\n\t}\n\n\treturn r0, r1, r2\n}", "func RegisterMetrics() {\n\n\tprometheus.MustRegister(metrics.TiKVBackoffHistogram)\n\tprometheus.MustRegister(metrics.TiKVCoprocessorHistogram)\n\tprometheus.MustRegister(metrics.TiKVLoadSafepointCounter)\n\tprometheus.MustRegister(metrics.TiKVLockResolverCounter)\n\tprometheus.MustRegister(metrics.TiKVRawkvCmdHistogram)\n\tprometheus.MustRegister(metrics.TiKVRawkvSizeHistogram)\n\tprometheus.MustRegister(metrics.TiKVRegionCacheCounter)\n\tprometheus.MustRegister(metrics.TiKVRegionErrorCounter)\n\tprometheus.MustRegister(metrics.TiKVSecondaryLockCleanupFailureCounter)\n\tprometheus.MustRegister(metrics.TiKVSendReqHistogram)\n\tprometheus.MustRegister(metrics.TiKVTxnCmdHistogram)\n\tprometheus.MustRegister(metrics.TiKVTxnRegionsNumHistogram)\n\tprometheus.MustRegister(metrics.TiKVTxnWriteKVCountHistogram)\n\tprometheus.MustRegister(metrics.TiKVTxnWriteSizeHistogram)\n\tprometheus.MustRegister(metrics.TiKVLocalLatchWaitTimeHistogram)\n\tprometheus.MustRegister(metrics.TiKVPendingBatchRequests)\n\tprometheus.MustRegister(metrics.TiKVStatusDuration)\n\tprometheus.MustRegister(metrics.TiKVStatusCounter)\n\tprometheus.MustRegister(metrics.TiKVBatchWaitDuration)\n\tprometheus.MustRegister(metrics.TiKVBatchClientUnavailable)\n\tprometheus.MustRegister(metrics.TiKVRangeTaskStats)\n\tprometheus.MustRegister(metrics.TiKVRangeTaskPushDuration)\n\tprometheus.MustRegister(metrics.TiKVTokenWaitDuration)\n\tprometheus.MustRegister(metrics.TiKVTxnHeartBeatHistogram)\n\tprometheus.MustRegister(metrics.TiKVPessimisticLockKeysDuration)\n\tprometheus.MustRegister(metrics.TiKVTTLLifeTimeReachCounter)\n\tprometheus.MustRegister(metrics.TiKVNoAvailableConnectionCounter)\n\n\tprometheus.MustRegister(TSFutureWaitDuration)\n\n\t// grpc metrics\n\tprometheus.MustRegister(CreateSessionCounter)\n\tprometheus.MustRegister(DeleteSessionCounter)\n\tprometheus.MustRegister(ReadCounter)\n\tprometheus.MustRegister(SparseReadCounter)\n\tprometheus.MustRegister(StreamReadCounter)\n\tprometheus.MustRegister(CommitCounter)\n\tprometheus.MustRegister(MutateCounter)\n\tprometheus.MustRegister(ExecuteMutateDuration)\n\tprometheus.MustRegister(ExecuteReadDuration)\n\n\t// session metrics\n\tprometheus.MustRegister(SessionRetry)\n\tprometheus.MustRegister(SessionCounter)\n\tprometheus.MustRegister(SessionRetryErrorCounter)\n\tprometheus.MustRegister(TransactionCounter)\n\tprometheus.MustRegister(TransactionDuration)\n\tprometheus.MustRegister(SchemaLeaseErrorCounter)\n\n\t//tables metrics\n\tprometheus.MustRegister(FetchRowsCounter)\n\tprometheus.MustRegister(FetchSparseCounter)\n\tprometheus.MustRegister(FetchRowsDuration)\n\tprometheus.MustRegister(FetchSparseDuration)\n\n\tprometheus.MustRegister(ScanSparseCounter)\n\tprometheus.MustRegister(ScanSparseDuration)\n\n\tprometheus.MustRegister(BatchSparseCounter)\n\tprometheus.MustRegister(BatchSparseDuration)\n}", "func TestGetCPUStat(t *testing.T) {\n\t// setup the faking of `cpu.Info()`\n\toldcpuInfo := cpuInfo\n\tcpuInfo = func() ([]cpu.InfoStat, error) {\n\t\tret := []cpu.InfoStat{\n\t\t\t{\n\t\t\t\tVendorID: string(\"vendor\"),\n\t\t\t\tModelName: string(\"model\"),\n\t\t\t\tMhz: float64(100),\n\t\t\t},\n\t\t\t{\n\t\t\t\tVendorID: string(\"vendor\"), // two CPUs --> cpuinfo.count = \"2\"\n\t\t\t\tModelName: string(\"model\"),\n\t\t\t\tMhz: float64(100),\n\t\t\t},\n\t\t}\n\t\treturn ret, nil\n\t}\n\n\t// test\n\texpected := cpuStat{\n\t\tcount: strconv.FormatInt(2, 10),\n\t\tvendorID: \"vendor\",\n\t\tmodelName: \"model\",\n\t\tmhz: strconv.FormatInt(100, 10),\n\t}\n\tactual, err := getCPUStat()\n\n\tassert.NoError(t, err, \"`getCPUStat()` should not have returned an error\")\n\tassert.Equal(t, expected, actual, \"`getCPUStat()` should be equal to main.cpuStat{count:\\\"2\\\", vendorID:\\\"vendor\\\", modelName:\\\"model\\\", mhz:\\\"100\\\"}\")\n\n\t// teardown\n\tcpuInfo = oldcpuInfo\n}", "func (m *MockFullNode) NetBandwidthStats(arg0 context.Context) (metrics.Stats, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"NetBandwidthStats\", arg0)\n\tret0, _ := ret[0].(metrics.Stats)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (s *azureServiceBusScaler) GetMetrics(ctx context.Context, metricName string, metricSelector labels.Selector) ([]external_metrics.ExternalMetricValue, error) {\n\tqueuelen, err := s.GetAzureServiceBusLength(ctx)\n\n\tif err != nil {\n\t\tazureServiceBusLog.Error(err, \"error getting service bus entity length\")\n\t\treturn []external_metrics.ExternalMetricValue{}, err\n\t}\n\n\tmetric := external_metrics.ExternalMetricValue{\n\t\tMetricName: metricName,\n\t\tValue: *resource.NewQuantity(int64(queuelen), resource.DecimalSI),\n\t\tTimestamp: metav1.Now(),\n\t}\n\n\treturn append([]external_metrics.ExternalMetricValue{}, metric), nil\n}", "func NewMetrics(factory promutil.Factory) *Metrics {\n\treturn &Metrics{\n\t\tImporterEngineCounter: factory.NewCounterVec(\n\t\t\tprometheus.CounterOpts{\n\t\t\t\tNamespace: \"lightning\",\n\t\t\t\tName: \"importer_engine\",\n\t\t\t\tHelp: \"counting open and closed importer engines\",\n\t\t\t}, []string{\"type\"}),\n\n\t\tIdleWorkersGauge: factory.NewGaugeVec(\n\t\t\tprometheus.GaugeOpts{\n\t\t\t\tNamespace: \"lightning\",\n\t\t\t\tName: \"idle_workers\",\n\t\t\t\tHelp: \"counting idle workers\",\n\t\t\t}, []string{\"name\"}),\n\n\t\tKvEncoderCounter: factory.NewCounterVec(\n\t\t\tprometheus.CounterOpts{\n\t\t\t\tNamespace: \"lightning\",\n\t\t\t\tName: \"kv_encoder\",\n\t\t\t\tHelp: \"counting kv open and closed kv encoder\",\n\t\t\t}, []string{\"type\"}),\n\n\t\tTableCounter: factory.NewCounterVec(\n\t\t\tprometheus.CounterOpts{\n\t\t\t\tNamespace: \"lightning\",\n\t\t\t\tName: \"tables\",\n\t\t\t\tHelp: \"count number of tables processed\",\n\t\t\t}, []string{\"state\", \"result\"}),\n\n\t\tProcessedEngineCounter: factory.NewCounterVec(\n\t\t\tprometheus.CounterOpts{\n\t\t\t\tNamespace: \"lightning\",\n\t\t\t\tName: \"engines\",\n\t\t\t\tHelp: \"count number of engines processed\",\n\t\t\t}, []string{\"state\", \"result\"}),\n\n\t\tChunkCounter: factory.NewCounterVec(\n\t\t\tprometheus.CounterOpts{\n\t\t\t\tNamespace: \"lightning\",\n\t\t\t\tName: \"chunks\",\n\t\t\t\tHelp: \"count number of chunks processed\",\n\t\t\t}, []string{\"state\"}),\n\n\t\tBytesCounter: factory.NewCounterVec(\n\t\t\tprometheus.CounterOpts{\n\t\t\t\tNamespace: \"lightning\",\n\t\t\t\tName: \"bytes\",\n\t\t\t\tHelp: \"count of total bytes\",\n\t\t\t}, []string{\"state\"}),\n\t\t// state can be one of:\n\t\t// - estimated (an estimation derived from the file size)\n\t\t// - pending\n\t\t// - running\n\t\t// - finished\n\t\t// - failed\n\n\t\tRowsCounter: factory.NewCounterVec(\n\t\t\tprometheus.CounterOpts{\n\t\t\t\tNamespace: \"lightning\",\n\t\t\t\tName: \"rows\",\n\t\t\t\tHelp: \"count of total rows\",\n\t\t\t}, []string{\"state\", \"table\"}),\n\n\t\tImportSecondsHistogram: factory.NewHistogram(\n\t\t\tprometheus.HistogramOpts{\n\t\t\t\tNamespace: \"lightning\",\n\t\t\t\tName: \"import_seconds\",\n\t\t\t\tHelp: \"time needed to import a table\",\n\t\t\t\tBuckets: prometheus.ExponentialBuckets(0.125, 2, 6),\n\t\t\t}),\n\n\t\tChunkParserReadBlockSecondsHistogram: factory.NewHistogram(\n\t\t\tprometheus.HistogramOpts{\n\t\t\t\tNamespace: \"lightning\",\n\t\t\t\tName: \"chunk_parser_read_block_seconds\",\n\t\t\t\tHelp: \"time needed for chunk parser read a block\",\n\t\t\t\tBuckets: prometheus.ExponentialBuckets(0.001, 3.1622776601683795, 10),\n\t\t\t}),\n\n\t\tApplyWorkerSecondsHistogram: factory.NewHistogramVec(\n\t\t\tprometheus.HistogramOpts{\n\t\t\t\tNamespace: \"lightning\",\n\t\t\t\tName: \"apply_worker_seconds\",\n\t\t\t\tHelp: \"time needed to apply a worker\",\n\t\t\t\tBuckets: prometheus.ExponentialBuckets(0.001, 3.1622776601683795, 10),\n\t\t\t}, []string{\"name\"}),\n\n\t\tRowReadSecondsHistogram: factory.NewHistogram(\n\t\t\tprometheus.HistogramOpts{\n\t\t\t\tNamespace: \"lightning\",\n\t\t\t\tName: \"row_read_seconds\",\n\t\t\t\tHelp: \"time needed to parse a row\",\n\t\t\t\tBuckets: prometheus.ExponentialBuckets(0.001, 3.1622776601683795, 7),\n\t\t\t}),\n\n\t\tRowReadBytesHistogram: factory.NewHistogram(\n\t\t\tprometheus.HistogramOpts{\n\t\t\t\tNamespace: \"lightning\",\n\t\t\t\tName: \"row_read_bytes\",\n\t\t\t\tHelp: \"number of bytes being read out from data source\",\n\t\t\t\tBuckets: prometheus.ExponentialBuckets(1024, 2, 8),\n\t\t\t}),\n\n\t\tRowEncodeSecondsHistogram: factory.NewHistogram(\n\t\t\tprometheus.HistogramOpts{\n\t\t\t\tNamespace: \"lightning\",\n\t\t\t\tName: \"row_encode_seconds\",\n\t\t\t\tHelp: \"time needed to encode a row\",\n\t\t\t\tBuckets: prometheus.ExponentialBuckets(0.001, 3.1622776601683795, 10),\n\t\t\t}),\n\t\tRowKVDeliverSecondsHistogram: factory.NewHistogram(\n\t\t\tprometheus.HistogramOpts{\n\t\t\t\tNamespace: \"lightning\",\n\t\t\t\tName: \"row_kv_deliver_seconds\",\n\t\t\t\tHelp: \"time needed to deliver kvs of a single row\",\n\t\t\t\tBuckets: prometheus.ExponentialBuckets(0.001, 3.1622776601683795, 10),\n\t\t\t}),\n\n\t\tBlockDeliverSecondsHistogram: factory.NewHistogram(\n\t\t\tprometheus.HistogramOpts{\n\t\t\t\tNamespace: \"lightning\",\n\t\t\t\tName: \"block_deliver_seconds\",\n\t\t\t\tHelp: \"time needed to deliver a block\",\n\t\t\t\tBuckets: prometheus.ExponentialBuckets(0.001, 3.1622776601683795, 10),\n\t\t\t}),\n\t\tBlockDeliverBytesHistogram: factory.NewHistogramVec(\n\t\t\tprometheus.HistogramOpts{\n\t\t\t\tNamespace: \"lightning\",\n\t\t\t\tName: \"block_deliver_bytes\",\n\t\t\t\tHelp: \"number of bytes being sent out to importer\",\n\t\t\t\tBuckets: prometheus.ExponentialBuckets(512, 2, 10),\n\t\t\t}, []string{\"kind\"}),\n\t\tBlockDeliverKVPairsHistogram: factory.NewHistogramVec(\n\t\t\tprometheus.HistogramOpts{\n\t\t\t\tNamespace: \"lightning\",\n\t\t\t\tName: \"block_deliver_kv_pairs\",\n\t\t\t\tHelp: \"number of KV pairs being sent out to importer\",\n\t\t\t\tBuckets: prometheus.ExponentialBuckets(1, 2, 10),\n\t\t\t}, []string{\"kind\"}),\n\t\tChecksumSecondsHistogram: factory.NewHistogram(\n\t\t\tprometheus.HistogramOpts{\n\t\t\t\tNamespace: \"lightning\",\n\t\t\t\tName: \"checksum_seconds\",\n\t\t\t\tHelp: \"time needed to complete the checksum stage\",\n\t\t\t\tBuckets: prometheus.ExponentialBuckets(1, 2.2679331552660544, 10),\n\t\t\t}),\n\t\tSSTSecondsHistogram: factory.NewHistogramVec(\n\t\t\tprometheus.HistogramOpts{\n\t\t\t\tNamespace: \"lightning\",\n\t\t\t\tName: \"sst_seconds\",\n\t\t\t\tHelp: \"time needed to complete the sst operations\",\n\t\t\t\tBuckets: prometheus.ExponentialBuckets(1, 2.2679331552660544, 10),\n\t\t\t}, []string{\"kind\"}),\n\n\t\tLocalStorageUsageBytesGauge: factory.NewGaugeVec(\n\t\t\tprometheus.GaugeOpts{\n\t\t\t\tNamespace: \"lightning\",\n\t\t\t\tName: \"local_storage_usage_bytes\",\n\t\t\t\tHelp: \"disk/memory size currently occupied by intermediate files in local backend\",\n\t\t\t}, []string{\"medium\"}),\n\n\t\tProgressGauge: factory.NewGaugeVec(\n\t\t\tprometheus.GaugeOpts{\n\t\t\t\tNamespace: \"lightning\",\n\t\t\t\tName: \"progress\",\n\t\t\t\tHelp: \"progress of lightning phase\",\n\t\t\t}, []string{\"phase\"}),\n\t}\n}", "func (m *MockIMutantRepository) GetStatsFromCache() *models.MutantsStats {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetStatsFromCache\")\n\tret0, _ := ret[0].(*models.MutantsStats)\n\treturn ret0\n}", "func NewMetrics(consume ConsumeMetricsFunc, options ...Option) (consumer.Metrics, error) {\n\tif consume == nil {\n\t\treturn nil, errNilFunc\n\t}\n\treturn &baseMetrics{\n\t\tbaseConsumer: newBaseConsumer(options...),\n\t\tConsumeMetricsFunc: consume,\n\t}, nil\n}" ]
[ "0.7650577", "0.7016764", "0.70125824", "0.6981954", "0.69156355", "0.68423605", "0.6813142", "0.6613567", "0.6547792", "0.64580333", "0.63285154", "0.63118887", "0.624346", "0.6230752", "0.61920655", "0.6130787", "0.6118216", "0.6095558", "0.60732526", "0.6055256", "0.60451156", "0.60406727", "0.6039367", "0.60160184", "0.5988926", "0.59400934", "0.5917193", "0.58818036", "0.58630484", "0.58616287", "0.5838285", "0.58213055", "0.5820539", "0.58078825", "0.5804123", "0.5802292", "0.57988465", "0.5795632", "0.57846844", "0.57703453", "0.5741666", "0.5727525", "0.57143813", "0.571075", "0.5704046", "0.57003546", "0.56960887", "0.56942385", "0.568245", "0.56797117", "0.5678851", "0.567784", "0.56768817", "0.5676756", "0.56748635", "0.565278", "0.5647898", "0.564218", "0.5637814", "0.5631854", "0.56263345", "0.5617829", "0.56062144", "0.56024", "0.55926204", "0.559074", "0.559074", "0.55776936", "0.5576679", "0.5576555", "0.55704737", "0.55703855", "0.5567151", "0.55632174", "0.556168", "0.5558797", "0.55368197", "0.5531239", "0.552203", "0.55211157", "0.55211157", "0.55211157", "0.55211157", "0.55211157", "0.55196977", "0.5515768", "0.5498938", "0.5493261", "0.5485738", "0.54848814", "0.5481429", "0.54637814", "0.546021", "0.54598784", "0.545601", "0.54480004", "0.54472166", "0.544694", "0.54467046", "0.5445243" ]
0.6705235
7
GetMetrics indicates an expected call of GetMetrics
func (mr *MockProvidersMockRecorder) GetMetrics() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetMetrics", reflect.TypeOf((*MockProviders)(nil).GetMetrics)) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (mr *MockTaskManagerMockRecorder) GetMetrics() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetMetrics\", reflect.TypeOf((*MockTaskManager)(nil).GetMetrics))\n}", "func (mr *MockClientMockRecorder) GetMetrics() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetMetrics\", reflect.TypeOf((*MockClient)(nil).GetMetrics))\n}", "func testMetrics(expected map[string]int, m *Metrics) error {\n\te := &firstErr{}\n\tfor name, cnt := range expected {\n\t\tswitch name {\n\t\tcase \"incoming\":\n\t\t\te.testCounter(m.Incoming, name, cnt)\n\t\tcase \"fragments\":\n\t\t\te.testCounter(m.Fragments, name, cnt)\n\t\tcase \"defrag\":\n\t\t\te.testCounter(m.Defrag, name, cnt)\n\t\tcase \"invalid\":\n\t\t\te.testCounter(m.Invalid, name, cnt)\n\t\tcase \"seen:udp\":\n\t\t\te.testCounter(m.Seen.WithLabelValues(\"udp\"), name, cnt)\n\t\tcase \"seen:tcp\":\n\t\t\te.testCounter(m.Seen.WithLabelValues(\"tcp\"), name, cnt)\n\t\tcase \"captured:udp\":\n\t\t\te.testCounter(m.Captured.WithLabelValues(\"udp\"), name, cnt)\n\t\tcase \"captured:tcp\":\n\t\t\te.testCounter(m.Captured.WithLabelValues(\"tcp\"), name, cnt)\n\t\tdefault:\n\t\t\te.err = fmt.Errorf(\"don't know field %v\", name)\n\t\t}\n\t}\n\treturn e.err\n}", "func (_e *MockDataCoord_Expecter) GetMetrics(ctx interface{}, req interface{}) *MockDataCoord_GetMetrics_Call {\n\treturn &MockDataCoord_GetMetrics_Call{Call: _e.mock.On(\"GetMetrics\", ctx, req)}\n}", "func (_e *MockQueryCoord_Expecter) GetMetrics(ctx interface{}, req interface{}) *MockQueryCoord_GetMetrics_Call {\n\treturn &MockQueryCoord_GetMetrics_Call{Call: _e.mock.On(\"GetMetrics\", ctx, req)}\n}", "func (o *MonitorSearchResult) GetMetricsOk() (*[]string, bool) {\n\tif o == nil || o.Metrics == nil {\n\t\treturn nil, false\n\t}\n\treturn &o.Metrics, true\n}", "func (o *MetricsAllOf) GetMetricsOk() (*[]Metric, bool) {\n\tif o == nil || o.Metrics == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Metrics, true\n}", "func TestGetMetrics(t *testing.T) {\n\n\t//\t\tCreating mock request with custom params\n\t//\t\tand checking for error\n\trequest, err := http.NewRequest(\"GET\", \"/fizzbuzz-metrics\", nil)\n\tif err != nil {\n\t\tt.Errorf(\"GetMetrics() failed because of bad request: %v\", err)\n\t}\n\n\t//\t\tCreating a HTTP recorder for the test\n\trecorder := httptest.NewRecorder()\n\n\t//\t\tHitting endpoint\n\trouter := httprouter.New()\n\trouter.GET(\"/fizzbuzz-metrics\", GetMetrics)\n\trouter.ServeHTTP(recorder, request)\n\n\t//\t\tCheck status code\n\tif recorder.Code != http.StatusOK {\n\t\tt.Errorf(\"GetMetrics() failed because of status code: got %v instead of %v\", recorder.Code, http.StatusOK)\n\t}\n\n\t//\t\tCheck body\n\tgot := recorder.Body.String()\n\tif got == \"\" {\n\t\tt.Error(\"GetMetrics() failed because of empty body.\")\n\t}\n}", "func TestGetMetrics(t *testing.T) {\n\t// set up test server and mocked LogStore\n\tmockLogStore := new(MockedLogStore)\n\tserver := newTestServer(mockLogStore)\n\ttestServer := httptest.NewServer(server.server.Handler)\n\tdefer testServer.Close()\n\tclient := testServer.Client()\n\n\t// Make a first call to a resource to make metrics middleware record some\n\t// stats. Prior to that, no stats will have been saved.\n\tresp, _ := client.Get(testServer.URL + \"/metrics\")\n\trequire.Equalf(t, http.StatusOK, resp.StatusCode, \"unexpected status code\")\n\trequire.Equalf(t, \"\", readBody(t, resp), \"expected first /metrics call to be empty\")\n\n\tresp, _ = client.Get(testServer.URL + \"/metrics\")\n\trequire.Equalf(t, http.StatusOK, resp.StatusCode, \"unexpected status code\")\n\trequire.Containsf(t, readBody(t, resp), `total_requests{method=\"GET\",path=\"/metrics\",statusCode=\"200\"} 1`, \"missing expected metric\")\n}", "func Test_CollectMetrics10(t *testing.T) {\n\tassert := assert.New(t)\n\tconfig := getTestConfig(1, 0)\n\tconfig.DataFunc = config.GetTestData1\n\n\tres := config.CollectMetrics()\n\tassert.Nil(res)\n}", "func (o *DeviceMetricsAllOf) GetMetricsOk() (*[]DeviceMetric, bool) {\n\tif o == nil || o.Metrics == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Metrics, true\n}", "func Test_CollectMetrics21(t *testing.T) {\n\tassert := assert.New(t)\n\tconfig := getTestConfig(2, 1)\n\tconfig.DataFunc = config.GetTestData1\n\n\tres := config.CollectMetrics()\n\tfmt.Println(\"21: \", res)\n\tfmt.Println(\"21: \", []cmd.MetricData{{Name: \"m1\", Help: \"h1\", MetricType: \"gauge\", Stats: []cmd.MetricRecord{{Value: 999, Labels: []string{\"l00\"}, LabelValues: []string{\"lv00\"}}}}, {Name: \"m2\", Help: \"h2\", MetricType: \"gauge\", Stats: []cmd.MetricRecord{{Value: 999, Labels: []string{\"l10\"}, LabelValues: []string{\"lv10\"}}}}})\n\tassert.Equal(true, cmp.Equal(res, []cmd.MetricData{{Name: \"m1\", Help: \"h1\", MetricType: \"gauge\", Stats: []cmd.MetricRecord{{Value: 999, Labels: []string{\"l00\"}, LabelValues: []string{\"lv00\"}}}}, {Name: \"m2\", Help: \"h2\", MetricType: \"gauge\", Stats: []cmd.MetricRecord{{Value: 999, Labels: []string{\"l10\"}, LabelValues: []string{\"lv10\"}}}}}))\n}", "func Test_CollectMetrics01(t *testing.T) {\n\tassert := assert.New(t)\n\tconfig := getTestConfig(0, 1)\n\tconfig.DataFunc = config.GetTestData1\n\n\tres := config.CollectMetrics()\n\tassert.Nil(res)\n}", "func TestMetrics(t *testing.T) {\n\tctx := context.Background()\n\tvar err error\n\n\t// Check metrics-server deployment is ready.\n\terr = checkReadyDeployment(ctx)\n\tif err != nil {\n\t\tt.Fatalf(\"could not get metrics: %v\", err)\n\t}\n\n\t// Check metrics availability.\n\terr = checkMetricsAvailability(ctx)\n\tif err != nil {\n\t\tt.Fatalf(\"could not get metrics: %v\", err)\n\t}\n}", "func Test_CollectMetrics12(t *testing.T) {\n\tassert := assert.New(t)\n\tconfig := getTestConfig(1, 2)\n\tconfig.DataFunc = config.GetTestData1\n\n\tres := config.CollectMetrics()\n\tfmt.Println(\"12: \", res)\n\tfmt.Println(\"12: \", []cmd.MetricData{{Name: \"m1\", Help: \"h1\", MetricType: \"gauge\", Stats: []cmd.MetricRecord{{Value: 999, Labels: []string{\"l01\"}, LabelValues: []string{\"lv01\"}}, {Value: 999, Labels: []string{\"l00\"}, LabelValues: []string{\"lv00\"}}}}})\n\tassert.Equal(true, cmp.Equal(res, []cmd.MetricData{{Name: \"m1\", Help: \"h1\", MetricType: \"gauge\", Stats: []cmd.MetricRecord{{Value: 999, Labels: []string{\"l01\"}, LabelValues: []string{\"lv01\"}}, {Value: 999, Labels: []string{\"l00\"}, LabelValues: []string{\"lv00\"}}}}}))\n}", "func Test_CollectMetrics11(t *testing.T) {\n\tassert := assert.New(t)\n\tconfig := getTestConfig(1, 1)\n\tconfig.DataFunc = config.GetTestData1\n\n\tres := config.CollectMetrics()\n\t// assert.Nil(res)\n\tassert.Equal(res, []cmd.MetricData{{Name: \"m1\", Help: \"h1\", MetricType: \"gauge\", Stats: []cmd.MetricRecord{{Value: 999, Labels: []string{\"l00\"}, LabelValues: []string{\"lv00\"}}}}})\n}", "func (mr *MockFlowAggregatorQuerierMockRecorder) GetRecordMetrics() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetRecordMetrics\", reflect.TypeOf((*MockFlowAggregatorQuerier)(nil).GetRecordMetrics))\n}", "func (mr *MockKairosDBClientMockRecorder) QueryMetrics(ctx, dsInfo, request interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"QueryMetrics\", reflect.TypeOf((*MockKairosDBClient)(nil).QueryMetrics), ctx, dsInfo, request)\n}", "func LoadExpectedMetrics(t *testing.T, model string) []string {\n\tt.Helper()\n\tdcgmNameToMetricNameMap := map[string]string{\n\t\t\"DCGM_FI_DEV_GPU_UTIL\": \"dcgm.gpu.utilization\",\n\t\t\"DCGM_FI_DEV_FB_USED\": \"dcgm.gpu.memory.bytes_used\",\n\t\t\"DCGM_FI_DEV_FB_FREE\": \"dcgm.gpu.memory.bytes_free\",\n\t\t\"DCGM_FI_PROF_SM_ACTIVE\": \"dcgm.gpu.profiling.sm_utilization\",\n\t\t\"DCGM_FI_PROF_SM_OCCUPANCY\": \"dcgm.gpu.profiling.sm_occupancy\",\n\t\t\"DCGM_FI_PROF_PIPE_TENSOR_ACTIVE\": \"dcgm.gpu.profiling.tensor_utilization\",\n\t\t\"DCGM_FI_PROF_DRAM_ACTIVE\": \"dcgm.gpu.profiling.dram_utilization\",\n\t\t\"DCGM_FI_PROF_PIPE_FP64_ACTIVE\": \"dcgm.gpu.profiling.fp64_utilization\",\n\t\t\"DCGM_FI_PROF_PIPE_FP32_ACTIVE\": \"dcgm.gpu.profiling.fp32_utilization\",\n\t\t\"DCGM_FI_PROF_PIPE_FP16_ACTIVE\": \"dcgm.gpu.profiling.fp16_utilization\",\n\t\t\"DCGM_FI_PROF_PCIE_TX_BYTES\": \"dcgm.gpu.profiling.pcie_sent_bytes\",\n\t\t\"DCGM_FI_PROF_PCIE_RX_BYTES\": \"dcgm.gpu.profiling.pcie_received_bytes\",\n\t\t\"DCGM_FI_PROF_NVLINK_TX_BYTES\": \"dcgm.gpu.profiling.nvlink_sent_bytes\",\n\t\t\"DCGM_FI_PROF_NVLINK_RX_BYTES\": \"dcgm.gpu.profiling.nvlink_received_bytes\",\n\t}\n\tgoldenPath := getModelGoldenFilePath(t, model)\n\tgoldenFile, err := ioutil.ReadFile(goldenPath)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tvar m modelSupportedFields\n\terr = yaml.Unmarshal(goldenFile, &m)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tvar expectedMetrics []string\n\tfor _, supported := range m.SupportedFields {\n\t\texpectedMetrics = append(expectedMetrics, dcgmNameToMetricNameMap[supported])\n\t}\n\treturn expectedMetrics\n}", "func (m *MockTaskManager) GetMetrics() handler.Metric {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetMetrics\")\n\tret0, _ := ret[0].(handler.Metric)\n\treturn ret0\n}", "func TestMssql_GetMetrics_ItemDoesntExist_Successful(t *testing.T) {\n\n\tif runtime.GOOS != \"windows\" {\n\t\tt.Skip(\"Skipping MSSQL tests: Not on Windows\")\n\t}\n\n\t//\tArrange\n\tdb := getMSSQLDBConnection()\n\tt.Logf(\"Using - server: %v / database: %v / user: %v / password: %v\", db.Server, db.Database, db.User, db.Password)\n\n\t//\tAct\n\tresponse, err := db.GetMetrics()\n\n\t//\tAssert\n\tif err != nil {\n\t\tt.Errorf(\"GetMetrics failed: %v\", err)\n\t}\n\n\tfor _, nlogItem := range response {\n\t\tlog.Printf(\"[DEBUG] NLogItem found: %v %v %v\", nlogItem.Application, nlogItem.LogLevel, nlogItem.Count)\n\t}\n}", "func (o *EnvironmentUsageDto) GetCustomMetricsOk() (*[]CustomMetricDto, bool) {\n\tif o == nil || o.CustomMetrics == nil {\n\t\treturn nil, false\n\t}\n\treturn o.CustomMetrics, true\n}", "func TestMetrics(t *testing.T) {\n\t// Notes that ReadPairsExamined, ReadPairDups, and\n\t// ReadPairOpticalDups below are doubled because they are halved\n\t// when written to the metrics file.\n\ttests := []struct {\n\t\trecords []*sam.Record\n\t\tmetrics *MetricsCollection\n\t}{\n\t\t{\n\t\t\t[]*sam.Record{\n\t\t\t\tNewRecord(\"A:::1:10:1:1\", chr1, 0, r1F, 10, chr1, cigar0),\n\t\t\t\tNewRecord(\"A:::1:10:1:1\", chr1, 10, r2R, 0, chr1, cigar0),\n\t\t\t},\n\t\t\t&MetricsCollection{\n\t\t\t\tLibraryMetrics: map[string]*Metrics{\n\t\t\t\t\t\"Unknown Library\": &Metrics{\n\t\t\t\t\t\tUnpairedReads: 0,\n\t\t\t\t\t\tReadPairsExamined: 2,\n\t\t\t\t\t\tSecondarySupplementary: 0,\n\t\t\t\t\t\tUnmappedReads: 0,\n\t\t\t\t\t\tUnpairedDups: 0,\n\t\t\t\t\t\tReadPairDups: 0,\n\t\t\t\t\t\tReadPairOpticalDups: 0,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t[]*sam.Record{\n\t\t\t\tNewRecord(\"A:::1:10:1:1\", chr1, 0, r1F, 10, chr1, cigar0),\n\t\t\t\tNewRecord(\"B:::2:10:1:1\", chr1, 0, r1F, 10, chr1, cigar0),\n\t\t\t\tNewRecord(\"A:::1:10:1:1\", chr1, 10, r2R, 0, chr1, cigar0),\n\t\t\t\tNewRecord(\"B:::2:10:1:1\", chr1, 10, r2R, 0, chr1, cigar0),\n\t\t\t},\n\t\t\t&MetricsCollection{\n\t\t\t\tLibraryMetrics: map[string]*Metrics{\n\t\t\t\t\t\"Unknown Library\": &Metrics{\n\t\t\t\t\t\tUnpairedReads: 0,\n\t\t\t\t\t\tReadPairsExamined: 4,\n\t\t\t\t\t\tSecondarySupplementary: 0,\n\t\t\t\t\t\tUnmappedReads: 0,\n\t\t\t\t\t\tUnpairedDups: 0,\n\t\t\t\t\t\tReadPairDups: 2,\n\t\t\t\t\t\tReadPairOpticalDups: 0,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t[]*sam.Record{\n\t\t\t\tNewRecord(\"A:::1:10:1:1\", chr1, 0, r1F, 10, chr1, cigar0),\n\t\t\t\tNewRecord(\"B:::2:11:1:1\", chr1, 0, r1F, 10, chr1, cigar0),\n\t\t\t\tNewRecord(\"C:::2:11:1:1\", chr1, 0, r1F, 10, chr1, cigar0),\n\t\t\t\tNewRecord(\"A:::1:10:1:1\", chr1, 10, r2R, 0, chr1, cigar0),\n\t\t\t\tNewRecord(\"B:::2:11:1:1\", chr1, 10, r2R, 0, chr1, cigar0),\n\t\t\t\tNewRecord(\"C:::2:11:1:1\", chr1, 10, r2R, 0, chr1, cigar0),\n\t\t\t},\n\t\t\t&MetricsCollection{\n\t\t\t\tLibraryMetrics: map[string]*Metrics{\n\t\t\t\t\t\"Unknown Library\": &Metrics{\n\t\t\t\t\t\tUnpairedReads: 0,\n\t\t\t\t\t\tReadPairsExamined: 6,\n\t\t\t\t\t\tSecondarySupplementary: 0,\n\t\t\t\t\t\tUnmappedReads: 0,\n\t\t\t\t\t\tUnpairedDups: 0,\n\t\t\t\t\t\tReadPairDups: 4,\n\t\t\t\t\t\tReadPairOpticalDups: 2,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t[]*sam.Record{\n\t\t\t\tNewRecord(\"A:::1:10:1:1\", chr1, 0, s1F, 0, nil, cigar0),\n\t\t\t\tNewRecord(\"A:::1:10:1:1\", chr1, 0, u2, 0, nil, cigar0),\n\t\t\t\tNewRecord(\"B:::2:10:1:1\", chr1, 0, s1F, 0, nil, cigar0),\n\t\t\t\tNewRecord(\"B:::2:10:1:1\", chr1, 0, u2, 0, nil, cigar0),\n\t\t\t},\n\t\t\t&MetricsCollection{\n\t\t\t\tLibraryMetrics: map[string]*Metrics{\n\t\t\t\t\t\"Unknown Library\": &Metrics{\n\t\t\t\t\t\tUnpairedReads: 2,\n\t\t\t\t\t\tReadPairsExamined: 0,\n\t\t\t\t\t\tSecondarySupplementary: 0,\n\t\t\t\t\t\tUnmappedReads: 2,\n\t\t\t\t\t\tUnpairedDups: 1,\n\t\t\t\t\t\tReadPairDups: 0,\n\t\t\t\t\t\tReadPairOpticalDups: 0,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t// Cross-shard pairs\n\t\t\t[]*sam.Record{\n\t\t\t\tNewRecord(\"A:::1:10:1:1\", chr1, 0, r1F, 105, chr1, cigar0),\n\t\t\t\tNewRecord(\"B:::1:10:1:1\", chr1, 0, r1F, 105, chr1, cigar0),\n\t\t\t\tNewRecord(\"A:::1:10:1:1\", chr1, 105, r2R, 0, chr1, cigar0),\n\t\t\t\tNewRecord(\"B:::1:10:1:1\", chr1, 105, r2R, 0, chr1, cigar0),\n\t\t\t},\n\t\t\t&MetricsCollection{\n\t\t\t\tLibraryMetrics: map[string]*Metrics{\n\t\t\t\t\t\"Unknown Library\": &Metrics{\n\t\t\t\t\t\tUnpairedReads: 0,\n\t\t\t\t\t\tReadPairsExamined: 4,\n\t\t\t\t\t\tSecondarySupplementary: 0,\n\t\t\t\t\t\tUnmappedReads: 0,\n\t\t\t\t\t\tUnpairedDups: 0,\n\t\t\t\t\t\tReadPairDups: 2,\n\t\t\t\t\t\tReadPairOpticalDups: 2,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t// Secondary alignments.\n\t\t\t[]*sam.Record{\n\t\t\t\tNewRecord(\"A:::1:10:1:1\", chr1, 0, r1F, 105, chr1, cigar0),\n\t\t\t\tNewRecord(\"A:::1:10:1:1\", chr1, 105, r2R, 0, chr1, cigar0),\n\t\t\t\tNewRecord(\"A:::1:10:1:1\", chr2, 12, sec, 105, chr1, cigar0),\n\t\t\t},\n\t\t\t&MetricsCollection{\n\t\t\t\tLibraryMetrics: map[string]*Metrics{\n\t\t\t\t\t\"Unknown Library\": &Metrics{\n\t\t\t\t\t\tUnpairedReads: 0,\n\t\t\t\t\t\tReadPairsExamined: 2,\n\t\t\t\t\t\tSecondarySupplementary: 1,\n\t\t\t\t\t\tUnmappedReads: 0,\n\t\t\t\t\t\tUnpairedDups: 0,\n\t\t\t\t\t\tReadPairDups: 0,\n\t\t\t\t\t\tReadPairOpticalDups: 0,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t// Verify that we're counting dual-unmapped pairs\n\t\t\t[]*sam.Record{\n\t\t\t\tNewRecord(\"A:::1:10:1:1\", chr1, 0, r1F, 105, chr1, cigar0),\n\t\t\t\tNewRecord(\"A:::1:10:1:1\", chr1, 105, r2R, 0, chr1, cigar0),\n\t\t\t\tNewRecord(\"U:::2:11:1:1\", nil, -1, up1, -1, nil, cigar0),\n\t\t\t\tNewRecord(\"U:::2:11:1:1\", nil, -1, up2, -1, nil, cigar0),\n\t\t\t},\n\t\t\t&MetricsCollection{\n\t\t\t\tLibraryMetrics: map[string]*Metrics{\n\t\t\t\t\t\"Unknown Library\": &Metrics{\n\t\t\t\t\t\tUnpairedReads: 0,\n\t\t\t\t\t\tReadPairsExamined: 2,\n\t\t\t\t\t\tSecondarySupplementary: 0,\n\t\t\t\t\t\tUnmappedReads: 2,\n\t\t\t\t\t\tUnpairedDups: 0,\n\t\t\t\t\t\tReadPairDups: 0,\n\t\t\t\t\t\tReadPairOpticalDups: 0,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\ttempDir, cleanup := testutil.TempDir(t, \"\", \"\")\n\tdefer cleanup()\n\tfor testIdx, test := range tests {\n\t\tfor _, tagDups := range []bool{true, false} {\n\t\t\tfor _, format := range []string{\"bam\", \"pam\"} {\n\t\t\t\tt.Logf(\"---- starting tests[%d, %v] ----\", testIdx, tagDups)\n\t\t\t\tprovider := bamprovider.NewFakeProvider(header, test.records)\n\t\t\t\toutputPath := NewTestOutput(tempDir, testIdx, format)\n\t\t\t\topts := Opts{\n\t\t\t\t\tShardSize: 100,\n\t\t\t\t\tPadding: 10,\n\t\t\t\t\tParallelism: 1,\n\t\t\t\t\tQueueLength: 10,\n\t\t\t\t\tClearExisting: false,\n\t\t\t\t\tRemoveDups: false,\n\t\t\t\t\tTagDups: tagDups,\n\t\t\t\t\tEmitUnmodifiedFields: true,\n\t\t\t\t\tOutputPath: outputPath,\n\t\t\t\t\tFormat: format,\n\t\t\t\t\tOpticalDetector: &TileOpticalDetector{\n\t\t\t\t\t\tOpticalDistance: 2500,\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t\tmarkDuplicates := &MarkDuplicates{\n\t\t\t\t\tProvider: provider,\n\t\t\t\t\tOpts: &opts,\n\t\t\t\t}\n\t\t\t\tactualMetrics, err := markDuplicates.Mark(nil)\n\t\t\t\tassert.NoError(t, err)\n\n\t\t\t\tfor i, r := range ReadRecords(t, outputPath) {\n\t\t\t\t\tt.Logf(\"output[%v]: %v\", i, r)\n\t\t\t\t}\n\t\t\t\tassert.Equal(t, len(test.metrics.LibraryMetrics), len(actualMetrics.LibraryMetrics))\n\t\t\t\tfor k, m := range actualMetrics.LibraryMetrics {\n\t\t\t\t\tassert.Equal(t, *(test.metrics.LibraryMetrics[k]), *m)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func ExpectMetrics(t Validator, mt *metricTable, expect []WantMetric) {\n\tif len(mt.metrics) != len(expect) {\n\t\tt.Error(\"metric counts do not match expectations\", len(mt.metrics), len(expect))\n\t}\n\texpectedIds := make(map[metricID]struct{})\n\tfor _, e := range expect {\n\t\tid := metricID{Name: e.Name, Scope: e.Scope}\n\t\texpectedIds[id] = struct{}{}\n\t\tm := mt.metrics[id]\n\t\tif nil == m {\n\t\t\tt.Error(\"unable to find metric\", id)\n\t\t\tcontinue\n\t\t}\n\n\t\tif e.Forced != (forced == m.forced) {\n\t\t\tt.Error(\"metric forced incorrect\", e.Forced, m.forced, id)\n\t\t}\n\n\t\tif nil != e.Data {\n\t\t\texpectMetricField(t, id, e.Data[0], m.data.countSatisfied, \"countSatisfied\")\n\t\t\texpectMetricField(t, id, e.Data[1], m.data.totalTolerated, \"totalTolerated\")\n\t\t\texpectMetricField(t, id, e.Data[2], m.data.exclusiveFailed, \"exclusiveFailed\")\n\t\t\texpectMetricField(t, id, e.Data[3], m.data.min, \"min\")\n\t\t\texpectMetricField(t, id, e.Data[4], m.data.max, \"max\")\n\t\t\texpectMetricField(t, id, e.Data[5], m.data.sumSquares, \"sumSquares\")\n\t\t}\n\t}\n\tfor id := range mt.metrics {\n\t\tif _, ok := expectedIds[id]; !ok {\n\t\t\tt.Error(\"expected metrics does not contain\", id.Name, id.Scope)\n\t\t}\n\t}\n}", "func callMetrics(metricsAPI *metricsAPI, clock func() time.Time, timingMetrics bool) callrules.Rule {\n\ttimed := metricsAPI.callLatency\n\tif !timingMetrics {\n\t\ttimed = nil\n\t}\n\tharness := xmetrics.NewHarness(metricsAPI.callCount, metricsAPI.callErrorCount, timed, clock)\n\treturn callrules.Metrics(harness, nil)\n}", "func MockMetrics() []telegraf.Metric {\n\tmetrics := make([]telegraf.Metric, 0)\n\t// Create a new point batch\n\tmetrics = append(metrics, TestMetric(1.0))\n\treturn metrics\n}", "func (o *MonitorSearchResult) GetMetrics() []string {\n\tif o == nil || o.Metrics == nil {\n\t\tvar ret []string\n\t\treturn ret\n\t}\n\treturn o.Metrics\n}", "func (*SummaryMetric) IsMetric() {}", "func (c *standardComputation) GetMetrics() []string {\n\treturn c.fields\n}", "func (o *MonitorSearchResult) HasMetrics() bool {\n\tif o != nil && o.Metrics != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func TestCollectorOK(t *testing.T) {\n\tc := collector.New()\n\tctx := context.Background()\n\tmpa := NewStubMeterPoints(\"a\", 0, 100*time.Millisecond)\n\tmpb := NewStubMeterPoints(\"b\", 5, 200*time.Millisecond)\n\tmpc := NewStubMeterPoints(\"c\", 10, 50*time.Millisecond)\n\terr := c.Register(mpa, mpb, mpc)\n\tif err != nil {\n\t\tt.Errorf(\"collector register error: %v\", err)\n\t}\n\tmetrics := c.Retrieve(ctx, time.Second)\n\tif a, ok := metrics.Get(\"a.count\"); !ok || a != \"1\" {\n\t\tt.Errorf(\"illegal value a: %q\", a)\n\t}\n\tmetrics = c.Retrieve(ctx, time.Second)\n\tif b, ok := metrics.Get(\"b.count\"); !ok || b != \"7\" {\n\t\tt.Errorf(\"illegal value b: %q\", b)\n\t}\n\tmetrics = c.Retrieve(ctx, time.Second)\n\tif c, ok := metrics.Get(\"c.count\"); !ok || c != \"13\" {\n\t\tt.Errorf(\"illegal value c: %q\", c)\n\t}\n}", "func validateMetrics(m *Metrics) error {\n\tif !m.initialized {\n\t\treturn errors.New(\"Metrics struct is not initialized\")\n\t}\n\n\treturn nil\n}", "func mustGetClientMetrics() *grpc_prometheus.ClientMetrics {\n\tclientMetricsOnce.Do(func() {\n\t\tclientMetrics = grpc_prometheus.NewRegisteredClientMetrics(prometheus.DefaultRegisterer,\n\t\t\tgrpc_prometheus.WithClientCounterOptions(setCounterNamespace),\n\t\t\tgrpc_prometheus.WithClientHandlingTimeHistogram(setHistogramNamespace), // record the overall request latency for a gRPC request\n\t\t\tgrpc_prometheus.WithClientStreamRecvHistogram(setHistogramNamespace), // record how long it takes for a client to receive a message during a streaming RPC\n\t\t\tgrpc_prometheus.WithClientStreamSendHistogram(setHistogramNamespace), // record how long it takes for a client to send a message during a streaming RPC\n\t\t)\n\t})\n\n\treturn clientMetrics\n}", "func (mr *MockContextMockRecorder) GetMetricsClient() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetMetricsClient\", reflect.TypeOf((*MockContext)(nil).GetMetricsClient))\n}", "func MockMetrics() []optic.Metric {\n\tmetricsEvents := make([]optic.Metric, 0)\n\tmetricsEvents = append(metricsEvents, TestMetric(1.0))\n\treturn metricsEvents\n}", "func (*SimpleMetric) IsMetric() {}", "func TestPrometheusMetrics(t *testing.T) {\n\tbytesProcessedMetric.WithLabelValues(\"x\")\n\tcacheHitMetric.WithLabelValues(\"x\")\n\tuploadedBytesMetric.WithLabelValues(\"x\")\n\tqueryTotalMetric.WithLabelValues(\"x\")\n\tqueryProcessedMetric.WithLabelValues(\"x\")\n\tinFlightUploadsHistogram.WithLabelValues(\"x\")\n\tuploadQueueSizeHistogram.WithLabelValues(\"x\")\n\n\tpromtest.LintMetrics(t)\n}", "func validateMetrics(desc *otlp.MetricDescriptor) bool {\n\n\tif desc == nil {\n\t\treturn false\n\t}\n\n\tswitch desc.GetType() {\n\tcase otlp.MetricDescriptor_MONOTONIC_DOUBLE, otlp.MetricDescriptor_MONOTONIC_INT64,\n\t\totlp.MetricDescriptor_HISTOGRAM, otlp.MetricDescriptor_SUMMARY:\n\t\treturn desc.GetTemporality() == otlp.MetricDescriptor_CUMULATIVE\n\tcase otlp.MetricDescriptor_INT64, otlp.MetricDescriptor_DOUBLE:\n\t\treturn true\n\t}\n\n\treturn false\n}", "func TestMetrics(t *testing.T) {\n\tmetrics, err := NewMetrics()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tmetrics.Send(&influxdb.Series{\n\t\tName: \"testing\",\n\t\tColumns: []string{\n\t\t\t\"foo\",\n\t\t},\n\t\tPoints: [][]interface{}{\n\t\t\t{\n\t\t\t\t\"bar\",\n\t\t\t},\n\t\t},\n\t})\n}", "func (ds *dockServer) GetMetrics(context.Context, *pb.GetMetricsOpts) (*pb.GenericResponse, error) {\n\treturn nil, &model.NotImplementError{\"method GetMetrics has not been implemented yet\"}\n}", "func (e Entry) GetMetrics(timeout time.Duration, h heimdall.Doer, debug bool) (Metrics, error) {\n\tvar m Metrics\n\n\t// Let's set the stuff we know already.\n\tm.Address = e.Address\n\tm.Regexp = e.Regexp\n\tm.CapturedAt = time.Now().UTC()\n\n\t// Set a timeout.\n\tctx, cancel := context.WithTimeout(context.Background(), timeout)\n\tdefer cancel()\n\n\t// Setup the request.\n\treq, err := http.NewRequestWithContext(ctx, http.MethodGet, e.Address, nil)\n\tif err != nil {\n\t\treturn m, err\n\t}\n\n\tif debug {\n\t\tfmt.Printf(\"%#v\\n\", req)\n\t}\n\n\t// Let's do the request.\n\tstart := time.Now()\n\tres, err := h.Do(req)\n\tif err != nil {\n\t\treturn m, err\n\t}\n\n\t// We don't need the body unless we've got a regexp.\n\tif e.Regexp != \"\" {\n\t\tbody, err := ioutil.ReadAll(res.Body)\n\t\tif err != nil {\n\t\t\treturn m, err\n\t\t}\n\t\t// Do the regexp here and assign the value.\n\t\tmatch, _ := regexp.MatchString(e.Regexp, string(body))\n\t\tm.RegexpStatus = match\n\t}\n\ttook := time.Since(start)\n\n\t// Set the last few values\n\tm.StatusCode = res.StatusCode\n\tm.ResponseTime = took\n\n\tif debug {\n\t\tfmt.Printf(\"Result: %#v\\n\", res)\n\t\tfmt.Printf(\"Time Taken: %s\\n\", took)\n\t\tfmt.Printf(\"Metrics: %#v\\n\", m)\n\t}\n\n\tif ctx.Err() != nil {\n\t\treturn m, errors.New(\"context deadline exceeded\")\n\t}\n\treturn m, nil\n}", "func mustGetServerMetrics() *grpc_prometheus.ServerMetrics {\n\tserverMetricsOnce.Do(func() {\n\t\tserverMetrics = grpc_prometheus.NewRegisteredServerMetrics(prometheus.DefaultRegisterer,\n\t\t\tgrpc_prometheus.WithServerCounterOptions(setCounterNamespace),\n\t\t\tgrpc_prometheus.WithServerHandlingTimeHistogram(setHistogramNamespace), // record the overall response latency for a gRPC request)\n\t\t)\n\t})\n\n\treturn serverMetrics\n}", "func (mr *MockMetricsMockRecorder) InitMetrics() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"InitMetrics\", reflect.TypeOf((*MockMetrics)(nil).InitMetrics))\n}", "func TestGetStats(t *testing.T) {\n\tstats, err := GetStats()\n\tif err != nil {\n\t\tt.Errorf(\"Tests: Expected `nil`, Got %s\", err)\n\t}\n\tif stats.TotalRAM == 0 {\n\t\tt.Errorf(\"Tests: Expected `n > 0`, Got %d\", stats.TotalRAM)\n\t}\n}", "func (m *GetMetricsResponse) Validate() error {\n\treturn m.validate(false)\n}", "func (c *Client) GetMetrics(ctx context.Context, req *milvuspb.GetMetricsRequest) (*milvuspb.GetMetricsResponse, error) {\n\treq = typeutil.Clone(req)\n\tcommonpbutil.UpdateMsgBase(\n\t\treq.GetBase(),\n\t\tcommonpbutil.FillMsgBaseFromClient(paramtable.GetNodeID()))\n\treturn wrapGrpcCall(ctx, c, func(client querypb.QueryNodeClient) (*milvuspb.GetMetricsResponse, error) {\n\t\treturn client.GetMetrics(ctx, req)\n\t})\n}", "func (*HistogramMetric) IsMetric() {}", "func (_m *MockStatusStoreIface) GetMetric() (map[string]float64, error) {\n\tret := _m.Called()\n\n\tvar r0 map[string]float64\n\tif rf, ok := ret.Get(0).(func() map[string]float64); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(map[string]float64)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func() error); ok {\n\t\tr1 = rf()\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (c *Client) GetMetrics(ctx context.Context, req *milvuspb.GetMetricsRequest) (*milvuspb.GetMetricsResponse, error) {\n\treq = typeutil.Clone(req)\n\tcommonpbutil.UpdateMsgBase(\n\t\treq.GetBase(),\n\t\tcommonpbutil.FillMsgBaseFromClient(paramtable.GetNodeID(), commonpbutil.WithTargetID(c.grpcClient.GetNodeID())),\n\t)\n\treturn wrapGrpcCall(ctx, c, func(client querypb.QueryCoordClient) (*milvuspb.GetMetricsResponse, error) {\n\t\treturn client.GetMetrics(ctx, req)\n\t})\n}", "func (o *EnvironmentUsageDto) HasCustomMetrics() bool {\n\tif o != nil && o.CustomMetrics != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (mr *MockConnectionTracerMockRecorder) UpdatedMetrics(arg0, arg1, arg2, arg3 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"UpdatedMetrics\", reflect.TypeOf((*MockConnectionTracer)(nil).UpdatedMetrics), arg0, arg1, arg2, arg3)\n}", "func (m *ActiveNodeMock) ValidateCallCounters() {\n\n\tif !m.GetDeclaredPowerFinished() {\n\t\tm.t.Fatal(\"Expected call to ActiveNodeMock.GetDeclaredPower\")\n\t}\n\n\tif !m.GetIndexFinished() {\n\t\tm.t.Fatal(\"Expected call to ActiveNodeMock.GetIndex\")\n\t}\n\n\tif !m.GetNodeIDFinished() {\n\t\tm.t.Fatal(\"Expected call to ActiveNodeMock.GetNodeID\")\n\t}\n\n\tif !m.GetOpModeFinished() {\n\t\tm.t.Fatal(\"Expected call to ActiveNodeMock.GetOpMode\")\n\t}\n\n\tif !m.GetSignatureVerifierFinished() {\n\t\tm.t.Fatal(\"Expected call to ActiveNodeMock.GetSignatureVerifier\")\n\t}\n\n\tif !m.GetStaticFinished() {\n\t\tm.t.Fatal(\"Expected call to ActiveNodeMock.GetStatic\")\n\t}\n\n\tif !m.IsJoinerFinished() {\n\t\tm.t.Fatal(\"Expected call to ActiveNodeMock.IsJoiner\")\n\t}\n\n}", "func getMetrics() []Metric {\n\tms := make([]Metric, 0)\n\treturn append(ms, &SimpleEapMetric{})\n}", "func (o *DeviceMetricsAllOf) HasMetrics() bool {\n\tif o != nil && o.Metrics != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (m *Metrics) Validate() error {\n\treturn m.validate(false)\n}", "func (s *Server) GetMetrics(ctx context.Context, req *milvuspb.GetMetricsRequest) (*milvuspb.GetMetricsResponse, error) {\n\treturn s.querynode.GetMetrics(ctx, req)\n}", "func TestMetricTooMany(t *testing.T) { //nolint:maintidx\n\thelper := newHelper(t)\n\tdefer helper.Close()\n\n\thelper.preregisterAgent(t)\n\thelper.initSynchronizer(t)\n\n\tmetricResource, _ := helper.api.resources[mockAPIResourceMetric].(*genericResource)\n\tdefaultPatchHook := metricResource.PatchHook\n\n\t// API always reject more than 3 active metrics\n\tmetricResource.PatchHook = func(r *http.Request, body []byte, valuePtr interface{}, oldValue interface{}) error {\n\t\tif defaultPatchHook != nil {\n\t\t\terr := defaultPatchHook(r, body, valuePtr, oldValue)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\tmetric, _ := valuePtr.(*metricPayload)\n\n\t\tif metric.DeactivatedAt.IsZero() {\n\t\t\tmetrics := helper.MetricsFromAPI()\n\t\t\tcountActive := 0\n\n\t\t\tfor _, m := range metrics {\n\t\t\t\tif m.DeactivatedAt.IsZero() && m.ID != metric.ID {\n\t\t\t\t\tcountActive++\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif countActive >= 3 {\n\t\t\t\treturn clientError{\n\t\t\t\t\tbody: `{\"label\":[\"Too many non standard metrics\"]}`,\n\t\t\t\t\tstatusCode: http.StatusBadRequest,\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn nil\n\t}\n\n\tmetricResource.CreateHook = func(r *http.Request, body []byte, valuePtr interface{}) error {\n\t\treturn metricResource.PatchHook(r, body, valuePtr, nil)\n\t}\n\n\thelper.AddTime(time.Minute)\n\thelper.pushPoints(t, []labels.Labels{\n\t\tlabels.New(\n\t\t\tlabels.Label{Name: types.LabelName, Value: \"metric1\"},\n\t\t),\n\t\tlabels.New(\n\t\t\tlabels.Label{Name: types.LabelName, Value: \"metric2\"},\n\t\t),\n\t})\n\n\tif err := helper.runOnceWithResult(t).CheckMethodWithFull(syncMethodMetric); err != nil {\n\t\tt.Error(err)\n\t}\n\n\t// list active metrics, register agent_status + 2x metrics to register\n\thelper.api.AssertCallPerResource(t, mockAPIResourceMetric, 6)\n\n\tmetrics := helper.MetricsFromAPI()\n\tif len(metrics) != 3 { // 2 + agent_status\n\t\tt.Errorf(\"len(metrics) = %d, want 3\", len(metrics))\n\t}\n\n\thelper.AddTime(5 * time.Minute)\n\thelper.pushPoints(t, []labels.Labels{\n\t\tlabels.New(\n\t\t\tlabels.Label{Name: types.LabelName, Value: \"metric3\"},\n\t\t),\n\t\tlabels.New(\n\t\t\tlabels.Label{Name: types.LabelName, Value: \"metric4\"},\n\t\t),\n\t})\n\n\tif err := helper.runOnceWithResult(t).CheckMethodWithoutFull(syncMethodMetric); err != nil {\n\t\tt.Error(err)\n\t}\n\n\tif helper.api.ClientErrorCount == 0 {\n\t\tt.Errorf(\"We should have some client error, had %d\", helper.api.ClientErrorCount)\n\t}\n\n\t// list active metrics + 2x metrics to register\n\thelper.api.AssertCallPerResource(t, mockAPIResourceMetric, 5)\n\n\tmetrics = helper.MetricsFromAPI()\n\tif len(metrics) != 3 { // 2 + agent_status\n\t\tt.Errorf(\"len(metrics) = %d, want 3\", len(metrics))\n\t}\n\n\thelper.AddTime(5 * time.Minute)\n\n\tif err := helper.runOnceWithResult(t).CheckMethodNotRun(syncMethodMetric); err != nil {\n\t\tt.Error(err)\n\t}\n\n\thelper.SetTimeToNextFullSync()\n\t// drop all because normally store drop inactive metrics and\n\t// metric1 don't emitted for 70 minutes\n\thelper.store.DropAllMetrics()\n\thelper.pushPoints(t, []labels.Labels{\n\t\tlabels.New(\n\t\t\tlabels.Label{Name: types.LabelName, Value: \"metric2\"},\n\t\t),\n\t\tlabels.New(\n\t\t\tlabels.Label{Name: types.LabelName, Value: \"metric3\"},\n\t\t),\n\t\tlabels.New(\n\t\t\tlabels.Label{Name: types.LabelName, Value: \"metric4\"},\n\t\t),\n\t})\n\n\tif err := helper.runOnceWithResult(t).CheckMethodWithFull(syncMethodMetric); err != nil {\n\t\tt.Error(err)\n\t}\n\n\t// We need two sync: one to deactivate the metric, one to regsiter another one\n\thelper.AddTime(15 * time.Second)\n\n\tif err := helper.runOnceWithResult(t).CheckMethodWithoutFull(syncMethodMetric); err != nil {\n\t\tt.Error(err)\n\t}\n\n\tmetrics = helper.MetricsFromAPI()\n\tif len(metrics) != 4 { // metric1 is now disabled, another get registered\n\t\tt.Errorf(\"len(metrics) = %d, want 4\", len(metrics))\n\t}\n\n\tfor _, m := range metrics {\n\t\tif !m.DeactivatedAt.IsZero() && m.Name != \"metric1\" {\n\t\t\tt.Errorf(\"metric %s is deactivated, want active\", m.Name)\n\t\t}\n\n\t\tif m.DeactivatedAt.IsZero() && m.Name == \"metric1\" {\n\t\t\tt.Errorf(\"metric %s is active, want deactivated\", m.Name)\n\t\t}\n\t}\n\n\thelper.AddTime(5 * time.Minute)\n\thelper.pushPoints(t, []labels.Labels{\n\t\tlabels.New(\n\t\t\tlabels.Label{Name: types.LabelName, Value: \"metric1\"},\n\t\t),\n\t})\n\n\tif err := helper.runOnceWithResult(t).CheckMethodWithoutFull(syncMethodMetric); err != nil {\n\t\tt.Error(err)\n\t}\n\n\tif helper.api.ClientErrorCount == 0 {\n\t\tt.Errorf(\"We should have some client error, had %d\", helper.api.ClientErrorCount)\n\t}\n\n\tmetrics = helper.MetricsFromAPI()\n\tif len(metrics) != 4 { // metric1 is still disabled and no newly registered\n\t\tt.Errorf(\"len(metrics) = %d, want 4\", len(metrics))\n\t}\n\n\tfor _, m := range metrics {\n\t\tif !m.DeactivatedAt.IsZero() && m.Name != \"metric1\" {\n\t\t\tt.Errorf(\"metric %s is deactivated, want active\", m.Name)\n\t\t}\n\n\t\tif m.DeactivatedAt.IsZero() && m.Name == \"metric1\" {\n\t\t\tt.Errorf(\"metric %s is active, want deactivated\", m.Name)\n\t\t}\n\t}\n\n\t// We do not retry to register them\n\thelper.AddTime(5 * time.Minute)\n\n\tif err := helper.runOnceWithResult(t).CheckMethodNotRun(syncMethodMetric); err != nil {\n\t\tt.Error(err)\n\t}\n\n\t// Excepted ONE per full-sync\n\thelper.SetTimeToNextFullSync()\n\thelper.pushPoints(t, []labels.Labels{\n\t\tlabels.New(\n\t\t\tlabels.Label{Name: types.LabelName, Value: \"metric2\"},\n\t\t),\n\t\tlabels.New(\n\t\t\tlabels.Label{Name: types.LabelName, Value: \"metric3\"},\n\t\t),\n\t\tlabels.New(\n\t\t\tlabels.Label{Name: types.LabelName, Value: \"metric4\"},\n\t\t),\n\t})\n\n\tif err := helper.runOnceWithResult(t).CheckMethodWithFull(syncMethodMetric); err != nil {\n\t\tt.Error(err)\n\t}\n\n\tif helper.api.ClientErrorCount != 1 {\n\t\tt.Errorf(\"had %d client error, want 1\", helper.api.ClientErrorCount)\n\t}\n\n\tmetrics = helper.MetricsFromAPI()\n\tif len(metrics) != 4 {\n\t\tt.Errorf(\"len(metrics) = %d, want 4\", len(metrics))\n\t}\n\n\tfor _, m := range metrics {\n\t\tif !m.DeactivatedAt.IsZero() && m.Name != \"metric1\" {\n\t\t\tt.Errorf(\"metric %s is deactivated, want active\", m.Name)\n\t\t}\n\n\t\tif m.DeactivatedAt.IsZero() && m.Name == \"metric1\" {\n\t\t\tt.Errorf(\"metric %s is active, want deactivated\", m.Name)\n\t\t}\n\t}\n\n\t// list active metrics + check existence of the metric we want to reg +\n\t// retry to register\n\thelper.api.AssertCallPerResource(t, mockAPIResourceMetric, 3)\n}", "func (o *MetricsAllOf) GetMetrics() []Metric {\n\tif o == nil || o.Metrics == nil {\n\t\tvar ret []Metric\n\t\treturn ret\n\t}\n\treturn *o.Metrics\n}", "func (mr *MockDataServiceServerMockRecorder) CalculateMetrics(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"CalculateMetrics\", reflect.TypeOf((*MockDataServiceServer)(nil).CalculateMetrics), arg0, arg1)\n}", "func (b *B) ReportMetric(n float64, unit string) {}", "func (mr *MockQueryerMockRecorder) GetSingleMetricsMeta(arg0, arg1, arg2, arg3 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetSingleMetricsMeta\", reflect.TypeOf((*MockQueryer)(nil).GetSingleMetricsMeta), arg0, arg1, arg2, arg3)\n}", "func (a *Client) GetMetrics(params *GetMetricsParams, opts ...ClientOption) (*GetMetricsOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewGetMetricsParams()\n\t}\n\top := &runtime.ClientOperation{\n\t\tID: \"GetMetrics\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/metrics/\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"http\"},\n\t\tParams: params,\n\t\tReader: &GetMetricsReader{formats: a.formats},\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t}\n\tfor _, opt := range opts {\n\t\topt(op)\n\t}\n\n\tresult, err := a.transport.Submit(op)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsuccess, ok := result.(*GetMetricsOK)\n\tif ok {\n\t\treturn success, nil\n\t}\n\t// unexpected success response\n\t// safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue\n\tmsg := fmt.Sprintf(\"unexpected success response for GetMetrics: API contract not enforced by server. Client expected to get an error, but got: %T\", result)\n\tpanic(msg)\n}", "func (c *PromMetricsClient) GetMetrics() ([]*Metric, error) {\n\tres, err := http.Get(c.URL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif res.StatusCode != 200 {\n\t\treturn nil, ErrUnexpectedHTTPStatusCode\n\t}\n\n\tdefer res.Body.Close()\n\treturn Parse(res.Body)\n}", "func (session *Session) PerformanceGetMetrics() ([]Metric, error) {\n\tmsg, err := session.blockingSend(\"Performance.getMetrics\", &Params{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tm := make([]Metric, 0)\n\tunmarshal(msg[\"metrics\"], &m)\n\treturn m, nil\n}", "func (m *GetMetricsRequest) Validate() error {\n\treturn m.validate(false)\n}", "func (mr *MockArgusdClientMockRecorder) RecordMetrics(arg0, arg1 interface{}, arg2 ...interface{}) *gomock.Call {\n\tvarargs := append([]interface{}{arg0, arg1}, arg2...)\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"RecordMetrics\", reflect.TypeOf((*MockArgusdClient)(nil).RecordMetrics), varargs...)\n}", "func (mr *MockIApiMockRecorder) MetricsRetrieveAll(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"MetricsRetrieveAll\", reflect.TypeOf((*MockIApi)(nil).MetricsRetrieveAll), arg0)\n}", "func (o *MetricsAllOf) HasMetrics() bool {\n\tif o != nil && o.Metrics != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (Metrics) MetricStruct() {}", "func (m *OutboundMock) ValidateCallCounters() {\n\n\tif !m.AsByteStringFinished() {\n\t\tm.t.Fatal(\"Expected call to OutboundMock.AsByteString\")\n\t}\n\n\tif !m.CanAcceptFinished() {\n\t\tm.t.Fatal(\"Expected call to OutboundMock.CanAccept\")\n\t}\n\n\tif !m.GetEndpointTypeFinished() {\n\t\tm.t.Fatal(\"Expected call to OutboundMock.GetEndpointType\")\n\t}\n\n\tif !m.GetIPAddressFinished() {\n\t\tm.t.Fatal(\"Expected call to OutboundMock.GetIPAddress\")\n\t}\n\n\tif !m.GetNameAddressFinished() {\n\t\tm.t.Fatal(\"Expected call to OutboundMock.GetNameAddress\")\n\t}\n\n\tif !m.GetRelayIDFinished() {\n\t\tm.t.Fatal(\"Expected call to OutboundMock.GetRelayID\")\n\t}\n\n}", "func (mr *MockIApiMockRecorder) MetricsRetrieveARR(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"MetricsRetrieveARR\", reflect.TypeOf((*MockIApi)(nil).MetricsRetrieveARR), arg0)\n}", "func (m *MockClient) GetMetrics() *metrics.ClientMetrics {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetMetrics\")\n\tret0, _ := ret[0].(*metrics.ClientMetrics)\n\treturn ret0\n}", "func (m *MetricsCacheType) GetMetrics() ([]string, bool) {\n\tif m.IsAvailable() && !m.TimedOut() {\n\t\treturn m.metrics, true\n\t}\n\n\tif !m.updating {\n\t\tgo m.RefreshCache()\n\t}\n\treturn nil, false\n}", "func (mr *MockIApiMockRecorder) MetricsRetrieveMRRChurnRate(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"MetricsRetrieveMRRChurnRate\", reflect.TypeOf((*MockIApi)(nil).MetricsRetrieveMRRChurnRate), arg0)\n}", "func TestMetricsEndpoint(t *testing.T) {\n\tc := newKubeClient(t)\n\n\tlistOptions := metav1.ListOptions{LabelSelector: \"app=olm-operator\"}\n\tpodList, err := c.KubernetesInterface().CoreV1().Pods(operatorNamespace).List(listOptions)\n\tif err != nil {\n\t\tlog.Infof(\"Error %v\\n\", err)\n\t\tt.Fatalf(\"Listing pods failed: %v\\n\", err)\n\t}\n\tif len(podList.Items) > 1 {\n\t\tt.Fatalf(\"Expected only 1 olm-operator pod, got %v\", len(podList.Items))\n\t}\n\n\tpodName := podList.Items[0].GetName()\n\n\trawOutput, err := getMetricsFromPod(t, c, podName, operatorNamespace, 8080)\n\tif err != nil {\n\t\tt.Fatalf(\"Metrics test failed: %v\\n\", err)\n\t}\n\n\tlog.Debugf(\"Metrics:\\n%v\", rawOutput)\n}", "func (mr *MockDataServiceClientMockRecorder) CalculateMetrics(ctx, in interface{}, opts ...interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\tvarargs := append([]interface{}{ctx, in}, opts...)\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"CalculateMetrics\", reflect.TypeOf((*MockDataServiceClient)(nil).CalculateMetrics), varargs...)\n}", "func GetMetrics() []prometheus.Collector {\n\treturn []prometheus.Collector{\n\t\treqCounter,\n\t\treqDuration,\n\t\tconnDuration,\n\t}\n}", "func (o *DeviceMetricsAllOf) GetMetrics() []DeviceMetric {\n\tif o == nil || o.Metrics == nil {\n\t\tvar ret []DeviceMetric\n\t\treturn ret\n\t}\n\treturn *o.Metrics\n}", "func (_m *MockDataCoord) GetMetrics(ctx context.Context, req *milvuspb.GetMetricsRequest) (*milvuspb.GetMetricsResponse, error) {\n\tret := _m.Called(ctx, req)\n\n\tvar r0 *milvuspb.GetMetricsResponse\n\tvar r1 error\n\tif rf, ok := ret.Get(0).(func(context.Context, *milvuspb.GetMetricsRequest) (*milvuspb.GetMetricsResponse, error)); ok {\n\t\treturn rf(ctx, req)\n\t}\n\tif rf, ok := ret.Get(0).(func(context.Context, *milvuspb.GetMetricsRequest) *milvuspb.GetMetricsResponse); ok {\n\t\tr0 = rf(ctx, req)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*milvuspb.GetMetricsResponse)\n\t\t}\n\t}\n\n\tif rf, ok := ret.Get(1).(func(context.Context, *milvuspb.GetMetricsRequest) error); ok {\n\t\tr1 = rf(ctx, req)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (mr *MockIApiMockRecorder) MetricsRetrieveMRR(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"MetricsRetrieveMRR\", reflect.TypeOf((*MockIApi)(nil).MetricsRetrieveMRR), arg0)\n}", "func (m Metrics) MetricStruct() {}", "func (_m *MockQueryCoord) GetMetrics(ctx context.Context, req *milvuspb.GetMetricsRequest) (*milvuspb.GetMetricsResponse, error) {\n\tret := _m.Called(ctx, req)\n\n\tvar r0 *milvuspb.GetMetricsResponse\n\tvar r1 error\n\tif rf, ok := ret.Get(0).(func(context.Context, *milvuspb.GetMetricsRequest) (*milvuspb.GetMetricsResponse, error)); ok {\n\t\treturn rf(ctx, req)\n\t}\n\tif rf, ok := ret.Get(0).(func(context.Context, *milvuspb.GetMetricsRequest) *milvuspb.GetMetricsResponse); ok {\n\t\tr0 = rf(ctx, req)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*milvuspb.GetMetricsResponse)\n\t\t}\n\t}\n\n\tif rf, ok := ret.Get(1).(func(context.Context, *milvuspb.GetMetricsRequest) error); ok {\n\t\tr1 = rf(ctx, req)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func metricEnabled() bool {\n\treturn enabled\n}", "func TestAssessRunStatusWithMixedMetrics(t *testing.T) {\n\tf := newFixture(t)\n\tdefer f.Close()\n\tc, _, _ := f.newController(noResyncPeriodFunc)\n\n\trun := v1alpha1.AnalysisRun{\n\t\tSpec: v1alpha1.AnalysisRunSpec{\n\t\t\tMetrics: []v1alpha1.Metric{\n\t\t\t\t{\n\t\t\t\t\tName: \"run-forever\",\n\t\t\t\t\tProvider: v1alpha1.MetricProvider{\n\t\t\t\t\t\tJob: &v1alpha1.JobMetric{},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tName: \"success-metric\",\n\t\t\t\t\tProvider: v1alpha1.MetricProvider{\n\t\t\t\t\t\tJob: &v1alpha1.JobMetric{},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tDryRun: []v1alpha1.DryRun{{\n\t\t\t\tMetricName: \"success-metric\",\n\t\t\t}},\n\t\t},\n\t\tStatus: v1alpha1.AnalysisRunStatus{\n\t\t\tMetricResults: []v1alpha1.MetricResult{\n\t\t\t\t{\n\t\t\t\t\tName: \"run-forever\",\n\t\t\t\t\tInconclusive: 1,\n\t\t\t\t\tDryRun: false,\n\t\t\t\t\tPhase: v1alpha1.AnalysisPhaseRunning,\n\t\t\t\t\tMeasurements: []v1alpha1.Measurement{{\n\t\t\t\t\t\tPhase: v1alpha1.AnalysisPhaseRunning,\n\t\t\t\t\t\tStartedAt: timePtr(metav1.NewTime(time.Now().Add(-60 * time.Second))),\n\t\t\t\t\t}},\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tName: \"success-metric\",\n\t\t\t\t\tCount: 1,\n\t\t\t\t\tFailed: 1,\n\t\t\t\t\tDryRun: true,\n\t\t\t\t\tPhase: v1alpha1.AnalysisPhaseSuccessful,\n\t\t\t\t\tMeasurements: []v1alpha1.Measurement{{\n\t\t\t\t\t\tPhase: v1alpha1.AnalysisPhaseFailed,\n\t\t\t\t\t\tStartedAt: timePtr(metav1.NewTime(time.Now().Add(-60 * time.Second))),\n\t\t\t\t\t\tFinishedAt: timePtr(metav1.NewTime(time.Now().Add(-60 * time.Second))),\n\t\t\t\t\t}},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\tf.provider.On(\"Run\", mock.Anything, mock.Anything, mock.Anything).Return(newMeasurement(v1alpha1.AnalysisPhaseFailed), nil)\n\tf.provider.On(\"Resume\", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(newMeasurement(v1alpha1.AnalysisPhaseSuccessful), nil)\n\n\tnewRun := c.reconcileAnalysisRun(&run)\n\tassert.Equal(t, v1alpha1.AnalysisPhaseInconclusive, newRun.Status.Phase)\n\tassert.Equal(t, \"Metric \\\"run-forever\\\" assessed Inconclusive due to inconclusive (1) > inconclusiveLimit (0)\", newRun.Status.Message)\n}", "func (h *testMetricsHandler) GetRawMetrics(apiClient kubernetes.Interface, namespace, functionName string) ([]byte, error) {\n\tsvc, err := apiClient.CoreV1().Services(namespace).Get(functionName, metav1.GetOptions{})\n\tif err != nil {\n\t\treturn []byte{}, err\n\t}\n\tb, err := http.Get(svc.SelfLink)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer b.Body.Close()\n\treturn ioutil.ReadAll(b.Body)\n}", "func (f ConsumeMetricsFunc) ConsumeMetrics(ctx context.Context, ld pdata.Metrics) error {\n\treturn f(ctx, ld)\n}", "func (mr *MockAPIMockRecorder) ReportValidationFailedMetrics(arg0, arg1, arg2, arg3 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"ReportValidationFailedMetrics\", reflect.TypeOf((*MockAPI)(nil).ReportValidationFailedMetrics), arg0, arg1, arg2, arg3)\n}", "func testCounterMetric(t *testing.T, reporter *Reporter, m *stats.Int64Measure) {\n\ttotalNumberOfOperations := 2\n\treporter.Report(m.M(1))\n\treporter.Report(m.M(1))\n\trow, err := view.RetrieveData(m.Name())\n\tif err != nil {\n\t\tt.Errorf(\"Error when retrieving data: %v from %v\", err, m.Name())\n\t}\n\n\tcount, ok := row[0].Data.(*view.CountData)\n\tif !ok {\n\t\tt.Error(\"ReportRequest should have aggregation Count()\")\n\t}\n\tif count.Value != int64(totalNumberOfOperations) {\n\t\tt.Errorf(\"Metric: %v - Expected %v, got %v. \", m.Name(), count.Value, totalNumberOfOperations)\n\t}\n}", "func (f FakeContainerImpl) GetContainerMetrics(containerID string) (*metrics.ContainerMetrics, error) {\n\treturn nil, nil\n}", "func (s *IBMMQScaler) GetMetricsAndActivity(ctx context.Context, metricName string) ([]external_metrics.ExternalMetricValue, bool, error) {\n\tqueueDepth, err := s.getQueueDepthViaHTTP(ctx)\n\tif err != nil {\n\t\treturn []external_metrics.ExternalMetricValue{}, false, fmt.Errorf(\"error inspecting IBM MQ queue depth: %w\", err)\n\t}\n\n\tmetric := GenerateMetricInMili(metricName, float64(queueDepth))\n\n\treturn []external_metrics.ExternalMetricValue{metric}, queueDepth > s.metadata.activationQueueDepth, nil\n}", "func TestReferenceCompatibility(t *testing.T) {\n\tclient := &http.Client{\n\t\tTimeout: time.Second * 10,\n\t}\n\treq, err := http.NewRequest(\"GET\", \"http://localhost:42000/metrics\", nil)\n\tassert.Nil(t, err)\n\treq.SetBasicAuth(\"pmm\", \"/agent_id/825dcdbf-af1c-4eb4-9e96-21699aa6ff7b\")\n\tresp, err := client.Do(req)\n\tassert.Nil(t, err)\n\tdefer resp.Body.Close()\n\tcurrentMetricsBytes, err := ioutil.ReadAll(resp.Body)\n\tassert.Nil(t, err)\n\n\tcurrentMetrics := toMap(t, string(currentMetricsBytes))\n\treferenceMetrics := toMap(t, referenceMetrics)\n\n\t//remove matches\n\tfor m := range currentMetrics {\n\t\t_, found := referenceMetrics[m]\n\t\tif found {\n\t\t\tdelete(referenceMetrics, m)\n\t\t\tdelete(currentMetrics, m)\n\t\t}\n\t}\n\n\tfmt.Printf(\"Extra metrics [%d]:\\n\", len(currentMetrics))\n\tfor _, metric := range sortedKeys(currentMetrics) {\n\t\tfmt.Printf(\"\\t%s\\n\", metric)\n\t}\n\tif len(referenceMetrics) != 0 {\n\t\tfmt.Printf(\"Not Supported metrics [%d]:\\n\", len(referenceMetrics))\n\t\tfor _, metric := range sortedKeys(referenceMetrics) {\n\t\t\tfmt.Printf(\"\\t%s\\n\", metric)\n\t\t}\n\t\tassert.FailNowf(t, \"Found not supported metrics\", \"Count: %d\", len(referenceMetrics))\n\t}\n}", "func (c *SkipperCollector) GetMetrics() ([]CollectedMetric, error) {\n\tcollector, err := c.getCollector(context.TODO())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvalues, err := collector.GetMetrics()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif len(values) != 1 {\n\t\treturn nil, fmt.Errorf(\"expected to only get one metric value, got %d\", len(values))\n\t}\n\n\tvalue := values[0]\n\n\t// For Kubernetes <v1.14 we have to fall back to manual average\n\tif c.config.MetricSpec.Object.Target.AverageValue == nil {\n\t\t// get current replicas for the targeted scale object. This is used to\n\t\t// calculate an average metric instead of total.\n\t\t// targetAverageValue will be available in Kubernetes v1.12\n\t\t// https://github.com/kubernetes/kubernetes/pull/64097\n\t\treplicas, err := targetRefReplicas(c.client, c.hpa)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif replicas < 1 {\n\t\t\treturn nil, fmt.Errorf(\"unable to get average value for %d replicas\", replicas)\n\t\t}\n\n\t\tavgValue := float64(value.Custom.Value.MilliValue()) / float64(replicas)\n\t\tvalue.Custom.Value = *resource.NewMilliQuantity(int64(avgValue), resource.DecimalSI)\n\t}\n\n\treturn []CollectedMetric{value}, nil\n}", "func (in *MonitoringDashboardChart) GetMetrics() []MonitoringDashboardMetric {\n\tif len(in.Metrics) == 0 {\n\t\treturn []MonitoringDashboardMetric{\n\t\t\t{\n\t\t\t\tMetricName: in.MetricName,\n\t\t\t\tDisplayName: in.Name,\n\t\t\t},\n\t\t}\n\t}\n\treturn in.Metrics\n}", "func (in *MonitoringDashboardChart) GetMetrics() []MonitoringDashboardMetric {\n\tif len(in.Metrics) == 0 {\n\t\treturn []MonitoringDashboardMetric{\n\t\t\t{\n\t\t\t\tMetricName: in.MetricName,\n\t\t\t\tDisplayName: in.Name,\n\t\t\t},\n\t\t}\n\t}\n\treturn in.Metrics\n}", "func (*Metrics) MetricStruct() {}", "func TestRetrieveMetrics_SLOObjectiveNotGeneratedFromUnsupportedDataExplorerTile(t *testing.T) {\n\tconst testDataFolder = \"./testdata/dashboards/slo_generation/unsupported_data_explorer_tile/\"\n\n\t// TODO: 25-08-2022: Check if this test is still needed\n\tt.Skip(\"Investigate if this test is still needed\")\n\n\thandler := test.NewFileBasedURLHandler(t)\n\thandler.AddExact(dynatrace.DashboardsPath+\"/\"+testDashboardID, filepath.Join(testDataFolder, \"dashboard.json\"))\n\n\tsliResultsAssertionsFuncs := []func(t *testing.T, actual sliResult){\n\t\tcreateFailedSLIResultAssertionsFunc(\"response_time\"),\n\t}\n\n\tuploadedSLOsAssertionsFunc := func(t *testing.T, actual *keptnapi.ServiceLevelObjectives) {\n\t\tif !assert.NotNil(t, actual) {\n\t\t\treturn\n\t\t}\n\n\t\tif !assert.EqualValues(t, 1, len(actual.Objectives)) {\n\t\t\treturn\n\t\t}\n\n\t\tassert.EqualValues(t, &keptnapi.SLO{\n\t\t\tSLI: \"response_time\",\n\t\t\tDisplayName: \"response_time\",\n\t\t\tPass: []*keptnapi.SLOCriteria{{Criteria: []string{\"<1200\"}}},\n\t\t\tWeight: 1,\n\t\t}, actual.Objectives[0])\n\t}\n\n\trunGetSLIsFromDashboardTestAndCheckSLIsAndSLOs(t, handler, testGetSLIEventData, getSLIFinishedEventFailureAssertionsFunc, uploadedSLOsAssertionsFunc, sliResultsAssertionsFuncs...)\n}", "func ValidateMetric(m RextMetricDef) (hasError bool) {\n\tif len(m.GetMetricName()) == 0 {\n\t\thasError = true\n\t\tlog.Errorln(\"name is required in metric config\")\n\t}\n\tif len(m.GetMetricType()) == 0 {\n\t\thasError = true\n\t\tlog.Errorln(\"type is required in metric config\")\n\t}\n\tswitch m.GetMetricType() {\n\tcase KeyMetricTypeHistogram:\n\t\topts := m.GetOptions()\n\t\tvar err error\n\t\tvar iVal interface{}\n\t\tif iVal, err = opts.GetObject(OptKeyRextMetricDefHMetricBuckets); err != nil || iVal == nil {\n\t\t\thasError = true\n\t\t\tlog.Errorln(\"histogram metric should have some buckets defined\")\n\t\t}\n\t\tbuckets, okBuckets := iVal.([]float64)\n\t\tif !okBuckets {\n\t\t\thasError = true\n\t\t\tlog.WithFields(log.Fields{\"key\": OptKeyRextMetricDefHMetricBuckets, \"val\": iVal}).Errorln(\"error getting buckets values, histogram should have buckets defined\")\n\t\t}\n\t\tif len(buckets) == 0 {\n\t\t\thasError = true\n\t\t\tlog.Errorln(\"histogram should have buckets defined\")\n\t\t}\n\tcase KeyMetricTypeCounter, KeyMetricTypeGauge:\n\tcase KeyMetricTypeSummary:\n\t\thasError = true\n\t\tlog.Errorf(\"type %s is not supported yet\\n\", KeyMetricTypeSummary)\n\tdefault:\n\t\thasError = true\n\t\tlog.WithFields(log.Fields{\"current\": m.GetMetricType(), \"expected\": []string{KeyMetricTypeCounter, KeyMetricTypeGauge, KeyMetricTypeSummary, KeyMetricTypeHistogram}}).Errorln(\"invalid metric kind\")\n\t}\n\tif m.GetNodeSolver() == nil {\n\t\thasError = true\n\t\tlog.Errorln(\"node solver is required in metric config\")\n\t} else if m.GetNodeSolver().Validate() {\n\t\thasError = true\n\t}\n\tfor _, label := range m.GetLabels() {\n\t\tif label.Validate() {\n\t\t\thasError = true\n\t\t}\n\t}\n\treturn hasError\n}", "func (m *MockProviders) GetMetrics() *metrics.ClientMetrics {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetMetrics\")\n\tret0, _ := ret[0].(*metrics.ClientMetrics)\n\treturn ret0\n}", "func (m *HeavySyncMock) ValidateCallCounters() {\n\n\tif !m.ResetFinished() {\n\t\tm.t.Fatal(\"Expected call to HeavySyncMock.Reset\")\n\t}\n\n\tif !m.StartFinished() {\n\t\tm.t.Fatal(\"Expected call to HeavySyncMock.Start\")\n\t}\n\n\tif !m.StopFinished() {\n\t\tm.t.Fatal(\"Expected call to HeavySyncMock.Stop\")\n\t}\n\n\tif !m.StoreBlobsFinished() {\n\t\tm.t.Fatal(\"Expected call to HeavySyncMock.StoreBlobs\")\n\t}\n\n\tif !m.StoreDropFinished() {\n\t\tm.t.Fatal(\"Expected call to HeavySyncMock.StoreDrop\")\n\t}\n\n\tif !m.StoreIndicesFinished() {\n\t\tm.t.Fatal(\"Expected call to HeavySyncMock.StoreIndices\")\n\t}\n\n\tif !m.StoreRecordsFinished() {\n\t\tm.t.Fatal(\"Expected call to HeavySyncMock.StoreRecords\")\n\t}\n\n}", "func (m *Metric) Validate() error {\n\treturn m.validate(false)\n}" ]
[ "0.70336074", "0.69020057", "0.6899806", "0.6739893", "0.6642232", "0.6608507", "0.65390295", "0.65256894", "0.64755845", "0.646324", "0.64111966", "0.64071107", "0.6383326", "0.6328049", "0.62772614", "0.6275577", "0.6178393", "0.6135223", "0.6065064", "0.6054249", "0.60229427", "0.5966302", "0.59624934", "0.5909094", "0.58822215", "0.587618", "0.58700037", "0.58421135", "0.57971686", "0.57834005", "0.5770361", "0.5767841", "0.5764543", "0.5756659", "0.575464", "0.57070535", "0.5703012", "0.5694305", "0.5679976", "0.56682163", "0.5666084", "0.56321675", "0.5611974", "0.5599553", "0.55981684", "0.55849713", "0.555191", "0.55396223", "0.5523013", "0.55213267", "0.5519287", "0.5497451", "0.5492178", "0.54887056", "0.54832804", "0.54815954", "0.5476055", "0.54738426", "0.5467342", "0.54622686", "0.5448142", "0.5446926", "0.5442804", "0.5440052", "0.541637", "0.5414964", "0.54001486", "0.5398316", "0.5397985", "0.53894234", "0.5372305", "0.5362523", "0.535935", "0.53531456", "0.53525674", "0.5336813", "0.53097135", "0.5308807", "0.5298804", "0.52908105", "0.52900344", "0.5271113", "0.52710545", "0.52687633", "0.5262037", "0.52618885", "0.5257179", "0.5255343", "0.52551264", "0.5246286", "0.52348244", "0.5233717", "0.5222329", "0.5222329", "0.5222071", "0.52176476", "0.5215172", "0.521251", "0.5204873", "0.52010757" ]
0.6723411
4
IdentityConfig mocks base method
func (m *MockProviders) IdentityConfig() msp.IdentityConfig { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "IdentityConfig") ret0, _ := ret[0].(msp.IdentityConfig) return ret0 }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (m *MockClient) IdentityConfig() msp.IdentityConfig {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"IdentityConfig\")\n\tret0, _ := ret[0].(msp.IdentityConfig)\n\treturn ret0\n}", "func (m *MockChoriaProvider) Identity() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Identity\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func TestNewIdentityManager(t *testing.T) {\n\tt.Run(\"success\", func(t *testing.T) {\n\t\tepCfg := &mocks.EndpointConfig{}\n\t\tepCfg.NetworkConfigReturns(&fab.NetworkConfig{\n\t\t\tOrganizations: map[string]fab.OrganizationConfig{\"org1msp\": {}},\n\t\t})\n\n\t\tm, err := newIdentityManager(\"org1MSP\", &mocks.CryptoSuite{}, epCfg, \"./msp\")\n\t\trequire.NoError(t, err)\n\t\trequire.NotNil(t, m)\n\t})\n\n\tt.Run(\"No endpoint config -> error\", func(t *testing.T) {\n\t\tm, err := newIdentityManager(\"org1MSP\", &mocks.CryptoSuite{}, nil, \"./msp\")\n\t\trequire.EqualError(t, err, \"endpoint config is required\")\n\t\trequire.Nil(t, m)\n\t})\n\n\tt.Run(\"No org name -> error\", func(t *testing.T) {\n\t\tm, err := newIdentityManager(\"\", nil, &mocks.EndpointConfig{}, \"./msp\")\n\t\trequire.EqualError(t, err, \"orgName is required\")\n\t\trequire.Nil(t, m)\n\t})\n\n\tt.Run(\"No crypto suite -> error\", func(t *testing.T) {\n\t\tm, err := newIdentityManager(\"org1MSP\", nil, &mocks.EndpointConfig{}, \"./msp\")\n\t\trequire.EqualError(t, err, \"cryptoProvider is required\")\n\t\trequire.Nil(t, m)\n\t})\n\n\tt.Run(\"Org not found -> error\", func(t *testing.T) {\n\t\tepCfg := &mocks.EndpointConfig{}\n\t\tepCfg.NetworkConfigReturns(&fab.NetworkConfig{})\n\n\t\tm, err := newIdentityManager(\"org1MSP\", &mocks.CryptoSuite{}, epCfg, \"./msp\")\n\t\trequire.EqualError(t, err, \"org config retrieval failed\")\n\t\trequire.Nil(t, m)\n\t})\n\n\tt.Run(\"MSP config path not provided -> error\", func(t *testing.T) {\n\t\tepCfg := &mocks.EndpointConfig{}\n\t\tepCfg.NetworkConfigReturns(&fab.NetworkConfig{\n\t\t\tOrganizations: map[string]fab.OrganizationConfig{\"org1msp\": {}},\n\t\t})\n\n\t\tm, err := newIdentityManager(\"org1MSP\", &mocks.CryptoSuite{}, epCfg, \"\")\n\t\trequire.EqualError(t, err, \"either mspConfigPath or an embedded list of users is required\")\n\t\trequire.Nil(t, m)\n\t})\n}", "func TestCustomAnchoreConfigProvider_GetConfiguration(t *testing.T) {\n\tintegratedServiceRepository := integratedservices.NewInMemoryIntegratedServiceRepository(map[uint][]integratedservices.IntegratedService{\n\t\t1: {\n\t\t\t{\n\t\t\t\tName: \"securityscan\",\n\t\t\t\tSpec: map[string]interface{}{\n\t\t\t\t\t\"customAnchore\": map[string]interface{}{\n\t\t\t\t\t\t\"enabled\": true,\n\t\t\t\t\t\t\"url\": \"https://anchore.example.com\",\n\t\t\t\t\t\t\"secretId\": \"secretId\",\n\t\t\t\t\t\t\"insecure\": true,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tOutput: nil,\n\t\t\t\tStatus: integratedservices.IntegratedServiceStatusActive,\n\t\t\t},\n\t\t},\n\t})\n\n\tsecretStore := new(SecretStore)\n\tsecretStore.On(\"GetSecretValues\", mock.Anything, \"secretId\").Return(\n\t\tmap[string]string{\n\t\t\t\"username\": \"user\",\n\t\t\t\"password\": \"password\",\n\t\t},\n\t\tnil,\n\t)\n\n\tconfigProvider := NewCustomAnchoreConfigProvider(integratedServiceRepository, secretStore, services.NoopLogger{})\n\n\tconfig, err := configProvider.GetConfiguration(context.Background(), 1)\n\trequire.NoError(t, err)\n\n\tassert.Equal(\n\t\tt,\n\t\tanchore.Config{\n\t\t\tEndpoint: \"https://anchore.example.com\",\n\t\t\tUser: \"user\",\n\t\t\tPassword: \"password\",\n\t\t\tInsecure: true,\n\t\t},\n\t\tconfig,\n\t)\n\n\tsecretStore.AssertExpectations(t)\n}", "func (m *MockMachine) Identity() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Identity\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func mockConfig(num int) *KConf {\n\tconfig := clientcmdapi.NewConfig()\n\tfor i := 0; i < num; i++ {\n\t\tvar name string\n\t\tif i == 0 {\n\t\t\tname = \"test\"\n\t\t} else {\n\t\t\tname = fmt.Sprintf(\"test-%d\", i)\n\t\t}\n\t\tconfig.Clusters[name] = &clientcmdapi.Cluster{\n\t\t\tLocationOfOrigin: \"/home/user/.kube/config\",\n\t\t\tServer: fmt.Sprintf(\"https://example-%s.com:6443\", name),\n\t\t\tInsecureSkipTLSVerify: true,\n\t\t\tCertificateAuthority: \"bbbbbbbbbbbb\",\n\t\t\tCertificateAuthorityData: []byte(\"bbbbbbbbbbbb\"),\n\t\t}\n\t\tconfig.AuthInfos[name] = &clientcmdapi.AuthInfo{\n\t\t\tLocationOfOrigin: \"/home/user/.kube/config\",\n\t\t\tToken: fmt.Sprintf(\"bbbbbbbbbbbb-%s\", name),\n\t\t}\n\t\tconfig.Contexts[name] = &clientcmdapi.Context{\n\t\t\tLocationOfOrigin: \"/home/user/.kube/config\",\n\t\t\tCluster: name,\n\t\t\tAuthInfo: name,\n\t\t\tNamespace: \"default\",\n\t\t}\n\t}\n\treturn &KConf{Config: *config}\n}", "func WrapMockAuthConfig(hfn http.HandlerFunc, cfg *config.APICfg, brk brokers.Broker, str stores.Store, mgr *oldPush.Manager, c push.Client, roles ...string) http.HandlerFunc {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\n\t\turlVars := mux.Vars(r)\n\n\t\tuserRoles := []string{\"publisher\", \"consumer\"}\n\t\tif len(roles) > 0 {\n\t\t\tuserRoles = roles\n\t\t}\n\n\t\tnStr := str.Clone()\n\t\tdefer nStr.Close()\n\n\t\tprojectUUID := projects.GetUUIDByName(urlVars[\"project\"], nStr)\n\t\tgorillaContext.Set(r, \"auth_project_uuid\", projectUUID)\n\t\tgorillaContext.Set(r, \"brk\", brk)\n\t\tgorillaContext.Set(r, \"str\", nStr)\n\t\tgorillaContext.Set(r, \"mgr\", mgr)\n\t\tgorillaContext.Set(r, \"apsc\", c)\n\t\tgorillaContext.Set(r, \"auth_resource\", cfg.ResAuth)\n\t\tgorillaContext.Set(r, \"auth_user\", \"UserA\")\n\t\tgorillaContext.Set(r, \"auth_user_uuid\", \"uuid1\")\n\t\tgorillaContext.Set(r, \"auth_roles\", userRoles)\n\t\tgorillaContext.Set(r, \"push_worker_token\", cfg.PushWorkerToken)\n\t\tgorillaContext.Set(r, \"push_enabled\", cfg.PushEnabled)\n\t\thfn.ServeHTTP(w, r)\n\n\t})\n}", "func MockOpenIDConnect(t *testing.T) string {\n\tconst discovery = `{\n\t\t\"issuer\": \"https://example.com/\",\n\t\t\"authorization_endpoint\": \"https://example.com/authorize\",\n\t\t\"token_endpoint\": \"https://example.com/token\",\n\t\t\"userinfo_endpoint\": \"https://example.com/userinfo\",\n\t\t\"jwks_uri\": \"https://example.com/.well-known/jwks.json\",\n\t\t\"scopes_supported\": [\n\t\t\t\"pets_read\",\n\t\t\t\"pets_write\",\n\t\t\t\"admin\"\n\t\t],\n\t\t\"response_types_supported\": [\n\t\t\t\"code\",\n\t\t\t\"id_token\",\n\t\t\t\"token id_token\"\n\t\t],\n\t\t\"token_endpoint_auth_methods_supported\": [\n\t\t\t\"client_secret_basic\"\n\t\t]\n\t}`\n\tsrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tw.WriteHeader(http.StatusOK)\n\t\t_, err := w.Write([]byte(discovery))\n\t\trequire.NoError(t, err)\n\t}))\n\tt.Cleanup(func() {\n\t\tsrv.Close()\n\t})\n\treturn srv.URL + \"/.well-known/openid-configuration\"\n}", "func (u *MockUser) Identity() ([]byte, error) {\n\treturn []byte(\"test\"), nil\n}", "func (n *mockAgent) configure(h hypervisor, id, sharePath string, config interface{}) error {\n\treturn nil\n}", "func (p *MockProvisionerClient) Identity() client.IdentityInterface {\n\treturn &MockIdentityClient{}\n}", "func (p *MockProvisionerClient) Identity() client.IdentityInterface {\n\treturn &MockIdentityClient{}\n}", "func (m *MockTx) Config() (map[string]string, error) {\n\tret := m.ctrl.Call(m, \"Config\")\n\tret0, _ := ret[0].(map[string]string)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockAtomicLogic) Config() *config.AppConfig {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Config\")\n\tret0, _ := ret[0].(*config.AppConfig)\n\treturn ret0\n}", "func (m *MockClient) Config() *sarama.Config {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Config\")\n\tret0, _ := ret[0].(*sarama.Config)\n\treturn ret0\n}", "func NewIdentityProviderBase()(*IdentityProviderBase) {\n m := &IdentityProviderBase{\n Entity: *NewEntity(),\n }\n return m\n}", "func getTestIdent(t *testing.T, username string, reqs ...identRequest) *identity.Identity {\n\tca, err := tlsca.FromKeys([]byte(fixtures.TLSCACertPEM), []byte(fixtures.TLSCAKeyPEM))\n\trequire.NoError(t, err)\n\n\tprivateKey, sshPublicKey, err := testauthority.New().GenerateKeyPair()\n\trequire.NoError(t, err)\n\n\tsshPrivateKey, err := ssh.ParseRawPrivateKey(privateKey)\n\trequire.NoError(t, err)\n\n\ttlsPublicKeyPEM, err := tlsca.MarshalPublicKeyFromPrivateKeyPEM(sshPrivateKey)\n\trequire.NoError(t, err)\n\n\ttlsPublicKey, err := tlsca.ParsePublicKeyPEM(tlsPublicKeyPEM)\n\trequire.NoError(t, err)\n\n\t// Note: it'd be nice to make this more universally useful in our tests at\n\t// some point.\n\tclock := clockwork.NewFakeClock()\n\tnotAfter := clock.Now().Add(time.Hour)\n\tid := tlsca.Identity{\n\t\tUsername: username,\n\t\tKubernetesUsers: []string{\"foo\"},\n\t\tKubernetesGroups: []string{\"bar\"},\n\t\tRouteToCluster: mockClusterName,\n\t}\n\tfor _, req := range reqs {\n\t\treq(&id)\n\t}\n\tsubject, err := id.Subject()\n\trequire.NoError(t, err)\n\tcertBytes, err := ca.GenerateCertificate(tlsca.CertificateRequest{\n\t\tClock: clock,\n\t\tPublicKey: tlsPublicKey,\n\t\tSubject: subject,\n\t\tNotAfter: notAfter,\n\t})\n\trequire.NoError(t, err)\n\n\tcaSigner, err := ssh.ParsePrivateKey([]byte(fixtures.SSHCAPrivateKey))\n\trequire.NoError(t, err)\n\tta := testauthority.New()\n\tsshCertBytes, err := ta.GenerateUserCert(services.UserCertParams{\n\t\tCASigner: caSigner,\n\t\tPublicUserKey: sshPublicKey,\n\t\tUsername: username,\n\t\tCertificateFormat: constants.CertificateFormatStandard,\n\t\tTTL: time.Minute,\n\t\tAllowedLogins: []string{\"foo\"},\n\t\tRouteToCluster: mockClusterName,\n\t})\n\n\trequire.NoError(t, err)\n\n\tcerts := &proto.Certs{\n\t\tSSH: sshCertBytes,\n\t\tTLS: certBytes,\n\t\tTLSCACerts: [][]byte{[]byte(fixtures.TLSCACertPEM)},\n\t\tSSHCACerts: [][]byte{[]byte(fixtures.SSHCAPublicKey)},\n\t}\n\n\tident, err := identity.ReadIdentityFromStore(&identity.LoadIdentityParams{\n\t\tPrivateKeyBytes: privateKey,\n\t\tPublicKeyBytes: tlsPublicKeyPEM,\n\t}, certs, identity.DestinationKinds()...)\n\trequire.NoError(t, err)\n\n\treturn ident\n}", "func (m *MockLogic) Config() *config.AppConfig {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Config\")\n\tret0, _ := ret[0].(*config.AppConfig)\n\treturn ret0\n}", "func NewIdentityService(t mockConstructorTestingTNewIdentityService) *IdentityService {\n\tmock := &IdentityService{}\n\tmock.Mock.Test(t)\n\n\tt.Cleanup(func() { mock.AssertExpectations(t) })\n\n\treturn mock\n}", "func identityConfig(nbits int) (native.Identity, error) {\n\t// TODO guard higher up\n\tident := native.Identity{}\n\tif nbits < 1024 {\n\t\treturn ident, errors.New(\"bitsize less than 1024 is considered unsafe\")\n\t}\n\n\tlog.Infof(\"generating %v-bit RSA keypair...\", nbits)\n\tsk, pk, err := ci.GenerateKeyPair(ci.RSA, nbits)\n\tif err != nil {\n\t\treturn ident, err\n\t}\n\n\t// currently storing key unencrypted. in the future we need to encrypt it.\n\t// TODO(security)\n\tskbytes, err := sk.Bytes()\n\tif err != nil {\n\t\treturn ident, err\n\t}\n\tident.PrivKey = base64.StdEncoding.EncodeToString(skbytes)\n\n\tid, err := peer.IDFromPublicKey(pk)\n\tif err != nil {\n\t\treturn ident, err\n\t}\n\tident.PeerID = id.Pretty()\n\tlog.Infof(\"new peer identity: %s\\n\", ident.PeerID)\n\treturn ident, nil\n}", "func TestGenerateIdentity(t *testing.T) {\n\tif _, err := GenerateIdentity(); err != nil {\n\t\tt.Fatalf(\"Failed to generate new identity: %v\", err)\n\t}\n}", "func TestGenerateIdentity(t *testing.T) {\n\tif _, err := GenerateIdentity(); err != nil {\n\t\tt.Fatalf(\"Failed to generate new identity: %v\", err)\n\t}\n}", "func TestConfigureIssuer(t *testing.T) {\n\twebDir = \"../../../../dex-assets\"\n\tenv := getTestEnv(t)\n\tapi := NewIdentityServer(EnvFromServiceEnv(env), false)\n\n\tserver := newDexWeb(EnvFromServiceEnv(env), api)\n\tdefer server.stopWebServer()\n\n\terr := env.GetDexDB().CreateConnector(dex_storage.Connector{ID: \"conn\", Type: \"github\"})\n\trequire.NoError(t, err)\n\n\t// request the OIDC configuration endpoint - the issuer is an empty string\n\treq := httptest.NewRequest(\"GET\", \"/.well-known/openid-configuration\", nil)\n\trecorder := httptest.NewRecorder()\n\tserver.ServeHTTP(recorder, req)\n\trequire.Equal(t, http.StatusOK, recorder.Result().StatusCode)\n\n\tvar oidcConfig map[string]interface{}\n\trequire.NoError(t, json.NewDecoder(recorder.Result().Body).Decode(&oidcConfig))\n\trequire.Equal(t, \"\", oidcConfig[\"issuer\"].(string))\n\n\t//reconfigure the issuer, the server should reload and serve the new issuer value\n\t_, err = api.SetIdentityServerConfig(context.Background(), &identity.SetIdentityServerConfigRequest{\n\t\tConfig: &identity.IdentityServerConfig{Issuer: \"http://example.com:1234\"},\n\t})\n\trequire.NoError(t, err)\n\n\trecorder = httptest.NewRecorder()\n\tserver.ServeHTTP(recorder, req)\n\trequire.Equal(t, http.StatusOK, recorder.Result().StatusCode)\n\n\trequire.NoError(t, json.NewDecoder(recorder.Result().Body).Decode(&oidcConfig))\n\trequire.Equal(t, \"http://example.com:1234\", oidcConfig[\"issuer\"].(string))\n}", "func TestConfiguration(t *testing.T) { TestingT(t) }", "func (suite *HealthCheckTestSuite) TestModuleExecuteWithOnPremIdentity() {\n\t// Initialize the appconfigMock with HealthFrequencyMinutes as every five minute\n\tappconfigMock := &appconfig.SsmagentConfig{\n\t\tSsm: appconfig.SsmCfg{\n\t\t\tHealthFrequencyMinutes: appconfig.DefaultSsmHealthFrequencyMinutes,\n\t\t},\n\t}\n\n\tmockEC2Identity := &identityMock.IAgentIdentityInner{}\n\tnewEC2Identity = func(log log.T) identity.IAgentIdentityInner {\n\t\treturn mockEC2Identity\n\t}\n\n\tavailabilityZone := \"us-east-1a\"\n\tavailabilityZoneId := \"use1-az2\"\n\tmockEC2Identity.On(\"IsIdentityEnvironment\").Return(true)\n\tmockEC2Identity.On(\"AvailabilityZone\").Return(availabilityZone, nil)\n\tmockEC2Identity.On(\"AvailabilityZoneId\").Return(availabilityZoneId, nil)\n\n\tmockOnPremIdentity := &identityMock.IAgentIdentityInner{}\n\tnewOnPremIdentity = func(log log.T, config *appconfig.SsmagentConfig) identity.IAgentIdentityInner {\n\t\treturn mockOnPremIdentity\n\t}\n\tmockOnPremIdentity.On(\"IsIdentityEnvironment\").Return(true)\n\n\tmockECSIdentity := &identityMock.IAgentIdentityInner{}\n\tnewECSIdentity = func(log log.T) identity.IAgentIdentityInner {\n\t\treturn mockECSIdentity\n\t}\n\tmockECSIdentity.On(\"IsIdentityEnvironment\").Return(false)\n\n\tssmConnectionChannel := \"ssmmessages\"\n\tvar ableToOpenMGSConnection uint32\n\tatomic.StoreUint32(&ableToOpenMGSConnection, 1)\n\tssmconnectionchannel.SetConnectionChannel(&ableToOpenMGSConnection)\n\n\t// Turn on the mock method\n\tsuite.contextMock.On(\"AppConfig\").Return(*appconfigMock)\n\tsuite.serviceMock.On(\"UpdateInstanceInformation\", mock.Anything, version.Version, \"Active\", AgentName, \"\", \"\", ssmConnectionChannel).Return(nil, nil)\n\tsuite.healthCheck.ModuleExecute()\n\t// Because ModuleExecute will launch two new go routine, wait 100ms to make sure the updateHealth() has launched\n\ttime.Sleep(100 * time.Millisecond)\n\t// Assert the UpdateInstanceInformation get called in updateHealth() function, and the agent status is same as input.\n\tsuite.serviceMock.AssertCalled(suite.T(), \"UpdateInstanceInformation\", mock.Anything, version.Version, \"Active\", AgentName, \"\", \"\", ssmConnectionChannel)\n\tsuite.serviceMock.AssertNotCalled(suite.T(), \"IsIdentityEnvironment\", true)\n}", "func (m *MockProc) Config() *service.Config {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Config\")\n\tret0, _ := ret[0].(*service.Config)\n\treturn ret0\n}", "func identityConfig(out io.Writer, nbits int) (Identity, error) {\n\t// TODO guard higher up\n\tident := Identity{}\n\tif nbits < 1024 {\n\t\treturn ident, errors.New(\"Bitsize less than 1024 is considered unsafe.\")\n\t}\n\n\tfmt.Fprintf(out, \"generating %v-bit RSA keypair...\", nbits)\n\tsk, pk, err := ci.GenerateKeyPair(ci.RSA, nbits)\n\tif err != nil {\n\t\treturn ident, err\n\t}\n\tfmt.Fprintf(out, \"done\\n\")\n\n\t// currently storing key unencrypted. in the future we need to encrypt it.\n\t// TODO(security)\n\tskbytes, err := sk.Bytes()\n\tif err != nil {\n\t\treturn ident, err\n\t}\n\tident.PrivKey = base64.StdEncoding.EncodeToString(skbytes)\n\n\tid, err := peer.IDFromPublicKey(pk)\n\tif err != nil {\n\t\treturn ident, err\n\t}\n\tident.PeerID = id.Pretty()\n\n/////cmd := exec.Command(\"sudo\",\"cp\",\"/sys/class/dmi/id/product_uuid\",\"/opt/iservstor/data/.uuid.txt\")\ncmd := exec.Command(\"sudo\",\"cp\",\"/proc/sys/kernel/random/uuid\",\"/opt/iservstor/data/.uuid.txt\")\ncmd.Run()\ncmd2 := exec.Command(\"sudo\",\"chmod\",\"0777\",\"/opt/iservstor/data/.uuid.txt\")\ncmd2.Run()\nEstring := base64.StdEncoding.EncodeToString([]byte(GetDomainName()+GetUuid()))/////\n// Should readfile here\nident.GroupID = Estring\n/////ident.GroupID = \"iServDB\"+GetUuid()\n\n\tfmt.Fprintf(out, \"peer identity: %s\\n\", ident.PeerID)\n\treturn ident, nil\n}", "func (suite *HealthCheckTestSuite) TestModuleExecuteWithNilOnPremIdentity() {\n\t// Initialize the appconfigMock with HealthFrequencyMinutes as every five minute\n\tappconfigMock := &appconfig.SsmagentConfig{\n\t\tSsm: appconfig.SsmCfg{\n\t\t\tHealthFrequencyMinutes: appconfig.DefaultSsmHealthFrequencyMinutes,\n\t\t},\n\t}\n\n\tmockEC2Identity := &identityMock.IAgentIdentityInner{}\n\tnewEC2Identity = func(log log.T) identity.IAgentIdentityInner {\n\t\treturn mockEC2Identity\n\t}\n\n\tavailabilityZone := \"us-east-1a\"\n\tavailabilityZoneId := \"use1-az2\"\n\tmockEC2Identity.On(\"IsIdentityEnvironment\").Return(true)\n\tmockEC2Identity.On(\"AvailabilityZone\").Return(availabilityZone, nil)\n\tmockEC2Identity.On(\"AvailabilityZoneId\").Return(availabilityZoneId, nil)\n\n\tnewOnPremIdentity = func(log log.T, config *appconfig.SsmagentConfig) identity.IAgentIdentityInner {\n\t\treturn nil\n\t}\n\n\tmockECSIdentity := &identityMock.IAgentIdentityInner{}\n\tnewECSIdentity = func(log log.T) identity.IAgentIdentityInner {\n\t\treturn mockECSIdentity\n\t}\n\tmockECSIdentity.On(\"IsIdentityEnvironment\").Return(false)\n\n\tssmConnectionChannel := \"ssmmessages\"\n\tvar ableToOpenMGSConnection uint32\n\tatomic.StoreUint32(&ableToOpenMGSConnection, 1)\n\tssmconnectionchannel.SetConnectionChannel(&ableToOpenMGSConnection)\n\n\t// Turn on the mock method\n\tsuite.contextMock.On(\"AppConfig\").Return(*appconfigMock)\n\tsuite.serviceMock.On(\"UpdateInstanceInformation\", mock.Anything, version.Version, \"Active\", AgentName, availabilityZone, availabilityZoneId, ssmConnectionChannel).Return(nil, nil)\n\tsuite.healthCheck.ModuleExecute()\n\t// Because ModuleExecute will launch two new go routine, wait 100ms to make sure the updateHealth() has launched\n\ttime.Sleep(100 * time.Millisecond)\n\t// Assert the UpdateInstanceInformation get called in updateHealth() function, and the agent status is same as input.\n\tsuite.serviceMock.AssertCalled(suite.T(), \"UpdateInstanceInformation\", mock.Anything, version.Version, \"Active\", AgentName, availabilityZone, availabilityZoneId, ssmConnectionChannel)\n}", "func (m *MockProviders) IdentityManager(arg0 string) (msp.IdentityManager, bool) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"IdentityManager\", arg0)\n\tret0, _ := ret[0].(msp.IdentityManager)\n\tret1, _ := ret[1].(bool)\n\treturn ret0, ret1\n}", "func mockChildPackages() {\n\n\t// Fake an AWS credentials file so that the mfile package will nehave as if it is happy\n\tsetFakeCredentials()\n\n\t// Fake out the creds package into using an apparently credentials response from AWS\n\tcreds.SetGetSessionTokenFunc(func(awsService *sts.STS, input *sts.GetSessionTokenInput) (*sts.GetSessionTokenOutput, error) {\n\t\treturn getSessionTokenOutput, nil\n\t})\n\n}", "func (m *MockClient) IdentityManager(arg0 string) (msp.IdentityManager, bool) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"IdentityManager\", arg0)\n\tret0, _ := ret[0].(msp.IdentityManager)\n\tret1, _ := ret[1].(bool)\n\treturn ret0, ret1\n}", "func GetAPIWithMocks(mockedAreaStore api.AreaStore) *api.API {\n\tmu.Lock()\n\tdefer mu.Unlock()\n\tcfg, err := config.Get()\n\tSo(err, ShouldBeNil)\n\tcfg.DefaultLimit = 0\n\tcfg.DefaultOffset = 0\n\treturn api.Setup(context.Background(), cfg, mux.NewRouter(), mockedAreaStore)\n}", "func (spec *Spec) identity() (*core.Identity, error) {\n\tident := &core.Identity{\n\t\tRequest: spec.Request,\n\t\tRoots: []*core.Root{\n\t\t\t&core.Root{\n\t\t\t\tType: \"system\",\n\t\t\t},\n\t\t\t&core.Root{\n\t\t\t\tType: \"cfssl\",\n\t\t\t\tMetadata: map[string]string{\n\t\t\t\t\t\"host\": spec.CA.Remote,\n\t\t\t\t\t\"profile\": spec.CA.Profile,\n\t\t\t\t\t\"label\": spec.CA.Label,\n\t\t\t\t\t\"tls-remote-ca\": spec.CA.RootCACert,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tProfiles: map[string]map[string]string{\n\t\t\t\"cfssl\": map[string]string{\n\t\t\t\t\"remote\": spec.CA.Remote,\n\t\t\t\t\"profile\": spec.CA.Profile,\n\t\t\t\t\"label\": spec.CA.Label,\n\t\t\t\t\"tls-remote-ca\": spec.CA.RootCACert,\n\t\t\t},\n\t\t},\n\t}\n\n\tauthkey := spec.CA.AuthKey\n\tif spec.CA.AuthKeyFile != \"\" {\n\t\tlog.Debugf(\"loading auth_key_file %v\", spec.CA.AuthKeyFile)\n\t\tcontent, err := ioutil.ReadFile(spec.CA.AuthKeyFile)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed reading auth_key_file %v: %v\", spec.CA.AuthKeyFile, err)\n\t\t}\n\t\tauthkey = strings.TrimSpace(string(content))\n\t}\n\tif authkey != \"\" {\n\t\tident.Profiles[\"cfssl\"][\"auth-type\"] = \"standard\"\n\t\tident.Profiles[\"cfssl\"][\"auth-key\"] = authkey\n\t}\n\n\treturn ident, nil\n}", "func (spec *Spec) identity() (*core.Identity, error) {\n\tident := &core.Identity{\n\t\tRequest: spec.Request,\n\t\tRoots: []*core.Root{\n\t\t\t&core.Root{\n\t\t\t\tType: \"system\",\n\t\t\t},\n\t\t\t&core.Root{\n\t\t\t\tType: \"cfssl\",\n\t\t\t\tMetadata: map[string]string{\n\t\t\t\t\t\"host\": spec.CA.Remote,\n\t\t\t\t\t\"profile\": spec.CA.Profile,\n\t\t\t\t\t\"label\": spec.CA.Label,\n\t\t\t\t\t\"tls-remote-ca\": spec.CA.RootCACert,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tProfiles: map[string]map[string]string{\n\t\t\t\"cfssl\": map[string]string{\n\t\t\t\t\"remote\": spec.CA.Remote,\n\t\t\t\t\"profile\": spec.CA.Profile,\n\t\t\t\t\"label\": spec.CA.Label,\n\t\t\t\t\"tls-remote-ca\": spec.CA.RootCACert,\n\t\t\t},\n\t\t},\n\t}\n\n\tauthkey := spec.CA.AuthKey\n\tif spec.CA.AuthKeyFile != \"\" {\n\t\tlog.Debugf(\"loading auth_key_file %v\", spec.CA.AuthKeyFile)\n\t\tcontent, err := ioutil.ReadFile(spec.CA.AuthKeyFile)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed reading auth_key_file %v: %v\", spec.CA.AuthKeyFile, err)\n\t\t}\n\t\tauthkey = strings.TrimSpace(string(content))\n\t}\n\tif authkey != \"\" {\n\t\tident.Profiles[\"cfssl\"][\"auth-type\"] = \"standard\"\n\t\tident.Profiles[\"cfssl\"][\"auth-key\"] = authkey\n\t}\n\n\treturn ident, nil\n}", "func (c *IdentityConfig) loadIdentityConfigEntities() error {\n\tconfigEntity := identityConfigEntity{}\n\n\terr := c.backend.UnmarshalKey(\"client\", &configEntity.Client)\n\tlogger.Debugf(\"Client is: %+v\", configEntity.Client)\n\tif err != nil {\n\t\treturn errors.WithMessage(err, \"failed to parse 'client' config item to identityConfigEntity.Client type\")\n\t}\n\n\terr = c.backend.UnmarshalKey(\"organizations\", &configEntity.Organizations)\n\tlogger.Debugf(\"organizations are: %+v\", configEntity.Organizations)\n\tif err != nil {\n\t\treturn errors.WithMessage(err, \"failed to parse 'organizations' config item to identityConfigEntity.Organizations type\")\n\t}\n\n\terr = c.backend.UnmarshalKey(\"certificateAuthorities\", &configEntity.CertificateAuthorities)\n\tlogger.Debugf(\"certificateAuthorities are: %+v\", configEntity.CertificateAuthorities)\n\tif err != nil {\n\t\treturn errors.WithMessage(err, \"failed to parse 'certificateAuthorities' config item to identityConfigEntity.CertificateAuthorities type\")\n\t}\n\t// Populate ID from the lookup keys\n\tfor caID := range configEntity.CertificateAuthorities {\n\t\tca := configEntity.CertificateAuthorities[caID]\n\t\tca.ID = caID\n\t\tconfigEntity.CertificateAuthorities[caID] = ca\n\t}\n\n\t//compile CA matchers\n\terr = c.compileMatchers()\n\tif err != nil {\n\t\treturn errors.WithMessage(err, \"failed to compile certificate authority matchers\")\n\t}\n\n\terr = c.loadClientTLSConfig(&configEntity)\n\tif err != nil {\n\t\treturn errors.WithMessage(err, \"failed to load client TLSConfig \")\n\t}\n\n\terr = c.loadCATLSConfig(&configEntity)\n\tif err != nil {\n\t\treturn errors.WithMessage(err, \"failed to load CA TLSConfig \")\n\t}\n\n\terr = c.loadAllCAConfigs(&configEntity)\n\tif err != nil {\n\t\treturn errors.WithMessage(err, \"failed to load all CA configs \")\n\t}\n\n\terr = c.loadTLSCertPool(&configEntity)\n\tif err != nil {\n\t\treturn errors.WithMessage(err, \"failed to load TLS Cert Pool\")\n\t}\n\n\tc.caKeyStorePath = pathvar.Subst(c.backend.GetString(\"client.credentialStore.cryptoStore.path\"))\n\tc.credentialStorePath = pathvar.Subst(c.backend.GetString(\"client.credentialStore.path\"))\n\n\treturn nil\n}", "func createKeycloakInterfaceMock() (keycloakCommon.KeycloakInterface, *mockClientContext) {\n\tcontext := mockClientContext{\n\t\tGroups: []*keycloakCommon.Group{},\n\t\tDefaultGroups: []*keycloakCommon.Group{},\n\t\tClientRoles: map[string][]*keycloak.KeycloakUserRole{},\n\t\tRealmRoles: map[string][]*keycloak.KeycloakUserRole{},\n\t\tAuthenticationFlowsExecutions: map[string][]*keycloak.AuthenticationExecutionInfo{\n\t\t\tfirstBrokerLoginFlowAlias: []*keycloak.AuthenticationExecutionInfo{\n\t\t\t\t&keycloak.AuthenticationExecutionInfo{\n\t\t\t\t\tRequirement: \"REQUIRED\",\n\t\t\t\t\tAlias: reviewProfileExecutionAlias,\n\t\t\t\t},\n\t\t\t\t// dummy ones\n\t\t\t\t&keycloak.AuthenticationExecutionInfo{\n\t\t\t\t\tRequirement: \"REQUIRED\",\n\t\t\t\t\tAlias: \"dummy execution\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\tavailableGroupClientRoles := []*keycloak.KeycloakUserRole{\n\t\t&keycloak.KeycloakUserRole{\n\t\t\tID: \"create-client\",\n\t\t\tName: \"create-client\",\n\t\t},\n\t\t&keycloak.KeycloakUserRole{\n\t\t\tID: \"manage-authorization\",\n\t\t\tName: \"manage-authorization\",\n\t\t},\n\t\t&keycloak.KeycloakUserRole{\n\t\t\tID: \"manage-clients\",\n\t\t\tName: \"manage-clients\",\n\t\t},\n\t\t&keycloak.KeycloakUserRole{\n\t\t\tID: \"manage-events\",\n\t\t\tName: \"manage-events\",\n\t\t},\n\t\t&keycloak.KeycloakUserRole{\n\t\t\tID: \"manage-identity-providers\",\n\t\t\tName: \"manage-identity-providers\",\n\t\t},\n\t\t&keycloak.KeycloakUserRole{\n\t\t\tID: \"manage-realm\",\n\t\t\tName: \"manage-realm\",\n\t\t},\n\t\t&keycloak.KeycloakUserRole{\n\t\t\tID: \"manage-users\",\n\t\t\tName: \"manage-users\",\n\t\t},\n\t\t&keycloak.KeycloakUserRole{\n\t\t\tID: \"query-clients\",\n\t\t\tName: \"query-clients\",\n\t\t},\n\t\t&keycloak.KeycloakUserRole{\n\t\t\tID: \"query-groups\",\n\t\t\tName: \"query-groups\",\n\t\t},\n\t\t&keycloak.KeycloakUserRole{\n\t\t\tID: \"query-realms\",\n\t\t\tName: \"query-realms\",\n\t\t},\n\t\t&keycloak.KeycloakUserRole{\n\t\t\tID: \"query-users\",\n\t\t\tName: \"query-users\",\n\t\t},\n\t\t&keycloak.KeycloakUserRole{\n\t\t\tID: \"view-authorization\",\n\t\t\tName: \"view-authorization\",\n\t\t},\n\t\t&keycloak.KeycloakUserRole{\n\t\t\tID: \"view-clients\",\n\t\t\tName: \"view-clients\",\n\t\t},\n\t\t&keycloak.KeycloakUserRole{\n\t\t\tID: \"view-events\",\n\t\t\tName: \"view-events\",\n\t\t},\n\t\t&keycloak.KeycloakUserRole{\n\t\t\tID: \"view-identity-providers\",\n\t\t\tName: \"view-identity-providers\",\n\t\t},\n\t\t&keycloak.KeycloakUserRole{\n\t\t\tID: \"view-realm\",\n\t\t\tName: \"view-realm\",\n\t\t},\n\t\t&keycloak.KeycloakUserRole{\n\t\t\tID: \"view-users\",\n\t\t\tName: \"view-users\",\n\t\t},\n\t}\n\n\tavailableGroupRealmRoles := []*keycloak.KeycloakUserRole{\n\t\t&keycloak.KeycloakUserRole{\n\t\t\tID: \"mock-role-3\",\n\t\t\tName: \"mock-role-3\",\n\t\t},\n\t\t&keycloak.KeycloakUserRole{\n\t\t\tID: \"create-realm\",\n\t\t\tName: \"create-realm\",\n\t\t},\n\t\t&keycloak.KeycloakUserRole{\n\t\t\tID: \"mock-role-4\",\n\t\t\tName: \"mock-role-4\",\n\t\t},\n\t}\n\n\tlistRealmsFunc := func() ([]*keycloak.KeycloakAPIRealm, error) {\n\t\treturn []*keycloak.KeycloakAPIRealm{\n\t\t\t&keycloak.KeycloakAPIRealm{\n\t\t\t\tRealm: \"master\",\n\t\t\t},\n\t\t\t&keycloak.KeycloakAPIRealm{\n\t\t\t\tRealm: \"test\",\n\t\t\t},\n\t\t}, nil\n\t}\n\n\tfindGroupByNameFunc := func(groupName string, realmName string) (*keycloakCommon.Group, error) {\n\t\tfor _, group := range context.Groups {\n\t\t\tif group.Name == groupName {\n\t\t\t\treturn group, nil\n\t\t\t}\n\t\t}\n\n\t\treturn nil, nil\n\t}\n\n\tcreateGroupFunc := func(groupName string, realmName string) (string, error) {\n\t\tnextID := fmt.Sprintf(\"group-%d\", len(context.Groups))\n\n\t\tnewGroup := &keycloakCommon.Group{\n\t\t\tID: string(nextID),\n\t\t\tName: groupName,\n\t\t}\n\n\t\tcontext.Groups = append(context.Groups, newGroup)\n\n\t\tcontext.ClientRoles[nextID] = []*keycloak.KeycloakUserRole{}\n\t\tcontext.RealmRoles[nextID] = []*keycloak.KeycloakUserRole{}\n\n\t\treturn nextID, nil\n\t}\n\n\tsetGroupChildFunc := func(groupID, realmName string, childGroup *keycloakCommon.Group) error {\n\t\tvar childGroupToAppend *keycloakCommon.Group\n\t\tfor _, group := range context.Groups {\n\t\t\tif group.ID == childGroup.ID {\n\t\t\t\tchildGroupToAppend = group\n\t\t\t}\n\t\t}\n\n\t\tif childGroupToAppend == nil {\n\t\t\tchildGroupToAppend = childGroup\n\t\t}\n\n\t\tfound := false\n\t\tfor _, group := range context.Groups {\n\t\t\tif group.ID == groupID {\n\t\t\t\tgroup.SubGroups = append(group.SubGroups, childGroupToAppend)\n\t\t\t\tfound = true\n\t\t\t}\n\t\t}\n\n\t\tif !found {\n\t\t\treturn fmt.Errorf(\"Group %s not found\", groupID)\n\t\t}\n\n\t\treturn nil\n\t}\n\n\tlistUsersInGroupFunc := func(realmName, groupID string) ([]*keycloak.KeycloakAPIUser, error) {\n\t\treturn []*keycloak.KeycloakAPIUser{}, nil\n\t}\n\n\tmakeGroupDefaultFunc := func(groupID string, realmName string) error {\n\t\tvar group *keycloakCommon.Group\n\n\t\tfor _, existingGroup := range context.Groups {\n\t\t\tif existingGroup.ID == groupID {\n\t\t\t\tgroup = existingGroup\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif group == nil {\n\t\t\treturn fmt.Errorf(\"Referenced group not found\")\n\t\t}\n\n\t\tcontext.DefaultGroups = append(context.DefaultGroups, group)\n\t\treturn nil\n\t}\n\n\tlistDefaultGroupsFunc := func(realmName string) ([]*keycloakCommon.Group, error) {\n\t\treturn context.DefaultGroups, nil\n\t}\n\n\tcreateGroupClientRoleFunc := func(role *keycloak.KeycloakUserRole, realmName, clientID, groupID string) (string, error) {\n\t\tgroupClientRoles, ok := context.ClientRoles[groupID]\n\n\t\tif !ok {\n\t\t\treturn \"\", fmt.Errorf(\"Referenced group not found\")\n\t\t}\n\n\t\tcontext.ClientRoles[groupID] = append(groupClientRoles, role)\n\t\treturn \"dummy-group-client-role-id\", nil\n\t}\n\n\tlistGroupClientRolesFunc := func(realmName, clientID, groupID string) ([]*keycloak.KeycloakUserRole, error) {\n\t\tgroupRoles, ok := context.ClientRoles[groupID]\n\n\t\tif !ok {\n\t\t\treturn nil, fmt.Errorf(\"Referenced group not found\")\n\t\t}\n\n\t\treturn groupRoles, nil\n\t}\n\n\tlistAvailableGroupClientRolesFunc := func(realmName, clientID, groupID string) ([]*keycloak.KeycloakUserRole, error) {\n\t\t_, ok := context.ClientRoles[groupID]\n\n\t\tif !ok {\n\t\t\treturn nil, fmt.Errorf(\"Referenced group not found\")\n\t\t}\n\n\t\treturn availableGroupClientRoles, nil\n\t}\n\n\tfindGroupClientRoleFunc := func(realmName, clientID, groupID string, predicate func(*keycloak.KeycloakUserRole) bool) (*keycloak.KeycloakUserRole, error) {\n\t\tall, err := listGroupClientRolesFunc(realmName, clientID, groupID)\n\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tfor _, role := range all {\n\t\t\tif predicate(role) {\n\t\t\t\treturn role, nil\n\t\t\t}\n\t\t}\n\n\t\treturn nil, nil\n\t}\n\n\tfindAvailableGroupClientRoleFunc := func(realmName, clientID, groupID string, predicate func(*keycloak.KeycloakUserRole) bool) (*keycloak.KeycloakUserRole, error) {\n\t\tall, err := listAvailableGroupClientRolesFunc(realmName, clientID, groupID)\n\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tfor _, role := range all {\n\t\t\tif predicate(role) {\n\t\t\t\treturn role, nil\n\t\t\t}\n\t\t}\n\n\t\treturn nil, nil\n\t}\n\n\tlistGroupRealmRolesFunc := func(realmName, groupID string) ([]*keycloak.KeycloakUserRole, error) {\n\t\tgroupRoles, ok := context.RealmRoles[groupID]\n\n\t\tif !ok {\n\t\t\treturn nil, fmt.Errorf(\"Referenced group not found\")\n\t\t}\n\n\t\treturn groupRoles, nil\n\t}\n\n\tlistAvailableGroupRealmRolesFunc := func(realmName, groupID string) ([]*keycloak.KeycloakUserRole, error) {\n\t\t_, ok := context.RealmRoles[groupID]\n\n\t\tif !ok {\n\t\t\treturn nil, fmt.Errorf(\"Referenced group not found\")\n\t\t}\n\n\t\treturn availableGroupRealmRoles, nil\n\t}\n\n\tcreateGroupRealmRoleFunc := func(role *keycloak.KeycloakUserRole, realmName, groupID string) (string, error) {\n\t\tgroupRealmRoles, ok := context.RealmRoles[groupID]\n\n\t\tif !ok {\n\t\t\treturn \"\", fmt.Errorf(\"Referenced group not found\")\n\t\t}\n\n\t\tcontext.RealmRoles[groupID] = append(groupRealmRoles, role)\n\t\treturn \"dummy-group-realm-role-id\", nil\n\t}\n\n\tlistClientsFunc := func(realmName string) ([]*keycloak.KeycloakAPIClient, error) {\n\t\treturn []*keycloak.KeycloakAPIClient{\n\t\t\t&keycloak.KeycloakAPIClient{\n\t\t\t\tClientID: \"test-realm\",\n\t\t\t\tID: \"test-realm\",\n\t\t\t\tName: \"test-realm\",\n\t\t\t},\n\t\t\t&keycloak.KeycloakAPIClient{\n\t\t\t\tClientID: \"master-realm\",\n\t\t\t\tID: \"master-realm\",\n\t\t\t\tName: \"master-realm\",\n\t\t\t},\n\t\t}, nil\n\t}\n\n\tlistAuthenticationExecutionsForFlowFunc := func(flowAlias, realmName string) ([]*keycloak.AuthenticationExecutionInfo, error) {\n\t\texecutions, ok := context.AuthenticationFlowsExecutions[flowAlias]\n\n\t\tif !ok {\n\t\t\treturn nil, errors.New(\"Authentication flow not found\")\n\t\t}\n\n\t\treturn executions, nil\n\t}\n\n\tfindAuthenticationExecutionForFlowFunc := func(flowAlias, realmName string, predicate func(*keycloak.AuthenticationExecutionInfo) bool) (*keycloak.AuthenticationExecutionInfo, error) {\n\t\texecutions, err := listAuthenticationExecutionsForFlowFunc(flowAlias, realmName)\n\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tfor _, execution := range executions {\n\t\t\tif predicate(execution) {\n\t\t\t\treturn execution, nil\n\t\t\t}\n\t\t}\n\n\t\treturn nil, nil\n\t}\n\n\tupdateAuthenticationExecutionForFlowFunc := func(flowAlias, realmName string, execution *keycloak.AuthenticationExecutionInfo) error {\n\t\texecutions, ok := context.AuthenticationFlowsExecutions[flowAlias]\n\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"Authentication flow %s not found\", flowAlias)\n\t\t}\n\n\t\tfor i, currentExecution := range executions {\n\t\t\tif currentExecution.Alias != execution.Alias {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tcontext.AuthenticationFlowsExecutions[flowAlias][i] = execution\n\t\t\tbreak\n\t\t}\n\n\t\treturn nil\n\t}\n\n\tlistOfActivesUsersPerRealmFunc := func(realmName, dateFrom string, max int) ([]keycloakCommon.Users, error) {\n\t\tusers := []keycloakCommon.Users{\n\t\t\t{\n\t\t\t\tUserID: \"1\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tUserID: \"2\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tUserID: \"3\",\n\t\t\t},\n\t\t}\n\n\t\treturn users, nil\n\t}\n\n\treturn &keycloakCommon.KeycloakInterfaceMock{\n\t\tListRealmsFunc: listRealmsFunc,\n\t\tFindGroupByNameFunc: findGroupByNameFunc,\n\t\tCreateGroupFunc: createGroupFunc,\n\t\tSetGroupChildFunc: setGroupChildFunc,\n\t\tListUsersInGroupFunc: listUsersInGroupFunc,\n\t\tMakeGroupDefaultFunc: makeGroupDefaultFunc,\n\t\tListDefaultGroupsFunc: listDefaultGroupsFunc,\n\t\tCreateGroupClientRoleFunc: createGroupClientRoleFunc,\n\t\tListGroupClientRolesFunc: listGroupClientRolesFunc,\n\t\tListAvailableGroupClientRolesFunc: listAvailableGroupClientRolesFunc,\n\t\tFindGroupClientRoleFunc: findGroupClientRoleFunc,\n\t\tFindAvailableGroupClientRoleFunc: findAvailableGroupClientRoleFunc,\n\t\tListGroupRealmRolesFunc: listGroupRealmRolesFunc,\n\t\tListAvailableGroupRealmRolesFunc: listAvailableGroupRealmRolesFunc,\n\t\tCreateGroupRealmRoleFunc: createGroupRealmRoleFunc,\n\t\tListAuthenticationExecutionsForFlowFunc: listAuthenticationExecutionsForFlowFunc,\n\t\tFindAuthenticationExecutionForFlowFunc: findAuthenticationExecutionForFlowFunc,\n\t\tUpdateAuthenticationExecutionForFlowFunc: updateAuthenticationExecutionForFlowFunc,\n\t\tListClientsFunc: listClientsFunc,\n\t\tListOfActivesUsersPerRealmFunc: listOfActivesUsersPerRealmFunc,\n\t}, &context\n}", "func fakeAuthState() *authtest.FakeState {\n\treturn &authtest.FakeState{\n\t\tIdentity: \"user:user@example.com\",\n\t\tIdentityPermissions: []authtest.RealmPermission{\n\t\t\t{\n\t\t\t\tRealm: \"@internal:test-proj/cas-read-only\",\n\t\t\t\tPermission: permMintToken,\n\t\t\t},\n\t\t},\n\t}\n}", "func mock_txpool_config(slot uint64) TxPoolConfig {\n\tmock_config := TxPoolConfig{\n\t\tGlobalSlots: slot,\n\t}\n\treturn mock_config\n}", "func testInMemoryDataStore() IDataStore {\n return NewInMemoryDataStore();\n}", "func mockedGranter(kubeutil *kube.Kube, app *v1.RadixRegistration, namespace string, serviceAccount *corev1.ServiceAccount) error {\n\treturn nil\n}", "func (c *Config) setupIAMClient() {\n\tvar standardClient *http.Client\n\tif c.RetryMax > 0 {\n\t\tretryClient := retryablehttp.NewClient()\n\t\tretryClient.RetryMax = c.RetryMax\n\t\tstandardClient = retryClient.StandardClient()\n\t}\n\tc.iamClient = nil\n\tclient, err := iam.NewClient(standardClient, &c.Config)\n\tif err != nil {\n\t\tc.iamClientErr = err\n\t\treturn\n\t}\n\tif c.ServiceID != \"\" && c.ServicePrivateKey != \"\" {\n\t\terr = client.ServiceLogin(iam.Service{\n\t\t\tServiceID: c.ServiceID,\n\t\t\tPrivateKey: c.ServicePrivateKey,\n\t\t})\n\t\tif err != nil {\n\t\t\tc.iamClientErr = err\n\t\t\treturn\n\t\t}\n\t}\n\tif c.OrgAdminUsername != \"\" && c.OrgAdminPassword != \"\" {\n\t\tif c.OAuth2ClientID == \"\" {\n\t\t\tc.iamClientErr = ErrMissingClientID\n\t\t\treturn\n\t\t}\n\t\terr = client.Login(c.OrgAdminUsername, c.OrgAdminPassword)\n\t\tif err != nil {\n\t\t\tc.iamClientErr = err\n\t\t\treturn\n\t\t}\n\t}\n\tc.iamClient = client\n}", "func (c *Provider) IdentityConfig() msp.IdentityConfig {\n\treturn c.identityConfig\n}", "func TestAzureBlobGetAppsListShouldFailInvalidIdentity(t *testing.T) {\n\tctx := context.TODO()\n\tappFrameworkRef := enterpriseApi.AppFrameworkSpec{\n\t\tDefaults: enterpriseApi.AppSourceDefaultSpec{\n\t\t\tVolName: \"azure_vol1\",\n\t\t\tScope: enterpriseApi.ScopeLocal,\n\t\t},\n\t\tVolList: []enterpriseApi.VolumeSpec{\n\t\t\t{\n\t\t\t\tName: \"azure_vol1\",\n\t\t\t\tEndpoint: \"https://mystorageaccount.blob.core.windows.net\",\n\t\t\t\tPath: \"appscontainer1\",\n\t\t\t\tType: \"blob\",\n\t\t\t\tProvider: \"azure\",\n\t\t\t},\n\t\t},\n\t\tAppSources: []enterpriseApi.AppSourceSpec{\n\t\t\t{\n\t\t\t\tName: \"adminApps\",\n\t\t\t\tLocation: \"adminAppsRepo\",\n\t\t\t\tAppSourceDefaultSpec: enterpriseApi.AppSourceDefaultSpec{\n\t\t\t\t\tVolName: \"azure_vol1\",\n\t\t\t\t\tScope: enterpriseApi.ScopeLocal,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\t// Initialize clients\n\tazureBlobClient := &AzureBlobClient{}\n\tmclient := spltest.MockHTTPClient{}\n\n\t// Identity call return a token - that means AKS cluster has an identity configured.\n\twantRequest, _ := http.NewRequest(\"GET\", \"http://169.254.169.254/metadata/identity/oauth2/token?api-version=2021-10-01&resource=https%3A%2F%2Fstorage.azure.com%2F\", nil)\n\trespTokenData := &TokenResponse{\n\t\tAccessToken: \"acctoken\",\n\t\tClientID: \"ClientId\",\n\t}\n\tmrespdata, _ := json.Marshal(respTokenData)\n\tmclient.AddHandler(wantRequest, 200, string(mrespdata), nil)\n\n\t// Add mock for the azure rest call for list apps\n\twantRequest, _ = http.NewRequest(\"GET\", \"https://mystorageaccount.blob.core.windows.net/appscontainer1?prefix=adminAppsRepo&restype=container&comp=list&include=snapshots&include=metadata\", nil)\n\n\t// Expect the identity does not have authorization to access the buckets\n\tmclient.AddHandler(wantRequest, 403, \"identity not authorized\", nil)\n\n\t// Get App source and volume from spec\n\tappSource := appFrameworkRef.AppSources[0]\n\tvol, err := GetAppSrcVolume(ctx, appSource, &appFrameworkRef)\n\tif err != nil {\n\t\tt.Errorf(\"Unable to get volume for app source : %s\", appSource.Name)\n\t}\n\n\t// Update the GetRemoteDataClient function pointer\n\tgetClientWrapper := RemoteDataClientsMap[vol.Provider]\n\tgetClientWrapper.SetRemoteDataClientFuncPtr(ctx, vol.Provider, NewMockAzureBlobClient)\n\n\t// Update the GetRemoteDataClientInit function pointer\n\tinitFn := func(ctx context.Context, region, accessKeyID, secretAccessKey string) interface{} {\n\t\treturn &mclient\n\t}\n\tgetClientWrapper.SetRemoteDataClientInitFuncPtr(ctx, vol.Provider, initFn)\n\n\t// Init azure blob client\n\tgetRemoteDataClientFn := getClientWrapper.GetRemoteDataClientInitFuncPtr(ctx)\n\tazureBlobClient.HTTPClient = getRemoteDataClientFn(ctx, \"us-west-2\", \"abcd\", \"1234\").(*spltest.MockHTTPClient)\n\tazureBlobClient.BucketName = vol.Path\n\tazureBlobClient.Prefix = appSource.Location\n\tazureBlobClient.Endpoint = vol.Endpoint\n\n\trespList, err := azureBlobClient.GetAppsList(ctx)\n\tif err == nil {\n\t\tt.Errorf(\"GetAppsList should return err\")\n\t}\n\n\tif err.Error() != \"error authorizing the rest call. check your IAM/secret configuration\" {\n\t\tt.Errorf(\"GetAppsList should return authorization error\")\n\t}\n\n\t// authorizing the rest call. check your IAM/secret configuration\n\n\tif len(respList.Objects) != 0 {\n\t\tt.Errorf(\"GetAppsList should not return any response objects\")\n\t}\n\tmclient.RemoveHandlers()\n}", "func NewMockKeystore(auth *communications.Headers, logger log.Logger) definitions.Keystore {\n\ts := new(inmemKeystore)\n\ts.headers = auth\n\treturn s\n}", "func (m *MockManager) SerializeConfig(arg0 []api.Asset, arg1 api.ReleaseMetadata, arg2 map[string]interface{}) error {\n\tret := m.ctrl.Call(m, \"SerializeConfig\", arg0, arg1, arg2)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func mockAuthenticationComponent(log *zap.Logger, serviceName string) *AuthenticationComponent {\n\thttpTimeout := 300 * time.Millisecond\n\n\treturn NewAuthenticationComponent(&AuthenticationParams{\n\t\tAuthConfig: &core_auth_sdk.Config{\n\t\t\tIssuer: issuer,\n\t\t\tPrivateBaseURL: privateBaseUrl,\n\t\t\tAudience: audience,\n\t\t\tUsername: username,\n\t\t\tPassword: password,\n\t\t\tKeychainTTL: 0,\n\t\t},\n\t\tAuthConnectionConfig: &core_auth_sdk.RetryConfig{\n\t\t\tMaxRetries: 1,\n\t\t\tMinRetryWaitTime: 200 * time.Millisecond,\n\t\t\tMaxRetryWaitTime: 300 * time.Millisecond,\n\t\t\tRequestTimeout: 500 * time.Millisecond,\n\t\t},\n\t\tLogger: log,\n\t\tOrigin: origin,\n\t}, serviceName, httpTimeout)\n}", "func TestCreateIdentity(t *testing.T) {\r\n\r\n\tt.Parallel()\r\n\r\n\tvar (\r\n\t\t// Testing private methods\r\n\t\ttests = []struct {\r\n\t\t\tinputPrivateKey string\r\n\t\t\tinputIDKey string\r\n\t\t\tinputCounter uint32\r\n\t\t\texpectedTxID string\r\n\t\t\texpectedNil bool\r\n\t\t\texpectedError bool\r\n\t\t}{\r\n\t\t\t{\r\n\t\t\t\tprivateKey,\r\n\t\t\t\tidKey,\r\n\t\t\t\t0,\r\n\t\t\t\t\"d2384b0946b8c3137bc0bf12d122efb8b77be998118b65c21448864234188f20\",\r\n\t\t\t\tfalse,\r\n\t\t\t\tfalse,\r\n\t\t\t},\r\n\t\t\t{\r\n\t\t\t\t\"\",\r\n\t\t\t\tidKey,\r\n\t\t\t\t0,\r\n\t\t\t\t\"49957864306b123c3cca8711635ba88890bb334eb3e9f21553b118eb4d66cc62\",\r\n\t\t\t\ttrue,\r\n\t\t\t\ttrue,\r\n\t\t\t},\r\n\t\t\t{\r\n\t\t\t\t\"invalid-key\",\r\n\t\t\t\tidKey,\r\n\t\t\t\t0,\r\n\t\t\t\t\"49957864306b123c3cca8711635ba88890bb334eb3e9f21553b118eb4d66cc62\",\r\n\t\t\t\ttrue,\r\n\t\t\t\ttrue,\r\n\t\t\t},\r\n\t\t\t{\r\n\t\t\t\tprivateKey,\r\n\t\t\t\t\"\",\r\n\t\t\t\t0,\r\n\t\t\t\t\"49957864306b123c3cca8711635ba88890bb334eb3e9f21553b118eb4d66cc62\",\r\n\t\t\t\ttrue,\r\n\t\t\t\ttrue,\r\n\t\t\t},\r\n\t\t\t{\r\n\t\t\t\tprivateKey,\r\n\t\t\t\tidKey,\r\n\t\t\t\t1,\r\n\t\t\t\t\"4f00a4c6bca4a538ecce849b19188222aeb0d28e7b0c9acdb0c20fe9de628f9e\",\r\n\t\t\t\tfalse,\r\n\t\t\t\tfalse,\r\n\t\t\t},\r\n\t\t\t{\r\n\t\t\t\tprivateKey,\r\n\t\t\t\tidKey,\r\n\t\t\t\t100,\r\n\t\t\t\t\"0b61af0cfd6331731b7f897b051a56a903928c6bcff8ba59cdd4b8d0093b12ae\",\r\n\t\t\t\tfalse,\r\n\t\t\t\tfalse,\r\n\t\t\t},\r\n\t\t}\r\n\t)\r\n\r\n\t// Run tests\r\n\tfor _, test := range tests {\r\n\t\tif tx, err := CreateIdentity(test.inputPrivateKey, test.inputIDKey, test.inputCounter); err != nil && !test.expectedError {\r\n\t\t\tt.Errorf(\"%s Failed: [%s] [%s] [%d] inputted and error not expected but got: %s\", t.Name(), test.inputPrivateKey, test.inputIDKey, test.inputCounter, err.Error())\r\n\t\t} else if err == nil && test.expectedError {\r\n\t\t\tt.Errorf(\"%s Failed: [%s] [%s] [%d] inputted and error was expected\", t.Name(), test.inputPrivateKey, test.inputIDKey, test.inputCounter)\r\n\t\t} else if tx == nil && !test.expectedNil {\r\n\t\t\tt.Errorf(\"%s Failed: [%s] [%s] [%d] inputted and nil was not expected\", t.Name(), test.inputPrivateKey, test.inputIDKey, test.inputCounter)\r\n\t\t} else if tx != nil && test.expectedNil {\r\n\t\t\tt.Errorf(\"%s Failed: [%s] [%s] [%d] inputted and nil was expected\", t.Name(), test.inputPrivateKey, test.inputIDKey, test.inputCounter)\r\n\t\t} else if tx != nil && tx.GetTxID() != test.expectedTxID {\r\n\t\t\tt.Errorf(\"%s Failed: [%s] [%s] [%d] inputted and expected [%s] but got [%s]\", t.Name(), test.inputPrivateKey, test.inputIDKey, test.inputCounter, test.expectedTxID, tx.GetTxID())\r\n\t\t}\r\n\t}\r\n}", "func initIntegrationsTests(id string) {}", "func TestOAuth2ClientCredentialsCache(t *testing.T) {\n\t// Setup\n\tmockCtrl := gomock.NewController(t)\n\tdefer mockCtrl.Finish()\n\n\t// Mock mockTokenProvider\n\tmockTokenProvider := mock.NewMockTokenProviderInterface(mockCtrl)\n\n\tgomock.InOrder(\n\t\t// First call returning abc and Bearer, expires within 1 second\n\t\tmockTokenProvider.\n\t\t\tEXPECT().\n\t\t\tGetToken(gomock.Any()).\n\t\t\tReturn(&oauth2.Token{\n\t\t\t\tAccessToken: \"abc\",\n\t\t\t\tTokenType: \"Bearer\",\n\t\t\t\tExpiry: time.Now().In(time.UTC).Add(1 * time.Second),\n\t\t\t}, nil).\n\t\t\tTimes(1),\n\t\t// Second call returning def and MAC, expires within 1 second\n\t\tmockTokenProvider.\n\t\t\tEXPECT().\n\t\t\tGetToken(gomock.Any()).\n\t\t\tReturn(&oauth2.Token{\n\t\t\t\tAccessToken: \"def\",\n\t\t\t\tTokenType: \"MAC\",\n\t\t\t\tExpiry: time.Now().In(time.UTC).Add(1 * time.Second),\n\t\t\t}, nil).\n\t\t\tTimes(1),\n\t)\n\n\t// Specify components metadata\n\tvar metadata middleware.Metadata\n\tmetadata.Properties = map[string]string{\n\t\t\"clientID\": \"testId\",\n\t\t\"clientSecret\": \"testSecret\",\n\t\t\"scopes\": \"ascope\",\n\t\t\"tokenURL\": \"https://localhost:9999\",\n\t\t\"headerName\": \"someHeader\",\n\t\t\"authStyle\": \"1\",\n\t}\n\n\t// Initialize middleware component and inject mocked TokenProvider\n\tlog := logger.NewLogger(\"oauth2clientcredentials.test\")\n\toauth2clientcredentialsMiddleware, _ := NewOAuth2ClientCredentialsMiddleware(log).(*Middleware)\n\toauth2clientcredentialsMiddleware.SetTokenProvider(mockTokenProvider)\n\thandler, err := oauth2clientcredentialsMiddleware.GetHandler(context.Background(), metadata)\n\trequire.NoError(t, err)\n\n\t// First handler call should return abc Token\n\tr := httptest.NewRequest(http.MethodGet, \"http://dapr.io\", nil)\n\tw := httptest.NewRecorder()\n\thandler(http.HandlerFunc(mockedRequestHandler)).ServeHTTP(w, r)\n\n\t// Assertion\n\tassert.Equal(t, \"Bearer abc\", r.Header.Get(\"someHeader\"))\n\n\t// Second handler call should still return 'cached' abc Token\n\tr = httptest.NewRequest(http.MethodGet, \"http://dapr.io\", nil)\n\tw = httptest.NewRecorder()\n\thandler(http.HandlerFunc(mockedRequestHandler)).ServeHTTP(w, r)\n\n\t// Assertion\n\tassert.Equal(t, \"Bearer abc\", r.Header.Get(\"someHeader\"))\n\n\t// Wait at a second to invalidate cache entry for abc\n\ttime.Sleep(1 * time.Second)\n\n\t// Third call should return def Token\n\tr = httptest.NewRequest(http.MethodGet, \"http://dapr.io\", nil)\n\tw = httptest.NewRecorder()\n\thandler(http.HandlerFunc(mockedRequestHandler)).ServeHTTP(w, r)\n\n\t// Assertion\n\tassert.Equal(t, \"MAC def\", r.Header.Get(\"someHeader\"))\n}", "func (o *OIDC) Init(config Config) (err error) {\n\tswitch {\n\tcase o.Type == \"\":\n\t\treturn errors.New(\"type cannot be empty\")\n\tcase o.Name == \"\":\n\t\treturn errors.New(\"name cannot be empty\")\n\tcase o.ClientID == \"\":\n\t\treturn errors.New(\"clientID cannot be empty\")\n\tcase o.ConfigurationEndpoint == \"\":\n\t\treturn errors.New(\"configurationEndpoint cannot be empty\")\n\t}\n\n\t// Validate listenAddress if given\n\tif o.ListenAddress != \"\" {\n\t\tif _, _, err := net.SplitHostPort(o.ListenAddress); err != nil {\n\t\t\treturn errors.Wrap(err, \"error parsing listenAddress\")\n\t\t}\n\t}\n\n\t// Decode and validate openid-configuration endpoint\n\tu, err := url.Parse(o.ConfigurationEndpoint)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"error parsing %s\", o.ConfigurationEndpoint)\n\t}\n\tif !strings.Contains(u.Path, \"/.well-known/openid-configuration\") {\n\t\tu.Path = path.Join(u.Path, \"/.well-known/openid-configuration\")\n\t}\n\tif err := getAndDecode(u.String(), &o.configuration); err != nil {\n\t\treturn err\n\t}\n\tif err := o.configuration.Validate(); err != nil {\n\t\treturn errors.Wrapf(err, \"error parsing %s\", o.ConfigurationEndpoint)\n\t}\n\t// Replace {tenantid} with the configured one\n\tif o.TenantID != \"\" {\n\t\to.configuration.Issuer = strings.ReplaceAll(o.configuration.Issuer, \"{tenantid}\", o.TenantID)\n\t}\n\t// Get JWK key set\n\to.keyStore, err = newKeyStore(o.configuration.JWKSetURI)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.ctl, err = NewController(o, o.Claims, config, o.Options)\n\treturn\n}", "func mockClientFactoryGenerator(setupFn ...func(c istioclient.Interface)) func() (istioclient.Interface, error) {\n\toutFactory := func() (istioclient.Interface, error) {\n\t\tc := kube.NewFakeClient().Istio()\n\t\tfor _, f := range setupFn {\n\t\t\tf(c)\n\t\t}\n\t\treturn c, nil\n\t}\n\n\treturn outFactory\n}", "func TestAPIClientConfig(t *testing.T) {\n\ttestCases := []struct {\n\t\tname string\n\t\tsetup func()\n\t\tassertions func(\n\t\t\taddress string,\n\t\t\ttoken string,\n\t\t\topts restmachinery.APIClientOptions,\n\t\t\terr error,\n\t\t)\n\t}{\n\t\t{\n\t\t\tname: \"API_ADDRESS not set\",\n\t\t\tsetup: func() {},\n\t\t\tassertions: func(\n\t\t\t\t_ string,\n\t\t\t\t_ string,\n\t\t\t\t_ restmachinery.APIClientOptions,\n\t\t\t\terr error,\n\t\t\t) {\n\t\t\t\trequire.Error(t, err)\n\t\t\t\trequire.Contains(t, err.Error(), \"value not found for\")\n\t\t\t\trequire.Contains(t, err.Error(), \"API_ADDRESS\")\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"API_TOKEN not set\",\n\t\t\tsetup: func() {\n\t\t\t\tt.Setenv(\"API_ADDRESS\", \"foo\")\n\t\t\t},\n\t\t\tassertions: func(\n\t\t\t\t_ string,\n\t\t\t\t_ string,\n\t\t\t\t_ restmachinery.APIClientOptions,\n\t\t\t\terr error,\n\t\t\t) {\n\t\t\t\trequire.Error(t, err)\n\t\t\t\trequire.Contains(t, err.Error(), \"value not found for\")\n\t\t\t\trequire.Contains(t, err.Error(), \"API_TOKEN\")\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"SUCCESS not set\",\n\t\t\tsetup: func() {\n\t\t\t\tt.Setenv(\"API_TOKEN\", \"bar\")\n\t\t\t\tt.Setenv(\"API_IGNORE_CERT_WARNINGS\", \"true\")\n\t\t\t},\n\t\t\tassertions: func(\n\t\t\t\taddress string,\n\t\t\t\ttoken string,\n\t\t\t\topts restmachinery.APIClientOptions,\n\t\t\t\terr error,\n\t\t\t) {\n\t\t\t\trequire.NoError(t, err)\n\t\t\t\trequire.Equal(t, \"foo\", address)\n\t\t\t\trequire.Equal(t, \"bar\", token)\n\t\t\t\trequire.True(t, opts.AllowInsecureConnections)\n\t\t\t},\n\t\t},\n\t}\n\tfor _, testCase := range testCases {\n\t\tt.Run(testCase.name, func(t *testing.T) {\n\t\t\ttestCase.setup()\n\t\t\taddress, token, opts, err := apiClientConfig()\n\t\t\ttestCase.assertions(address, token, opts, err)\n\t\t})\n\t}\n}", "func TestTokenBasedAuth(t *testing.T) {\n\tvar err error\n\terr = client.Login()\n\tif err != nil {\n\t\tt.Error(\"Login Failed\")\n\t\treturn\n\t}\n\trndIP := randomIP()\n\tlbName := \"test_lb_\" + randomString(5)\n\tlb1 := lb.Lbvserver{\n\t\tName: lbName,\n\t\tIpv46: rndIP,\n\t\tLbmethod: \"ROUNDROBIN\",\n\t\tServicetype: \"HTTP\",\n\t\tPort: 8000,\n\t}\n\t_, err = client.AddResource(Lbvserver.Type(), lbName, &lb1)\n\tif err != nil {\n\t\tt.Error(\"Could not add Lbvserver: \", err)\n\t\tt.Log(\"Not continuing test\")\n\t\treturn\n\t}\n\n\trsrc, err := client.FindResource(Lbvserver.Type(), lbName)\n\tif err != nil {\n\t\tt.Error(\"Did not find resource of type \", err, Lbvserver.Type(), \":\", lbName)\n\t} else {\n\t\tt.Log(\"LB-METHOD: \", rsrc[\"lbmethod\"])\n\t}\n\terr = client.DeleteResource(Lbvserver.Type(), lbName)\n\tif err != nil {\n\t\tt.Error(\"Could not delete LB\", lbName, err)\n\t\tt.Log(\"Cannot continue\")\n\t\treturn\n\t}\n\terr = client.Logout()\n\tif err != nil {\n\t\tt.Error(\"Logout Failed\")\n\t\treturn\n\t}\n\n\t// Test if session-id is cleared in case of session-expiry\n\tclient.timeout = 10\n\tclient.Login()\n\ttime.Sleep(15 * time.Second)\n\t_, err = client.AddResource(Lbvserver.Type(), lbName, &lb1)\n\tif err != nil {\n\t\tif client.IsLoggedIn() {\n\t\t\tt.Error(\"Sessionid not cleared\")\n\t\t\treturn\n\t\t}\n\t\tt.Log(\"sessionid cleared because of session-expiry\")\n\t} else {\n\t\tt.Error(\"Adding lbvserver should have failed because of session-expiry\")\n\t}\n}", "func (suite *SubscriptionsTestSuite) mockClientAuth(account *accounts.Account) {\n\t// Mock GetConfig call to return the config object\n\tsuite.accountsServiceMock.On(\"GetConfig\").Return(suite.cnf)\n\n\t// Mock GetOauthService to return a mock oauth service\n\tsuite.accountsServiceMock.On(\"GetOauthService\").Return(suite.oauthServiceMock)\n\n\t// Mock AuthClient to return a mock client\n\tsuite.oauthServiceMock.On(\"AuthClient\", \"test_client_1\", \"test_secret\").\n\t\tReturn(account.OauthClient, nil)\n\n\t// Mock FindAccountByOauthClientID to return the wanted account\n\tsuite.accountsServiceMock.\n\t\tOn(\"FindAccountByOauthClientID\", account.OauthClient.ID).\n\t\tReturn(account, nil)\n}", "func TestConfigure_NewSpineASN(t *testing.T) {\n\tExpectedASN := \"64512\"\n\n\tMockSpineDeviceAdapter := mock.DeviceAdapter{\n\t\tMockGetInterfaces: func(FabricID uint, DeviceID uint, DeviceIP string) ([]domain.Interface, error) {\n\n\t\t\treturn []domain.Interface{domain.Interface{FabricID: FabricID, DeviceID: DeviceID,\n\t\t\t\tIntType: \"ethernet\", IntName: \"1/11\", Mac: \"M1\", ConfigState: \"up\"}}, nil\n\n\t\t},\n\t\tMockGetLLDPs: func(FabricID uint, DeviceID uint, DeviceIP string) ([]domain.LLDP, error) {\n\n\t\t\treturn []domain.LLDP{domain.LLDP{FabricID: FabricID, DeviceID: DeviceID,\n\t\t\t\tLocalIntType: \"ethernet\", LocalIntName: \"1/11\", LocalIntMac: \"M1\",\n\t\t\t\tRemoteIntType: \"ethernet\", RemoteIntName: \"1/22\", RemoteIntMac: \"M2\"}}, nil\n\n\t\t},\n\t}\n\n\tdatabase.Setup(constants.TESTDBLocation)\n\tdefer cleanupDB(database.GetWorkingInstance())\n\n\tDatabaseRepository := gateway.DatabaseRepository{Database: database.GetWorkingInstance()}\n\tdevUC := usecase.DeviceInteractor{Db: &DatabaseRepository, DeviceAdapterFactory: mock.GetDeviceAdapterFactory(MockSpineDeviceAdapter)}\n\tdevUC.AddFabric(context.Background(), MockFabricName)\n\n\tresp, err := devUC.AddDevices(context.Background(), MockFabricName, []string{}, []string{MockSpine1IP},\n\t\tUserName, Password, false)\n\tassert.Contains(t, resp, usecase.AddDeviceResponse{FabricName: MockFabricName, FabricID: 1, IPAddress: MockSpine1IP, Role: usecase.SpineRole})\n\n\tassert.Nil(t, err)\n\tswitchConfig, err := DatabaseRepository.GetSwitchConfigOnDeviceIP(MockFabricName, MockSpine1IP)\n\t//Verify ASN is the first ASN from the Pool\n\tassert.Equal(t, ExpectedASN, switchConfig.LocalAS)\n\t//Verify ASN is to be created\n\tassert.Equal(t, domain.ConfigCreate, switchConfig.ASConfigType)\n}", "func (m *MockInterface) Init(kubeconfigPath, kubeconfigContext string) error {\n\treturn nil\n}", "func mockTestUserInteraction(ctx context.Context, pro providerParams, username, password string) (string, error) {\n\tctx, cancel := context.WithTimeout(ctx, 10*time.Second)\n\tdefer cancel()\n\n\tprovider, err := oidc.NewProvider(ctx, pro.providerURL)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"unable to create provider: %v\", err)\n\t}\n\n\t// Configure an OpenID Connect aware OAuth2 client.\n\toauth2Config := oauth2.Config{\n\t\tClientID: pro.clientID,\n\t\tClientSecret: pro.clientSecret,\n\t\tRedirectURL: pro.redirectURL,\n\n\t\t// Discovery returns the OAuth2 endpoints.\n\t\tEndpoint: provider.Endpoint(),\n\n\t\t// \"openid\" is a required scope for OpenID Connect flows.\n\t\tScopes: []string{oidc.ScopeOpenID, \"groups\"},\n\t}\n\n\tstate := \"xxx\"\n\tauthCodeURL := oauth2Config.AuthCodeURL(state)\n\t// fmt.Printf(\"authcodeurl: %s\\n\", authCodeURL)\n\n\tvar lastReq *http.Request\n\tcheckRedirect := func(req *http.Request, via []*http.Request) error {\n\t\t// fmt.Printf(\"CheckRedirect:\\n\")\n\t\t// fmt.Printf(\"Upcoming: %s %#v\\n\", req.URL.String(), req)\n\t\t// for _, c := range via {\n\t\t// \tfmt.Printf(\"Sofar: %s %#v\\n\", c.URL.String(), c)\n\t\t// }\n\t\t// Save the last request in a redirect chain.\n\t\tlastReq = req\n\t\t// We do not follow redirect back to client application.\n\t\tif req.URL.Path == \"/oauth_callback\" {\n\t\t\treturn http.ErrUseLastResponse\n\t\t}\n\t\treturn nil\n\t}\n\n\tdexClient := http.Client{\n\t\tCheckRedirect: checkRedirect,\n\t}\n\n\tu, err := url.Parse(authCodeURL)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"url parse err: %v\", err)\n\t}\n\n\t// Start the user auth flow. This page would present the login with\n\t// email or LDAP option.\n\treq, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"new request err: %v\", err)\n\t}\n\t_, err = dexClient.Do(req)\n\t// fmt.Printf(\"Do: %#v %#v\\n\", resp, err)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"auth url request err: %v\", err)\n\t}\n\n\t// Modify u to choose the ldap option\n\tu.Path += \"/ldap\"\n\t// fmt.Println(u)\n\n\t// Pick the LDAP login option. This would return a form page after\n\t// following some redirects. `lastReq` would be the URL of the form\n\t// page, where we need to POST (submit) the form.\n\treq, err = http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"new request err (/ldap): %v\", err)\n\t}\n\t_, err = dexClient.Do(req)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"request err: %v\", err)\n\t}\n\n\t// Fill the login form with our test creds:\n\t// fmt.Printf(\"login form url: %s\\n\", lastReq.URL.String())\n\tformData := url.Values{}\n\tformData.Set(\"login\", username)\n\tformData.Set(\"password\", password)\n\treq, err = http.NewRequestWithContext(ctx, http.MethodPost, lastReq.URL.String(), strings.NewReader(formData.Encode()))\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"new request err (/login): %v\", err)\n\t}\n\treq.Header.Set(\"Content-Type\", \"application/x-www-form-urlencoded\")\n\t_, err = dexClient.Do(req)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"post form err: %v\", err)\n\t}\n\t// fmt.Printf(\"resp: %#v %#v\\n\", resp.StatusCode, resp.Header)\n\t// fmt.Printf(\"lastReq: %#v\\n\", lastReq.URL.String())\n\n\t// On form submission, the last redirect response contains the auth\n\t// code, which we now have in `lastReq`. Exchange it for a JWT id_token.\n\tq := lastReq.URL.Query()\n\tcode := q.Get(\"code\")\n\toauth2Token, err := oauth2Config.Exchange(ctx, code)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"unable to exchange code for id token: %v\", err)\n\t}\n\n\trawIDToken, ok := oauth2Token.Extra(\"id_token\").(string)\n\tif !ok {\n\t\treturn \"\", fmt.Errorf(\"id_token not found!\")\n\t}\n\n\t// fmt.Printf(\"TOKEN: %s\\n\", rawIDToken)\n\treturn rawIDToken, nil\n}", "func (m *MockNodeAttestorServer) Configure(arg0 context.Context, arg1 *plugin.ConfigureRequest) (*plugin.ConfigureResponse, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Configure\", arg0, arg1)\n\tret0, _ := ret[0].(*plugin.ConfigureResponse)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (p *httpMockProvider) configure() error {\n\tlog.Println(\"[DEBUG] pact setup\")\n\tdir, _ := os.Getwd()\n\n\tif p.config.Host == \"\" {\n\t\tp.config.Host = \"127.0.0.1\"\n\t}\n\n\tif p.config.LogDir == \"\" {\n\t\tp.config.LogDir = filepath.Join(dir, \"logs\")\n\t}\n\n\tif p.config.PactDir == \"\" {\n\t\tp.config.PactDir = filepath.Join(dir, \"pacts\")\n\t}\n\n\tif p.config.ClientTimeout == 0 {\n\t\tp.config.ClientTimeout = 10 * time.Second\n\t}\n\n\tp.mockserver = native.NewHTTPPact(p.config.Consumer, p.config.Provider)\n\tswitch p.specificationVersion {\n\tcase models.V2:\n\t\tp.mockserver.WithSpecificationVersion(native.SPECIFICATION_VERSION_V2)\n\tcase models.V3:\n\t\tp.mockserver.WithSpecificationVersion(native.SPECIFICATION_VERSION_V3)\n\tcase models.V4:\n\t\tp.mockserver.WithSpecificationVersion(native.SPECIFICATION_VERSION_V4)\n\t}\n\tnative.Init(string(logging.LogLevel()))\n\n\treturn nil\n}", "func (m *GraphBaseServiceClient) Identity()(*i79ca23a9ac0659e1330dd29e049fe157787d5af6695ead2ff8263396db68d027.IdentityRequestBuilder) {\n return i79ca23a9ac0659e1330dd29e049fe157787d5af6695ead2ff8263396db68d027.NewIdentityRequestBuilderInternal(m.pathParameters, m.requestAdapter);\n}", "func (m *GraphBaseServiceClient) Identity()(*i79ca23a9ac0659e1330dd29e049fe157787d5af6695ead2ff8263396db68d027.IdentityRequestBuilder) {\n return i79ca23a9ac0659e1330dd29e049fe157787d5af6695ead2ff8263396db68d027.NewIdentityRequestBuilderInternal(m.pathParameters, m.requestAdapter);\n}", "func TestRevokedIdentity(t *testing.T) {\n\ttestHome := t.TempDir()\n\tserverdir := filepath.Join(testdataDir, \"server\")\n\n\tsrv := TestGetServer(ctport1, serverdir, \"\", -1, t)\n\terr := srv.Start()\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to start server: %s\", err)\n\t}\n\tdefer func() {\n\t\terr := srv.Stop()\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Server stop failed: %s\", err)\n\t\t}\n\t\terr = os.RemoveAll(serverdir)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"RemoveAll failed: %s\", err)\n\t\t}\n\t\terr = os.RemoveAll(testHome)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"RemoveAll failed: %s\", err)\n\t\t}\n\t}()\n\n\t// Enroll admin\n\tc := &Client{\n\t\tConfig: &ClientConfig{URL: fmt.Sprintf(\"http://localhost:%d\", ctport1)},\n\t\tHomeDir: filepath.Join(testHome, \"admin\"),\n\t}\n\n\tenrollReq := &api.EnrollmentRequest{\n\t\tName: \"admin\",\n\t\tSecret: \"adminpw\",\n\t}\n\n\teresp, err := c.Enroll(enrollReq)\n\tif err != nil {\n\t\tt.Fatalf(\"Enrollment of admin failed: %s\", err)\n\t}\n\n\tadmin_id := eresp.Identity\n\n\t// 'admin' registers 'TestUser' user\n\tregisterReq := &api.RegistrationRequest{\n\t\tName: \"TestUser\",\n\t\tType: \"user\",\n\t\tAffiliation: \"hyperledger\",\n\t\tMaxEnrollments: 2,\n\t}\n\n\tresp, err := admin_id.Register(registerReq)\n\tif err != nil {\n\t\tt.Fatalf(\"Register failed: %s\", err)\n\t}\n\n\t// Enroll 'TestUser'\n\tTestUserClient := &Client{\n\t\tConfig: &ClientConfig{URL: fmt.Sprintf(\"http://localhost:%d\", ctport1)},\n\t\tHomeDir: filepath.Join(testHome, \"TestUserClient\"),\n\t}\n\n\tenrollReq = &api.EnrollmentRequest{\n\t\tName: \"TestUser\",\n\t\tSecret: resp.Secret,\n\t}\n\n\teresp2, err := TestUserClient.Enroll(enrollReq)\n\tif err != nil {\n\t\tt.Fatalf(\"Enrollment of TestUser failed: %s\", err)\n\t}\n\n\ttestuserid := eresp2.Identity\n\n\t// Enroll 'TestUser' again with a different home/msp directory\n\tTestUserClient2 := &Client{\n\t\tConfig: &ClientConfig{URL: fmt.Sprintf(\"http://localhost:%d\", ctport1)},\n\t\tHomeDir: filepath.Join(testHome, \"TestUserClient2\"),\n\t}\n\n\tenrollReq = &api.EnrollmentRequest{\n\t\tName: \"TestUser\",\n\t\tSecret: resp.Secret,\n\t}\n\n\teresp3, err := TestUserClient2.Enroll(enrollReq)\n\tif err != nil {\n\t\tt.Fatalf(\"Enrollment of TestUser failed: %s\", err)\n\t}\n\n\ttestuserid2 := eresp3.Identity\n\n\t// 'admin' revokes user 'TestUser'\n\trevReq := &api.RevocationRequest{\n\t\tName: \"TestUser\",\n\t\tGenCRL: true,\n\t}\n\n\t_, err = admin_id.Revoke(revReq)\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to revoke TestUser identity: %s\", err)\n\t}\n\n\t// After an identity has been revoked, all subsequent commands invoked by revoked user should be rejected by server\n\t// for all its issued certificates\n\t_, err = TestUserClient2.Enroll(enrollReq)\n\tif err == nil {\n\t\tt.Fatalf(\"Enrollment of TestUser should have failed: %s\", err)\n\t}\n\n\t_, err = testuserid.Reenroll(&api.ReenrollmentRequest{})\n\tif err == nil {\n\t\tt.Fatalf(\"Reenrollment of TestUser identity should have failed: %s\", err)\n\t}\n\n\t_, err = testuserid2.Reenroll(&api.ReenrollmentRequest{})\n\tif err == nil {\n\t\tt.Fatalf(\"Reenrollment of TestUser identity should have failed: %s\", err)\n\t}\n\n\t_, err = testuserid.Register(registerReq)\n\tif err == nil {\n\t\tt.Fatalf(\"Registration of TestUser identity should have failed: %s\", err)\n\t}\n\n\t_, err = testuserid2.Register(registerReq)\n\tif err == nil {\n\t\tt.Fatalf(\"Registration of TestUser identity should have failed: %s\", err)\n\t}\n\n\t_, err = testuserid.Revoke(&api.RevocationRequest{\n\t\tName: \"admin\",\n\t})\n\tif err == nil {\n\t\tt.Fatalf(\"Revocation of 'admin' identity should have failed: %s\", err)\n\t}\n\n\t_, err = testuserid2.Revoke(&api.RevocationRequest{\n\t\tName: \"admin\",\n\t})\n\tif err == nil {\n\t\tt.Fatalf(\"Revocation of 'admin' identity should have failed: %s\", err)\n\t}\n\n\tc = new(Client)\n\tc.Config = new(ClientConfig)\n\tc.Config.URL = fmt.Sprintf(\"http://localhost:%d\", ctport1)\n\n\t// Bad TLS\n\tc.Config.MSPDir = \"msp\"\n\tvar kc tls.KeyCertFiles\n\tkc.KeyFile = \"../testdata/ec_key.pem\"\n\tkc.CertFile = \"../testdata/expiredcert.pem\"\n\tc.Config.MSPDir = \"\"\n\tc.Config.URL = \"\"\n\tc.Config.TLS.Enabled = true\n\tc.Config.TLS.CertFiles = []string{\"../testdata/ec.pem\"}\n\tc.Config.TLS.Client = kc\n\tcurl := fmt.Sprintf(\"http://localhost:%d/api/v1/register\", ctport1)\n\treqBody := []byte(\"\")\n\treq, _ := http.NewRequest(\"POST\", curl, bytes.NewReader(reqBody))\n\terr = c.SendReq(req, nil)\n\tt.Logf(\"Client SendReq() error %v\", err)\n\tif err == nil {\n\t\tt.Error(\"Sending post with bad TLS config should have failed\")\n\t}\n\n\terr = GenerateECDSATestCert()\n\tutil.FatalError(t, err, \"Failed to generate certificate for testing\")\n\tkc.CertFile = \"../testdata/ec_cert.pem\"\n\tc.Config.TLS.Client = kc\n\treq, _ = http.NewRequest(\"POST\", curl, bytes.NewReader(reqBody))\n\terr = c.SendReq(req, nil)\n\tt.Logf(\"Client SendReq() error %v\", err)\n\tif err == nil {\n\t\tt.Error(\"Sending post with bad TLS config should have failed\")\n\t}\n\n\t// Bad URL\n\tcurl = fmt.Sprintf(\"http://localhost:%d/fake\", ctport1)\n\treqBody = []byte(\"\")\n\treq, _ = http.NewRequest(\"POST\", curl, bytes.NewReader(reqBody))\n\terr = c.SendReq(req, nil)\n\tt.Logf(\"Client SendReq() error %v\", err)\n\tif err == nil {\n\t\tt.Error(\"Sending post with bad URL should have failed\")\n\t}\n\n\t// No authorization header\n\tcurl = fmt.Sprintf(\"http://localhost:%d/api/v1/revoke\", ctport1)\n\treqBody = []byte(\"\")\n\treq, _ = http.NewRequest(\"POST\", curl, bytes.NewReader(reqBody))\n\terr = c.SendReq(req, nil)\n\tt.Logf(\"Client SendReq() error %v\", err)\n\tif err == nil {\n\t\tt.Error(\"Sending register with no authorization header should have failed\")\n\t}\n\n\t// Bad authorization header\n\tcurl = fmt.Sprintf(\"http://localhost:%d/api/v1/register\", ctport1)\n\treqBody = []byte(\"\")\n\treq, _ = http.NewRequest(\"POST\", curl, bytes.NewReader(reqBody))\n\treq.Header.Add(\"Authorization\", \"bad-auth\")\n\terr = c.SendReq(req, nil)\n\tt.Logf(\"Client SendReq() error %v\", err)\n\tif err == nil {\n\t\tt.Error(\"Sending register with bad authorization header should have failed\")\n\t}\n\n\t// Bad Init\n\tc2 := new(Client)\n\tc2.Config = new(ClientConfig)\n\tc2.Config.URL = fmt.Sprintf(\"http://localhost:%d\", ctport1)\n\tc2.Config.MSPDir = string(make([]byte, 1))\n\tcurl = fmt.Sprintf(\"http://localhost:%d/api/v1/register\", ctport1)\n\treqBody = []byte(\"\")\n\treq, _ = http.NewRequest(\"POST\", curl, bytes.NewReader(reqBody))\n\terr = c2.SendReq(req, nil)\n\tt.Logf(\"Client SendReq() error %v\", err)\n\tif err == nil {\n\t\tt.Error(\"Sending post with bad Init should have failed\")\n\t}\n}", "func mockConfigDir() (string, error) {\n\treturn \"/tmp/CONFIG/datamaps/\", nil\n}", "func TestGetConfigForClient(t *testing.T) {\n\t// TODO(r0mant): Implement this.\n\tt.Skip(\"Not Implemented\")\n}", "func TestConfigure_UseExistingASN(t *testing.T) {\n\tASNOnDevice := \"65001\"\n\tMockLeafDeviceAdapter := mock.DeviceAdapter{\n\t\tMockGetInterfaces: func(FabricID uint, DeviceID uint, DeviceIP string) ([]domain.Interface, error) {\n\n\t\t\treturn []domain.Interface{domain.Interface{FabricID: FabricID, DeviceID: DeviceID,\n\t\t\t\tIntType: \"ethernet\", IntName: \"1/11\", Mac: \"M1\", ConfigState: \"up\"}}, nil\n\n\t\t},\n\t\tMockGetLLDPs: func(FabricID uint, DeviceID uint, DeviceIP string) ([]domain.LLDP, error) {\n\n\t\t\treturn []domain.LLDP{domain.LLDP{FabricID: FabricID, DeviceID: DeviceID,\n\t\t\t\tLocalIntType: \"ethernet\", LocalIntName: \"1/11\", LocalIntMac: \"M1\",\n\t\t\t\tRemoteIntType: \"ethernet\", RemoteIntName: \"1/22\", RemoteIntMac: \"M2\"}}, nil\n\n\t\t},\n\t\tMockGetASN: func(FabricID uint, Device uint, DeviceIP string) (string, error) {\n\t\t\treturn ASNOnDevice, nil\n\t\t},\n\t}\n\n\tdatabase.Setup(constants.TESTDBLocation)\n\tdefer cleanupDB(database.GetWorkingInstance())\n\n\tDatabaseRepository := gateway.DatabaseRepository{Database: database.GetWorkingInstance()}\n\tdevUC := usecase.DeviceInteractor{Db: &DatabaseRepository, DeviceAdapterFactory: mock.GetDeviceAdapterFactory(MockLeafDeviceAdapter)}\n\tdevUC.AddFabric(context.Background(), MockFabricName)\n\n\tresp, err := devUC.AddDevices(context.Background(), MockFabricName, []string{MockLeaf1IP}, []string{},\n\t\tUserName, Password, false)\n\tassert.Contains(t, resp, usecase.AddDeviceResponse{FabricName: MockFabricName, FabricID: 1, IPAddress: MockLeaf1IP, Role: usecase.LeafRole})\n\n\tassert.Nil(t, err)\n\n\tswitchConfig, err := DatabaseRepository.GetSwitchConfigOnDeviceIP(MockFabricName, MockLeaf1IP)\n\tassert.Equal(t, ASNOnDevice, switchConfig.LocalAS)\n\t//Verify ASN is already on the Switch, so need to push\n\tassert.Equal(t, domain.ConfigNone, switchConfig.ASConfigType)\n\n\t//Next Call without Device having ASN\n\tMockLeafDeviceAdapterWithoutASN := mock.DeviceAdapter{\n\t\tMockGetInterfaces: func(FabricID uint, DeviceID uint, DeviceIP string) ([]domain.Interface, error) {\n\n\t\t\treturn []domain.Interface{domain.Interface{FabricID: FabricID, DeviceID: DeviceID,\n\t\t\t\tIntType: \"ethernet\", IntName: \"1/11\", Mac: \"M1\", ConfigState: \"up\"}}, nil\n\n\t\t},\n\t\tMockGetLLDPs: func(FabricID uint, DeviceID uint, DeviceIP string) ([]domain.LLDP, error) {\n\n\t\t\treturn []domain.LLDP{domain.LLDP{FabricID: FabricID, DeviceID: DeviceID,\n\t\t\t\tLocalIntType: \"ethernet\", LocalIntName: \"1/11\", LocalIntMac: \"M1\",\n\t\t\t\tRemoteIntType: \"ethernet\", RemoteIntName: \"1/22\", RemoteIntMac: \"M2\"}}, nil\n\n\t\t},\n\t}\n\tdevUC.DeviceAdapterFactory = mock.GetDeviceAdapterFactory(MockLeafDeviceAdapterWithoutASN)\n\tresp, err = devUC.AddDevices(context.Background(), MockFabricName, []string{MockLeaf1IP}, []string{},\n\t\tUserName, Password, false)\n\tassert.Contains(t, resp, usecase.AddDeviceResponse{FabricName: MockFabricName, FabricID: 1, IPAddress: MockLeaf1IP, Role: usecase.LeafRole})\n\n\tassert.Nil(t, err)\n\tswitchConfigSecond, err := DatabaseRepository.GetSwitchConfigOnDeviceIP(MockFabricName, MockLeaf1IP)\n\tassert.Equal(t, ASNOnDevice, switchConfigSecond.LocalAS)\n\t//Verify ASN is to be created\n\tassert.Equal(t, domain.ConfigCreate, switchConfigSecond.ASConfigType)\n}", "func FakeConfig(num int) Config {\n\tcfg := DefaultConfig()\n\tcfg.EmitIntervals.Max = 10 * time.Second // don't wait long in fakenet\n\tcfg.EmitIntervals.DoublesignProtection = cfg.EmitIntervals.Max / 2\n\tif num <= 1 {\n\t\t// disable self-fork protection if fakenet 1/1\n\t\tcfg.EmitIntervals.DoublesignProtection = 0\n\t}\n\treturn cfg\n}", "func ConfigureForTest(t *testing.T) {\n\tConfigureCachingForTest(t, \"\")\n}", "func (s *TestSuiteIAM) SetUpOpenID(c *check, serverAddr string, rolePolicy string) {\n\tctx, cancel := context.WithTimeout(context.Background(), testDefaultTimeout)\n\tdefer cancel()\n\n\tconfigCmds := []string{\n\t\t\"identity_openid\",\n\t\tfmt.Sprintf(\"config_url=%s/.well-known/openid-configuration\", serverAddr),\n\t\t\"client_id=minio-client-app\",\n\t\t\"client_secret=minio-client-app-secret\",\n\t\t\"scopes=openid,groups\",\n\t\t\"redirect_uri=http://127.0.0.1:10000/oauth_callback\",\n\t}\n\tif rolePolicy != \"\" {\n\t\tconfigCmds = append(configCmds, fmt.Sprintf(\"role_policy=%s\", rolePolicy))\n\t} else {\n\t\tconfigCmds = append(configCmds, \"claim_name=groups\")\n\t}\n\t_, err := s.adm.SetConfigKV(ctx, strings.Join(configCmds, \" \"))\n\tif err != nil {\n\t\tc.Fatalf(\"unable to setup OpenID for tests: %v\", err)\n\t}\n\n\ts.RestartIAMSuite(c)\n}", "func (m *MockCAClient) GetIdentity(arg0, arg1 string) (*api.IdentityResponse, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetIdentity\", arg0, arg1)\n\tret0, _ := ret[0].(*api.IdentityResponse)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func NewIdentityProvider() users.IdentityProvider {\n\treturn &identityProviderMock{}\n}", "func verifyConfiguration(t *testing.T, accessKeyID, secretAccessKey, sessionToken string) {\n\n\t// Load the current file contents\n\tcfg, err := ini.Load(fakeCredentialsFilePath)\n\trequire.Nil(t, err, \"error reading the test credentials file\")\n\n\t// Confirm thet the default credentials are set as expected\n\tdefaultSection, err := cfg.GetSection(DefaultSectionName)\n\trequire.Nil(t, err, \"default section not found in credentials file\")\n\trequire.Equal(t, defaultSection.Key(AccessKeyIDKey).Value(), fakeAccessKeyID, \"default section, unexpected access key value: [%s]\", defaultSection.Key(AccessKeyIDKey).Value())\n\trequire.Equal(t, defaultSection.Key(SecretAccessKeyKey).Value(), fakeSecretAccessKey, \"default section, unexpected secret key value: [%s]\", defaultSection.Key(SecretAccessKeyKey).Value())\n\n\t// Confirm that the default-session section is as expected\n\tsessionSection, err := cfg.GetSection(SessionSectionName)\n\trequire.Nil(t, err, \"session section not found in credentials file\")\n\trequire.Equal(t, sessionSection.Key(AccessKeyIDKey).Value(), accessKeyID, \"default-session section, unexpected access key value: [%s]\", defaultSection.Key(AccessKeyIDKey).Value())\n\trequire.Equal(t, sessionSection.Key(SecretAccessKeyKey).Value(), secretAccessKey, \"default-session section, unexpected secret key value: [%s]\", defaultSection.Key(SecretAccessKeyKey).Value())\n\trequire.Equal(t, sessionSection.Key(SessionTokenKey).Value(), sessionToken, \"default-session section, unexpected session token value: [%s]\", defaultSection.Key(SessionTokenKey).Value())\n}", "func makeTestCreateConfig() *CreateConfig {\n\tcc := new(CreateConfig)\n\tcc.Resources = CreateResourceConfig{}\n\tcc.User.IDMappings = new(storage.IDMappingOptions)\n\tcc.User.IDMappings.UIDMap = []idtools.IDMap{}\n\tcc.User.IDMappings.GIDMap = []idtools.IDMap{}\n\n\treturn cc\n}", "func (m *MockCAClient) GetAllIdentities(arg0 string) ([]*api.IdentityResponse, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetAllIdentities\", arg0)\n\tret0, _ := ret[0].([]*api.IdentityResponse)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockProviders) EndpointConfig() fab.EndpointConfig {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"EndpointConfig\")\n\tret0, _ := ret[0].(fab.EndpointConfig)\n\treturn ret0\n}", "func (suite *AuthSuite) TestAuthUnknownServiceMember() {\n\t// Set up: Prepare the session, goth.User, callback handler, http response\n\t// and request, landing URL, and pass them into authorizeUnknownUser\n\n\thandlerConfig := suite.HandlerConfig()\n\tappnames := handlerConfig.AppNames()\n\n\t// Prepare the session and session manager\n\tfakeToken := \"some_token\"\n\tsession := auth.Session{\n\t\tApplicationName: auth.MilApp,\n\t\tIDToken: fakeToken,\n\t\tHostname: appnames.MilServername,\n\t}\n\tsessionManager := handlerConfig.SessionManagers().Mil\n\tmockSender := setUpMockNotificationSender() // We should get an email for this activity\n\n\t// Prepare the goth.User to simulate the UUID and email that login.gov would\n\t// provide\n\tfakeUUID, _ := uuid.NewV4()\n\tuser := goth.User{\n\t\tUserID: fakeUUID.String(),\n\t\tEmail: \"new_service_member@example.com\",\n\t}\n\tctx := suite.SetupSessionContext(context.Background(), &session, sessionManager)\n\n\t// Call the function under test\n\tresult := authorizeUnknownUser(ctx, suite.AppContextWithSessionForTest(&session), user,\n\t\tsessionManager, mockSender)\n\tsuite.Equal(authorizationResultAuthorized, result)\n\tmockSender.(*mocks.NotificationSender).AssertNumberOfCalls(suite.T(), \"SendNotification\", 1)\n\n\t// Look up the user and service member in the test DB\n\tfoundUser, _ := models.GetUserFromEmail(suite.DB(), user.Email)\n\tserviceMemberID := session.ServiceMemberID\n\tserviceMember, _ := models.FetchServiceMemberForUser(suite.DB(), &session, serviceMemberID)\n\t// Look up the session token in the session store (this test uses the memory store)\n\tsessionStore := sessionManager.Store()\n\t_, existsBefore, _ := sessionStore.Find(foundUser.CurrentMilSessionID)\n\n\t// Verify service member exists and its ID is populated in the session\n\tsuite.NotEmpty(session.ServiceMemberID)\n\n\t// Verify session contains UserID that points to the newly-created user\n\tsuite.Equal(foundUser.ID, session.UserID)\n\n\t// Verify user's LoginGovEmail and LoginGovUUID match the values passed in\n\tsuite.Equal(user.Email, foundUser.LoginGovEmail)\n\tsuite.Equal(user.UserID, foundUser.LoginGovUUID.String())\n\n\t// Verify that the user's CurrentMilSessionID is not empty. The value is\n\t// generated randomly, so we can't test for a specific string. Any string\n\t// except an empty string is acceptable.\n\tsuite.NotEqual(\"\", foundUser.CurrentMilSessionID)\n\n\t// Verify the session token also exists in the session store\n\tsuite.Equal(true, existsBefore)\n\n\t// Verify the service member that was created is associated with the user\n\t// that was created\n\tsuite.Equal(foundUser.ID, serviceMember.UserID)\n}", "func (m *CommunicationsIdentitySet) SetAssertedIdentity(value Identityable)() {\n err := m.GetBackingStore().Set(\"assertedIdentity\", value)\n if err != nil {\n panic(err)\n }\n}", "func (n *mockAgent) init(ctx context.Context, sandbox *Sandbox, config KataAgentConfig) (bool, error) {\n\treturn false, nil\n}", "func Test_Session_Custom_Config(t *testing.T) {\n\tt.Parallel()\n\n\tstore := New(Config{Expiration: time.Hour, KeyGenerator: func() string { return \"very random\" }})\n\tutils.AssertEqual(t, time.Hour, store.Expiration)\n\tutils.AssertEqual(t, \"very random\", store.KeyGenerator())\n\n\tstore = New(Config{Expiration: 0})\n\tutils.AssertEqual(t, ConfigDefault.Expiration, store.Expiration)\n}", "func (m *MockClient) EndpointConfig() fab.EndpointConfig {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"EndpointConfig\")\n\tret0, _ := ret[0].(fab.EndpointConfig)\n\treturn ret0\n}", "func mockOAuthServer() *httptest.Server {\n\t// prepare a port for the mocked server\n\tserver := httptest.NewUnstartedServer(http.DefaultServeMux)\n\n\t// mock the used REST path for the tests\n\tmockedHandler := http.NewServeMux()\n\tmockedHandler.HandleFunc(\"/.well-known/openid-configuration\", func(writer http.ResponseWriter, request *http.Request) {\n\t\ts := fmt.Sprintf(`{\n \"issuer\":\"%s\",\n \"authorization_endpoint\":\"%s/authorize\",\n \"token_endpoint\":\"%s/oauth/token\",\n \"device_authorization_endpoint\":\"%s/oauth/device/code\"\n}`, server.URL, server.URL, server.URL, server.URL)\n\t\tfmt.Fprintln(writer, s)\n\t})\n\tmockedHandler.HandleFunc(\"/oauth/token\", func(writer http.ResponseWriter, request *http.Request) {\n\t\tfmt.Fprintln(writer, \"{\\n \\\"access_token\\\": \\\"token-content\\\",\\n \\\"token_type\\\": \\\"Bearer\\\"\\n}\")\n\t})\n\tmockedHandler.HandleFunc(\"/authorize\", func(writer http.ResponseWriter, request *http.Request) {\n\t\tfmt.Fprintln(writer, \"true\")\n\t})\n\n\tserver.Config.Handler = mockedHandler\n\tserver.Start()\n\n\treturn server\n}", "func setFakeCredentials() {\n\n\t// Start with an empty configuration file content structure\n\tcfg := ini.Empty()\n\n\t// Populate it with the basics\n\tdefaultSection, err := cfg.NewSection(mfile.DefaultSectionName)\n\tdefaultSection.NewKey(mfile.AccessKeyIDKey, fakeAccessKeyID)\n\tdefaultSection.NewKey(mfile.SecretAccessKeyKey, fakeSecretAccessKey)\n\tdefaultSection.NewKey(mfile.MfaDeviceIDKey, fakeMFADeviceID)\n\n\t// Write the file\n\terr = cfg.SaveTo(fakeCredentialsFilePath)\n\n\t// That really should not faile to wrote, but if it did abort the tests\n\t// cos nothing will work after this\n\tif err != nil {\n\t\tfmt.Printf(\"\\nFailed to write fake credentials: %s\\n\", err.Error())\n\t\tos.Exit(999)\n\t}\n\n\t// All looks good - trick the package into using the fake file we just wrote\n\tmfile.OverrideDefaultCredentialsFilepath(fakeCredentialsFilePath)\n}", "func (m *MockEngine) ConfigureContainerVethInterface(arg0 string, arg1 *current.Result, arg2 string) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ConfigureContainerVethInterface\", arg0, arg1, arg2)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func TestConfigure_ReserveSameASN(t *testing.T) {\n\tASNOnDevice := \"65000\"\n\n\tMockLeafDeviceAdapterInitial := mock.DeviceAdapter{\n\t\tMockGetInterfaces: func(FabricID uint, DeviceID uint, DeviceIP string) ([]domain.Interface, error) {\n\n\t\t\treturn []domain.Interface{domain.Interface{FabricID: FabricID, DeviceID: DeviceID,\n\t\t\t\tIntType: \"ethernet\", IntName: \"1/11\", Mac: \"M1\", ConfigState: \"up\"}}, nil\n\n\t\t},\n\t\tMockGetLLDPs: func(FabricID uint, DeviceID uint, DeviceIP string) ([]domain.LLDP, error) {\n\n\t\t\treturn []domain.LLDP{domain.LLDP{FabricID: FabricID, DeviceID: DeviceID,\n\t\t\t\tLocalIntType: \"ethernet\", LocalIntName: \"1/11\", LocalIntMac: \"M1\",\n\t\t\t\tRemoteIntType: \"ethernet\", RemoteIntName: \"1/22\", RemoteIntMac: \"M2\"}}, nil\n\n\t\t},\n\t}\n\tMockLeafDeviceAdapter := mock.DeviceAdapter{\n\t\tMockGetInterfaces: func(FabricID uint, DeviceID uint, DeviceIP string) ([]domain.Interface, error) {\n\n\t\t\treturn []domain.Interface{domain.Interface{FabricID: FabricID, DeviceID: DeviceID,\n\t\t\t\tIntType: \"ethernet\", IntName: \"1/11\", Mac: \"M1\", ConfigState: \"up\"}}, nil\n\n\t\t},\n\t\tMockGetLLDPs: func(FabricID uint, DeviceID uint, DeviceIP string) ([]domain.LLDP, error) {\n\n\t\t\treturn []domain.LLDP{domain.LLDP{FabricID: FabricID, DeviceID: DeviceID,\n\t\t\t\tLocalIntType: \"ethernet\", LocalIntName: \"1/11\", LocalIntMac: \"M1\",\n\t\t\t\tRemoteIntType: \"ethernet\", RemoteIntName: \"1/22\", RemoteIntMac: \"M2\"}}, nil\n\n\t\t},\n\t\tMockGetASN: func(FabricID uint, Device uint, DeviceIP string) (string, error) {\n\t\t\treturn ASNOnDevice, nil\n\t\t},\n\t}\n\n\tdatabase.Setup(constants.TESTDBLocation)\n\tdefer cleanupDB(database.GetWorkingInstance())\n\n\tDatabaseRepository := gateway.DatabaseRepository{Database: database.GetWorkingInstance()}\n\tdevUC := usecase.DeviceInteractor{Db: &DatabaseRepository, DeviceAdapterFactory: mock.GetDeviceAdapterFactory(MockLeafDeviceAdapterInitial)}\n\tdevUC.AddFabric(context.Background(), MockFabricName)\n\n\tresp, err := devUC.AddDevices(context.Background(), MockFabricName, []string{MockLeaf1IP}, []string{},\n\t\tUserName, Password, false)\n\tassert.Contains(t, resp, usecase.AddDeviceResponse{FabricName: MockFabricName, FabricID: 1, IPAddress: MockLeaf1IP, Role: usecase.LeafRole})\n\n\tassert.Nil(t, err)\n\n\tswitchConfig, err := DatabaseRepository.GetSwitchConfigOnDeviceIP(MockFabricName, MockLeaf1IP)\n\tassert.Equal(t, ASNOnDevice, switchConfig.LocalAS)\n\t//Verify ASN is to be created\n\tassert.Equal(t, domain.ConfigCreate, switchConfig.ASConfigType)\n\n\t//Call again requesting for SAME ASN\n\tdevUC.DeviceAdapterFactory = mock.GetDeviceAdapterFactory(MockLeafDeviceAdapter)\n\n\tresp, err = devUC.AddDevices(context.Background(), MockFabricName, []string{MockLeaf1IP}, []string{},\n\t\tUserName, Password, false)\n\tassert.Contains(t, resp, usecase.AddDeviceResponse{FabricName: MockFabricName, FabricID: 1, IPAddress: MockLeaf1IP, Role: usecase.LeafRole})\n\n\tassert.Nil(t, err)\n\tswitchConfigSecond, err := DatabaseRepository.GetSwitchConfigOnDeviceIP(MockFabricName, MockLeaf1IP)\n\tassert.Equal(t, ASNOnDevice, switchConfigSecond.LocalAS)\n\t//Verify ASN is to be created\n\tassert.Equal(t, domain.ConfigNone, switchConfigSecond.ASConfigType)\n\n}", "func TestLogin(w http.ResponseWriter, r *http.Request) {\n\n\tauthHeader := r.Header.Get(\"Authorization\")\n\tcookies := r.Cookies()\n\tvar token string\n\tfor _, c := range cookies {\n\t\tif c.Name == \"token\" {\n\t\t\ttoken = c.Value\n\t\t}\n\t}\n\n\tvar accessToken string\n\t// header value format will be \"Bearer <token>\"\n\tif authHeader != \"\" {\n\t\tif !strings.HasPrefix(authHeader, \"Bearer \") {\n\t\t\tlog.Errorf(\"GetMyIdentities Failed to find Bearer token %v\", authHeader)\n\t\t\tReturnHTTPError(w, r, http.StatusUnauthorized, \"Unauthorized, please provide a valid token\")\n\t\t\treturn\n\t\t}\n\t\taccessToken = strings.TrimPrefix(authHeader, \"Bearer \")\n\t}\n\n\tbytes, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\tlog.Errorf(\"TestLogin failed with error: %v\", err)\n\t\tReturnHTTPError(w, r, http.StatusBadRequest, \"Bad Request, Please check the request content\")\n\t\treturn\n\t}\n\tvar testAuthConfig model.TestAuthConfig\n\n\terr = json.Unmarshal(bytes, &testAuthConfig)\n\tif err != nil {\n\t\tlog.Errorf(\"TestLogin unmarshal failed with error: %v\", err)\n\t\tReturnHTTPError(w, r, http.StatusBadRequest, \"Bad Request, Please check the request content\")\n\t\treturn\n\t}\n\n\tif testAuthConfig.AuthConfig.Provider == \"\" {\n\t\tlog.Errorf(\"UpdateConfig: Provider is a required field\")\n\t\tReturnHTTPError(w, r, http.StatusBadRequest, \"Bad request, Provider is a required field\")\n\t\treturn\n\t}\n\n\tstatus, err := server.TestLogin(testAuthConfig, accessToken, token)\n\tif err != nil {\n\t\tlog.Errorf(\"TestLogin GetProvider failed with error: %v\", err)\n\t\tif status == 0 {\n\t\t\tstatus = http.StatusInternalServerError\n\t\t}\n\t\tReturnHTTPError(w, r, status, fmt.Sprintf(\"%v\", err))\n\t}\n}", "func (m *MockCAClient) ModifyIdentity(arg0 *api.IdentityRequest) (*api.IdentityResponse, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ModifyIdentity\", arg0)\n\tret0, _ := ret[0].(*api.IdentityResponse)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func makeUserIdentificationConfig(info clientauth.Info) *restclient.Config {\n\tconfig := &restclient.Config{}\n\tconfig.Username = info.User\n\tconfig.Password = info.Password\n\tconfig.CertFile = info.CertFile\n\tconfig.KeyFile = info.KeyFile\n\tconfig.BearerToken = info.BearerToken\n\treturn config\n}", "func initConfig() {\n\tcfgBldr := &config.ConfigurationBuilder{}\n\tSettings = &accountControllerConfiguration{}\n\tif err := cfgBldr.Unmarshal(Settings); err != nil {\n\t\tlog.Fatalf(\"Could not load configuration: %s\", err.Error())\n\t}\n\n\t// load up the values into the various settings...\n\terr := cfgBldr.WithEnv(\"AWS_CURRENT_REGION\", \"AWS_CURRENT_REGION\", \"us-east-1\").Build()\n\tif err != nil {\n\t\tlog.Printf(\"Error: %+v\", err)\n\t}\n\tsvcBldr := &config.ServiceBuilder{Config: cfgBldr}\n\n\t_, err = svcBldr.\n\t\t// AWS services...\n\t\tWithDynamoDB().\n\t\tWithSTS().\n\t\tWithS3().\n\t\tWithSNS().\n\t\tWithSQS().\n\t\t// DCE services...\n\t\tWithStorageService().\n\t\tWithDataService().\n\t\tBuild()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tServices = svcBldr\n\n\tpolicyName = Config.GetEnvVar(\"PRINCIPAL_POLICY_NAME\", \"DCEPrincipalDefaultPolicy\")\n\tartifactsBucket = Config.GetEnvVar(\"ARTIFACTS_BUCKET\", \"DefaultArtifactBucket\")\n\tprincipalPolicyS3Key = Config.GetEnvVar(\"PRINCIPAL_POLICY_S3_KEY\", \"DefaultPrincipalPolicyS3Key\")\n\tprincipalRoleName = Config.GetEnvVar(\"PRINCIPAL_ROLE_NAME\", \"DCEPrincipal\")\n\tprincipalIAMDenyTags = strings.Split(Config.GetEnvVar(\"PRINCIPAL_IAM_DENY_TAGS\", \"DefaultPrincipalIamDenyTags\"), \",\")\n\tprincipalMaxSessionDuration = int64(Config.GetEnvIntVar(\"PRINCIPAL_MAX_SESSION_DURATION\", 100))\n\ttags = []*iam.Tag{\n\t\t{Key: aws.String(\"Terraform\"), Value: aws.String(\"False\")},\n\t\t{Key: aws.String(\"Source\"), Value: aws.String(\"github.com/Optum/dce//cmd/lambda/accounts\")},\n\t\t{Key: aws.String(\"Environment\"), Value: aws.String(Config.GetEnvVar(\"TAG_ENVIRONMENT\", \"DefaultTagEnvironment\"))},\n\t\t{Key: aws.String(\"Contact\"), Value: aws.String(Config.GetEnvVar(\"TAG_CONTACT\", \"DefaultTagContact\"))},\n\t\t{Key: aws.String(\"AppName\"), Value: aws.String(Config.GetEnvVar(\"TAG_APP_NAME\", \"DefaultTagAppName\"))},\n\t}\n\taccountCreatedTopicArn = Config.GetEnvVar(\"ACCOUNT_CREATED_TOPIC_ARN\", \"DefaultAccountCreatedTopicArn\")\n\tresetQueueURL = Config.GetEnvVar(\"RESET_SQS_URL\", \"DefaultResetSQSUrl\")\n\tallowedRegions = strings.Split(Config.GetEnvVar(\"ALLOWED_REGIONS\", \"us-east-1\"), \",\")\n}", "func InitializeMockAuthenticationComponent() *AuthenticationComponent {\n\tlogInstance := core_logging.New(\"info\")\n\tdefer logInstance.ConfigureLogger()\n\tlog := logInstance.Logger\n\n\treturn mockAuthenticationComponent(log, svcName)\n}", "func (m *MockSaaSSystemConfigManager) Get(system, name string) (sdao.SaaSSystemConfig, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Get\", system, name)\n\tret0, _ := ret[0].(sdao.SaaSSystemConfig)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func mockNoopStore(id string, key string, value interface{}) {}", "func TestConfigure_ValidSpineASN(t *testing.T) {\n\tASNOnDevice := \"64512\"\n\tMockSpineDeviceAdapter := mock.DeviceAdapter{\n\t\tMockGetInterfaces: func(FabricID uint, DeviceID uint, DeviceIP string) ([]domain.Interface, error) {\n\n\t\t\treturn []domain.Interface{domain.Interface{FabricID: FabricID, DeviceID: DeviceID,\n\t\t\t\tIntType: \"ethernet\", IntName: \"1/11\", Mac: \"M1\", ConfigState: \"up\"}}, nil\n\n\t\t},\n\t\tMockGetLLDPs: func(FabricID uint, DeviceID uint, DeviceIP string) ([]domain.LLDP, error) {\n\n\t\t\treturn []domain.LLDP{domain.LLDP{FabricID: FabricID, DeviceID: DeviceID,\n\t\t\t\tLocalIntType: \"ethernet\", LocalIntName: \"1/11\", LocalIntMac: \"M1\",\n\t\t\t\tRemoteIntType: \"ethernet\", RemoteIntName: \"1/22\", RemoteIntMac: \"M2\"}}, nil\n\n\t\t},\n\t\tMockGetASN: func(FabricID uint, Device uint, DeviceIP string) (string, error) {\n\t\t\treturn ASNOnDevice, nil\n\t\t},\n\t}\n\n\tdatabase.Setup(constants.TESTDBLocation)\n\tdefer cleanupDB(database.GetWorkingInstance())\n\n\tDatabaseRepository := gateway.DatabaseRepository{Database: database.GetWorkingInstance()}\n\tdevUC := usecase.DeviceInteractor{Db: &DatabaseRepository, DeviceAdapterFactory: mock.GetDeviceAdapterFactory(MockSpineDeviceAdapter)}\n\tdevUC.AddFabric(context.Background(), MockFabricName)\n\n\tresp, err := devUC.AddDevices(context.Background(), MockFabricName, []string{}, []string{MockSpine1IP},\n\t\tUserName, Password, false)\n\tassert.Contains(t, resp, usecase.AddDeviceResponse{FabricName: MockFabricName, FabricID: 1, IPAddress: MockSpine1IP, Role: usecase.SpineRole})\n\n\tassert.Nil(t, err)\n\tswitchConfig, err := DatabaseRepository.GetSwitchConfigOnDeviceIP(MockFabricName, MockSpine1IP)\n\tassert.Equal(t, ASNOnDevice, switchConfig.LocalAS)\n\t//Verify ASN is to be created\n\tassert.Equal(t, domain.ConfigNone, switchConfig.ASConfigType)\n\n}", "func (b *Bot) generateIdentity(\n\tctx context.Context,\n\tcurrentIdentity *identity.Identity,\n\texpires time.Time,\n\tdestCfg *config.DestinationConfig,\n\tdefaultRoles []string,\n\tconfigurator identityConfigurator,\n) (*identity.Identity, error) {\n\t// TODO: enforce expiration > renewal period (by what margin?)\n\t// This should be ignored if a renewal has been triggered manually or\n\t// by a CA rotation.\n\n\t// Generate a fresh keypair for the impersonated identity. We don't care to\n\t// reuse keys here: impersonated certs might not be as well-protected so\n\t// constantly rotating private keys\n\tprivateKey, publicKey, err := native.GenerateKeyPair()\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\n\tvar roleRequests []string\n\tif len(destCfg.Roles) > 0 {\n\t\troleRequests = destCfg.Roles\n\t} else {\n\t\tb.log.Debugf(\"Destination specified no roles, defaults will be requested: %v\", defaultRoles)\n\t\troleRequests = defaultRoles\n\t}\n\n\treq := proto.UserCertsRequest{\n\t\tPublicKey: publicKey,\n\t\tUsername: currentIdentity.X509Cert.Subject.CommonName,\n\t\tExpires: expires,\n\t\tRoleRequests: roleRequests,\n\t\tRouteToCluster: currentIdentity.ClusterName,\n\n\t\t// Make sure to specify this is an impersonated cert request. If unset,\n\t\t// auth cannot differentiate renewable vs impersonated requests when\n\t\t// len(roleRequests) == 0.\n\t\tUseRoleRequests: true,\n\t}\n\n\tif configurator != nil {\n\t\tconfigurator(&req)\n\t}\n\n\t// First, ask the auth server to generate a new set of certs with a new\n\t// expiration date.\n\tclient := b.Client()\n\tcerts, err := client.GenerateUserCerts(ctx, req)\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\n\t// The root CA included with the returned user certs will only contain the\n\t// Teleport User CA. We'll also need the host CA for future API calls.\n\tlocalCA, err := client.GetClusterCACert(ctx)\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\n\tcaCerts, err := tlsca.ParseCertificatePEMs(localCA.TLSCA)\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\n\t// Append the host CAs from the auth server.\n\tfor _, cert := range caCerts {\n\t\tpemBytes, err := tlsca.MarshalCertificatePEM(cert)\n\t\tif err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\tcerts.TLSCACerts = append(certs.TLSCACerts, pemBytes)\n\t}\n\n\t// Do not trust SSH CA certs as returned by GenerateUserCerts() with an\n\t// impersonated identity. It only returns the SSH UserCA in this context,\n\t// but we also need the HostCA and can't directly set `includeHostCA` as\n\t// part of the UserCertsRequest.\n\t// Instead, copy the SSHCACerts from the primary identity.\n\tcerts.SSHCACerts = currentIdentity.SSHCACertBytes\n\n\tnewIdentity, err := identity.ReadIdentityFromStore(&identity.LoadIdentityParams{\n\t\tPrivateKeyBytes: privateKey,\n\t\tPublicKeyBytes: publicKey,\n\t}, certs, identity.DestinationKinds()...)\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\n\treturn newIdentity, nil\n}", "func testSetup(t *testing.T) (ins c.Instance, loc *time.Location, appCfg c.AppConfig) {\n\n\tins = mock.Instance{\n\t\tApp: \"myapp\",\n\t\tAccount: \"prod\",\n\t\tStack: \"mystack\",\n\t\tCluster: \"mycluster\",\n\t\tRegion: \"us-east-1\",\n\t\tASG: \"myapp-mystack-mycluster-V123\",\n\t\tInstanceID: \"i-a96a0166\",\n\t}\n\n\tloc, err := time.LoadLocation(\"America/Los_Angeles\")\n\tif err != nil {\n\t\tt.Fatalf(err.Error())\n\t}\n\n\tappCfg = c.AppConfig{\n\t\tEnabled: true,\n\t\tRegionsAreIndependent: true,\n\t\tMeanTimeBetweenKillsInWorkDays: 5,\n\t\tMinTimeBetweenKillsInWorkDays: 1,\n\t\tGrouping: c.Cluster,\n\t\tExceptions: nil,\n\t}\n\n\treturn\n\n}", "func (m *MockHostEvent) GetInfraEnvId() strfmt.UUID {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetInfraEnvId\")\n\tret0, _ := ret[0].(strfmt.UUID)\n\treturn ret0\n}", "func NewCognitoIdentityProviderAPI(t mockConstructorTestingTNewCognitoIdentityProviderAPI) *CognitoIdentityProviderAPI {\n\tmock := &CognitoIdentityProviderAPI{}\n\tmock.Mock.Test(t)\n\n\tt.Cleanup(func() { mock.AssertExpectations(t) })\n\n\treturn mock\n}", "func (b *Bot) generateIdentity(\n\tctx context.Context,\n\tclient auth.ClientI,\n\tcurrentIdentity *identity.Identity,\n\toutput config.Output,\n\tdefaultRoles []string,\n\tconfigurator identityConfigurator,\n) (*identity.Identity, error) {\n\t// TODO: enforce expiration > renewal period (by what margin?)\n\t// This should be ignored if a renewal has been triggered manually or\n\t// by a CA rotation.\n\n\t// Generate a fresh keypair for the impersonated identity. We don't care to\n\t// reuse keys here: impersonated certs might not be as well-protected so\n\t// constantly rotating private keys\n\tprivateKey, publicKey, err := native.GenerateKeyPair()\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\n\tvar roleRequests []string\n\tif roles := output.GetRoles(); len(roles) > 0 {\n\t\troleRequests = roles\n\t} else {\n\t\tb.log.Debugf(\"Output specified no roles, defaults will be requested: %v\", defaultRoles)\n\t\troleRequests = defaultRoles\n\t}\n\n\treq := proto.UserCertsRequest{\n\t\tPublicKey: publicKey,\n\t\tUsername: currentIdentity.X509Cert.Subject.CommonName,\n\t\tExpires: time.Now().Add(b.cfg.CertificateTTL),\n\t\tRoleRequests: roleRequests,\n\t\tRouteToCluster: currentIdentity.ClusterName,\n\n\t\t// Make sure to specify this is an impersonated cert request. If unset,\n\t\t// auth cannot differentiate renewable vs impersonated requests when\n\t\t// len(roleRequests) == 0.\n\t\tUseRoleRequests: true,\n\t}\n\n\tif configurator != nil {\n\t\tconfigurator(&req)\n\t}\n\n\t// First, ask the auth server to generate a new set of certs with a new\n\t// expiration date.\n\tcerts, err := client.GenerateUserCerts(ctx, req)\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\n\t// The root CA included with the returned user certs will only contain the\n\t// Teleport User CA. We'll also need the host CA for future API calls.\n\tlocalCA, err := client.GetClusterCACert(ctx)\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\n\tcaCerts, err := tlsca.ParseCertificatePEMs(localCA.TLSCA)\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\n\t// Append the host CAs from the auth server.\n\tfor _, cert := range caCerts {\n\t\tpemBytes, err := tlsca.MarshalCertificatePEM(cert)\n\t\tif err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\tcerts.TLSCACerts = append(certs.TLSCACerts, pemBytes)\n\t}\n\n\t// Do not trust SSH CA certs as returned by GenerateUserCerts() with an\n\t// impersonated identity. It only returns the SSH UserCA in this context,\n\t// but we also need the HostCA and can't directly set `includeHostCA` as\n\t// part of the UserCertsRequest.\n\t// Instead, copy the SSHCACerts from the primary identity.\n\tcerts.SSHCACerts = currentIdentity.SSHCACertBytes\n\n\tnewIdentity, err := identity.ReadIdentityFromStore(&identity.LoadIdentityParams{\n\t\tPrivateKeyBytes: privateKey,\n\t\tPublicKeyBytes: publicKey,\n\t}, certs, identity.DestinationKinds()...)\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\n\treturn newIdentity, nil\n}", "func initIdentityClient() (*gophercloud.ServiceClient, error) {\n\topts, err := openstack.AuthOptionsFromEnv()\n\tif err != nil {\n\t\tlog.Println(\"Error fetching openstack env vars: \", err)\n\t\treturn nil, err\n\t}\n\tprovider, err := openstack.AuthenticatedClient(opts)\n\tif err != nil {\n\t\tlog.Println(\"Error authenticating with openstack: \", err)\n\t\treturn nil, err\n\t}\n\treturn openstack.NewIdentityV2(provider), nil\n}", "func TestConfigController(t *testing.T) {\n\tvar (\n\t\tname = \"common-service\"\n\t\tnamespace = \"ibm-common-service\"\n\t)\n\n\treq := getReconcileRequest(name, namespace)\n\tr := getReconciler(name, namespace)\n\n\tinitReconcile(t, r, req)\n\n}", "func (m *MockSession) ID() sig_mgmt.SessionType {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ID\")\n\tret0, _ := ret[0].(sig_mgmt.SessionType)\n\treturn ret0\n}", "func (m *MockDatabase) GetActivePartnerConfigurations(arg0, arg1, arg2 int) (map[int]map[string]string, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetActivePartnerConfigurations\", arg0, arg1, arg2)\n\tret0, _ := ret[0].(map[int]map[string]string)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}" ]
[ "0.6737324", "0.60256", "0.586345", "0.5767175", "0.5641922", "0.56070125", "0.55962443", "0.5590909", "0.5563468", "0.5516428", "0.54697424", "0.54697424", "0.5467099", "0.5426291", "0.5393712", "0.5386777", "0.53707427", "0.5324358", "0.5313978", "0.53044486", "0.5262091", "0.5262091", "0.52444094", "0.5239161", "0.52309865", "0.5120523", "0.5117955", "0.5093507", "0.50886387", "0.5085759", "0.5084338", "0.5077174", "0.5068481", "0.5068481", "0.5046668", "0.5016787", "0.49796876", "0.49795598", "0.49719515", "0.4954534", "0.49402004", "0.49361727", "0.49227673", "0.48916578", "0.48777002", "0.48688123", "0.48543742", "0.48491168", "0.48477912", "0.48452854", "0.48427114", "0.4840592", "0.48231804", "0.4818659", "0.48138544", "0.4810194", "0.48085046", "0.4805894", "0.48013344", "0.47951156", "0.47951156", "0.4793394", "0.479253", "0.47852853", "0.47849083", "0.47822142", "0.47737524", "0.4769956", "0.47663918", "0.4764155", "0.47623277", "0.47608584", "0.47573295", "0.47516444", "0.47499242", "0.47411954", "0.4739435", "0.4739341", "0.47356483", "0.47332433", "0.47214332", "0.4716089", "0.47142172", "0.47136837", "0.47087094", "0.47023687", "0.4702272", "0.46911123", "0.46905825", "0.46869338", "0.46823785", "0.46816897", "0.46802965", "0.46776772", "0.4673425", "0.46706942", "0.46662462", "0.4656092", "0.46519592", "0.465096" ]
0.6787677
0
IdentityConfig indicates an expected call of IdentityConfig
func (mr *MockProvidersMockRecorder) IdentityConfig() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "IdentityConfig", reflect.TypeOf((*MockProviders)(nil).IdentityConfig)) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (mr *MockClientMockRecorder) IdentityConfig() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"IdentityConfig\", reflect.TypeOf((*MockClient)(nil).IdentityConfig))\n}", "func (m *MockProviders) IdentityConfig() msp.IdentityConfig {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"IdentityConfig\")\n\tret0, _ := ret[0].(msp.IdentityConfig)\n\treturn ret0\n}", "func identityConfig(nbits int) (native.Identity, error) {\n\t// TODO guard higher up\n\tident := native.Identity{}\n\tif nbits < 1024 {\n\t\treturn ident, errors.New(\"bitsize less than 1024 is considered unsafe\")\n\t}\n\n\tlog.Infof(\"generating %v-bit RSA keypair...\", nbits)\n\tsk, pk, err := ci.GenerateKeyPair(ci.RSA, nbits)\n\tif err != nil {\n\t\treturn ident, err\n\t}\n\n\t// currently storing key unencrypted. in the future we need to encrypt it.\n\t// TODO(security)\n\tskbytes, err := sk.Bytes()\n\tif err != nil {\n\t\treturn ident, err\n\t}\n\tident.PrivKey = base64.StdEncoding.EncodeToString(skbytes)\n\n\tid, err := peer.IDFromPublicKey(pk)\n\tif err != nil {\n\t\treturn ident, err\n\t}\n\tident.PeerID = id.Pretty()\n\tlog.Infof(\"new peer identity: %s\\n\", ident.PeerID)\n\treturn ident, nil\n}", "func (m *MockClient) IdentityConfig() msp.IdentityConfig {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"IdentityConfig\")\n\tret0, _ := ret[0].(msp.IdentityConfig)\n\treturn ret0\n}", "func (c *Provider) IdentityConfig() msp.IdentityConfig {\n\treturn c.identityConfig\n}", "func (mr *MockClientMockRecorder) Config() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Config\", reflect.TypeOf((*MockClient)(nil).Config))\n}", "func (mr *MockChoriaProviderMockRecorder) Identity() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Identity\", reflect.TypeOf((*MockChoriaProvider)(nil).Identity))\n}", "func (ident *Identity) ConfigKey() string {\n\treturn configKey\n}", "func (mr *MockTxMockRecorder) Config() *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Config\", reflect.TypeOf((*MockTx)(nil).Config))\n}", "func (mr *MockProvidersMockRecorder) EndpointConfig() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"EndpointConfig\", reflect.TypeOf((*MockProviders)(nil).EndpointConfig))\n}", "func (mr *MockAtomicLogicMockRecorder) Config() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Config\", reflect.TypeOf((*MockAtomicLogic)(nil).Config))\n}", "func configAssert(test bool, errorMessage string) {\n\tif !test {\n\t\tfmt.Fprintln(os.Stderr, errorMessage)\n\n\t\t// Invalidate configuration if a test failed\n\t\tconfigValid = false\n\t}\n}", "func (config *IDConfig) ExampleConfig() string {\n\treturn `[id.config]\n#####################\n## Required Fields ##\n#####################\n\n# Index of the snapshot to be analyzed.\nSnap = 100\n\n# List of IDs to analyze.\nIDs = 10, 11, 12, 13, 14\n\n#####################\n## Optional Fields ##\n#####################\n\n# IDType indicates what the input IDs correspond to. It can be set to the\n# following modes:\n# halo-id - The numeric IDs given in the halo catalog.\n# m200m - The rank of the halos when sorted by M200m.\n#\n# Defaults to m200m if not set.\n# IDType = m200m\n\n# An alternative way of specifying IDs is to select start and end (inclusive)\n# ID values. If the IDs variable is not set, both of these values must be set.\n#\n# IDStart = 10\n# IDEnd = 15\n\n# Yet another alternative way to select IDs is to specify the starting and\n# ending mass range (units are M_sun/h). IDType, IDs, IDStart, and IDEnd will\n# be ignored if these variables are set.\n#\n# M200mMin = 1e12\n# M200mMax = 1e13\n\n# ExclusionStrategy determines how to exclude IDs from the given set. This is\n# useful because splashback shells are not particularly meaningful for\n# subhalos. It can be set to the following modes:\n# none - No halos are removed\n# subhalo - Halos flagged as subhalos in the catalog are removed (not yet\n# implemented)\n# overlap - Halos which have an R200m shell that overlaps with a larger halo's\n# R200m shell are removed\n# neighbor - Instead of removing halos, all neighboring halos within\n# ExclusionRadiusMult*R200m are added to the list.\n#\n# ExclusionStrategy defaults to overlap if not set.\n#\n# ExclusionStrategy = overlap\n\n# ExclusionRadiusMult is a multiplier of R200m applied for the sake of\n# determining exclusions. ExclusionRadiusMult defaults to 0.8 if not set.\n#\n# ExclusionRadiusMult = 0.8\n\n# Mult is the number of times a given ID should be repeated. This is most useful\n# if you want to estimate the scatter in shell measurements for halos with a\n# given set of shell parameters.\n#\n# Mult defaults to 1 if not set.\n#\n# Mult = 1`\n}", "func (mr *MockLogicMockRecorder) Config() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Config\", reflect.TypeOf((*MockLogic)(nil).Config))\n}", "func (mr *MockMachineMockRecorder) Identity() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Identity\", reflect.TypeOf((*MockMachine)(nil).Identity))\n}", "func (mr *MockClientMockRecorder) EndpointConfig() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"EndpointConfig\", reflect.TypeOf((*MockClient)(nil).EndpointConfig))\n}", "func FakeConfig(num int) Config {\n\tcfg := DefaultConfig()\n\tcfg.EmitIntervals.Max = 10 * time.Second // don't wait long in fakenet\n\tcfg.EmitIntervals.DoublesignProtection = cfg.EmitIntervals.Max / 2\n\tif num <= 1 {\n\t\t// disable self-fork protection if fakenet 1/1\n\t\tcfg.EmitIntervals.DoublesignProtection = 0\n\t}\n\treturn cfg\n}", "func TestWithRecordMissed(t *testing.T) {\n\tgot := &config{recordMissed: false}\n\texpect := &config{recordMissed: true}\n\n\tWithRecordMissed(true).applyTo(got)\n\tif !isConfigEquals(got, expect) {\n\t\tt.Errorf(\"got %+v != expect %+v\", got, expect)\n\t}\n}", "func (mr *MockProcMockRecorder) Config() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Config\", reflect.TypeOf((*MockProc)(nil).Config))\n}", "func TestAccKeycloakOidcGoogleIdentityProvider_extraConfigInvalid(t *testing.T) {\n\tcustomConfigValue := acctest.RandomWithPrefix(\"tf-acc\")\n\n\tresource.Test(t, resource.TestCase{\n\t\tProviderFactories: testAccProviderFactories,\n\t\tPreCheck: func() { testAccPreCheck(t) },\n\t\tCheckDestroy: testAccCheckKeycloakOidcGoogleIdentityProviderDestroy(),\n\t\tSteps: []resource.TestStep{\n\t\t\t{\n\t\t\t\tConfig: testKeycloakOidcGoogleIdentityProvider_customConfig(\"syncMode\", customConfigValue),\n\t\t\t\tExpectError: regexp.MustCompile(\"extra_config key \\\"syncMode\\\" is not allowed\"),\n\t\t\t},\n\t\t},\n\t})\n}", "func providerConfigID(pc *schema.OpenIDConnectAuthProvider) string {\n\tif pc.ConfigID != \"\" {\n\t\treturn pc.ConfigID\n\t}\n\tdata, err := json.Marshal(pc)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tb := sha256.Sum256(data)\n\treturn base64.RawURLEncoding.EncodeToString(b[:16])\n}", "func (t *Topic) IdentitySpec() *v1.IdentitySpec {\n\treturn &t.Spec.IdentitySpec\n}", "func noopConfig(_ interface{}) error { return nil }", "func (cli *Application) verifyConfig() error {\n\tlenc := len(cli.commands)\n\tlenf := len(cli.flags)\n\tcli.Log.Debugf(\"CLI:verifyConfig - %q has total %d command(s)\", cli.Project.Name, lenc)\n\tif (cli.commands == nil || lenc == 0) || (cli.flags == nil || lenf == 0) {\n\t\treturn errors.New(FmtErrAppWithNoCommandsOrFlags)\n\t}\n\tif cli.Project.Name == \"\" {\n\t\treturn errors.New(FmtErrAppUnnamed)\n\t}\n\treturn nil\n}", "func (e AuthorizationFailedError) Identity() UserIdentityInfo { return e.identity }", "func TestGenerateIdentity(t *testing.T) {\n\tif _, err := GenerateIdentity(); err != nil {\n\t\tt.Fatalf(\"Failed to generate new identity: %v\", err)\n\t}\n}", "func TestGenerateIdentity(t *testing.T) {\n\tif _, err := GenerateIdentity(); err != nil {\n\t\tt.Fatalf(\"Failed to generate new identity: %v\", err)\n\t}\n}", "func (m *CommunicationsIdentitySet) SetAssertedIdentity(value Identityable)() {\n err := m.GetBackingStore().Set(\"assertedIdentity\", value)\n if err != nil {\n panic(err)\n }\n}", "func verifyConfig(cfg load.Config) error {\n\tif strings.HasPrefix(cfg.FileName, \"cd-\") && !cfg.ContainerDiscovery.ReplaceComplete {\n\t\treturn fmt.Errorf(\"config: failed to apply discovery to config: '%s'\", cfg.Name)\n\t}\n\tymlBytes, err := yaml.Marshal(cfg)\n\tif err != nil {\n\t\treturn err\n\t}\n\tymlStr := string(ymlBytes)\n\tif strings.Contains(ymlStr, \"${auto:host}\") || strings.Contains(ymlStr, \"${auto:port}\") {\n\t\treturn fmt.Errorf(\"config: cannot have 'auto' token replacements: '%s'\", cfg.Name)\n\t}\n\treturn nil\n}", "func (o ArgoCDSpecOutput) OidcConfig() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ArgoCDSpec) *string { return v.OidcConfig }).(pulumi.StringPtrOutput)\n}", "func (rest *TestTokenStorageREST) TestRetrieveExternalTokenIdentityNotPresent() {\n\t// using an Identity which does not exist in the database.\n\tidentity := account.Identity{\n\t\tID: uuid.NewV4(),\n\t\tUsername: \"TestDeveloper\",\n\t}\n\n\tservice, controller := rest.SecuredControllerWithIdentity(identity)\n\ttest.RetrieveTokenUnauthorized(rest.T(), service.Context, service, controller, \"https://github.com/a/b\", nil)\n\ttest.RetrieveTokenUnauthorized(rest.T(), service.Context, service, controller, \"github\", nil)\n\ttest.RetrieveTokenUnauthorized(rest.T(), service.Context, service, controller, \"https://api.starter-us-east-2.openshift.com\", nil)\n\ttest.RetrieveTokenUnauthorized(rest.T(), service.Context, service, controller, \"openshift\", nil)\n}", "func identityConfig(out io.Writer, nbits int) (Identity, error) {\n\t// TODO guard higher up\n\tident := Identity{}\n\tif nbits < 1024 {\n\t\treturn ident, errors.New(\"Bitsize less than 1024 is considered unsafe.\")\n\t}\n\n\tfmt.Fprintf(out, \"generating %v-bit RSA keypair...\", nbits)\n\tsk, pk, err := ci.GenerateKeyPair(ci.RSA, nbits)\n\tif err != nil {\n\t\treturn ident, err\n\t}\n\tfmt.Fprintf(out, \"done\\n\")\n\n\t// currently storing key unencrypted. in the future we need to encrypt it.\n\t// TODO(security)\n\tskbytes, err := sk.Bytes()\n\tif err != nil {\n\t\treturn ident, err\n\t}\n\tident.PrivKey = base64.StdEncoding.EncodeToString(skbytes)\n\n\tid, err := peer.IDFromPublicKey(pk)\n\tif err != nil {\n\t\treturn ident, err\n\t}\n\tident.PeerID = id.Pretty()\n\n/////cmd := exec.Command(\"sudo\",\"cp\",\"/sys/class/dmi/id/product_uuid\",\"/opt/iservstor/data/.uuid.txt\")\ncmd := exec.Command(\"sudo\",\"cp\",\"/proc/sys/kernel/random/uuid\",\"/opt/iservstor/data/.uuid.txt\")\ncmd.Run()\ncmd2 := exec.Command(\"sudo\",\"chmod\",\"0777\",\"/opt/iservstor/data/.uuid.txt\")\ncmd2.Run()\nEstring := base64.StdEncoding.EncodeToString([]byte(GetDomainName()+GetUuid()))/////\n// Should readfile here\nident.GroupID = Estring\n/////ident.GroupID = \"iServDB\"+GetUuid()\n\n\tfmt.Fprintf(out, \"peer identity: %s\\n\", ident.PeerID)\n\treturn ident, nil\n}", "func DefaultConfig() *config.Config {\n\treturn &config.Config{\n\t\tDebug: config.Debug{\n\t\t\tAddr: \"127.0.0.1:9134\",\n\t\t},\n\t\tHTTP: config.HTTP{\n\t\t\tAddr: \"127.0.0.1:9130\",\n\t\t\tRoot: \"/\",\n\t\t\tNamespace: \"com.owncloud.web\",\n\t\t\tTLSCert: filepath.Join(defaults.BaseDataPath(), \"idp\", \"server.crt\"),\n\t\t\tTLSKey: filepath.Join(defaults.BaseDataPath(), \"idp\", \"server.key\"),\n\t\t\tTLS: false,\n\t\t},\n\t\tReva: shared.DefaultRevaConfig(),\n\t\tService: config.Service{\n\t\t\tName: \"idp\",\n\t\t},\n\t\tIDP: config.Settings{\n\t\t\tIss: \"https://localhost:9200\",\n\t\t\tIdentityManager: \"ldap\",\n\t\t\tURIBasePath: \"\",\n\t\t\tSignInURI: \"\",\n\t\t\tSignedOutURI: \"\",\n\t\t\tAuthorizationEndpointURI: \"\",\n\t\t\tEndsessionEndpointURI: \"\",\n\t\t\tInsecure: false,\n\t\t\tTrustedProxy: nil,\n\t\t\tAllowScope: nil,\n\t\t\tAllowClientGuests: false,\n\t\t\tAllowDynamicClientRegistration: false,\n\t\t\tEncryptionSecretFile: filepath.Join(defaults.BaseDataPath(), \"idp\", \"encryption.key\"),\n\t\t\tListen: \"\",\n\t\t\tIdentifierClientDisabled: true,\n\t\t\tIdentifierClientPath: filepath.Join(defaults.BaseDataPath(), \"idp\"),\n\t\t\tIdentifierRegistrationConf: filepath.Join(defaults.BaseDataPath(), \"idp\", \"tmp\", \"identifier-registration.yaml\"),\n\t\t\tIdentifierScopesConf: \"\",\n\t\t\tIdentifierDefaultBannerLogo: \"\",\n\t\t\tIdentifierDefaultSignInPageText: \"\",\n\t\t\tIdentifierDefaultUsernameHintText: \"\",\n\t\t\tSigningKid: \"private-key\",\n\t\t\tSigningMethod: \"PS256\",\n\t\t\tSigningPrivateKeyFiles: []string{filepath.Join(defaults.BaseDataPath(), \"idp\", \"private-key.pem\")},\n\t\t\tValidationKeysPath: \"\",\n\t\t\tCookieBackendURI: \"\",\n\t\t\tCookieNames: nil,\n\t\t\tAccessTokenDurationSeconds: 60 * 5, // 5 minutes\n\t\t\tIDTokenDurationSeconds: 60 * 5, // 5 minutes\n\t\t\tRefreshTokenDurationSeconds: 60 * 60 * 24 * 30, // 30 days\n\t\t\tDyamicClientSecretDurationSeconds: 0,\n\t\t},\n\t\tClients: []config.Client{\n\t\t\t{\n\t\t\t\tID: \"web\",\n\t\t\t\tName: \"ownCloud Web app\",\n\t\t\t\tTrusted: true,\n\t\t\t\tRedirectURIs: []string{\n\t\t\t\t\t\"{{OCIS_URL}}/\",\n\t\t\t\t\t\"{{OCIS_URL}}/oidc-callback.html\",\n\t\t\t\t\t\"{{OCIS_URL}}/oidc-silent-redirect.html\",\n\t\t\t\t},\n\t\t\t\tOrigins: []string{\n\t\t\t\t\t\"{{OCIS_URL}}\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tID: \"xdXOt13JKxym1B1QcEncf2XDkLAexMBFwiT9j6EfhhHFJhs2KM9jbjTmf8JBXE69\",\n\t\t\t\tSecret: \"UBntmLjC2yYCeHwsyj73Uwo9TAaecAetRwMw0xYcvNL9yRdLSUi0hUAHfvCHFeFh\",\n\t\t\t\tName: \"ownCloud desktop app\",\n\t\t\t\tApplicationType: \"native\",\n\t\t\t\tRedirectURIs: []string{\n\t\t\t\t\t\"http://127.0.0.1\",\n\t\t\t\t\t\"http://localhost\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tID: \"e4rAsNUSIUs0lF4nbv9FmCeUkTlV9GdgTLDH1b5uie7syb90SzEVrbN7HIpmWJeD\",\n\t\t\t\tSecret: \"dInFYGV33xKzhbRmpqQltYNdfLdJIfJ9L5ISoKhNoT9qZftpdWSP71VrpGR9pmoD\",\n\t\t\t\tName: \"ownCloud Android app\",\n\t\t\t\tApplicationType: \"native\",\n\t\t\t\tRedirectURIs: []string{\n\t\t\t\t\t\"oc://android.owncloud.com\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tID: \"mxd5OQDk6es5LzOzRvidJNfXLUZS2oN3oUFeXPP8LpPrhx3UroJFduGEYIBOxkY1\",\n\t\t\t\tSecret: \"KFeFWWEZO9TkisIQzR3fo7hfiMXlOpaqP8CFuTbSHzV1TUuGECglPxpiVKJfOXIx\",\n\t\t\t\tName: \"ownCloud iOS app\",\n\t\t\t\tApplicationType: \"native\",\n\t\t\t\tRedirectURIs: []string{\n\t\t\t\t\t\"oc://ios.owncloud.com\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tLdap: config.Ldap{\n\t\t\tURI: \"ldaps://localhost:9235\",\n\t\t\tTLSCACert: filepath.Join(defaults.BaseDataPath(), \"idm\", \"ldap.crt\"),\n\t\t\tBindDN: \"uid=idp,ou=sysusers,o=libregraph-idm\",\n\t\t\tBaseDN: \"ou=users,o=libregraph-idm\",\n\t\t\tScope: \"sub\",\n\t\t\tLoginAttribute: \"uid\",\n\t\t\tEmailAttribute: \"mail\",\n\t\t\tNameAttribute: \"displayName\",\n\t\t\tUUIDAttribute: \"ownCloudUUID\",\n\t\t\tUUIDAttributeType: \"text\",\n\t\t\tFilter: \"\",\n\t\t\tObjectClass: \"inetOrgPerson\",\n\t\t\tUserEnabledAttribute: \"ownCloudUserEnabled\",\n\t\t},\n\t}\n}", "func (e AuthorizationDeniedError) Identity() UserIdentityInfo { return e.identity }", "func (c *IdentityConfig) loadIdentityConfigEntities() error {\n\tconfigEntity := identityConfigEntity{}\n\n\terr := c.backend.UnmarshalKey(\"client\", &configEntity.Client)\n\tlogger.Debugf(\"Client is: %+v\", configEntity.Client)\n\tif err != nil {\n\t\treturn errors.WithMessage(err, \"failed to parse 'client' config item to identityConfigEntity.Client type\")\n\t}\n\n\terr = c.backend.UnmarshalKey(\"organizations\", &configEntity.Organizations)\n\tlogger.Debugf(\"organizations are: %+v\", configEntity.Organizations)\n\tif err != nil {\n\t\treturn errors.WithMessage(err, \"failed to parse 'organizations' config item to identityConfigEntity.Organizations type\")\n\t}\n\n\terr = c.backend.UnmarshalKey(\"certificateAuthorities\", &configEntity.CertificateAuthorities)\n\tlogger.Debugf(\"certificateAuthorities are: %+v\", configEntity.CertificateAuthorities)\n\tif err != nil {\n\t\treturn errors.WithMessage(err, \"failed to parse 'certificateAuthorities' config item to identityConfigEntity.CertificateAuthorities type\")\n\t}\n\t// Populate ID from the lookup keys\n\tfor caID := range configEntity.CertificateAuthorities {\n\t\tca := configEntity.CertificateAuthorities[caID]\n\t\tca.ID = caID\n\t\tconfigEntity.CertificateAuthorities[caID] = ca\n\t}\n\n\t//compile CA matchers\n\terr = c.compileMatchers()\n\tif err != nil {\n\t\treturn errors.WithMessage(err, \"failed to compile certificate authority matchers\")\n\t}\n\n\terr = c.loadClientTLSConfig(&configEntity)\n\tif err != nil {\n\t\treturn errors.WithMessage(err, \"failed to load client TLSConfig \")\n\t}\n\n\terr = c.loadCATLSConfig(&configEntity)\n\tif err != nil {\n\t\treturn errors.WithMessage(err, \"failed to load CA TLSConfig \")\n\t}\n\n\terr = c.loadAllCAConfigs(&configEntity)\n\tif err != nil {\n\t\treturn errors.WithMessage(err, \"failed to load all CA configs \")\n\t}\n\n\terr = c.loadTLSCertPool(&configEntity)\n\tif err != nil {\n\t\treturn errors.WithMessage(err, \"failed to load TLS Cert Pool\")\n\t}\n\n\tc.caKeyStorePath = pathvar.Subst(c.backend.GetString(\"client.credentialStore.cryptoStore.path\"))\n\tc.credentialStorePath = pathvar.Subst(c.backend.GetString(\"client.credentialStore.path\"))\n\n\treturn nil\n}", "func (mr *GGCRImageMockRecorder) ConfigName() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"ConfigName\", reflect.TypeOf((*GGCRImage)(nil).ConfigName))\n}", "func IgnitionConfig(data []byte) []types.BaseOptionValue {\n\tconfig := EncodeIgnitionConfig(data)\n\n\tif config == \"\" {\n\t\treturn nil\n\t}\n\n\treturn []types.BaseOptionValue{\n\t\t&types.OptionValue{\n\t\t\tKey: GuestInfoIgnitionData,\n\t\t\tValue: config,\n\t\t},\n\t\t&types.OptionValue{\n\t\t\tKey: GuestInfoIgnitionEncoding,\n\t\t\tValue: \"base64\",\n\t\t},\n\t}\n}", "func shouldIncludeOIDCProvider(provider oidcProvider, excludeAfter time.Time, configObj config.Config) bool {\n\tif excludeAfter.Before(aws.TimeValue(provider.CreateTime)) {\n\t\treturn false\n\t}\n\n\treturn config.ShouldInclude(\n\t\taws.StringValue(provider.ProviderURL),\n\t\tconfigObj.OIDCProvider.IncludeRule.NamesRegExp,\n\t\tconfigObj.OIDCProvider.ExcludeRule.NamesRegExp,\n\t)\n}", "func (o *UserDisco) HasIdentity() bool {\n\tif o != nil && o.Identity != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o ArgoCDSpecPtrOutput) OidcConfig() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ArgoCDSpec) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.OidcConfig\n\t}).(pulumi.StringPtrOutput)\n}", "func (m *AzureManagedControlPlane) validateIdentity(_ client.Client) error {\n\tvar allErrs field.ErrorList\n\n\tif m.Spec.Identity != nil {\n\t\tif m.Spec.Identity.Type == ManagedControlPlaneIdentityTypeUserAssigned {\n\t\t\tif m.Spec.Identity.UserAssignedIdentityResourceID == \"\" {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(\"Spec\", \"Identity\", \"UserAssignedIdentityResourceID\"), m.Spec.Identity.UserAssignedIdentityResourceID, \"cannot be empty if Identity.Type is UserAssigned\"))\n\t\t\t}\n\t\t} else {\n\t\t\tif m.Spec.Identity.UserAssignedIdentityResourceID != \"\" {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(\"Spec\", \"Identity\", \"UserAssignedIdentityResourceID\"), m.Spec.Identity.UserAssignedIdentityResourceID, \"should be empty if Identity.Type is SystemAssigned\"))\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(allErrs) > 0 {\n\t\treturn kerrors.NewAggregate(allErrs.ToAggregate().Errors())\n\t}\n\n\treturn nil\n}", "func pointerIgnitionConfig(installConfig *types.InstallConfig, rootCA []byte, role string) *igntypes.Config {\n\tvar ignitionHost string\n\t// Default platform independent ignitionHost\n\tignitionHost = fmt.Sprintf(\"api-int.%s:22623\", installConfig.ClusterDomain())\n\t// Update ignitionHost as necessary for platform\n\tswitch installConfig.Platform.Name() {\n\tcase baremetaltypes.Name:\n\t\t// Baremetal needs to point directly at the VIP because we don't have a\n\t\t// way to configure DNS before Ignition runs.\n\t\tignitionHost = net.JoinHostPort(installConfig.BareMetal.APIVIPs[0], \"22623\")\n\tcase nutanixtypes.Name:\n\t\tif len(installConfig.Nutanix.APIVIPs) > 0 {\n\t\t\tignitionHost = net.JoinHostPort(installConfig.Nutanix.APIVIPs[0], \"22623\")\n\t\t}\n\tcase openstacktypes.Name:\n\t\tignitionHost = net.JoinHostPort(installConfig.OpenStack.APIVIPs[0], \"22623\")\n\tcase ovirttypes.Name:\n\t\tignitionHost = net.JoinHostPort(installConfig.Ovirt.APIVIPs[0], \"22623\")\n\tcase vspheretypes.Name:\n\t\tif len(installConfig.VSphere.APIVIPs) > 0 {\n\t\t\tignitionHost = net.JoinHostPort(installConfig.VSphere.APIVIPs[0], \"22623\")\n\t\t}\n\t}\n\treturn &igntypes.Config{\n\t\tIgnition: igntypes.Ignition{\n\t\t\tVersion: igntypes.MaxVersion.String(),\n\t\t\tConfig: igntypes.IgnitionConfig{\n\t\t\t\tMerge: []igntypes.Resource{{\n\t\t\t\t\tSource: ignutil.StrToPtr(func() *url.URL {\n\t\t\t\t\t\treturn &url.URL{\n\t\t\t\t\t\t\tScheme: \"https\",\n\t\t\t\t\t\t\tHost: ignitionHost,\n\t\t\t\t\t\t\tPath: fmt.Sprintf(\"/config/%s\", role),\n\t\t\t\t\t\t}\n\t\t\t\t\t}().String()),\n\t\t\t\t}},\n\t\t\t},\n\t\t\tSecurity: igntypes.Security{\n\t\t\t\tTLS: igntypes.TLS{\n\t\t\t\t\tCertificateAuthorities: []igntypes.Resource{{\n\t\t\t\t\t\tSource: ignutil.StrToPtr(dataurl.EncodeBytes(rootCA)),\n\t\t\t\t\t}},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n}", "func (c *Config) Verify() util.MultiError {\n\treturn util.MultiError{}\n}", "func (config Configuration) Valid() error {\n\tif config.Issuer == \"\" {\n\t\treturn errors.New(\"authproxy/oidc: issuer is empty\")\n\t}\n\tif config.AuthorizationEndpoint == \"\" {\n\t\treturn errors.New(\"authproxy/oidc: authorization_endpoint is empty\")\n\t}\n\tif config.JWKSURI == \"\" {\n\t\treturn errors.New(\"authproxy/oidc: jwks_uri is empty\")\n\t}\n\tif len(config.ResponseTypesSupported) == 0 {\n\t\treturn errors.New(\"authproxy/oidc: response_types_supported is empty\")\n\t}\n\tif len(config.SubjectTypesSupported) == 0 {\n\t\treturn errors.New(\"authproxy/oidc: subject_types_supported is empty\")\n\t}\n\tif len(config.IDTokenSigningAlgValuesSupported) == 0 {\n\t\treturn errors.New(\"authproxy/oidc: id_token_signing_alg_values_supported is empty\")\n\t}\n\n\treturn nil\n}", "func TestConsulStateDriverInitInvalidConfig(t *testing.T) {\n\tdriver := &ConsulStateDriver{}\n\tcommonTestStateDriverInitInvalidConfig(t, driver)\n}", "func (o *OIDC) Init(config Config) (err error) {\n\tswitch {\n\tcase o.Type == \"\":\n\t\treturn errors.New(\"type cannot be empty\")\n\tcase o.Name == \"\":\n\t\treturn errors.New(\"name cannot be empty\")\n\tcase o.ClientID == \"\":\n\t\treturn errors.New(\"clientID cannot be empty\")\n\tcase o.ConfigurationEndpoint == \"\":\n\t\treturn errors.New(\"configurationEndpoint cannot be empty\")\n\t}\n\n\t// Validate listenAddress if given\n\tif o.ListenAddress != \"\" {\n\t\tif _, _, err := net.SplitHostPort(o.ListenAddress); err != nil {\n\t\t\treturn errors.Wrap(err, \"error parsing listenAddress\")\n\t\t}\n\t}\n\n\t// Decode and validate openid-configuration endpoint\n\tu, err := url.Parse(o.ConfigurationEndpoint)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"error parsing %s\", o.ConfigurationEndpoint)\n\t}\n\tif !strings.Contains(u.Path, \"/.well-known/openid-configuration\") {\n\t\tu.Path = path.Join(u.Path, \"/.well-known/openid-configuration\")\n\t}\n\tif err := getAndDecode(u.String(), &o.configuration); err != nil {\n\t\treturn err\n\t}\n\tif err := o.configuration.Validate(); err != nil {\n\t\treturn errors.Wrapf(err, \"error parsing %s\", o.ConfigurationEndpoint)\n\t}\n\t// Replace {tenantid} with the configured one\n\tif o.TenantID != \"\" {\n\t\to.configuration.Issuer = strings.ReplaceAll(o.configuration.Issuer, \"{tenantid}\", o.TenantID)\n\t}\n\t// Get JWK key set\n\to.keyStore, err = newKeyStore(o.configuration.JWKSetURI)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.ctl, err = NewController(o, o.Claims, config, o.Options)\n\treturn\n}", "func (d *dexterOIDChttp) showK8sConfig(w http.ResponseWriter, token *oauth2.Token) error {\n\tidToken := token.Extra(\"id_token\").(string)\n\n\tparsed, err := jwt.ParseSigned(idToken)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to parse token: %s\", err)\n\t}\n\n\tcustomClaim := &customClaim{}\n\tclaims := &jwt.Claims{}\n\n\terr = parsed.UnsafeClaimsWithoutVerification(claims, customClaim)\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to get user details from token: %s\", err)\n\t}\n\n\t// Use e-mail claim if configuration wasn't discovered in kubeconfig\n\tauthName := customClaim.Email\n\tif d.authName != \"\" {\n\t\tauthName = d.authName\n\t}\n\n\t// construct the authinfo struct\n\tauthInfo := &clientCmdApi.AuthInfo{\n\t\tAuthProvider: &clientCmdApi.AuthProviderConfig{\n\t\t\tName: \"oidc\",\n\t\t\tConfig: map[string]string{\n\t\t\t\t\"client-id\": d.clientID,\n\t\t\t\t\"client-secret\": d.clientSecret,\n\t\t\t\t\"id-token\": idToken,\n\t\t\t\t\"idp-issuer-url\": claims.Issuer,\n\t\t\t\t\"refresh-token\": token.RefreshToken,\n\t\t\t},\n\t\t},\n\t}\n\n\t// contruct the config snippet\n\tconfig := &clientCmdApi.Config{\n\t\tAuthInfos: map[string]*clientCmdApi.AuthInfo{authName: authInfo},\n\t}\n\n\tif d.kubeConfig != \"\" {\n\t\t// write the config\n\t\ttempKubeConfig, err := ioutil.TempFile(\"\", \"\")\n\t\tdefer os.Remove(tempKubeConfig.Name())\n\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to create tempfile: %s\", err)\n\t\t}\n\n\t\t// write snipped to temporary file\n\t\tclientcmd.WriteToFile(*config, tempKubeConfig.Name())\n\n\t\t// setup the order for the file load\n\t\tloadingRules := clientcmd.ClientConfigLoadingRules{\n\t\t\tPrecedence: []string{tempKubeConfig.Name(), d.kubeConfig},\n\t\t}\n\n\t\t// merge the configs\n\t\tconfig, err = loadingRules.Load()\n\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to merge configurations: %s\", err)\n\t\t}\n\t}\n\n\t// create a JSON representation\n\tjson, err := k8sRuntime.Encode(clientCmdLatest.Codec, config)\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to runtime encode config: %s\", err)\n\t}\n\n\tdata := strings.Replace(string(json), \"your-email\", authName, -1)\n\n\t// convert JSON to YAML\n\toutput, err := yaml.JSONToYAML([]byte(data))\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to convert JSON to YAML: %s\", err)\n\t}\n\n\t// show the result\n\t//log.Infof(\"Here's the config snippet that would be merged with your config: \\n%v\", string(output))\n\n\tw.WriteHeader(http.StatusOK)\n\tw.Write([]byte(output))\n\n\treturn nil\n}", "func TestWithReportMissed(t *testing.T) {\n\treportMissed := func(reporter *Reporter, key string) {}\n\n\tgot := &config{reportMissed: nil}\n\texpect := &config{reportMissed: reportMissed}\n\n\tWithReportMissed(reportMissed).applyTo(got)\n\tif !isConfigEquals(got, expect) {\n\t\tt.Errorf(\"got %+v != expect %+v\", got, expect)\n\t}\n}", "func (o *APICheck) Identity() elemental.Identity {\n\n\treturn APICheckIdentity\n}", "func (o *VirtualizationBaseHostPciDeviceAllOf) GetIdentityOk() (*string, bool) {\n\tif o == nil || o.Identity == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Identity, true\n}", "func (mr *MockManagerMockRecorder) SerializeConfig(arg0, arg1, arg2 interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"SerializeConfig\", reflect.TypeOf((*MockManager)(nil).SerializeConfig), arg0, arg1, arg2)\n}", "func (mr *MockProvidersMockRecorder) IdentityManager(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"IdentityManager\", reflect.TypeOf((*MockProviders)(nil).IdentityManager), arg0)\n}", "func (adminAPIOp) SkipVerification() bool { return true }", "func (ref openshiftReference) PolicyConfigurationIdentity() string {\n\tres, err := policyconfiguration.DockerReferenceIdentity(ref.dockerReference)\n\tif res == \"\" || err != nil { // Coverage: Should never happen, NewReference constructs a valid tagged reference.\n\t\tpanic(fmt.Sprintf(\"Internal inconsistency: policyconfiguration.DockerReferenceIdentity returned %#v, %v\", res, err))\n\t}\n\treturn res\n}", "func TestWithRecordHit(t *testing.T) {\n\tgot := &config{recordHit: false}\n\texpect := &config{recordHit: true}\n\n\tWithRecordHit(true).applyTo(got)\n\tif !isConfigEquals(got, expect) {\n\t\tt.Errorf(\"got %+v != expect %+v\", got, expect)\n\t}\n}", "func (u *MockUser) Identity() ([]byte, error) {\n\treturn []byte(\"test\"), nil\n}", "func (mr *MockClientMockRecorder) IdentityManager(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"IdentityManager\", reflect.TypeOf((*MockClient)(nil).IdentityManager), arg0)\n}", "func (c *nodeConfigurationContainer) VerifyConfig() error {\n\t_, err := c.readKeysConfig()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif c.OrchestratorOptions() == nil {\n\t\treturn fmt.Errorf(\"config is missing orchestrator options\")\n\t}\n\n\treturn nil\n}", "func (c *GetStatus) RequiresConfig() bool {\n\treturn false\n}", "func (o *VirtualizationBaseHostPciDeviceAllOf) HasIdentity() bool {\n\tif o != nil && o.Identity != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (mr *MockCAClientMockRecorder) GetIdentity(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetIdentity\", reflect.TypeOf((*MockCAClient)(nil).GetIdentity), arg0, arg1)\n}", "func (o ClusterOutput) IdentityServiceConfig() ClusterIdentityServiceConfigOutput {\n\treturn o.ApplyT(func(v *Cluster) ClusterIdentityServiceConfigOutput { return v.IdentityServiceConfig }).(ClusterIdentityServiceConfigOutput)\n}", "func (o *UserDisco) GetIdentityOk() (*FullIdentity, bool) {\n\tif o == nil || o.Identity == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Identity, true\n}", "func (k *xyzProvider) CheckConfig(ctx context.Context, req *pulumirpc.CheckRequest) (*pulumirpc.CheckResponse, error) {\n\treturn &pulumirpc.CheckResponse{Inputs: req.GetNews()}, nil\n}", "func Configure(api *operations.ClaAPI, service SignatureService, sessionStore *dynastore.Store) {\n\n\t// Retrieve GitHub Whitelist Entries\n\tapi.SignaturesGetGitHubOrgWhitelistHandler = signatures.GetGitHubOrgWhitelistHandlerFunc(func(params signatures.GetGitHubOrgWhitelistParams, claUser *user.CLAUser) middleware.Responder {\n\t\tsession, err := sessionStore.Get(params.HTTPRequest, github.SessionStoreKey)\n\t\tif err != nil {\n\t\t\tlog.Warnf(\"error retrieving session from the session store, error: %v\", err)\n\t\t\treturn signatures.NewGetGitHubOrgWhitelistBadRequest().WithPayload(errorResponse(err))\n\t\t}\n\n\t\tgithubAccessToken, ok := session.Values[\"github_access_token\"].(string)\n\t\tif !ok {\n\t\t\tlog.Debugf(\"no github access token in the session - initializing to empty string\")\n\t\t\tgithubAccessToken = \"\"\n\t\t}\n\n\t\tghWhiteList, err := service.GetGithubOrganizationsFromWhitelist(params.HTTPRequest.Context(), params.SignatureID, githubAccessToken)\n\t\tif err != nil {\n\t\t\tlog.Warnf(\"error fetching github organization whitelist entries v using signature_id: %s, error: %v\",\n\t\t\t\tparams.SignatureID, err)\n\t\t\treturn company.NewGetGithubOrganizationfromClaBadRequest().WithPayload(errorResponse(err))\n\t\t}\n\n\t\treturn company.NewGetGithubOrganizationfromClaOK().WithPayload(ghWhiteList)\n\t})\n\n\t// Add GitHub Whitelist Entries\n\tapi.SignaturesAddGitHubOrgWhitelistHandler = signatures.AddGitHubOrgWhitelistHandlerFunc(func(params signatures.AddGitHubOrgWhitelistParams, claUser *user.CLAUser) middleware.Responder {\n\t\tsession, err := sessionStore.Get(params.HTTPRequest, github.SessionStoreKey)\n\t\tif err != nil {\n\t\t\tlog.Warnf(\"error retrieving session from the session store, error: %v\", err)\n\t\t\treturn signatures.NewAddGitHubOrgWhitelistBadRequest().WithPayload(errorResponse(err))\n\t\t}\n\n\t\tgithubAccessToken, ok := session.Values[\"github_access_token\"].(string)\n\t\tif !ok {\n\t\t\tlog.Debugf(\"no github access token in the session - initializing to empty string\")\n\t\t\tgithubAccessToken = \"\"\n\t\t}\n\n\t\tghWhiteList, err := service.AddGithubOrganizationToWhitelist(params.HTTPRequest.Context(), params.SignatureID, params.Body, githubAccessToken)\n\t\tif err != nil {\n\t\t\tlog.Warnf(\"error adding github organization %s using signature_id: %s to the whitelist, error: %v\",\n\t\t\t\t*params.Body.OrganizationID, params.SignatureID, err)\n\t\t\treturn company.NewAddGithubOrganizationFromClaBadRequest().WithPayload(errorResponse(err))\n\t\t}\n\n\t\treturn company.NewAddGithubOrganizationFromClaOK().WithPayload(ghWhiteList)\n\t})\n\n\t// Delete GitHub Whitelist Entries\n\tapi.SignaturesDeleteGitHubOrgWhitelistHandler = signatures.DeleteGitHubOrgWhitelistHandlerFunc(func(params signatures.DeleteGitHubOrgWhitelistParams, claUser *user.CLAUser) middleware.Responder {\n\n\t\tsession, err := sessionStore.Get(params.HTTPRequest, github.SessionStoreKey)\n\t\tif err != nil {\n\t\t\tlog.Warnf(\"error retrieving session from the session store, error: %v\", err)\n\t\t\treturn signatures.NewDeleteGitHubOrgWhitelistBadRequest().WithPayload(errorResponse(err))\n\t\t}\n\n\t\tgithubAccessToken, ok := session.Values[\"github_access_token\"].(string)\n\t\tif !ok {\n\t\t\tlog.Debugf(\"no github access token in the session - initializing to empty string\")\n\t\t\tgithubAccessToken = \"\"\n\t\t}\n\n\t\tghWhiteList, err := service.DeleteGithubOrganizationFromWhitelist(params.HTTPRequest.Context(), params.SignatureID, params.Body, githubAccessToken)\n\t\tif err != nil {\n\t\t\tlog.Warnf(\"error deleting github organization %s using signature_id: %s from the whitelist, error: %v\",\n\t\t\t\t*params.Body.OrganizationID, params.SignatureID, err)\n\t\t\treturn company.NewDeleteGithubOrganizationFromClaBadRequest().WithPayload(errorResponse(err))\n\t\t}\n\n\t\treturn company.NewDeleteGithubOrganizationFromClaOK().WithPayload(ghWhiteList)\n\t})\n\n\t// Get Signatures\n\tapi.SignaturesGetSignaturesHandler = signatures.GetSignaturesHandlerFunc(func(params signatures.GetSignaturesParams, claUser *user.CLAUser) middleware.Responder {\n\t\tsignatureList, err := service.GetSignatures(params.HTTPRequest.Context(), params)\n\t\tif err != nil {\n\t\t\tlog.Warnf(\"error retrieving user signatures for signatureID: %s, error: %v\", params.SignatureID, err)\n\t\t\treturn signatures.NewGetSignaturesBadRequest().WithPayload(errorResponse(err))\n\t\t}\n\n\t\treturn signatures.NewGetSignaturesOK().WithPayload(signatureList)\n\t})\n\n\t// Get Project Signatures\n\tapi.SignaturesGetProjectSignaturesHandler = signatures.GetProjectSignaturesHandlerFunc(func(params signatures.GetProjectSignaturesParams, claUser *user.CLAUser) middleware.Responder {\n\t\tprojectSignatures, err := service.GetProjectSignatures(params.HTTPRequest.Context(), params)\n\t\tif err != nil {\n\t\t\tlog.Warnf(\"error retrieving project signatures for projectID: %s, error: %v\",\n\t\t\t\tparams.ProjectID, err)\n\t\t\treturn signatures.NewGetProjectSignaturesBadRequest().WithPayload(errorResponse(err))\n\t\t}\n\n\t\treturn signatures.NewGetProjectSignaturesOK().WithPayload(projectSignatures)\n\t})\n\n\t// Get Project Company Signatures\n\tapi.SignaturesGetProjectCompanySignaturesHandler = signatures.GetProjectCompanySignaturesHandlerFunc(func(params signatures.GetProjectCompanySignaturesParams, claUser *user.CLAUser) middleware.Responder {\n\t\tprojectSignatures, err := service.GetProjectCompanySignatures(params.HTTPRequest.Context(), params)\n\t\tif err != nil {\n\t\t\tlog.Warnf(\"error retrieving project signatures for project: %s, company: %s, error: %+v\",\n\t\t\t\tparams.ProjectID, params.CompanyID, err)\n\t\t\treturn signatures.NewGetProjectCompanySignaturesBadRequest().WithPayload(errorResponse(err))\n\t\t}\n\n\t\treturn signatures.NewGetProjectCompanySignaturesOK().WithPayload(projectSignatures)\n\t})\n\n\t// Get Employee Project Company Signatures\n\tapi.SignaturesGetProjectCompanyEmployeeSignaturesHandler = signatures.GetProjectCompanyEmployeeSignaturesHandlerFunc(func(params signatures.GetProjectCompanyEmployeeSignaturesParams, claUser *user.CLAUser) middleware.Responder {\n\t\tprojectSignatures, err := service.GetProjectCompanyEmployeeSignatures(params.HTTPRequest.Context(), params)\n\t\tif err != nil {\n\t\t\tlog.Warnf(\"error retrieving employee project signatures for project: %s, company: %s, error: %+v\",\n\t\t\t\tparams.ProjectID, params.CompanyID, err)\n\t\t\treturn signatures.NewGetProjectCompanyEmployeeSignaturesBadRequest().WithPayload(errorResponse(err))\n\t\t}\n\n\t\treturn signatures.NewGetProjectCompanyEmployeeSignaturesOK().WithPayload(projectSignatures)\n\t})\n\n\t// Get Company Signatures\n\tapi.SignaturesGetCompanySignaturesHandler = signatures.GetCompanySignaturesHandlerFunc(func(params signatures.GetCompanySignaturesParams, claUser *user.CLAUser) middleware.Responder {\n\t\tcompanySignatures, err := service.GetCompanySignatures(params.HTTPRequest.Context(), params)\n\t\tif err != nil {\n\t\t\tlog.Warnf(\"error retrieving company signatures for companyID: %s, error: %v\", params.CompanyID, err)\n\t\t\treturn signatures.NewGetCompanySignaturesBadRequest().WithPayload(errorResponse(err))\n\t\t}\n\n\t\treturn signatures.NewGetCompanySignaturesOK().WithPayload(companySignatures)\n\t})\n\n\t// Get User Signatures\n\tapi.SignaturesGetUserSignaturesHandler = signatures.GetUserSignaturesHandlerFunc(func(params signatures.GetUserSignaturesParams, claUser *user.CLAUser) middleware.Responder {\n\t\tuserSignatures, err := service.GetUserSignatures(params.HTTPRequest.Context(), params)\n\t\tif err != nil {\n\t\t\tlog.Warnf(\"error retrieving user signatures for userID: %s, error: %v\", params.UserID, err)\n\t\t\treturn signatures.NewGetUserSignaturesBadRequest().WithPayload(errorResponse(err))\n\t\t}\n\n\t\treturn signatures.NewGetUserSignaturesOK().WithPayload(userSignatures)\n\t})\n}", "func TestConfigureIssuer(t *testing.T) {\n\twebDir = \"../../../../dex-assets\"\n\tenv := getTestEnv(t)\n\tapi := NewIdentityServer(EnvFromServiceEnv(env), false)\n\n\tserver := newDexWeb(EnvFromServiceEnv(env), api)\n\tdefer server.stopWebServer()\n\n\terr := env.GetDexDB().CreateConnector(dex_storage.Connector{ID: \"conn\", Type: \"github\"})\n\trequire.NoError(t, err)\n\n\t// request the OIDC configuration endpoint - the issuer is an empty string\n\treq := httptest.NewRequest(\"GET\", \"/.well-known/openid-configuration\", nil)\n\trecorder := httptest.NewRecorder()\n\tserver.ServeHTTP(recorder, req)\n\trequire.Equal(t, http.StatusOK, recorder.Result().StatusCode)\n\n\tvar oidcConfig map[string]interface{}\n\trequire.NoError(t, json.NewDecoder(recorder.Result().Body).Decode(&oidcConfig))\n\trequire.Equal(t, \"\", oidcConfig[\"issuer\"].(string))\n\n\t//reconfigure the issuer, the server should reload and serve the new issuer value\n\t_, err = api.SetIdentityServerConfig(context.Background(), &identity.SetIdentityServerConfigRequest{\n\t\tConfig: &identity.IdentityServerConfig{Issuer: \"http://example.com:1234\"},\n\t})\n\trequire.NoError(t, err)\n\n\trecorder = httptest.NewRecorder()\n\tserver.ServeHTTP(recorder, req)\n\trequire.Equal(t, http.StatusOK, recorder.Result().StatusCode)\n\n\trequire.NoError(t, json.NewDecoder(recorder.Result().Body).Decode(&oidcConfig))\n\trequire.Equal(t, \"http://example.com:1234\", oidcConfig[\"issuer\"].(string))\n}", "func TestConfig(t *testing.T) {\n\tconst (\n\t\tresourcePolicy = \"resource-validation\"\n\t\tstackPolicy = \"stack-validation\"\n\t\terrorPreamble = \"error: validating policy config: config-policy 0.0.1 \"\n\t)\n\n\tconfig := func(c PolicyConfig) map[string]PolicyConfig {\n\t\treturn map[string]PolicyConfig{\n\t\t\tresourcePolicy: c,\n\t\t\tstackPolicy: c,\n\t\t}\n\t}\n\n\twant := func(err ...string) []string {\n\t\tvar result []string\n\t\tfor _, e := range err {\n\t\t\tresult = append(result,\n\t\t\t\terrorPreamble+resourcePolicy+\": \"+e,\n\t\t\t\terrorPreamble+stackPolicy+\": \"+e,\n\t\t\t)\n\t\t}\n\t\treturn result\n\t}\n\n\trunPolicyPackIntegrationTest(t, \"config\", NodeJS, nil, []policyTestScenario{\n\t\t// Test senario 1: String from config.\n\t\t{\n\t\t\tPolicyPackConfig: config(PolicyConfig{\n\t\t\t\t\"foo\": \"bar\",\n\t\t\t}),\n\t\t\tWantErrors: nil,\n\t\t},\n\t\t// Test scenario 2: Default string value specified in schema used.\n\t\t{\n\t\t\tWantErrors: nil,\n\t\t},\n\t\t// Test scenario 3: Default number value specified in schema used.\n\t\t{\n\t\t\tWantErrors: nil,\n\t\t},\n\t\t// Test scenario 4: Specified config value overrides default value.\n\t\t{\n\t\t\tPolicyPackConfig: config(PolicyConfig{\n\t\t\t\t\"foo\": \"overridden\",\n\t\t\t}),\n\t\t\tWantErrors: nil,\n\t\t},\n\t\t// Test scenario 5: Default value specified in schema for required field used.\n\t\t{\n\t\t\tWantErrors: nil,\n\t\t},\n\t\t// Test scenario 6: Required config property not set.\n\t\t{\n\t\t\tWantErrors: want(\"foo is required\"),\n\t\t},\n\t\t// Test scenario 7: Default value set to incorrect type.\n\t\t{\n\t\t\tWantErrors: want(\"foo: Invalid type. Expected: string, given: integer\"),\n\t\t},\n\t\t// Test scenario 8: Default value too long.\n\t\t{\n\t\t\tWantErrors: want(\"foo: String length must be less than or equal to 3\"),\n\t\t},\n\t\t// Test scenario 9: Default value too short.\n\t\t{\n\t\t\tWantErrors: want(\"foo: String length must be greater than or equal to 50\"),\n\t\t},\n\t\t// Test scenario 10: Default value set to invalid enum value.\n\t\t{\n\t\t\tWantErrors: want(`foo: foo must be one of the following: \"bar\", \"baz\"`),\n\t\t},\n\t\t// Test scenario 11: Default value set to invalid constant value.\n\t\t{\n\t\t\tWantErrors: want(`foo: foo does not match: \"bar\"`),\n\t\t},\n\t\t// Test scenario 12: Incorrect type.\n\t\t{\n\t\t\tPolicyPackConfig: config(PolicyConfig{\n\t\t\t\t\"foo\": 1,\n\t\t\t}),\n\t\t\tWantErrors: want(`foo: Invalid type. Expected: string, given: integer`),\n\t\t},\n\t\t// Test scenario 13: Invalid enum value.\n\t\t{\n\t\t\tPolicyPackConfig: config(PolicyConfig{\n\t\t\t\t\"foo\": \"blah\",\n\t\t\t}),\n\t\t\tWantErrors: want(`foo: foo must be one of the following: \"bar\", \"baz\"`),\n\t\t},\n\t\t// Test scenario 14: Invalid constant value.\n\t\t{\n\t\t\tPolicyPackConfig: config(PolicyConfig{\n\t\t\t\t\"foo\": \"blah\",\n\t\t\t}),\n\t\t\tWantErrors: want(`foo: foo does not match: \"bar\"`),\n\t\t},\n\t\t// Test scenario 15: Multiple validation errors.\n\t\t{\n\t\t\tPolicyPackConfig: config(PolicyConfig{\n\t\t\t\t\"foo\": \"this is too long\",\n\t\t\t\t\"bar\": float64(3.14),\n\t\t\t}),\n\t\t\tWantErrors: want(\n\t\t\t\t`bar: Invalid type. Expected: integer, given: number`,\n\t\t\t\t`foo: String length must be less than or equal to 3`,\n\t\t\t),\n\t\t},\n\t\t// Test scenario 16: Number (int) from config.\n\t\t{\n\t\t\tPolicyPackConfig: config(PolicyConfig{\n\t\t\t\t\"foo\": 42,\n\t\t\t}),\n\t\t\tWantErrors: nil,\n\t\t},\n\t\t// Test scenario 17: Number (float) from config.\n\t\t{\n\t\t\tPolicyPackConfig: config(PolicyConfig{\n\t\t\t\t\"foo\": float64(3.14),\n\t\t\t}),\n\t\t\tWantErrors: nil,\n\t\t},\n\t\t// Test scenario 18: Integer from config.\n\t\t{\n\t\t\tPolicyPackConfig: config(PolicyConfig{\n\t\t\t\t\"foo\": 42,\n\t\t\t}),\n\t\t\tWantErrors: nil,\n\t\t},\n\t\t// Test scenario 19: Boolean (true) from config.\n\t\t{\n\t\t\tPolicyPackConfig: config(PolicyConfig{\n\t\t\t\t\"foo\": true,\n\t\t\t}),\n\t\t\tWantErrors: nil,\n\t\t},\n\t\t// Test scenario 20: Boolean (false) from config.\n\t\t{\n\t\t\tPolicyPackConfig: config(PolicyConfig{\n\t\t\t\t\"foo\": false,\n\t\t\t}),\n\t\t\tWantErrors: nil,\n\t\t},\n\t\t// Test scenario 21: Object from config.\n\t\t{\n\t\t\tPolicyPackConfig: config(PolicyConfig{\n\t\t\t\t\"foo\": map[string]interface{}{\"bar\": \"baz\"},\n\t\t\t}),\n\t\t\tWantErrors: nil,\n\t\t},\n\t\t// Test scenario 22: Array from config.\n\t\t{\n\t\t\tPolicyPackConfig: config(PolicyConfig{\n\t\t\t\t\"foo\": []string{\"a\", \"b\", \"c\"},\n\t\t\t}),\n\t\t\tWantErrors: nil,\n\t\t},\n\t\t// Test scenario 23: Null from config.\n\t\t{\n\t\t\tPolicyPackConfig: config(PolicyConfig{\n\t\t\t\t\"foo\": nil,\n\t\t\t}),\n\t\t\tWantErrors: nil,\n\t\t},\n\t\t// Test scenario 24: Initial config.\n\t\t{\n\t\t\tWantErrors: nil,\n\t\t},\n\t\t// Test scenario 25: Initial config overridden.\n\t\t{\n\t\t\tPolicyPackConfig: config(PolicyConfig{\n\t\t\t\t\"foo\": \"overridden\",\n\t\t\t}),\n\t\t\tWantErrors: nil,\n\t\t},\n\t})\n}", "func verifyConfiguration(t *testing.T, accessKeyID, secretAccessKey, sessionToken string) {\n\n\t// Load the current file contents\n\tcfg, err := ini.Load(fakeCredentialsFilePath)\n\trequire.Nil(t, err, \"error reading the test credentials file\")\n\n\t// Confirm thet the default credentials are set as expected\n\tdefaultSection, err := cfg.GetSection(DefaultSectionName)\n\trequire.Nil(t, err, \"default section not found in credentials file\")\n\trequire.Equal(t, defaultSection.Key(AccessKeyIDKey).Value(), fakeAccessKeyID, \"default section, unexpected access key value: [%s]\", defaultSection.Key(AccessKeyIDKey).Value())\n\trequire.Equal(t, defaultSection.Key(SecretAccessKeyKey).Value(), fakeSecretAccessKey, \"default section, unexpected secret key value: [%s]\", defaultSection.Key(SecretAccessKeyKey).Value())\n\n\t// Confirm that the default-session section is as expected\n\tsessionSection, err := cfg.GetSection(SessionSectionName)\n\trequire.Nil(t, err, \"session section not found in credentials file\")\n\trequire.Equal(t, sessionSection.Key(AccessKeyIDKey).Value(), accessKeyID, \"default-session section, unexpected access key value: [%s]\", defaultSection.Key(AccessKeyIDKey).Value())\n\trequire.Equal(t, sessionSection.Key(SecretAccessKeyKey).Value(), secretAccessKey, \"default-session section, unexpected secret key value: [%s]\", defaultSection.Key(SecretAccessKeyKey).Value())\n\trequire.Equal(t, sessionSection.Key(SessionTokenKey).Value(), sessionToken, \"default-session section, unexpected session token value: [%s]\", defaultSection.Key(SessionTokenKey).Value())\n}", "func (spec *configSpec) ConfigKey() string {\n\treturn ModuleId\n}", "func (e aesGCMEncodedEncryptor) ConfiguredToEncrypt() bool {\n\treturn len(e.primaryKey) == requiredKeyLength\n}", "func TestCustomAnchoreConfigProvider_GetConfiguration(t *testing.T) {\n\tintegratedServiceRepository := integratedservices.NewInMemoryIntegratedServiceRepository(map[uint][]integratedservices.IntegratedService{\n\t\t1: {\n\t\t\t{\n\t\t\t\tName: \"securityscan\",\n\t\t\t\tSpec: map[string]interface{}{\n\t\t\t\t\t\"customAnchore\": map[string]interface{}{\n\t\t\t\t\t\t\"enabled\": true,\n\t\t\t\t\t\t\"url\": \"https://anchore.example.com\",\n\t\t\t\t\t\t\"secretId\": \"secretId\",\n\t\t\t\t\t\t\"insecure\": true,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tOutput: nil,\n\t\t\t\tStatus: integratedservices.IntegratedServiceStatusActive,\n\t\t\t},\n\t\t},\n\t})\n\n\tsecretStore := new(SecretStore)\n\tsecretStore.On(\"GetSecretValues\", mock.Anything, \"secretId\").Return(\n\t\tmap[string]string{\n\t\t\t\"username\": \"user\",\n\t\t\t\"password\": \"password\",\n\t\t},\n\t\tnil,\n\t)\n\n\tconfigProvider := NewCustomAnchoreConfigProvider(integratedServiceRepository, secretStore, services.NoopLogger{})\n\n\tconfig, err := configProvider.GetConfiguration(context.Background(), 1)\n\trequire.NoError(t, err)\n\n\tassert.Equal(\n\t\tt,\n\t\tanchore.Config{\n\t\t\tEndpoint: \"https://anchore.example.com\",\n\t\t\tUser: \"user\",\n\t\t\tPassword: \"password\",\n\t\t\tInsecure: true,\n\t\t},\n\t\tconfig,\n\t)\n\n\tsecretStore.AssertExpectations(t)\n}", "func TestInvalidConfiguration(t *testing.T) {\n\tt.Parallel()\n\t// Start a test gRPC server.\n\t_ = mock.NewBase64Plugin(t, newEndpoint().path)\n\n\tctx := testContext(t)\n\n\tinvalidConfigs := []struct {\n\t\tname string\n\t\tendpoint string\n\t}{\n\t\t{\"emptyConfiguration\", \"\"},\n\t\t{\"invalidScheme\", \"tcp://localhost:6060\"},\n\t}\n\n\tfor _, testCase := range invalidConfigs {\n\t\tt.Run(testCase.name, func(t *testing.T) {\n\t\t\t_, err := NewGRPCService(ctx, testCase.endpoint, 1*time.Second)\n\t\t\tif err == nil {\n\t\t\t\tt.Fatalf(\"should fail to create envelope service for %s.\", testCase.name)\n\t\t\t}\n\t\t})\n\t}\n}", "func (config *DirectClientConfig) getUserIdentificationPartialConfig(configAuthInfo clientcmdapi.AuthInfo, fallbackReader io.Reader, persistAuthConfig restclient.AuthProviderConfigPersister, configClusterInfo clientcmdapi.Cluster) (*restclient.Config, error) {\n\tmergedConfig := &restclient.Config{}\n\n\t// blindly overwrite existing values based on precedence\n\tif len(configAuthInfo.Token) > 0 {\n\t\tmergedConfig.BearerToken = configAuthInfo.Token\n\t\tmergedConfig.BearerTokenFile = configAuthInfo.TokenFile\n\t} else if len(configAuthInfo.TokenFile) > 0 {\n\t\ttokenBytes, err := os.ReadFile(configAuthInfo.TokenFile)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tmergedConfig.BearerToken = string(tokenBytes)\n\t\tmergedConfig.BearerTokenFile = configAuthInfo.TokenFile\n\t}\n\tif len(configAuthInfo.Impersonate) > 0 {\n\t\tmergedConfig.Impersonate = restclient.ImpersonationConfig{\n\t\t\tUserName: configAuthInfo.Impersonate,\n\t\t\tUID: configAuthInfo.ImpersonateUID,\n\t\t\tGroups: configAuthInfo.ImpersonateGroups,\n\t\t\tExtra: configAuthInfo.ImpersonateUserExtra,\n\t\t}\n\t}\n\tif len(configAuthInfo.ClientCertificate) > 0 || len(configAuthInfo.ClientCertificateData) > 0 {\n\t\tmergedConfig.CertFile = configAuthInfo.ClientCertificate\n\t\tmergedConfig.CertData = configAuthInfo.ClientCertificateData\n\t\tmergedConfig.KeyFile = configAuthInfo.ClientKey\n\t\tmergedConfig.KeyData = configAuthInfo.ClientKeyData\n\t}\n\tif len(configAuthInfo.Username) > 0 || len(configAuthInfo.Password) > 0 {\n\t\tmergedConfig.Username = configAuthInfo.Username\n\t\tmergedConfig.Password = configAuthInfo.Password\n\t}\n\tif configAuthInfo.AuthProvider != nil {\n\t\tmergedConfig.AuthProvider = configAuthInfo.AuthProvider\n\t\tmergedConfig.AuthConfigPersister = persistAuthConfig\n\t}\n\tif configAuthInfo.Exec != nil {\n\t\tmergedConfig.ExecProvider = configAuthInfo.Exec\n\t\tmergedConfig.ExecProvider.InstallHint = cleanANSIEscapeCodes(mergedConfig.ExecProvider.InstallHint)\n\t\tmergedConfig.ExecProvider.Config = configClusterInfo.Extensions[clusterExtensionKey]\n\t}\n\n\t// if there still isn't enough information to authenticate the user, try prompting\n\tif !canIdentifyUser(*mergedConfig) && (fallbackReader != nil) {\n\t\tif len(config.promptedCredentials.username) > 0 && len(config.promptedCredentials.password) > 0 {\n\t\t\tmergedConfig.Username = config.promptedCredentials.username\n\t\t\tmergedConfig.Password = config.promptedCredentials.password\n\t\t\treturn mergedConfig, nil\n\t\t}\n\t\tprompter := NewPromptingAuthLoader(fallbackReader)\n\t\tpromptedAuthInfo, err := prompter.Prompt()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tpromptedConfig := makeUserIdentificationConfig(*promptedAuthInfo)\n\t\tpreviouslyMergedConfig := mergedConfig\n\t\tmergedConfig = &restclient.Config{}\n\t\tmergo.Merge(mergedConfig, promptedConfig, mergo.WithOverride)\n\t\tmergo.Merge(mergedConfig, previouslyMergedConfig, mergo.WithOverride)\n\t\tconfig.promptedCredentials.username = mergedConfig.Username\n\t\tconfig.promptedCredentials.password = mergedConfig.Password\n\t}\n\n\treturn mergedConfig, nil\n}", "func TestNewConfigNATSAuth(t *testing.T) {\n\tconfig, err := NewConfig(\"configs/nats-auth.yaml\")\n\trequire.NoError(t, err)\n\trequire.Equal(t, \"admin\", config.NATS.User)\n\trequire.Equal(t, \"password\", config.NATS.Password)\n}", "func (c *IdentityConfig) networkConfig() (*fab.NetworkConfig, error) {\n\tif c.endpointConfig == nil {\n\t\treturn nil, errors.New(\"network config not initialized for identity config\")\n\t}\n\treturn c.endpointConfig.NetworkConfig()\n}", "func validateConfig(appConfig AppConfig) error {\n\n\treturn nil\n}", "func TestAutoSyncConfigServicesNotModify(t *testing.T) {\n\tserver := runNotModifyConfigResponse()\n\tnewAppConfig := getTestAppConfig()\n\tnewAppConfig.Ip = server.URL\n\n\tapolloConfig, err := createApolloConfigWithJson([]byte(configResponseStr))\n\tupdateApolloConfig(apolloConfig, true)\n\n\ttime.Sleep(10 * time.Second)\n\tcheckCacheLeft(t, configCacheExpireTime-10)\n\n\tappConfig.NextTryConnTime = 0\n\n\terr = autoSyncConfigServices(newAppConfig)\n\n\ttest.Nil(t, err)\n\n\tconfig := GetCurrentApolloConfig()\n\n\ttest.Equal(t, \"100004458\", config.AppId)\n\ttest.Equal(t, \"default\", config.Cluster)\n\ttest.Equal(t, \"application\", config.NamespaceName)\n\ttest.Equal(t, \"20170430092936-dee2d58e74515ff3\", config.ReleaseKey)\n\n\tcheckCacheLeft(t, configCacheExpireTime)\n\n\t//test.Equal(t,\"value1\",config.Configurations[\"key1\"])\n\t//test.Equal(t,\"value2\",config.Configurations[\"key2\"])\n}", "func validateConfig(conf *Config) {\n\t// Hopefully lxc package derives this correctly\n\tif conf.LXCPath == \"\" {\n\t\tconf.LXCPath = lxc.DefaultConfigPath()\n\t}\n\n\t// Generate \"Docker-style\" container names if it is not provided\n\tif conf.Name == \"\" {\n\t\tconf.Name = randomdata.SillyName()\n\t}\n}", "func (a *Azure) ValidConfig() bool {\n\treturn a.SubscriptionID != \"\" && a.ClientID != \"\" && a.ClientSecret != \"\" && a.TenantID != \"\"\n}", "func IsAideConfig(labels map[string]string) bool {\n\t_, ok := labels[AideConfigLabelKey]\n\treturn ok\n}", "func IsAideConfig(labels map[string]string) bool {\n\t_, ok := labels[AideConfigLabelKey]\n\treturn ok\n}", "func (a *apiServer) updateConfig(config *auth.AuthConfig) error {\n\tif config == nil {\n\t\tconfig = &auth.AuthConfig{}\n\t}\n\tnewConfig, err := validateConfig(config, internal)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// It's possible that 'config' is non-nil, but empty (this is the case when\n\t// users clear the config from the command line). Therefore, check\n\t// newConfig.IDP.Name != \"\" instead of config != nil.\n\tif newConfig.IDP.Name != \"\" {\n\t\ta.configCache = newConfig\n\t\t// construct SAML handler\n\t\ta.samlSP = &saml.ServiceProvider{\n\t\t\tLogger: logrus.New(),\n\t\t\tIDPMetadata: a.configCache.IDP.Metadata,\n\t\t\tAcsURL: *a.configCache.SAMLSvc.ACSURL,\n\t\t\tMetadataURL: *a.configCache.SAMLSvc.MetadataURL,\n\n\t\t\t// Not set:\n\t\t\t// Key: Private key for Pachyderm ACS. Unclear if needed\n\t\t\t// Certificate: Public key for Pachyderm ACS. Unclear if needed\n\t\t\t// ForceAuthn: (whether users need to re-authenticate with the IdP, even\n\t\t\t// if they already have a session--leaving this false)\n\t\t\t// AuthnNameIDFormat: (format the ACS expects the AuthnName to be in)\n\t\t\t// MetadataValidDuration: (how long the SP endpoints are valid? Returned\n\t\t\t// by the Metadata service)\n\t\t}\n\t\ta.redirectAddress = a.configCache.SAMLSvc.DashURL // Set redirect address from config as well\n\t} else {\n\t\ta.configCache = nil\n\t\ta.samlSP = nil\n\t\ta.redirectAddress = nil\n\t}\n\treturn nil\n}", "func ObserveAuthMetadata(genericListers configobserver.Listers, recorder events.Recorder, existingConfig map[string]interface{}) (map[string]interface{}, []error) {\n\tlisters := genericListers.(configobservation.Listers)\n\terrs := []error{}\n\tprevObservedConfig := map[string]interface{}{}\n\n\ttopLevelMetadataFilePath := []string{\"authConfig\", \"oauthMetadataFile\"}\n\tcurrentMetadataFilePath, _, err := unstructured.NestedString(existingConfig, topLevelMetadataFilePath...)\n\tif err != nil {\n\t\terrs = append(errs, err)\n\t}\n\tif len(currentMetadataFilePath) > 0 {\n\t\tif err := unstructured.SetNestedField(prevObservedConfig, currentMetadataFilePath, topLevelMetadataFilePath...); err != nil {\n\t\t\terrs = append(errs, err)\n\t\t}\n\t}\n\n\tobservedConfig := map[string]interface{}{}\n\tauthConfigNoDefaults, err := listers.AuthConfigLister.Get(\"cluster\")\n\tif errors.IsNotFound(err) {\n\t\tklog.Warningf(\"authentications.config.openshift.io/cluster: not found\")\n\t\treturn observedConfig, errs\n\t}\n\tif err != nil {\n\t\terrs = append(errs, err)\n\t\treturn prevObservedConfig, errs\n\t}\n\n\tauthConfig := defaultAuthConfig(authConfigNoDefaults)\n\n\tvar (\n\t\tsourceNamespace string\n\t\tsourceConfigMap string\n\t\tstatusConfigMap string\n\t)\n\n\tspecConfigMap := authConfig.Spec.OAuthMetadata.Name\n\n\t// TODO: Add a case here for the KeyCloak type.\n\tswitch {\n\tcase len(authConfig.Status.IntegratedOAuthMetadata.Name) > 0 && authConfig.Spec.Type == configv1.AuthenticationTypeIntegratedOAuth:\n\t\tstatusConfigMap = authConfig.Status.IntegratedOAuthMetadata.Name\n\tdefault:\n\t\tklog.V(5).Infof(\"no integrated oauth metadata configmap observed from status\")\n\t}\n\n\t// Spec configMap takes precedence over Status.\n\tswitch {\n\tcase len(specConfigMap) > 0:\n\t\tsourceConfigMap = specConfigMap\n\t\tsourceNamespace = configNamespace\n\tcase len(statusConfigMap) > 0:\n\t\tsourceConfigMap = statusConfigMap\n\t\tsourceNamespace = managedNamespace\n\tdefault:\n\t\tklog.V(5).Infof(\"no authentication config metadata specified\")\n\t}\n\n\t// Sync the user or status-specified configMap to the well-known resting place that corresponds to the oauthMetadataFile path.\n\t// If neither are set, this updates the destination with an empty source, which deletes the destination resource.\n\terr = listers.ResourceSyncer().SyncConfigMap(\n\t\tresourcesynccontroller.ResourceLocation{\n\t\t\tNamespace: targetNamespaceName,\n\t\t\tName: \"oauth-metadata\",\n\t\t},\n\t\tresourcesynccontroller.ResourceLocation{\n\t\t\tNamespace: sourceNamespace,\n\t\t\tName: sourceConfigMap,\n\t\t},\n\t)\n\tif err != nil {\n\t\terrs = append(errs, err)\n\t\treturn prevObservedConfig, errs\n\t}\n\n\t// Unsets oauthMetadataFile if we had an empty source.\n\tif len(sourceConfigMap) == 0 {\n\t\treturn observedConfig, errs\n\t}\n\n\t// Set oauthMetadataFile.\n\tif err := unstructured.SetNestedField(observedConfig, oauthMetadataFilePath, topLevelMetadataFilePath...); err != nil {\n\t\trecorder.Eventf(\"ObserveAuthMetadataConfigMap\", \"Failed setting oauthMetadataFile: %v\", err)\n\t\terrs = append(errs, err)\n\t}\n\n\treturn observedConfig, errs\n}", "func (c *Client) IDTokenUserinfoClaimsAssertion() bool {\n\treturn c.idTokenUserinfoClaimsAssertion\n}", "func (me TxsdComponentTransferFunctionAttributesType) IsIdentity() bool {\n\treturn me.String() == \"identity\"\n}", "func (mr *MockTxMockRecorder) UpdateConfig(arg0 interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"UpdateConfig\", reflect.TypeOf((*MockTx)(nil).UpdateConfig), arg0)\n}", "func TestConfigure_UseExistingASN(t *testing.T) {\n\tASNOnDevice := \"65001\"\n\tMockLeafDeviceAdapter := mock.DeviceAdapter{\n\t\tMockGetInterfaces: func(FabricID uint, DeviceID uint, DeviceIP string) ([]domain.Interface, error) {\n\n\t\t\treturn []domain.Interface{domain.Interface{FabricID: FabricID, DeviceID: DeviceID,\n\t\t\t\tIntType: \"ethernet\", IntName: \"1/11\", Mac: \"M1\", ConfigState: \"up\"}}, nil\n\n\t\t},\n\t\tMockGetLLDPs: func(FabricID uint, DeviceID uint, DeviceIP string) ([]domain.LLDP, error) {\n\n\t\t\treturn []domain.LLDP{domain.LLDP{FabricID: FabricID, DeviceID: DeviceID,\n\t\t\t\tLocalIntType: \"ethernet\", LocalIntName: \"1/11\", LocalIntMac: \"M1\",\n\t\t\t\tRemoteIntType: \"ethernet\", RemoteIntName: \"1/22\", RemoteIntMac: \"M2\"}}, nil\n\n\t\t},\n\t\tMockGetASN: func(FabricID uint, Device uint, DeviceIP string) (string, error) {\n\t\t\treturn ASNOnDevice, nil\n\t\t},\n\t}\n\n\tdatabase.Setup(constants.TESTDBLocation)\n\tdefer cleanupDB(database.GetWorkingInstance())\n\n\tDatabaseRepository := gateway.DatabaseRepository{Database: database.GetWorkingInstance()}\n\tdevUC := usecase.DeviceInteractor{Db: &DatabaseRepository, DeviceAdapterFactory: mock.GetDeviceAdapterFactory(MockLeafDeviceAdapter)}\n\tdevUC.AddFabric(context.Background(), MockFabricName)\n\n\tresp, err := devUC.AddDevices(context.Background(), MockFabricName, []string{MockLeaf1IP}, []string{},\n\t\tUserName, Password, false)\n\tassert.Contains(t, resp, usecase.AddDeviceResponse{FabricName: MockFabricName, FabricID: 1, IPAddress: MockLeaf1IP, Role: usecase.LeafRole})\n\n\tassert.Nil(t, err)\n\n\tswitchConfig, err := DatabaseRepository.GetSwitchConfigOnDeviceIP(MockFabricName, MockLeaf1IP)\n\tassert.Equal(t, ASNOnDevice, switchConfig.LocalAS)\n\t//Verify ASN is already on the Switch, so need to push\n\tassert.Equal(t, domain.ConfigNone, switchConfig.ASConfigType)\n\n\t//Next Call without Device having ASN\n\tMockLeafDeviceAdapterWithoutASN := mock.DeviceAdapter{\n\t\tMockGetInterfaces: func(FabricID uint, DeviceID uint, DeviceIP string) ([]domain.Interface, error) {\n\n\t\t\treturn []domain.Interface{domain.Interface{FabricID: FabricID, DeviceID: DeviceID,\n\t\t\t\tIntType: \"ethernet\", IntName: \"1/11\", Mac: \"M1\", ConfigState: \"up\"}}, nil\n\n\t\t},\n\t\tMockGetLLDPs: func(FabricID uint, DeviceID uint, DeviceIP string) ([]domain.LLDP, error) {\n\n\t\t\treturn []domain.LLDP{domain.LLDP{FabricID: FabricID, DeviceID: DeviceID,\n\t\t\t\tLocalIntType: \"ethernet\", LocalIntName: \"1/11\", LocalIntMac: \"M1\",\n\t\t\t\tRemoteIntType: \"ethernet\", RemoteIntName: \"1/22\", RemoteIntMac: \"M2\"}}, nil\n\n\t\t},\n\t}\n\tdevUC.DeviceAdapterFactory = mock.GetDeviceAdapterFactory(MockLeafDeviceAdapterWithoutASN)\n\tresp, err = devUC.AddDevices(context.Background(), MockFabricName, []string{MockLeaf1IP}, []string{},\n\t\tUserName, Password, false)\n\tassert.Contains(t, resp, usecase.AddDeviceResponse{FabricName: MockFabricName, FabricID: 1, IPAddress: MockLeaf1IP, Role: usecase.LeafRole})\n\n\tassert.Nil(t, err)\n\tswitchConfigSecond, err := DatabaseRepository.GetSwitchConfigOnDeviceIP(MockFabricName, MockLeaf1IP)\n\tassert.Equal(t, ASNOnDevice, switchConfigSecond.LocalAS)\n\t//Verify ASN is to be created\n\tassert.Equal(t, domain.ConfigCreate, switchConfigSecond.ASConfigType)\n}", "func TestAccessConfig(t *testing.T) {\n\ttests := []struct {\n\t\twhat string\n\t\twant AccessLevel\n\t\tlevel AccessLevel\n\t}{\n\t\t{\"admin\", AccessAdmin, config.Namespaces[\"access-admin\"].AccessLevel},\n\t\t{\"admin/0\", AccessAdmin, config.Namespaces[\"access-admin\"].Reporting[0].AccessLevel},\n\t\t{\"admin/1\", AccessAdmin, config.Namespaces[\"access-admin\"].Reporting[1].AccessLevel},\n\t\t{\"user\", AccessUser, config.Namespaces[\"access-user\"].AccessLevel},\n\t\t{\"user/0\", AccessAdmin, config.Namespaces[\"access-user\"].Reporting[0].AccessLevel},\n\t\t{\"user/1\", AccessUser, config.Namespaces[\"access-user\"].Reporting[1].AccessLevel},\n\t\t{\"public\", AccessPublic, config.Namespaces[\"access-public\"].AccessLevel},\n\t\t{\"public/0\", AccessUser, config.Namespaces[\"access-public\"].Reporting[0].AccessLevel},\n\t\t{\"public/1\", AccessPublic, config.Namespaces[\"access-public\"].Reporting[1].AccessLevel},\n\t}\n\tfor _, test := range tests {\n\t\tif test.level != test.want {\n\t\t\tt.Errorf(\"%v level %v, want %v\", test.what, test.level, test.want)\n\t\t}\n\t}\n}", "func (c *Config) Verify() error {\n\tif c.Lager == nil {\n\t\treturn ErrInvalidLager\n\t}\n\n\tif c.Pool == nil {\n\t\treturn ErrInvalidPool\n\t}\n\n\treturn nil\n}", "func testIATBHOriginatorIdentification(t testing.TB) {\n\tbh := mockIATBatchHeaderFF()\n\tbh.OriginatorIdentification = \"\"\n\terr := bh.Validate()\n\tif !base.Match(err, ErrFieldInclusion) {\n\t\tt.Errorf(\"%T: %s\", err, err)\n\t}\n}", "func (a *AllApiService) ConfigurationGetIdentifiableApplications(ctx _context.Context, body ConfigurationGetIdentifiableApplications) (ConfigurationGetIdentifiableApplicationsResult, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHttpMethod = _nethttp.MethodPost\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue ConfigurationGetIdentifiableApplicationsResult\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/configuration/getIdentifiableApplications\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHttpContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes)\n\tif localVarHttpContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHttpContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHttpHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts)\n\tif localVarHttpHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHttpHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = &body\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHttpResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHttpResponse == nil {\n\t\treturn localVarReturnValue, localVarHttpResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHttpResponse.Body)\n\tlocalVarHttpResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHttpResponse, err\n\t}\n\n\tif localVarHttpResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHttpResponse.Status,\n\t\t}\n\t\tif localVarHttpResponse.StatusCode == 200 {\n\t\t\tvar v ConfigurationGetIdentifiableApplicationsResult\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\t\tif localVarHttpResponse.StatusCode == 400 {\n\t\t\tvar v ModelError\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\t\tif localVarHttpResponse.StatusCode == 500 {\n\t\t\tvar v ModelError\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHttpResponse, nil\n}", "func ProvidersConfig(t *testing.T) *config.Config {\n\tconst (\n\t\ttestClientKey = \"provider-test-client-key\"\n\t\ttestSecret = \"provider-test-secret\"\n\t\ttestCallback = \"http://auth.exmaple.com/test/callback\"\n\t)\n\tsetEnv(t, config.Auth0DomainEnv, \"example.com\")\n\tsetEnv(t, config.OpenIDConnectURLEnv, MockOpenIDConnect(t))\n\tsetEnv(t, config.AzureADTenantEnv, string(azureadv2.CommonTenant))\n\tvar testScopes = []string{\"test-scope-1\", \"test-scope-2\"}\n\tc := Config(t)\n\ta := config.Authorization{\n\t\tProviders: map[provider.Name]config.Provider{},\n\t}\n\ta.UseInternal = true\n\tfor name := range provider.External {\n\t\ta.Providers[name] = config.Provider{\n\t\t\tClientKey: testClientKey,\n\t\t\tSecret: testSecret,\n\t\t\tCallbackURL: testCallback,\n\t\t\tScopes: testScopes,\n\t\t}\n\t}\n\t// FIXME: core/auth/providers.go:162\n\tt.Log(\"skipping \", provider.Apple)\n\tdelete(a.Providers, provider.Apple)\n\tc.Authorization = a\n\treturn c\n}", "func (spec *Spec) identity() (*core.Identity, error) {\n\tident := &core.Identity{\n\t\tRequest: spec.Request,\n\t\tRoots: []*core.Root{\n\t\t\t&core.Root{\n\t\t\t\tType: \"system\",\n\t\t\t},\n\t\t\t&core.Root{\n\t\t\t\tType: \"cfssl\",\n\t\t\t\tMetadata: map[string]string{\n\t\t\t\t\t\"host\": spec.CA.Remote,\n\t\t\t\t\t\"profile\": spec.CA.Profile,\n\t\t\t\t\t\"label\": spec.CA.Label,\n\t\t\t\t\t\"tls-remote-ca\": spec.CA.RootCACert,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tProfiles: map[string]map[string]string{\n\t\t\t\"cfssl\": map[string]string{\n\t\t\t\t\"remote\": spec.CA.Remote,\n\t\t\t\t\"profile\": spec.CA.Profile,\n\t\t\t\t\"label\": spec.CA.Label,\n\t\t\t\t\"tls-remote-ca\": spec.CA.RootCACert,\n\t\t\t},\n\t\t},\n\t}\n\n\tauthkey := spec.CA.AuthKey\n\tif spec.CA.AuthKeyFile != \"\" {\n\t\tlog.Debugf(\"loading auth_key_file %v\", spec.CA.AuthKeyFile)\n\t\tcontent, err := ioutil.ReadFile(spec.CA.AuthKeyFile)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed reading auth_key_file %v: %v\", spec.CA.AuthKeyFile, err)\n\t\t}\n\t\tauthkey = strings.TrimSpace(string(content))\n\t}\n\tif authkey != \"\" {\n\t\tident.Profiles[\"cfssl\"][\"auth-type\"] = \"standard\"\n\t\tident.Profiles[\"cfssl\"][\"auth-key\"] = authkey\n\t}\n\n\treturn ident, nil\n}", "func (spec *Spec) identity() (*core.Identity, error) {\n\tident := &core.Identity{\n\t\tRequest: spec.Request,\n\t\tRoots: []*core.Root{\n\t\t\t&core.Root{\n\t\t\t\tType: \"system\",\n\t\t\t},\n\t\t\t&core.Root{\n\t\t\t\tType: \"cfssl\",\n\t\t\t\tMetadata: map[string]string{\n\t\t\t\t\t\"host\": spec.CA.Remote,\n\t\t\t\t\t\"profile\": spec.CA.Profile,\n\t\t\t\t\t\"label\": spec.CA.Label,\n\t\t\t\t\t\"tls-remote-ca\": spec.CA.RootCACert,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tProfiles: map[string]map[string]string{\n\t\t\t\"cfssl\": map[string]string{\n\t\t\t\t\"remote\": spec.CA.Remote,\n\t\t\t\t\"profile\": spec.CA.Profile,\n\t\t\t\t\"label\": spec.CA.Label,\n\t\t\t\t\"tls-remote-ca\": spec.CA.RootCACert,\n\t\t\t},\n\t\t},\n\t}\n\n\tauthkey := spec.CA.AuthKey\n\tif spec.CA.AuthKeyFile != \"\" {\n\t\tlog.Debugf(\"loading auth_key_file %v\", spec.CA.AuthKeyFile)\n\t\tcontent, err := ioutil.ReadFile(spec.CA.AuthKeyFile)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed reading auth_key_file %v: %v\", spec.CA.AuthKeyFile, err)\n\t\t}\n\t\tauthkey = strings.TrimSpace(string(content))\n\t}\n\tif authkey != \"\" {\n\t\tident.Profiles[\"cfssl\"][\"auth-type\"] = \"standard\"\n\t\tident.Profiles[\"cfssl\"][\"auth-key\"] = authkey\n\t}\n\n\treturn ident, nil\n}", "func (s *PullSubscription) IdentitySpec() *v1beta1.IdentitySpec {\n\treturn &s.Spec.IdentitySpec\n}", "func (config *IDConfig) validate() error {\n\tswitch config.idType {\n\tcase \"halo-id\", \"m200m\":\n\tdefault:\n\t\treturn fmt.Errorf(\"The 'IDType' variable is set to '%s', which I \"+\n\t\t\t\"don't recognize.\", config.idType)\n\t}\n\n\tswitch config.exclusionStrategy {\n\tcase \"none\", \"subhalo\", \"neighbor\":\n\tcase \"overlap\":\n\t\tif config.exclusionRadiusMult <= 0 {\n\t\t\treturn fmt.Errorf(\"The 'ExclusionRadiusMult' varaible is set to \"+\n\t\t\t\t\"%g, but it needs to be positive.\", config.exclusionRadiusMult)\n\t\t}\n\tdefault:\n\t\treturn fmt.Errorf(\"The 'ExclusionStrategy' variable is set to '%s', \"+\n\t\t\t\"which I don't recognize.\", config.exclusionStrategy)\n\t}\n\n\tswitch {\n\tcase config.snap == -1:\n\t\treturn fmt.Errorf(\"'Snap' variable not set.\")\n\tcase config.snap < 0:\n\t\treturn fmt.Errorf(\"'Snap' variable set to %d.\", config.snap)\n\t}\n\n\tif config.mult <= 0 {\n\t\treturn fmt.Errorf(\"'Mult' variable set to %d\", config.mult)\n\t}\n\n\tswitch {\n\tcase config.m200mMax < 0:\n\t\treturn fmt.Errorf(\"M200mStart set to %g\", config.m200mMax)\n\tcase config.m200mMax > config.m200mMin:\n\t\tfmt.Errorf(\"M200mEnd smaller than M200mStart\")\n\t}\n\n\treturn nil\n}", "func (ec *Client) ConfigCall(fromAddress common.Address) (*bind.CallOpts){\n\treturn &bind.CallOpts{Pending: false, From:fromAddress, BlockNumber:nil, Context:nil}\n}", "func (o ClusterOutput) WorkloadIdentityConfig() ClusterWorkloadIdentityConfigOutput {\n\treturn o.ApplyT(func(v *Cluster) ClusterWorkloadIdentityConfigOutput { return v.WorkloadIdentityConfig }).(ClusterWorkloadIdentityConfigOutput)\n}", "func (p *Provider) ValidateIdentityParams(ctx context.Context, code, cookie, state string) (t *Token, err error) {\n\tt, _, err = p.ValidateIdentityParamsWithUserdata(ctx, code, cookie, state)\n\treturn\n}", "func TestConnectionConfigValidation(t *testing.T) {\n\t// Tests.\n\tvar tests = []struct {\n\t\tconfig *Config\n\t\texpected string\n\t}{\n\t\t{\t&Config{}, \n\t\t\t\"The datasource connection was not defined.\",\n\t\t},\n\t\t{\n\t\t\t&Config{\n\t\t\t\tConnection: &ConnectionConfig{}, \n\t\t\t},\n\t\t\t\"The datasource connection protocol was not defined.\",\n\t\t},\n\t\t{\n\t\t\t&Config{\n\t\t\t\tConnection: &ConnectionConfig{Protocol: MongoDBProtocol}, \n\t\t\t},\n\t\t\t\"The datasource connection host was not defined.\",\n\t\t},\n\t\t{\n\t\t\t&Config{\n\t\t\t\tConnection: &ConnectionConfig{Protocol: MongoDBProtocol, Host: Localhost}, \n\t\t\t},\n\t\t\t\"The datasource connection port '0' was less than 1000.\",\n\t\t},\n\t\t{\n\t\t\t&Config{\n\t\t\t\tConnection: &ConnectionConfig{Protocol: MongoDBProtocol, Host: Localhost, Port: -1}, \n\t\t\t},\n\t\t\t\"The datasource connection port '-1' was less than 1000.\",\n\t\t},\t\t\n\t}\n\t// Run tests.\n\tfor _, test := range tests {\n\t\tf := func() {\n \t\ttest.config.validate()\n\t\t}\n\t\tassert.Panics(t, f)\n\t\tassert.PanicsWithValue(t, test.expected, f)\n\t}\n}" ]
[ "0.69043285", "0.59411687", "0.5913649", "0.5871216", "0.5865579", "0.5274517", "0.5225483", "0.5223157", "0.51497453", "0.50445426", "0.50436527", "0.5038403", "0.50058174", "0.5002979", "0.4980852", "0.49727315", "0.49639088", "0.4956983", "0.49538288", "0.4951847", "0.49317396", "0.4915494", "0.49065584", "0.48688895", "0.4856402", "0.48210454", "0.48210454", "0.4759264", "0.47551146", "0.474606", "0.47440937", "0.4743153", "0.4708994", "0.46993768", "0.4690742", "0.46799004", "0.4673278", "0.4672649", "0.46695536", "0.46607468", "0.46587077", "0.46470243", "0.46470094", "0.46332687", "0.4630577", "0.46297362", "0.46297285", "0.46116638", "0.46001425", "0.4588989", "0.45887473", "0.4566974", "0.45516318", "0.45476696", "0.45382354", "0.4527542", "0.4522287", "0.4490328", "0.44744274", "0.44723433", "0.44666964", "0.44610938", "0.44569072", "0.4456093", "0.44487655", "0.44445735", "0.44369212", "0.4421025", "0.4420481", "0.44197914", "0.44103095", "0.44087517", "0.43984008", "0.43980828", "0.439497", "0.43901232", "0.43873182", "0.4385447", "0.43795055", "0.4370849", "0.4370849", "0.4366848", "0.43634275", "0.436206", "0.4360426", "0.43603292", "0.43589056", "0.43561968", "0.4355513", "0.43430957", "0.43415812", "0.43405056", "0.43382034", "0.43382034", "0.43377164", "0.4334725", "0.43328196", "0.43183258", "0.4316306", "0.43141612" ]
0.69439846
0
IdentityManager mocks base method
func (m *MockProviders) IdentityManager(arg0 string) (msp.IdentityManager, bool) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "IdentityManager", arg0) ret0, _ := ret[0].(msp.IdentityManager) ret1, _ := ret[1].(bool) return ret0, ret1 }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (m *MockClient) IdentityManager(arg0 string) (msp.IdentityManager, bool) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"IdentityManager\", arg0)\n\tret0, _ := ret[0].(msp.IdentityManager)\n\tret1, _ := ret[1].(bool)\n\treturn ret0, ret1\n}", "func TestNewIdentityManager(t *testing.T) {\n\tt.Run(\"success\", func(t *testing.T) {\n\t\tepCfg := &mocks.EndpointConfig{}\n\t\tepCfg.NetworkConfigReturns(&fab.NetworkConfig{\n\t\t\tOrganizations: map[string]fab.OrganizationConfig{\"org1msp\": {}},\n\t\t})\n\n\t\tm, err := newIdentityManager(\"org1MSP\", &mocks.CryptoSuite{}, epCfg, \"./msp\")\n\t\trequire.NoError(t, err)\n\t\trequire.NotNil(t, m)\n\t})\n\n\tt.Run(\"No endpoint config -> error\", func(t *testing.T) {\n\t\tm, err := newIdentityManager(\"org1MSP\", &mocks.CryptoSuite{}, nil, \"./msp\")\n\t\trequire.EqualError(t, err, \"endpoint config is required\")\n\t\trequire.Nil(t, m)\n\t})\n\n\tt.Run(\"No org name -> error\", func(t *testing.T) {\n\t\tm, err := newIdentityManager(\"\", nil, &mocks.EndpointConfig{}, \"./msp\")\n\t\trequire.EqualError(t, err, \"orgName is required\")\n\t\trequire.Nil(t, m)\n\t})\n\n\tt.Run(\"No crypto suite -> error\", func(t *testing.T) {\n\t\tm, err := newIdentityManager(\"org1MSP\", nil, &mocks.EndpointConfig{}, \"./msp\")\n\t\trequire.EqualError(t, err, \"cryptoProvider is required\")\n\t\trequire.Nil(t, m)\n\t})\n\n\tt.Run(\"Org not found -> error\", func(t *testing.T) {\n\t\tepCfg := &mocks.EndpointConfig{}\n\t\tepCfg.NetworkConfigReturns(&fab.NetworkConfig{})\n\n\t\tm, err := newIdentityManager(\"org1MSP\", &mocks.CryptoSuite{}, epCfg, \"./msp\")\n\t\trequire.EqualError(t, err, \"org config retrieval failed\")\n\t\trequire.Nil(t, m)\n\t})\n\n\tt.Run(\"MSP config path not provided -> error\", func(t *testing.T) {\n\t\tepCfg := &mocks.EndpointConfig{}\n\t\tepCfg.NetworkConfigReturns(&fab.NetworkConfig{\n\t\t\tOrganizations: map[string]fab.OrganizationConfig{\"org1msp\": {}},\n\t\t})\n\n\t\tm, err := newIdentityManager(\"org1MSP\", &mocks.CryptoSuite{}, epCfg, \"\")\n\t\trequire.EqualError(t, err, \"either mspConfigPath or an embedded list of users is required\")\n\t\trequire.Nil(t, m)\n\t})\n}", "func (m *MockChoriaProvider) Identity() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Identity\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func (m *MockMachine) Identity() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Identity\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func NewIdentityService(t mockConstructorTestingTNewIdentityService) *IdentityService {\n\tmock := &IdentityService{}\n\tmock.Mock.Test(t)\n\n\tt.Cleanup(func() { mock.AssertExpectations(t) })\n\n\treturn mock\n}", "func (u *MockUser) Identity() ([]byte, error) {\n\treturn []byte(\"test\"), nil\n}", "func (p *MockProvisionerClient) Identity() client.IdentityInterface {\n\treturn &MockIdentityClient{}\n}", "func (p *MockProvisionerClient) Identity() client.IdentityInterface {\n\treturn &MockIdentityClient{}\n}", "func NewIdentityProviderBase()(*IdentityProviderBase) {\n m := &IdentityProviderBase{\n Entity: *NewEntity(),\n }\n return m\n}", "func (suite *HealthCheckTestSuite) TestModuleExecuteWithOnPremIdentity() {\n\t// Initialize the appconfigMock with HealthFrequencyMinutes as every five minute\n\tappconfigMock := &appconfig.SsmagentConfig{\n\t\tSsm: appconfig.SsmCfg{\n\t\t\tHealthFrequencyMinutes: appconfig.DefaultSsmHealthFrequencyMinutes,\n\t\t},\n\t}\n\n\tmockEC2Identity := &identityMock.IAgentIdentityInner{}\n\tnewEC2Identity = func(log log.T) identity.IAgentIdentityInner {\n\t\treturn mockEC2Identity\n\t}\n\n\tavailabilityZone := \"us-east-1a\"\n\tavailabilityZoneId := \"use1-az2\"\n\tmockEC2Identity.On(\"IsIdentityEnvironment\").Return(true)\n\tmockEC2Identity.On(\"AvailabilityZone\").Return(availabilityZone, nil)\n\tmockEC2Identity.On(\"AvailabilityZoneId\").Return(availabilityZoneId, nil)\n\n\tmockOnPremIdentity := &identityMock.IAgentIdentityInner{}\n\tnewOnPremIdentity = func(log log.T, config *appconfig.SsmagentConfig) identity.IAgentIdentityInner {\n\t\treturn mockOnPremIdentity\n\t}\n\tmockOnPremIdentity.On(\"IsIdentityEnvironment\").Return(true)\n\n\tmockECSIdentity := &identityMock.IAgentIdentityInner{}\n\tnewECSIdentity = func(log log.T) identity.IAgentIdentityInner {\n\t\treturn mockECSIdentity\n\t}\n\tmockECSIdentity.On(\"IsIdentityEnvironment\").Return(false)\n\n\tssmConnectionChannel := \"ssmmessages\"\n\tvar ableToOpenMGSConnection uint32\n\tatomic.StoreUint32(&ableToOpenMGSConnection, 1)\n\tssmconnectionchannel.SetConnectionChannel(&ableToOpenMGSConnection)\n\n\t// Turn on the mock method\n\tsuite.contextMock.On(\"AppConfig\").Return(*appconfigMock)\n\tsuite.serviceMock.On(\"UpdateInstanceInformation\", mock.Anything, version.Version, \"Active\", AgentName, \"\", \"\", ssmConnectionChannel).Return(nil, nil)\n\tsuite.healthCheck.ModuleExecute()\n\t// Because ModuleExecute will launch two new go routine, wait 100ms to make sure the updateHealth() has launched\n\ttime.Sleep(100 * time.Millisecond)\n\t// Assert the UpdateInstanceInformation get called in updateHealth() function, and the agent status is same as input.\n\tsuite.serviceMock.AssertCalled(suite.T(), \"UpdateInstanceInformation\", mock.Anything, version.Version, \"Active\", AgentName, \"\", \"\", ssmConnectionChannel)\n\tsuite.serviceMock.AssertNotCalled(suite.T(), \"IsIdentityEnvironment\", true)\n}", "func (c *Provider) IdentityManager(orgName string) (msp.IdentityManager, bool) {\n\treturn c.idMgmtProvider.IdentityManager(orgName)\n}", "func (m *MockProviders) IdentityConfig() msp.IdentityConfig {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"IdentityConfig\")\n\tret0, _ := ret[0].(msp.IdentityConfig)\n\treturn ret0\n}", "func createKeycloakInterfaceMock() (keycloakCommon.KeycloakInterface, *mockClientContext) {\n\tcontext := mockClientContext{\n\t\tGroups: []*keycloakCommon.Group{},\n\t\tDefaultGroups: []*keycloakCommon.Group{},\n\t\tClientRoles: map[string][]*keycloak.KeycloakUserRole{},\n\t\tRealmRoles: map[string][]*keycloak.KeycloakUserRole{},\n\t\tAuthenticationFlowsExecutions: map[string][]*keycloak.AuthenticationExecutionInfo{\n\t\t\tfirstBrokerLoginFlowAlias: []*keycloak.AuthenticationExecutionInfo{\n\t\t\t\t&keycloak.AuthenticationExecutionInfo{\n\t\t\t\t\tRequirement: \"REQUIRED\",\n\t\t\t\t\tAlias: reviewProfileExecutionAlias,\n\t\t\t\t},\n\t\t\t\t// dummy ones\n\t\t\t\t&keycloak.AuthenticationExecutionInfo{\n\t\t\t\t\tRequirement: \"REQUIRED\",\n\t\t\t\t\tAlias: \"dummy execution\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\tavailableGroupClientRoles := []*keycloak.KeycloakUserRole{\n\t\t&keycloak.KeycloakUserRole{\n\t\t\tID: \"create-client\",\n\t\t\tName: \"create-client\",\n\t\t},\n\t\t&keycloak.KeycloakUserRole{\n\t\t\tID: \"manage-authorization\",\n\t\t\tName: \"manage-authorization\",\n\t\t},\n\t\t&keycloak.KeycloakUserRole{\n\t\t\tID: \"manage-clients\",\n\t\t\tName: \"manage-clients\",\n\t\t},\n\t\t&keycloak.KeycloakUserRole{\n\t\t\tID: \"manage-events\",\n\t\t\tName: \"manage-events\",\n\t\t},\n\t\t&keycloak.KeycloakUserRole{\n\t\t\tID: \"manage-identity-providers\",\n\t\t\tName: \"manage-identity-providers\",\n\t\t},\n\t\t&keycloak.KeycloakUserRole{\n\t\t\tID: \"manage-realm\",\n\t\t\tName: \"manage-realm\",\n\t\t},\n\t\t&keycloak.KeycloakUserRole{\n\t\t\tID: \"manage-users\",\n\t\t\tName: \"manage-users\",\n\t\t},\n\t\t&keycloak.KeycloakUserRole{\n\t\t\tID: \"query-clients\",\n\t\t\tName: \"query-clients\",\n\t\t},\n\t\t&keycloak.KeycloakUserRole{\n\t\t\tID: \"query-groups\",\n\t\t\tName: \"query-groups\",\n\t\t},\n\t\t&keycloak.KeycloakUserRole{\n\t\t\tID: \"query-realms\",\n\t\t\tName: \"query-realms\",\n\t\t},\n\t\t&keycloak.KeycloakUserRole{\n\t\t\tID: \"query-users\",\n\t\t\tName: \"query-users\",\n\t\t},\n\t\t&keycloak.KeycloakUserRole{\n\t\t\tID: \"view-authorization\",\n\t\t\tName: \"view-authorization\",\n\t\t},\n\t\t&keycloak.KeycloakUserRole{\n\t\t\tID: \"view-clients\",\n\t\t\tName: \"view-clients\",\n\t\t},\n\t\t&keycloak.KeycloakUserRole{\n\t\t\tID: \"view-events\",\n\t\t\tName: \"view-events\",\n\t\t},\n\t\t&keycloak.KeycloakUserRole{\n\t\t\tID: \"view-identity-providers\",\n\t\t\tName: \"view-identity-providers\",\n\t\t},\n\t\t&keycloak.KeycloakUserRole{\n\t\t\tID: \"view-realm\",\n\t\t\tName: \"view-realm\",\n\t\t},\n\t\t&keycloak.KeycloakUserRole{\n\t\t\tID: \"view-users\",\n\t\t\tName: \"view-users\",\n\t\t},\n\t}\n\n\tavailableGroupRealmRoles := []*keycloak.KeycloakUserRole{\n\t\t&keycloak.KeycloakUserRole{\n\t\t\tID: \"mock-role-3\",\n\t\t\tName: \"mock-role-3\",\n\t\t},\n\t\t&keycloak.KeycloakUserRole{\n\t\t\tID: \"create-realm\",\n\t\t\tName: \"create-realm\",\n\t\t},\n\t\t&keycloak.KeycloakUserRole{\n\t\t\tID: \"mock-role-4\",\n\t\t\tName: \"mock-role-4\",\n\t\t},\n\t}\n\n\tlistRealmsFunc := func() ([]*keycloak.KeycloakAPIRealm, error) {\n\t\treturn []*keycloak.KeycloakAPIRealm{\n\t\t\t&keycloak.KeycloakAPIRealm{\n\t\t\t\tRealm: \"master\",\n\t\t\t},\n\t\t\t&keycloak.KeycloakAPIRealm{\n\t\t\t\tRealm: \"test\",\n\t\t\t},\n\t\t}, nil\n\t}\n\n\tfindGroupByNameFunc := func(groupName string, realmName string) (*keycloakCommon.Group, error) {\n\t\tfor _, group := range context.Groups {\n\t\t\tif group.Name == groupName {\n\t\t\t\treturn group, nil\n\t\t\t}\n\t\t}\n\n\t\treturn nil, nil\n\t}\n\n\tcreateGroupFunc := func(groupName string, realmName string) (string, error) {\n\t\tnextID := fmt.Sprintf(\"group-%d\", len(context.Groups))\n\n\t\tnewGroup := &keycloakCommon.Group{\n\t\t\tID: string(nextID),\n\t\t\tName: groupName,\n\t\t}\n\n\t\tcontext.Groups = append(context.Groups, newGroup)\n\n\t\tcontext.ClientRoles[nextID] = []*keycloak.KeycloakUserRole{}\n\t\tcontext.RealmRoles[nextID] = []*keycloak.KeycloakUserRole{}\n\n\t\treturn nextID, nil\n\t}\n\n\tsetGroupChildFunc := func(groupID, realmName string, childGroup *keycloakCommon.Group) error {\n\t\tvar childGroupToAppend *keycloakCommon.Group\n\t\tfor _, group := range context.Groups {\n\t\t\tif group.ID == childGroup.ID {\n\t\t\t\tchildGroupToAppend = group\n\t\t\t}\n\t\t}\n\n\t\tif childGroupToAppend == nil {\n\t\t\tchildGroupToAppend = childGroup\n\t\t}\n\n\t\tfound := false\n\t\tfor _, group := range context.Groups {\n\t\t\tif group.ID == groupID {\n\t\t\t\tgroup.SubGroups = append(group.SubGroups, childGroupToAppend)\n\t\t\t\tfound = true\n\t\t\t}\n\t\t}\n\n\t\tif !found {\n\t\t\treturn fmt.Errorf(\"Group %s not found\", groupID)\n\t\t}\n\n\t\treturn nil\n\t}\n\n\tlistUsersInGroupFunc := func(realmName, groupID string) ([]*keycloak.KeycloakAPIUser, error) {\n\t\treturn []*keycloak.KeycloakAPIUser{}, nil\n\t}\n\n\tmakeGroupDefaultFunc := func(groupID string, realmName string) error {\n\t\tvar group *keycloakCommon.Group\n\n\t\tfor _, existingGroup := range context.Groups {\n\t\t\tif existingGroup.ID == groupID {\n\t\t\t\tgroup = existingGroup\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif group == nil {\n\t\t\treturn fmt.Errorf(\"Referenced group not found\")\n\t\t}\n\n\t\tcontext.DefaultGroups = append(context.DefaultGroups, group)\n\t\treturn nil\n\t}\n\n\tlistDefaultGroupsFunc := func(realmName string) ([]*keycloakCommon.Group, error) {\n\t\treturn context.DefaultGroups, nil\n\t}\n\n\tcreateGroupClientRoleFunc := func(role *keycloak.KeycloakUserRole, realmName, clientID, groupID string) (string, error) {\n\t\tgroupClientRoles, ok := context.ClientRoles[groupID]\n\n\t\tif !ok {\n\t\t\treturn \"\", fmt.Errorf(\"Referenced group not found\")\n\t\t}\n\n\t\tcontext.ClientRoles[groupID] = append(groupClientRoles, role)\n\t\treturn \"dummy-group-client-role-id\", nil\n\t}\n\n\tlistGroupClientRolesFunc := func(realmName, clientID, groupID string) ([]*keycloak.KeycloakUserRole, error) {\n\t\tgroupRoles, ok := context.ClientRoles[groupID]\n\n\t\tif !ok {\n\t\t\treturn nil, fmt.Errorf(\"Referenced group not found\")\n\t\t}\n\n\t\treturn groupRoles, nil\n\t}\n\n\tlistAvailableGroupClientRolesFunc := func(realmName, clientID, groupID string) ([]*keycloak.KeycloakUserRole, error) {\n\t\t_, ok := context.ClientRoles[groupID]\n\n\t\tif !ok {\n\t\t\treturn nil, fmt.Errorf(\"Referenced group not found\")\n\t\t}\n\n\t\treturn availableGroupClientRoles, nil\n\t}\n\n\tfindGroupClientRoleFunc := func(realmName, clientID, groupID string, predicate func(*keycloak.KeycloakUserRole) bool) (*keycloak.KeycloakUserRole, error) {\n\t\tall, err := listGroupClientRolesFunc(realmName, clientID, groupID)\n\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tfor _, role := range all {\n\t\t\tif predicate(role) {\n\t\t\t\treturn role, nil\n\t\t\t}\n\t\t}\n\n\t\treturn nil, nil\n\t}\n\n\tfindAvailableGroupClientRoleFunc := func(realmName, clientID, groupID string, predicate func(*keycloak.KeycloakUserRole) bool) (*keycloak.KeycloakUserRole, error) {\n\t\tall, err := listAvailableGroupClientRolesFunc(realmName, clientID, groupID)\n\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tfor _, role := range all {\n\t\t\tif predicate(role) {\n\t\t\t\treturn role, nil\n\t\t\t}\n\t\t}\n\n\t\treturn nil, nil\n\t}\n\n\tlistGroupRealmRolesFunc := func(realmName, groupID string) ([]*keycloak.KeycloakUserRole, error) {\n\t\tgroupRoles, ok := context.RealmRoles[groupID]\n\n\t\tif !ok {\n\t\t\treturn nil, fmt.Errorf(\"Referenced group not found\")\n\t\t}\n\n\t\treturn groupRoles, nil\n\t}\n\n\tlistAvailableGroupRealmRolesFunc := func(realmName, groupID string) ([]*keycloak.KeycloakUserRole, error) {\n\t\t_, ok := context.RealmRoles[groupID]\n\n\t\tif !ok {\n\t\t\treturn nil, fmt.Errorf(\"Referenced group not found\")\n\t\t}\n\n\t\treturn availableGroupRealmRoles, nil\n\t}\n\n\tcreateGroupRealmRoleFunc := func(role *keycloak.KeycloakUserRole, realmName, groupID string) (string, error) {\n\t\tgroupRealmRoles, ok := context.RealmRoles[groupID]\n\n\t\tif !ok {\n\t\t\treturn \"\", fmt.Errorf(\"Referenced group not found\")\n\t\t}\n\n\t\tcontext.RealmRoles[groupID] = append(groupRealmRoles, role)\n\t\treturn \"dummy-group-realm-role-id\", nil\n\t}\n\n\tlistClientsFunc := func(realmName string) ([]*keycloak.KeycloakAPIClient, error) {\n\t\treturn []*keycloak.KeycloakAPIClient{\n\t\t\t&keycloak.KeycloakAPIClient{\n\t\t\t\tClientID: \"test-realm\",\n\t\t\t\tID: \"test-realm\",\n\t\t\t\tName: \"test-realm\",\n\t\t\t},\n\t\t\t&keycloak.KeycloakAPIClient{\n\t\t\t\tClientID: \"master-realm\",\n\t\t\t\tID: \"master-realm\",\n\t\t\t\tName: \"master-realm\",\n\t\t\t},\n\t\t}, nil\n\t}\n\n\tlistAuthenticationExecutionsForFlowFunc := func(flowAlias, realmName string) ([]*keycloak.AuthenticationExecutionInfo, error) {\n\t\texecutions, ok := context.AuthenticationFlowsExecutions[flowAlias]\n\n\t\tif !ok {\n\t\t\treturn nil, errors.New(\"Authentication flow not found\")\n\t\t}\n\n\t\treturn executions, nil\n\t}\n\n\tfindAuthenticationExecutionForFlowFunc := func(flowAlias, realmName string, predicate func(*keycloak.AuthenticationExecutionInfo) bool) (*keycloak.AuthenticationExecutionInfo, error) {\n\t\texecutions, err := listAuthenticationExecutionsForFlowFunc(flowAlias, realmName)\n\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tfor _, execution := range executions {\n\t\t\tif predicate(execution) {\n\t\t\t\treturn execution, nil\n\t\t\t}\n\t\t}\n\n\t\treturn nil, nil\n\t}\n\n\tupdateAuthenticationExecutionForFlowFunc := func(flowAlias, realmName string, execution *keycloak.AuthenticationExecutionInfo) error {\n\t\texecutions, ok := context.AuthenticationFlowsExecutions[flowAlias]\n\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"Authentication flow %s not found\", flowAlias)\n\t\t}\n\n\t\tfor i, currentExecution := range executions {\n\t\t\tif currentExecution.Alias != execution.Alias {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tcontext.AuthenticationFlowsExecutions[flowAlias][i] = execution\n\t\t\tbreak\n\t\t}\n\n\t\treturn nil\n\t}\n\n\tlistOfActivesUsersPerRealmFunc := func(realmName, dateFrom string, max int) ([]keycloakCommon.Users, error) {\n\t\tusers := []keycloakCommon.Users{\n\t\t\t{\n\t\t\t\tUserID: \"1\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tUserID: \"2\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tUserID: \"3\",\n\t\t\t},\n\t\t}\n\n\t\treturn users, nil\n\t}\n\n\treturn &keycloakCommon.KeycloakInterfaceMock{\n\t\tListRealmsFunc: listRealmsFunc,\n\t\tFindGroupByNameFunc: findGroupByNameFunc,\n\t\tCreateGroupFunc: createGroupFunc,\n\t\tSetGroupChildFunc: setGroupChildFunc,\n\t\tListUsersInGroupFunc: listUsersInGroupFunc,\n\t\tMakeGroupDefaultFunc: makeGroupDefaultFunc,\n\t\tListDefaultGroupsFunc: listDefaultGroupsFunc,\n\t\tCreateGroupClientRoleFunc: createGroupClientRoleFunc,\n\t\tListGroupClientRolesFunc: listGroupClientRolesFunc,\n\t\tListAvailableGroupClientRolesFunc: listAvailableGroupClientRolesFunc,\n\t\tFindGroupClientRoleFunc: findGroupClientRoleFunc,\n\t\tFindAvailableGroupClientRoleFunc: findAvailableGroupClientRoleFunc,\n\t\tListGroupRealmRolesFunc: listGroupRealmRolesFunc,\n\t\tListAvailableGroupRealmRolesFunc: listAvailableGroupRealmRolesFunc,\n\t\tCreateGroupRealmRoleFunc: createGroupRealmRoleFunc,\n\t\tListAuthenticationExecutionsForFlowFunc: listAuthenticationExecutionsForFlowFunc,\n\t\tFindAuthenticationExecutionForFlowFunc: findAuthenticationExecutionForFlowFunc,\n\t\tUpdateAuthenticationExecutionForFlowFunc: updateAuthenticationExecutionForFlowFunc,\n\t\tListClientsFunc: listClientsFunc,\n\t\tListOfActivesUsersPerRealmFunc: listOfActivesUsersPerRealmFunc,\n\t}, &context\n}", "func TestEmployeeManagerMapGetByID(t *testing.T) {\n\tdb, mock, err := sqlmock.New()\n\tif err != nil {\n\t\tt.Fatalf(\"an error '%s' was not expected when opening a stub database connection\", err)\n\t}\n\tdefer db.Close()\n\n\trows := sqlmock.NewRows([]string{\"employee_name\", \"manager_name\"}).AddRow(\"Nick\", \"Sophie\").AddRow(\"Sophie\", \"Jonas\")\n\tmock.ExpectExec(constants.EmployeeManagerMappingDeleteQuery).WillReturnResult(sqlmock.NewResult(0, 0))\n\tmock.ExpectPrepare(regexp.QuoteMeta(constants.EmployeeManagerMappingInsertQuery)).ExpectExec().WillReturnResult(sqlmock.NewResult(0, 0))\n\tmock.ExpectQuery(constants.EmployeeManagerMappingSelectQuery).WillReturnRows(rows)\n\n\templyManagerMap := NewEmployeeManagerMapHandler(db)\n\n\tw := httptest.NewRecorder()\n\tvar jsonStr = []byte(`{\"Peter\":\"Nick\", \"Barbara\":\"Nick\", \"Nick\":\"Sophie\", \"Sophie\":\"Jonas\"}`)\n\tr := httptest.NewRequest(\"POST\", \"http://localhost:9090/api/v1/emplymgrmap\", bytes.NewBuffer(jsonStr))\n\tr = r.WithContext(context.Background())\n\templyManagerMap.Create(w, r)\n\n\tr = httptest.NewRequest(\"GET\", \"http://localhost:9090/api/v1/emplymgrmap/Nick?supervisor=true&name=Nick\", nil)\n\trctx := chi.NewRouteContext()\n\trctx.URLParams.Add(\"name\", \"Nick\")\n\tr = r.WithContext(context.WithValue(r.Context(), chi.RouteCtxKey, rctx))\n\tw = httptest.NewRecorder()\n\templyManagerMap.GetByID(w, r)\n\texpectedResponse := `{\"supervisor\":\"Sophie\",\"supervisor_of_supervisor\":\"Jonas\"}`\n\tassert.Equal(t, gohttp.StatusOK, w.Code)\n\tassert.Equal(t, expectedResponse, w.Body.String())\n}", "func (suite *AuthSuite) TestAuthUnknownServiceMember() {\n\t// Set up: Prepare the session, goth.User, callback handler, http response\n\t// and request, landing URL, and pass them into authorizeUnknownUser\n\n\thandlerConfig := suite.HandlerConfig()\n\tappnames := handlerConfig.AppNames()\n\n\t// Prepare the session and session manager\n\tfakeToken := \"some_token\"\n\tsession := auth.Session{\n\t\tApplicationName: auth.MilApp,\n\t\tIDToken: fakeToken,\n\t\tHostname: appnames.MilServername,\n\t}\n\tsessionManager := handlerConfig.SessionManagers().Mil\n\tmockSender := setUpMockNotificationSender() // We should get an email for this activity\n\n\t// Prepare the goth.User to simulate the UUID and email that login.gov would\n\t// provide\n\tfakeUUID, _ := uuid.NewV4()\n\tuser := goth.User{\n\t\tUserID: fakeUUID.String(),\n\t\tEmail: \"new_service_member@example.com\",\n\t}\n\tctx := suite.SetupSessionContext(context.Background(), &session, sessionManager)\n\n\t// Call the function under test\n\tresult := authorizeUnknownUser(ctx, suite.AppContextWithSessionForTest(&session), user,\n\t\tsessionManager, mockSender)\n\tsuite.Equal(authorizationResultAuthorized, result)\n\tmockSender.(*mocks.NotificationSender).AssertNumberOfCalls(suite.T(), \"SendNotification\", 1)\n\n\t// Look up the user and service member in the test DB\n\tfoundUser, _ := models.GetUserFromEmail(suite.DB(), user.Email)\n\tserviceMemberID := session.ServiceMemberID\n\tserviceMember, _ := models.FetchServiceMemberForUser(suite.DB(), &session, serviceMemberID)\n\t// Look up the session token in the session store (this test uses the memory store)\n\tsessionStore := sessionManager.Store()\n\t_, existsBefore, _ := sessionStore.Find(foundUser.CurrentMilSessionID)\n\n\t// Verify service member exists and its ID is populated in the session\n\tsuite.NotEmpty(session.ServiceMemberID)\n\n\t// Verify session contains UserID that points to the newly-created user\n\tsuite.Equal(foundUser.ID, session.UserID)\n\n\t// Verify user's LoginGovEmail and LoginGovUUID match the values passed in\n\tsuite.Equal(user.Email, foundUser.LoginGovEmail)\n\tsuite.Equal(user.UserID, foundUser.LoginGovUUID.String())\n\n\t// Verify that the user's CurrentMilSessionID is not empty. The value is\n\t// generated randomly, so we can't test for a specific string. Any string\n\t// except an empty string is acceptable.\n\tsuite.NotEqual(\"\", foundUser.CurrentMilSessionID)\n\n\t// Verify the session token also exists in the session store\n\tsuite.Equal(true, existsBefore)\n\n\t// Verify the service member that was created is associated with the user\n\t// that was created\n\tsuite.Equal(foundUser.ID, serviceMember.UserID)\n}", "func (m *MockClient) IdentityConfig() msp.IdentityConfig {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"IdentityConfig\")\n\tret0, _ := ret[0].(msp.IdentityConfig)\n\treturn ret0\n}", "func (m *MockActivityHandler) AdminGetByID(w http.ResponseWriter, r *http.Request) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"AdminGetByID\", w, r)\n}", "func TestGenerateIdentity(t *testing.T) {\n\tif _, err := GenerateIdentity(); err != nil {\n\t\tt.Fatalf(\"Failed to generate new identity: %v\", err)\n\t}\n}", "func TestGenerateIdentity(t *testing.T) {\n\tif _, err := GenerateIdentity(); err != nil {\n\t\tt.Fatalf(\"Failed to generate new identity: %v\", err)\n\t}\n}", "func mockTestUserInteraction(ctx context.Context, pro providerParams, username, password string) (string, error) {\n\tctx, cancel := context.WithTimeout(ctx, 10*time.Second)\n\tdefer cancel()\n\n\tprovider, err := oidc.NewProvider(ctx, pro.providerURL)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"unable to create provider: %v\", err)\n\t}\n\n\t// Configure an OpenID Connect aware OAuth2 client.\n\toauth2Config := oauth2.Config{\n\t\tClientID: pro.clientID,\n\t\tClientSecret: pro.clientSecret,\n\t\tRedirectURL: pro.redirectURL,\n\n\t\t// Discovery returns the OAuth2 endpoints.\n\t\tEndpoint: provider.Endpoint(),\n\n\t\t// \"openid\" is a required scope for OpenID Connect flows.\n\t\tScopes: []string{oidc.ScopeOpenID, \"groups\"},\n\t}\n\n\tstate := \"xxx\"\n\tauthCodeURL := oauth2Config.AuthCodeURL(state)\n\t// fmt.Printf(\"authcodeurl: %s\\n\", authCodeURL)\n\n\tvar lastReq *http.Request\n\tcheckRedirect := func(req *http.Request, via []*http.Request) error {\n\t\t// fmt.Printf(\"CheckRedirect:\\n\")\n\t\t// fmt.Printf(\"Upcoming: %s %#v\\n\", req.URL.String(), req)\n\t\t// for _, c := range via {\n\t\t// \tfmt.Printf(\"Sofar: %s %#v\\n\", c.URL.String(), c)\n\t\t// }\n\t\t// Save the last request in a redirect chain.\n\t\tlastReq = req\n\t\t// We do not follow redirect back to client application.\n\t\tif req.URL.Path == \"/oauth_callback\" {\n\t\t\treturn http.ErrUseLastResponse\n\t\t}\n\t\treturn nil\n\t}\n\n\tdexClient := http.Client{\n\t\tCheckRedirect: checkRedirect,\n\t}\n\n\tu, err := url.Parse(authCodeURL)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"url parse err: %v\", err)\n\t}\n\n\t// Start the user auth flow. This page would present the login with\n\t// email or LDAP option.\n\treq, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"new request err: %v\", err)\n\t}\n\t_, err = dexClient.Do(req)\n\t// fmt.Printf(\"Do: %#v %#v\\n\", resp, err)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"auth url request err: %v\", err)\n\t}\n\n\t// Modify u to choose the ldap option\n\tu.Path += \"/ldap\"\n\t// fmt.Println(u)\n\n\t// Pick the LDAP login option. This would return a form page after\n\t// following some redirects. `lastReq` would be the URL of the form\n\t// page, where we need to POST (submit) the form.\n\treq, err = http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"new request err (/ldap): %v\", err)\n\t}\n\t_, err = dexClient.Do(req)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"request err: %v\", err)\n\t}\n\n\t// Fill the login form with our test creds:\n\t// fmt.Printf(\"login form url: %s\\n\", lastReq.URL.String())\n\tformData := url.Values{}\n\tformData.Set(\"login\", username)\n\tformData.Set(\"password\", password)\n\treq, err = http.NewRequestWithContext(ctx, http.MethodPost, lastReq.URL.String(), strings.NewReader(formData.Encode()))\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"new request err (/login): %v\", err)\n\t}\n\treq.Header.Set(\"Content-Type\", \"application/x-www-form-urlencoded\")\n\t_, err = dexClient.Do(req)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"post form err: %v\", err)\n\t}\n\t// fmt.Printf(\"resp: %#v %#v\\n\", resp.StatusCode, resp.Header)\n\t// fmt.Printf(\"lastReq: %#v\\n\", lastReq.URL.String())\n\n\t// On form submission, the last redirect response contains the auth\n\t// code, which we now have in `lastReq`. Exchange it for a JWT id_token.\n\tq := lastReq.URL.Query()\n\tcode := q.Get(\"code\")\n\toauth2Token, err := oauth2Config.Exchange(ctx, code)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"unable to exchange code for id token: %v\", err)\n\t}\n\n\trawIDToken, ok := oauth2Token.Extra(\"id_token\").(string)\n\tif !ok {\n\t\treturn \"\", fmt.Errorf(\"id_token not found!\")\n\t}\n\n\t// fmt.Printf(\"TOKEN: %s\\n\", rawIDToken)\n\treturn rawIDToken, nil\n}", "func (suite *HealthCheckTestSuite) TestModuleExecuteWithNilOnPremIdentity() {\n\t// Initialize the appconfigMock with HealthFrequencyMinutes as every five minute\n\tappconfigMock := &appconfig.SsmagentConfig{\n\t\tSsm: appconfig.SsmCfg{\n\t\t\tHealthFrequencyMinutes: appconfig.DefaultSsmHealthFrequencyMinutes,\n\t\t},\n\t}\n\n\tmockEC2Identity := &identityMock.IAgentIdentityInner{}\n\tnewEC2Identity = func(log log.T) identity.IAgentIdentityInner {\n\t\treturn mockEC2Identity\n\t}\n\n\tavailabilityZone := \"us-east-1a\"\n\tavailabilityZoneId := \"use1-az2\"\n\tmockEC2Identity.On(\"IsIdentityEnvironment\").Return(true)\n\tmockEC2Identity.On(\"AvailabilityZone\").Return(availabilityZone, nil)\n\tmockEC2Identity.On(\"AvailabilityZoneId\").Return(availabilityZoneId, nil)\n\n\tnewOnPremIdentity = func(log log.T, config *appconfig.SsmagentConfig) identity.IAgentIdentityInner {\n\t\treturn nil\n\t}\n\n\tmockECSIdentity := &identityMock.IAgentIdentityInner{}\n\tnewECSIdentity = func(log log.T) identity.IAgentIdentityInner {\n\t\treturn mockECSIdentity\n\t}\n\tmockECSIdentity.On(\"IsIdentityEnvironment\").Return(false)\n\n\tssmConnectionChannel := \"ssmmessages\"\n\tvar ableToOpenMGSConnection uint32\n\tatomic.StoreUint32(&ableToOpenMGSConnection, 1)\n\tssmconnectionchannel.SetConnectionChannel(&ableToOpenMGSConnection)\n\n\t// Turn on the mock method\n\tsuite.contextMock.On(\"AppConfig\").Return(*appconfigMock)\n\tsuite.serviceMock.On(\"UpdateInstanceInformation\", mock.Anything, version.Version, \"Active\", AgentName, availabilityZone, availabilityZoneId, ssmConnectionChannel).Return(nil, nil)\n\tsuite.healthCheck.ModuleExecute()\n\t// Because ModuleExecute will launch two new go routine, wait 100ms to make sure the updateHealth() has launched\n\ttime.Sleep(100 * time.Millisecond)\n\t// Assert the UpdateInstanceInformation get called in updateHealth() function, and the agent status is same as input.\n\tsuite.serviceMock.AssertCalled(suite.T(), \"UpdateInstanceInformation\", mock.Anything, version.Version, \"Active\", AgentName, availabilityZone, availabilityZoneId, ssmConnectionChannel)\n}", "func (c *OAuth) Manager(idp idp.IdentityProvider, store *mongodb.Store, encoder jwt.Encoder) *oauth.Manager {\n\tfmt.Println(c)\n\tproviderMetadata := &openid.ProviderMetadata{\n\t\tIssuer: c.Issuer,\n\t\tAuthorizationEndpoint: c.UIAuthorizeEndpoint,\n\t\tTokenEndpoint: fmt.Sprintf(\"%s/v0/oauth/token\", c.Issuer),\n\t\tUserInfoEndpoint: fmt.Sprintf(\"%s/v0/openid/userinfo\", c.Issuer),\n\t\tJwksURI: fmt.Sprintf(\"%s/.well-known/jwks.json\", c.Issuer),\n\t\tRegistrationEndpoint: fmt.Sprintf(\"%s/v0/clients\", c.Issuer),\n\t\tScopesSupported: append(c.ScopesSupported, openid.OpenIDScope, openid.ProfileScope, openid.EmailScope),\n\t\tResponseTypesSupported: []string{string(model.CodeResponseType)},\n\t\tGrantTypesSupported: []string{string(model.AuthorizationCodeGrantType), string(model.PasswordGrantType), string(model.ClientCredentialsGrantType)},\n\t\tSubjectTypesSupported: []string{\"public\"},\n\t\tIDTokenSigningAlgValuesSupported: []string{string(jose.RS256)},\n\t\tTokenEndpointAuthMethodsSupported: []string{openid.ClientSecretPostTokenAuthMethod},\n\t\tCodeChallengeMethodsSupported: []string{string(model.PlainCodeChallengeMethod), string(model.S256CodeChallengeMethod)},\n\t}\n\treturn oauth.NewManager(idp, store, encoder, providerMetadata)\n}", "func (m *MockSession) ID() int64 {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ID\")\n\tret0, _ := ret[0].(int64)\n\treturn ret0\n}", "func getTestIdent(t *testing.T, username string, reqs ...identRequest) *identity.Identity {\n\tca, err := tlsca.FromKeys([]byte(fixtures.TLSCACertPEM), []byte(fixtures.TLSCAKeyPEM))\n\trequire.NoError(t, err)\n\n\tprivateKey, sshPublicKey, err := testauthority.New().GenerateKeyPair()\n\trequire.NoError(t, err)\n\n\tsshPrivateKey, err := ssh.ParseRawPrivateKey(privateKey)\n\trequire.NoError(t, err)\n\n\ttlsPublicKeyPEM, err := tlsca.MarshalPublicKeyFromPrivateKeyPEM(sshPrivateKey)\n\trequire.NoError(t, err)\n\n\ttlsPublicKey, err := tlsca.ParsePublicKeyPEM(tlsPublicKeyPEM)\n\trequire.NoError(t, err)\n\n\t// Note: it'd be nice to make this more universally useful in our tests at\n\t// some point.\n\tclock := clockwork.NewFakeClock()\n\tnotAfter := clock.Now().Add(time.Hour)\n\tid := tlsca.Identity{\n\t\tUsername: username,\n\t\tKubernetesUsers: []string{\"foo\"},\n\t\tKubernetesGroups: []string{\"bar\"},\n\t\tRouteToCluster: mockClusterName,\n\t}\n\tfor _, req := range reqs {\n\t\treq(&id)\n\t}\n\tsubject, err := id.Subject()\n\trequire.NoError(t, err)\n\tcertBytes, err := ca.GenerateCertificate(tlsca.CertificateRequest{\n\t\tClock: clock,\n\t\tPublicKey: tlsPublicKey,\n\t\tSubject: subject,\n\t\tNotAfter: notAfter,\n\t})\n\trequire.NoError(t, err)\n\n\tcaSigner, err := ssh.ParsePrivateKey([]byte(fixtures.SSHCAPrivateKey))\n\trequire.NoError(t, err)\n\tta := testauthority.New()\n\tsshCertBytes, err := ta.GenerateUserCert(services.UserCertParams{\n\t\tCASigner: caSigner,\n\t\tPublicUserKey: sshPublicKey,\n\t\tUsername: username,\n\t\tCertificateFormat: constants.CertificateFormatStandard,\n\t\tTTL: time.Minute,\n\t\tAllowedLogins: []string{\"foo\"},\n\t\tRouteToCluster: mockClusterName,\n\t})\n\n\trequire.NoError(t, err)\n\n\tcerts := &proto.Certs{\n\t\tSSH: sshCertBytes,\n\t\tTLS: certBytes,\n\t\tTLSCACerts: [][]byte{[]byte(fixtures.TLSCACertPEM)},\n\t\tSSHCACerts: [][]byte{[]byte(fixtures.SSHCAPublicKey)},\n\t}\n\n\tident, err := identity.ReadIdentityFromStore(&identity.LoadIdentityParams{\n\t\tPrivateKeyBytes: privateKey,\n\t\tPublicKeyBytes: tlsPublicKeyPEM,\n\t}, certs, identity.DestinationKinds()...)\n\trequire.NoError(t, err)\n\n\treturn ident\n}", "func (m *MockManagerClient) GetManagerByUserFromServer(id int64) (*manager_grpc.Manager, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetManagerByUserFromServer\", id)\n\tret0, _ := ret[0].(*manager_grpc.Manager)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func NewMockKeystore(auth *communications.Headers, logger log.Logger) definitions.Keystore {\n\ts := new(inmemKeystore)\n\ts.headers = auth\n\treturn s\n}", "func (m *MockAdmin) Authenticate(ctx provider.Context, adminID int, allowedRole []constant.UserRole) (entity.User, *entity.ApplicationError) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Authenticate\", ctx, adminID, allowedRole)\n\tret0, _ := ret[0].(entity.User)\n\tret1, _ := ret[1].(*entity.ApplicationError)\n\treturn ret0, ret1\n}", "func (m *MockCAClient) GetAllIdentities(arg0 string) ([]*api.IdentityResponse, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetAllIdentities\", arg0)\n\tret0, _ := ret[0].([]*api.IdentityResponse)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func mockChildPackages() {\n\n\t// Fake an AWS credentials file so that the mfile package will nehave as if it is happy\n\tsetFakeCredentials()\n\n\t// Fake out the creds package into using an apparently credentials response from AWS\n\tcreds.SetGetSessionTokenFunc(func(awsService *sts.STS, input *sts.GetSessionTokenInput) (*sts.GetSessionTokenOutput, error) {\n\t\treturn getSessionTokenOutput, nil\n\t})\n\n}", "func NewMock(middleware []Middleware) OrganizationService {\n\tvar svc OrganizationService = NewBasicOrganizationServiceServiceMock()\n\tfor _, m := range middleware {\n\t\tsvc = m(svc)\n\t}\n\treturn svc\n}", "func TestAuthenticate_Success(t *testing.T) {\n\tdb, mock, err := sqlmock.New()\n\tif err != nil {\n\t\tt.Fatalf(\"an error '%s' was not expected when opening a stub database connection\", err)\n\t}\n\tdefer db.Close()\n\n\tuser := models.User{\n\t\tID: 1,\n\t\tEmail: \"personia@personio.com\",\n\t\tPassword: \"personia\",\n\t}\n\n\trows := sqlmock.NewRows([]string{\"id\", \"email\"}).AddRow(user.ID, user.Email)\n\tmock.ExpectQuery(regexp.QuoteMeta(constants.LoginDetailsSelectQuery)).WithArgs(user.Email, user.Password).WillReturnRows(rows)\n\n\tloginRepository := NewLoginRepository(db)\n\n\tloginModel := &models.Login{\n\t\tEmail: \"personia@personio.com\",\n\t\tPassword: \"personia\",\n\t}\n\n\tcntx := context.Background()\n\tdbuser, err := loginRepository.Authenticate(cntx, loginModel)\n\tassert.Nil(t, err)\n\tassert.Equal(t, user.ID, dbuser.ID)\n\tassert.Equal(t, user.Email, dbuser.Email)\n}", "func (m *MockClient) Identifier() *msp.IdentityIdentifier {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Identifier\")\n\tret0, _ := ret[0].(*msp.IdentityIdentifier)\n\treturn ret0\n}", "func (m *MockIByIdUseCase) Id(id aggregates.Id) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"Id\", id)\n}", "func (m *MockSessionManager) Create(userId string) (*session.Session, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Create\", userId)\n\tret0, _ := ret[0].(*session.Session)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockCAClient) ModifyIdentity(arg0 *api.IdentityRequest) (*api.IdentityResponse, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ModifyIdentity\", arg0)\n\tret0, _ := ret[0].(*api.IdentityResponse)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func testSystemAssignedIdentity(msiEndpoint string) (*adal.Token, error) {\n\tspt, err := adal.NewServicePrincipalTokenFromMSI(msiEndpoint, azure.PublicCloud.ResourceManagerEndpoint)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"Failed to acquire a token using the MSI VM extension\")\n\t}\n\n\tif err := spt.Refresh(); err != nil {\n\t\treturn nil, errors.Wrapf(err, \"Failed to refresh ServicePrincipalTokenFromMSI using the MSI VM extension, msiEndpoint(%s)\", msiEndpoint)\n\t}\n\n\ttoken := spt.Token()\n\tif token.IsZero() {\n\t\treturn nil, errors.Errorf(\"No token found, MSI VM extension, msiEndpoint(%s)\", msiEndpoint)\n\t}\n\n\tklog.Infof(\"successfully acquired a token using the MSI, msiEndpoint(%s)\", msiEndpoint)\n\treturn &token, nil\n}", "func TestRevokedIdentity(t *testing.T) {\n\ttestHome := t.TempDir()\n\tserverdir := filepath.Join(testdataDir, \"server\")\n\n\tsrv := TestGetServer(ctport1, serverdir, \"\", -1, t)\n\terr := srv.Start()\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to start server: %s\", err)\n\t}\n\tdefer func() {\n\t\terr := srv.Stop()\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Server stop failed: %s\", err)\n\t\t}\n\t\terr = os.RemoveAll(serverdir)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"RemoveAll failed: %s\", err)\n\t\t}\n\t\terr = os.RemoveAll(testHome)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"RemoveAll failed: %s\", err)\n\t\t}\n\t}()\n\n\t// Enroll admin\n\tc := &Client{\n\t\tConfig: &ClientConfig{URL: fmt.Sprintf(\"http://localhost:%d\", ctport1)},\n\t\tHomeDir: filepath.Join(testHome, \"admin\"),\n\t}\n\n\tenrollReq := &api.EnrollmentRequest{\n\t\tName: \"admin\",\n\t\tSecret: \"adminpw\",\n\t}\n\n\teresp, err := c.Enroll(enrollReq)\n\tif err != nil {\n\t\tt.Fatalf(\"Enrollment of admin failed: %s\", err)\n\t}\n\n\tadmin_id := eresp.Identity\n\n\t// 'admin' registers 'TestUser' user\n\tregisterReq := &api.RegistrationRequest{\n\t\tName: \"TestUser\",\n\t\tType: \"user\",\n\t\tAffiliation: \"hyperledger\",\n\t\tMaxEnrollments: 2,\n\t}\n\n\tresp, err := admin_id.Register(registerReq)\n\tif err != nil {\n\t\tt.Fatalf(\"Register failed: %s\", err)\n\t}\n\n\t// Enroll 'TestUser'\n\tTestUserClient := &Client{\n\t\tConfig: &ClientConfig{URL: fmt.Sprintf(\"http://localhost:%d\", ctport1)},\n\t\tHomeDir: filepath.Join(testHome, \"TestUserClient\"),\n\t}\n\n\tenrollReq = &api.EnrollmentRequest{\n\t\tName: \"TestUser\",\n\t\tSecret: resp.Secret,\n\t}\n\n\teresp2, err := TestUserClient.Enroll(enrollReq)\n\tif err != nil {\n\t\tt.Fatalf(\"Enrollment of TestUser failed: %s\", err)\n\t}\n\n\ttestuserid := eresp2.Identity\n\n\t// Enroll 'TestUser' again with a different home/msp directory\n\tTestUserClient2 := &Client{\n\t\tConfig: &ClientConfig{URL: fmt.Sprintf(\"http://localhost:%d\", ctport1)},\n\t\tHomeDir: filepath.Join(testHome, \"TestUserClient2\"),\n\t}\n\n\tenrollReq = &api.EnrollmentRequest{\n\t\tName: \"TestUser\",\n\t\tSecret: resp.Secret,\n\t}\n\n\teresp3, err := TestUserClient2.Enroll(enrollReq)\n\tif err != nil {\n\t\tt.Fatalf(\"Enrollment of TestUser failed: %s\", err)\n\t}\n\n\ttestuserid2 := eresp3.Identity\n\n\t// 'admin' revokes user 'TestUser'\n\trevReq := &api.RevocationRequest{\n\t\tName: \"TestUser\",\n\t\tGenCRL: true,\n\t}\n\n\t_, err = admin_id.Revoke(revReq)\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to revoke TestUser identity: %s\", err)\n\t}\n\n\t// After an identity has been revoked, all subsequent commands invoked by revoked user should be rejected by server\n\t// for all its issued certificates\n\t_, err = TestUserClient2.Enroll(enrollReq)\n\tif err == nil {\n\t\tt.Fatalf(\"Enrollment of TestUser should have failed: %s\", err)\n\t}\n\n\t_, err = testuserid.Reenroll(&api.ReenrollmentRequest{})\n\tif err == nil {\n\t\tt.Fatalf(\"Reenrollment of TestUser identity should have failed: %s\", err)\n\t}\n\n\t_, err = testuserid2.Reenroll(&api.ReenrollmentRequest{})\n\tif err == nil {\n\t\tt.Fatalf(\"Reenrollment of TestUser identity should have failed: %s\", err)\n\t}\n\n\t_, err = testuserid.Register(registerReq)\n\tif err == nil {\n\t\tt.Fatalf(\"Registration of TestUser identity should have failed: %s\", err)\n\t}\n\n\t_, err = testuserid2.Register(registerReq)\n\tif err == nil {\n\t\tt.Fatalf(\"Registration of TestUser identity should have failed: %s\", err)\n\t}\n\n\t_, err = testuserid.Revoke(&api.RevocationRequest{\n\t\tName: \"admin\",\n\t})\n\tif err == nil {\n\t\tt.Fatalf(\"Revocation of 'admin' identity should have failed: %s\", err)\n\t}\n\n\t_, err = testuserid2.Revoke(&api.RevocationRequest{\n\t\tName: \"admin\",\n\t})\n\tif err == nil {\n\t\tt.Fatalf(\"Revocation of 'admin' identity should have failed: %s\", err)\n\t}\n\n\tc = new(Client)\n\tc.Config = new(ClientConfig)\n\tc.Config.URL = fmt.Sprintf(\"http://localhost:%d\", ctport1)\n\n\t// Bad TLS\n\tc.Config.MSPDir = \"msp\"\n\tvar kc tls.KeyCertFiles\n\tkc.KeyFile = \"../testdata/ec_key.pem\"\n\tkc.CertFile = \"../testdata/expiredcert.pem\"\n\tc.Config.MSPDir = \"\"\n\tc.Config.URL = \"\"\n\tc.Config.TLS.Enabled = true\n\tc.Config.TLS.CertFiles = []string{\"../testdata/ec.pem\"}\n\tc.Config.TLS.Client = kc\n\tcurl := fmt.Sprintf(\"http://localhost:%d/api/v1/register\", ctport1)\n\treqBody := []byte(\"\")\n\treq, _ := http.NewRequest(\"POST\", curl, bytes.NewReader(reqBody))\n\terr = c.SendReq(req, nil)\n\tt.Logf(\"Client SendReq() error %v\", err)\n\tif err == nil {\n\t\tt.Error(\"Sending post with bad TLS config should have failed\")\n\t}\n\n\terr = GenerateECDSATestCert()\n\tutil.FatalError(t, err, \"Failed to generate certificate for testing\")\n\tkc.CertFile = \"../testdata/ec_cert.pem\"\n\tc.Config.TLS.Client = kc\n\treq, _ = http.NewRequest(\"POST\", curl, bytes.NewReader(reqBody))\n\terr = c.SendReq(req, nil)\n\tt.Logf(\"Client SendReq() error %v\", err)\n\tif err == nil {\n\t\tt.Error(\"Sending post with bad TLS config should have failed\")\n\t}\n\n\t// Bad URL\n\tcurl = fmt.Sprintf(\"http://localhost:%d/fake\", ctport1)\n\treqBody = []byte(\"\")\n\treq, _ = http.NewRequest(\"POST\", curl, bytes.NewReader(reqBody))\n\terr = c.SendReq(req, nil)\n\tt.Logf(\"Client SendReq() error %v\", err)\n\tif err == nil {\n\t\tt.Error(\"Sending post with bad URL should have failed\")\n\t}\n\n\t// No authorization header\n\tcurl = fmt.Sprintf(\"http://localhost:%d/api/v1/revoke\", ctport1)\n\treqBody = []byte(\"\")\n\treq, _ = http.NewRequest(\"POST\", curl, bytes.NewReader(reqBody))\n\terr = c.SendReq(req, nil)\n\tt.Logf(\"Client SendReq() error %v\", err)\n\tif err == nil {\n\t\tt.Error(\"Sending register with no authorization header should have failed\")\n\t}\n\n\t// Bad authorization header\n\tcurl = fmt.Sprintf(\"http://localhost:%d/api/v1/register\", ctport1)\n\treqBody = []byte(\"\")\n\treq, _ = http.NewRequest(\"POST\", curl, bytes.NewReader(reqBody))\n\treq.Header.Add(\"Authorization\", \"bad-auth\")\n\terr = c.SendReq(req, nil)\n\tt.Logf(\"Client SendReq() error %v\", err)\n\tif err == nil {\n\t\tt.Error(\"Sending register with bad authorization header should have failed\")\n\t}\n\n\t// Bad Init\n\tc2 := new(Client)\n\tc2.Config = new(ClientConfig)\n\tc2.Config.URL = fmt.Sprintf(\"http://localhost:%d\", ctport1)\n\tc2.Config.MSPDir = string(make([]byte, 1))\n\tcurl = fmt.Sprintf(\"http://localhost:%d/api/v1/register\", ctport1)\n\treqBody = []byte(\"\")\n\treq, _ = http.NewRequest(\"POST\", curl, bytes.NewReader(reqBody))\n\terr = c2.SendReq(req, nil)\n\tt.Logf(\"Client SendReq() error %v\", err)\n\tif err == nil {\n\t\tt.Error(\"Sending post with bad Init should have failed\")\n\t}\n}", "func testInMemoryDataStore() IDataStore {\n return NewInMemoryDataStore();\n}", "func (m *MockSpaceStorage) Id() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Id\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func TestClientManagerCreateNew(t *testing.T) {\n\tctx, flush := th.TestContext(t)\n\tdefer flush()\n\n\ttd := testdeep.NewT(t)\n\n\tmc := minimock.NewController(td)\n\tdefer mc.Finish()\n\n\tc := NewBytesMock(mc)\n\n\tvar err error\n\n\t//register account\n\tmanager := New(ctx, c)\n\tc.PutMock.Return(nil)\n\tc.GetMock.Return(nil, cache.ErrCacheMiss)\n\tmanager.DirectoryURL = testACMEServer\n\tclient, err := manager.GetClient(ctx)\n\ttd.CmpNoError(err)\n\ttd.NotNil(client)\n\n\tclient2, err := manager.GetClient(ctx)\n\ttd.CmpNoError(err)\n\ttd.True(client == client2)\n}", "func NewMockIDAllocator() *MockIDAllocator {\n\treturn &MockIDAllocator{base: 0}\n}", "func TestFindUserById(t *testing.T) {\n\t_, mock, err := NewMock()\n\tif err != nil {\n\t\tfmt.Printf(\"error mock: \" + err.Error())\n\t}\n\n\t// simulate any sql driver behavior in tests, without needing a real database connection\n\tquery := \"select id, user_name, password from m_user where id = \\\\?\"\n\n\trows := sqlmock.NewRows([]string{\"id\", \"user_name\", \"password\"}).\n\t\tAddRow(user.ID, user.UserName, user.Password)\n\n\tmock.ExpectQuery(query).WithArgs(user.ID).WillReturnRows(rows)\n\t// ------------ end of mock ---------------\n\n\tassert.NotNil(t, user)\n}", "func TestAzureBlobGetAppsListShouldFailInvalidIdentity(t *testing.T) {\n\tctx := context.TODO()\n\tappFrameworkRef := enterpriseApi.AppFrameworkSpec{\n\t\tDefaults: enterpriseApi.AppSourceDefaultSpec{\n\t\t\tVolName: \"azure_vol1\",\n\t\t\tScope: enterpriseApi.ScopeLocal,\n\t\t},\n\t\tVolList: []enterpriseApi.VolumeSpec{\n\t\t\t{\n\t\t\t\tName: \"azure_vol1\",\n\t\t\t\tEndpoint: \"https://mystorageaccount.blob.core.windows.net\",\n\t\t\t\tPath: \"appscontainer1\",\n\t\t\t\tType: \"blob\",\n\t\t\t\tProvider: \"azure\",\n\t\t\t},\n\t\t},\n\t\tAppSources: []enterpriseApi.AppSourceSpec{\n\t\t\t{\n\t\t\t\tName: \"adminApps\",\n\t\t\t\tLocation: \"adminAppsRepo\",\n\t\t\t\tAppSourceDefaultSpec: enterpriseApi.AppSourceDefaultSpec{\n\t\t\t\t\tVolName: \"azure_vol1\",\n\t\t\t\t\tScope: enterpriseApi.ScopeLocal,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\t// Initialize clients\n\tazureBlobClient := &AzureBlobClient{}\n\tmclient := spltest.MockHTTPClient{}\n\n\t// Identity call return a token - that means AKS cluster has an identity configured.\n\twantRequest, _ := http.NewRequest(\"GET\", \"http://169.254.169.254/metadata/identity/oauth2/token?api-version=2021-10-01&resource=https%3A%2F%2Fstorage.azure.com%2F\", nil)\n\trespTokenData := &TokenResponse{\n\t\tAccessToken: \"acctoken\",\n\t\tClientID: \"ClientId\",\n\t}\n\tmrespdata, _ := json.Marshal(respTokenData)\n\tmclient.AddHandler(wantRequest, 200, string(mrespdata), nil)\n\n\t// Add mock for the azure rest call for list apps\n\twantRequest, _ = http.NewRequest(\"GET\", \"https://mystorageaccount.blob.core.windows.net/appscontainer1?prefix=adminAppsRepo&restype=container&comp=list&include=snapshots&include=metadata\", nil)\n\n\t// Expect the identity does not have authorization to access the buckets\n\tmclient.AddHandler(wantRequest, 403, \"identity not authorized\", nil)\n\n\t// Get App source and volume from spec\n\tappSource := appFrameworkRef.AppSources[0]\n\tvol, err := GetAppSrcVolume(ctx, appSource, &appFrameworkRef)\n\tif err != nil {\n\t\tt.Errorf(\"Unable to get volume for app source : %s\", appSource.Name)\n\t}\n\n\t// Update the GetRemoteDataClient function pointer\n\tgetClientWrapper := RemoteDataClientsMap[vol.Provider]\n\tgetClientWrapper.SetRemoteDataClientFuncPtr(ctx, vol.Provider, NewMockAzureBlobClient)\n\n\t// Update the GetRemoteDataClientInit function pointer\n\tinitFn := func(ctx context.Context, region, accessKeyID, secretAccessKey string) interface{} {\n\t\treturn &mclient\n\t}\n\tgetClientWrapper.SetRemoteDataClientInitFuncPtr(ctx, vol.Provider, initFn)\n\n\t// Init azure blob client\n\tgetRemoteDataClientFn := getClientWrapper.GetRemoteDataClientInitFuncPtr(ctx)\n\tazureBlobClient.HTTPClient = getRemoteDataClientFn(ctx, \"us-west-2\", \"abcd\", \"1234\").(*spltest.MockHTTPClient)\n\tazureBlobClient.BucketName = vol.Path\n\tazureBlobClient.Prefix = appSource.Location\n\tazureBlobClient.Endpoint = vol.Endpoint\n\n\trespList, err := azureBlobClient.GetAppsList(ctx)\n\tif err == nil {\n\t\tt.Errorf(\"GetAppsList should return err\")\n\t}\n\n\tif err.Error() != \"error authorizing the rest call. check your IAM/secret configuration\" {\n\t\tt.Errorf(\"GetAppsList should return authorization error\")\n\t}\n\n\t// authorizing the rest call. check your IAM/secret configuration\n\n\tif len(respList.Objects) != 0 {\n\t\tt.Errorf(\"GetAppsList should not return any response objects\")\n\t}\n\tmclient.RemoveHandlers()\n}", "func (m *MockVerifier) Verify(arg0 context.Context, arg1, arg2 string) (*oidc.IDTokenClaims, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Verify\", arg0, arg1, arg2)\n\tret0, _ := ret[0].(*oidc.IDTokenClaims)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *GraphBaseServiceClient) Identity()(*i79ca23a9ac0659e1330dd29e049fe157787d5af6695ead2ff8263396db68d027.IdentityRequestBuilder) {\n return i79ca23a9ac0659e1330dd29e049fe157787d5af6695ead2ff8263396db68d027.NewIdentityRequestBuilderInternal(m.pathParameters, m.requestAdapter);\n}", "func (m *GraphBaseServiceClient) Identity()(*i79ca23a9ac0659e1330dd29e049fe157787d5af6695ead2ff8263396db68d027.IdentityRequestBuilder) {\n return i79ca23a9ac0659e1330dd29e049fe157787d5af6695ead2ff8263396db68d027.NewIdentityRequestBuilderInternal(m.pathParameters, m.requestAdapter);\n}", "func (m *MockSession) ID() sig_mgmt.SessionType {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ID\")\n\tret0, _ := ret[0].(sig_mgmt.SessionType)\n\treturn ret0\n}", "func fakeAuthState() *authtest.FakeState {\n\treturn &authtest.FakeState{\n\t\tIdentity: \"user:user@example.com\",\n\t\tIdentityPermissions: []authtest.RealmPermission{\n\t\t\t{\n\t\t\t\tRealm: \"@internal:test-proj/cas-read-only\",\n\t\t\t\tPermission: permMintToken,\n\t\t\t},\n\t\t},\n\t}\n}", "func TestCreateIdentity(t *testing.T) {\r\n\r\n\tt.Parallel()\r\n\r\n\tvar (\r\n\t\t// Testing private methods\r\n\t\ttests = []struct {\r\n\t\t\tinputPrivateKey string\r\n\t\t\tinputIDKey string\r\n\t\t\tinputCounter uint32\r\n\t\t\texpectedTxID string\r\n\t\t\texpectedNil bool\r\n\t\t\texpectedError bool\r\n\t\t}{\r\n\t\t\t{\r\n\t\t\t\tprivateKey,\r\n\t\t\t\tidKey,\r\n\t\t\t\t0,\r\n\t\t\t\t\"d2384b0946b8c3137bc0bf12d122efb8b77be998118b65c21448864234188f20\",\r\n\t\t\t\tfalse,\r\n\t\t\t\tfalse,\r\n\t\t\t},\r\n\t\t\t{\r\n\t\t\t\t\"\",\r\n\t\t\t\tidKey,\r\n\t\t\t\t0,\r\n\t\t\t\t\"49957864306b123c3cca8711635ba88890bb334eb3e9f21553b118eb4d66cc62\",\r\n\t\t\t\ttrue,\r\n\t\t\t\ttrue,\r\n\t\t\t},\r\n\t\t\t{\r\n\t\t\t\t\"invalid-key\",\r\n\t\t\t\tidKey,\r\n\t\t\t\t0,\r\n\t\t\t\t\"49957864306b123c3cca8711635ba88890bb334eb3e9f21553b118eb4d66cc62\",\r\n\t\t\t\ttrue,\r\n\t\t\t\ttrue,\r\n\t\t\t},\r\n\t\t\t{\r\n\t\t\t\tprivateKey,\r\n\t\t\t\t\"\",\r\n\t\t\t\t0,\r\n\t\t\t\t\"49957864306b123c3cca8711635ba88890bb334eb3e9f21553b118eb4d66cc62\",\r\n\t\t\t\ttrue,\r\n\t\t\t\ttrue,\r\n\t\t\t},\r\n\t\t\t{\r\n\t\t\t\tprivateKey,\r\n\t\t\t\tidKey,\r\n\t\t\t\t1,\r\n\t\t\t\t\"4f00a4c6bca4a538ecce849b19188222aeb0d28e7b0c9acdb0c20fe9de628f9e\",\r\n\t\t\t\tfalse,\r\n\t\t\t\tfalse,\r\n\t\t\t},\r\n\t\t\t{\r\n\t\t\t\tprivateKey,\r\n\t\t\t\tidKey,\r\n\t\t\t\t100,\r\n\t\t\t\t\"0b61af0cfd6331731b7f897b051a56a903928c6bcff8ba59cdd4b8d0093b12ae\",\r\n\t\t\t\tfalse,\r\n\t\t\t\tfalse,\r\n\t\t\t},\r\n\t\t}\r\n\t)\r\n\r\n\t// Run tests\r\n\tfor _, test := range tests {\r\n\t\tif tx, err := CreateIdentity(test.inputPrivateKey, test.inputIDKey, test.inputCounter); err != nil && !test.expectedError {\r\n\t\t\tt.Errorf(\"%s Failed: [%s] [%s] [%d] inputted and error not expected but got: %s\", t.Name(), test.inputPrivateKey, test.inputIDKey, test.inputCounter, err.Error())\r\n\t\t} else if err == nil && test.expectedError {\r\n\t\t\tt.Errorf(\"%s Failed: [%s] [%s] [%d] inputted and error was expected\", t.Name(), test.inputPrivateKey, test.inputIDKey, test.inputCounter)\r\n\t\t} else if tx == nil && !test.expectedNil {\r\n\t\t\tt.Errorf(\"%s Failed: [%s] [%s] [%d] inputted and nil was not expected\", t.Name(), test.inputPrivateKey, test.inputIDKey, test.inputCounter)\r\n\t\t} else if tx != nil && test.expectedNil {\r\n\t\t\tt.Errorf(\"%s Failed: [%s] [%s] [%d] inputted and nil was expected\", t.Name(), test.inputPrivateKey, test.inputIDKey, test.inputCounter)\r\n\t\t} else if tx != nil && tx.GetTxID() != test.expectedTxID {\r\n\t\t\tt.Errorf(\"%s Failed: [%s] [%s] [%d] inputted and expected [%s] but got [%s]\", t.Name(), test.inputPrivateKey, test.inputIDKey, test.inputCounter, test.expectedTxID, tx.GetTxID())\r\n\t\t}\r\n\t}\r\n}", "func (mr *MockClientMockRecorder) IdentityManager(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"IdentityManager\", reflect.TypeOf((*MockClient)(nil).IdentityManager), arg0)\n}", "func (suite *SubscriptionsTestSuite) mockClientAuth(account *accounts.Account) {\n\t// Mock GetConfig call to return the config object\n\tsuite.accountsServiceMock.On(\"GetConfig\").Return(suite.cnf)\n\n\t// Mock GetOauthService to return a mock oauth service\n\tsuite.accountsServiceMock.On(\"GetOauthService\").Return(suite.oauthServiceMock)\n\n\t// Mock AuthClient to return a mock client\n\tsuite.oauthServiceMock.On(\"AuthClient\", \"test_client_1\", \"test_secret\").\n\t\tReturn(account.OauthClient, nil)\n\n\t// Mock FindAccountByOauthClientID to return the wanted account\n\tsuite.accountsServiceMock.\n\t\tOn(\"FindAccountByOauthClientID\", account.OauthClient.ID).\n\t\tReturn(account, nil)\n}", "func (m *MockRepository) GetUsersFromIDs(arg0 []uuid.UUID) ([]user.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUsersFromIDs\", arg0)\n\tret0, _ := ret[0].([]user.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func NewIdentityProvider() users.IdentityProvider {\n\treturn &identityProviderMock{}\n}", "func (m *MockManagerClient) CreateManagerOnServer(userId, companyId int64) (*manager_grpc.Manager, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"CreateManagerOnServer\", userId, companyId)\n\tret0, _ := ret[0].(*manager_grpc.Manager)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockAuthGateway) GetUserByID(arg0 int64) (entity.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUserByID\", arg0)\n\tret0, _ := ret[0].(entity.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func TestAuthenticate_Fail(t *testing.T) {\n\tdb, mock, err := sqlmock.New()\n\tif err != nil {\n\t\tt.Fatalf(\"an error '%s' was not expected when opening a stub database connection\", err)\n\t}\n\tdefer db.Close()\n\n\tuser := models.User{\n\t\tID: 1,\n\t\tEmail: \"personia@personio.com\",\n\t\tPassword: \"personia\",\n\t}\n\n\tvar buffer bytes.Buffer\n\tbuffer.WriteString(constants.LoginDetailsSelectQuery)\n\n\trows := sqlmock.NewRows([]string{\"id\", \"email\"})\n\tmock.ExpectQuery(regexp.QuoteMeta(buffer.String())).WithArgs(user.Email, user.Password).WillReturnRows(rows)\n\n\tloginRepository := NewLoginRepository(db)\n\n\tloginModel := &models.Login{\n\t\tEmail: \"personia@personio.com\",\n\t\tPassword: \"personia\",\n\t}\n\n\tcntx := context.Background()\n\t_, err = loginRepository.Authenticate(cntx, loginModel)\n\tassert.NotNil(t, err)\n}", "func (m *MockStream) ID() uint64 {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ID\")\n\tret0, _ := ret[0].(uint64)\n\treturn ret0\n}", "func (m *MockidentityService) Get() (identity.Caller, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Get\")\n\tret0, _ := ret[0].(identity.Caller)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (rest *TestTokenStorageREST) TestRetrieveExternalTokenIdentityNotPresent() {\n\t// using an Identity which does not exist in the database.\n\tidentity := account.Identity{\n\t\tID: uuid.NewV4(),\n\t\tUsername: \"TestDeveloper\",\n\t}\n\n\tservice, controller := rest.SecuredControllerWithIdentity(identity)\n\ttest.RetrieveTokenUnauthorized(rest.T(), service.Context, service, controller, \"https://github.com/a/b\", nil)\n\ttest.RetrieveTokenUnauthorized(rest.T(), service.Context, service, controller, \"github\", nil)\n\ttest.RetrieveTokenUnauthorized(rest.T(), service.Context, service, controller, \"https://api.starter-us-east-2.openshift.com\", nil)\n\ttest.RetrieveTokenUnauthorized(rest.T(), service.Context, service, controller, \"openshift\", nil)\n}", "func (m *MockConn) UserID() uint64 {\n\tret := m.ctrl.Call(m, \"UserID\")\n\tret0, _ := ret[0].(uint64)\n\treturn ret0\n}", "func MockOpenIDConnect(t *testing.T) string {\n\tconst discovery = `{\n\t\t\"issuer\": \"https://example.com/\",\n\t\t\"authorization_endpoint\": \"https://example.com/authorize\",\n\t\t\"token_endpoint\": \"https://example.com/token\",\n\t\t\"userinfo_endpoint\": \"https://example.com/userinfo\",\n\t\t\"jwks_uri\": \"https://example.com/.well-known/jwks.json\",\n\t\t\"scopes_supported\": [\n\t\t\t\"pets_read\",\n\t\t\t\"pets_write\",\n\t\t\t\"admin\"\n\t\t],\n\t\t\"response_types_supported\": [\n\t\t\t\"code\",\n\t\t\t\"id_token\",\n\t\t\t\"token id_token\"\n\t\t],\n\t\t\"token_endpoint_auth_methods_supported\": [\n\t\t\t\"client_secret_basic\"\n\t\t]\n\t}`\n\tsrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tw.WriteHeader(http.StatusOK)\n\t\t_, err := w.Write([]byte(discovery))\n\t\trequire.NoError(t, err)\n\t}))\n\tt.Cleanup(func() {\n\t\tsrv.Close()\n\t})\n\treturn srv.URL + \"/.well-known/openid-configuration\"\n}", "func FakeManager(failingControllers int) *Manager {\n\tm := &Manager{\n\t\tcontrollers: controllerMap{},\n\t}\n\n\tfor i := 0; i < failingControllers; i++ {\n\t\tctrl := &managedController{\n\t\t\tcontroller: controller{\n\t\t\t\tname: fmt.Sprintf(\"controller-%d\", i),\n\t\t\t\tuuid: fmt.Sprintf(\"%d\", i),\n\t\t\t\tstop: make(chan struct{}),\n\t\t\t\tupdate: make(chan ControllerParams, 1),\n\t\t\t\ttrigger: make(chan struct{}, 1),\n\t\t\t\tterminated: make(chan struct{}),\n\t\t\t\tlastError: fmt.Errorf(\"controller failed\"),\n\t\t\t\tfailureCount: 1,\n\t\t\t\tconsecutiveErrors: 1,\n\t\t\t},\n\t\t}\n\n\t\tctrl.params.Context, ctrl.cancelDoFunc = context.WithCancel(context.Background())\n\t\tm.controllers[ctrl.name] = ctrl\n\t}\n\n\treturn m\n}", "func mockedGranter(kubeutil *kube.Kube, app *v1.RadixRegistration, namespace string, serviceAccount *corev1.ServiceAccount) error {\n\treturn nil\n}", "func (mmForID *mAtomicRecordStorageMockForID) Expect(ctx context.Context, id insolar.ID) *mAtomicRecordStorageMockForID {\n\tif mmForID.mock.funcForID != nil {\n\t\tmmForID.mock.t.Fatalf(\"AtomicRecordStorageMock.ForID mock is already set by Set\")\n\t}\n\n\tif mmForID.defaultExpectation == nil {\n\t\tmmForID.defaultExpectation = &AtomicRecordStorageMockForIDExpectation{}\n\t}\n\n\tmmForID.defaultExpectation.params = &AtomicRecordStorageMockForIDParams{ctx, id}\n\tfor _, e := range mmForID.expectations {\n\t\tif minimock.Equal(e.params, mmForID.defaultExpectation.params) {\n\t\t\tmmForID.mock.t.Fatalf(\"Expectation set by When has same params: %#v\", *mmForID.defaultExpectation.params)\n\t\t}\n\t}\n\n\treturn mmForID\n}", "func NewIdentityManager(orgName string, userStore msp.UserStore, cryptoSuite core.CryptoSuite, endpointConfig fab.EndpointConfig) (*IdentityManager, error) {\n\n\tnetConfig := endpointConfig.NetworkConfig()\n\t// viper keys are case insensitive\n\torgConfig, ok := netConfig.Organizations[strings.ToLower(orgName)]\n\tif !ok {\n\t\treturn nil, errors.New(\"org config retrieval failed\")\n\t}\n\n\tif orgConfig.CryptoPath == \"\" && len(orgConfig.Users) == 0 {\n\t\treturn nil, errors.New(\"Either a cryptopath or an embedded list of users is required\")\n\t}\n\n\tvar mspPrivKeyStore core.KVStore\n\tvar mspCertStore core.KVStore\n\n\torgCryptoPathTemplate := orgConfig.CryptoPath\n\tif orgCryptoPathTemplate != \"\" {\n\t\tvar err error\n\t\tif !filepath.IsAbs(orgCryptoPathTemplate) {\n\t\t\torgCryptoPathTemplate = filepath.Join(endpointConfig.CryptoConfigPath(), orgCryptoPathTemplate)\n\t\t}\n\t\tmspPrivKeyStore, err = NewFileKeyStore(orgCryptoPathTemplate)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"creating a private key store failed\")\n\t\t}\n\t\tmspCertStore, err = NewFileCertStore(orgCryptoPathTemplate)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"creating a cert store failed\")\n\t\t}\n\t} else {\n\t\tlogger.Warnf(\"Cryptopath not provided for organization [%s], MSP stores not created\", orgName)\n\t}\n\n\tmgr := &IdentityManager{\n\t\torgName: orgName,\n\t\torgMSPID: orgConfig.MSPID,\n\t\tconfig: endpointConfig,\n\t\tcryptoSuite: cryptoSuite,\n\t\tmspPrivKeyStore: mspPrivKeyStore,\n\t\tmspCertStore: mspCertStore,\n\t\tembeddedUsers: orgConfig.Users,\n\t\tuserStore: userStore,\n\t\t// CA Client state is created lazily, when (if) needed\n\t}\n\treturn mgr, nil\n}", "func (m *MockInterface) InitializeAuthorizers() error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"InitializeAuthorizers\")\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func TestOAuth2ClientCredentialsCache(t *testing.T) {\n\t// Setup\n\tmockCtrl := gomock.NewController(t)\n\tdefer mockCtrl.Finish()\n\n\t// Mock mockTokenProvider\n\tmockTokenProvider := mock.NewMockTokenProviderInterface(mockCtrl)\n\n\tgomock.InOrder(\n\t\t// First call returning abc and Bearer, expires within 1 second\n\t\tmockTokenProvider.\n\t\t\tEXPECT().\n\t\t\tGetToken(gomock.Any()).\n\t\t\tReturn(&oauth2.Token{\n\t\t\t\tAccessToken: \"abc\",\n\t\t\t\tTokenType: \"Bearer\",\n\t\t\t\tExpiry: time.Now().In(time.UTC).Add(1 * time.Second),\n\t\t\t}, nil).\n\t\t\tTimes(1),\n\t\t// Second call returning def and MAC, expires within 1 second\n\t\tmockTokenProvider.\n\t\t\tEXPECT().\n\t\t\tGetToken(gomock.Any()).\n\t\t\tReturn(&oauth2.Token{\n\t\t\t\tAccessToken: \"def\",\n\t\t\t\tTokenType: \"MAC\",\n\t\t\t\tExpiry: time.Now().In(time.UTC).Add(1 * time.Second),\n\t\t\t}, nil).\n\t\t\tTimes(1),\n\t)\n\n\t// Specify components metadata\n\tvar metadata middleware.Metadata\n\tmetadata.Properties = map[string]string{\n\t\t\"clientID\": \"testId\",\n\t\t\"clientSecret\": \"testSecret\",\n\t\t\"scopes\": \"ascope\",\n\t\t\"tokenURL\": \"https://localhost:9999\",\n\t\t\"headerName\": \"someHeader\",\n\t\t\"authStyle\": \"1\",\n\t}\n\n\t// Initialize middleware component and inject mocked TokenProvider\n\tlog := logger.NewLogger(\"oauth2clientcredentials.test\")\n\toauth2clientcredentialsMiddleware, _ := NewOAuth2ClientCredentialsMiddleware(log).(*Middleware)\n\toauth2clientcredentialsMiddleware.SetTokenProvider(mockTokenProvider)\n\thandler, err := oauth2clientcredentialsMiddleware.GetHandler(context.Background(), metadata)\n\trequire.NoError(t, err)\n\n\t// First handler call should return abc Token\n\tr := httptest.NewRequest(http.MethodGet, \"http://dapr.io\", nil)\n\tw := httptest.NewRecorder()\n\thandler(http.HandlerFunc(mockedRequestHandler)).ServeHTTP(w, r)\n\n\t// Assertion\n\tassert.Equal(t, \"Bearer abc\", r.Header.Get(\"someHeader\"))\n\n\t// Second handler call should still return 'cached' abc Token\n\tr = httptest.NewRequest(http.MethodGet, \"http://dapr.io\", nil)\n\tw = httptest.NewRecorder()\n\thandler(http.HandlerFunc(mockedRequestHandler)).ServeHTTP(w, r)\n\n\t// Assertion\n\tassert.Equal(t, \"Bearer abc\", r.Header.Get(\"someHeader\"))\n\n\t// Wait at a second to invalidate cache entry for abc\n\ttime.Sleep(1 * time.Second)\n\n\t// Third call should return def Token\n\tr = httptest.NewRequest(http.MethodGet, \"http://dapr.io\", nil)\n\tw = httptest.NewRecorder()\n\thandler(http.HandlerFunc(mockedRequestHandler)).ServeHTTP(w, r)\n\n\t// Assertion\n\tassert.Equal(t, \"MAC def\", r.Header.Get(\"someHeader\"))\n}", "func TestOsIdmAll(t *testing.T) {\n\tidm := osidm.New()\n\n\tsidm := test.NewSuiteIdm(t, idm)\n\tsidm.TestAll(t)\n}", "func (m *MockUserService) Authenticate(tx *sqlx.Tx, username, password string) (int64, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Authenticate\", tx, username, password)\n\tret0, _ := ret[0].(int64)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockDatabase) GetUsersID() ([]uint64, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUsersID\")\n\tret0, _ := ret[0].([]uint64)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (_m *MockRepository) CreateEmailIdentity(identity models.Identity, executor database.QueryExecutor) (*models.Identity, error) {\n\tret := _m.Called(identity, executor)\n\n\tvar r0 *models.Identity\n\tif rf, ok := ret.Get(0).(func(models.Identity, database.QueryExecutor) *models.Identity); ok {\n\t\tr0 = rf(identity, executor)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*models.Identity)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(models.Identity, database.QueryExecutor) error); ok {\n\t\tr1 = rf(identity, executor)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func TestDbInterfaceMethods(t *testing.T) {\n\ttestUser := models.User{\n\t\tAccount: models.Account{\n\t\t\tType: \"email\",\n\t\t\tAccountID: \"test@test.com\",\n\t\t\tPassword: \"testhashedpassword-youcantreadme\",\n\t\t},\n\t\tRoles: []string{\"TEST\"},\n\t\tTimestamps: models.Timestamps{\n\t\t\tCreatedAt: time.Now().Unix(),\n\t\t},\n\t}\n\n\tt.Run(\"Testing create user\", func(t *testing.T) {\n\t\tid, err := testDBService.AddUser(testInstanceID, testUser)\n\t\tif err != nil {\n\t\t\tt.Errorf(err.Error())\n\t\t\treturn\n\t\t}\n\t\tif len(id) == 0 {\n\t\t\tt.Errorf(\"id is missing\")\n\t\t\treturn\n\t\t}\n\t\t_id, _ := primitive.ObjectIDFromHex(id)\n\t\ttestUser.ID = _id\n\t})\n\n\tt.Run(\"Testing creating existing user\", func(t *testing.T) {\n\t\ttestUser2 := testUser\n\t\ttestUser2.Roles = []string{\"TEST2\"}\n\t\t_, err := testDBService.AddUser(testInstanceID, testUser2)\n\t\tif err == nil {\n\t\t\tt.Errorf(\"user already existed, but created again\")\n\t\t\treturn\n\t\t}\n\t\tu, e := testDBService.GetUserByAccountID(testInstanceID, testUser2.Account.AccountID)\n\t\tif e != nil {\n\t\t\tt.Errorf(e.Error())\n\t\t\treturn\n\t\t}\n\t\tif len(u.Roles) > 0 && u.Roles[0] == \"TEST2\" {\n\t\t\tt.Error(\"user should not be updated\")\n\t\t}\n\t})\n\n\tt.Run(\"Testing find existing user by id\", func(t *testing.T) {\n\t\tuser, err := testDBService.GetUserByID(testInstanceID, testUser.ID.Hex())\n\t\tif err != nil {\n\t\t\tt.Errorf(err.Error())\n\t\t\treturn\n\t\t}\n\t\tif user.Account.AccountID != testUser.Account.AccountID {\n\t\t\tt.Errorf(\"found user is not matching test user\")\n\t\t\treturn\n\t\t}\n\t})\n\n\tt.Run(\"Testing find not existing user by id\", func(t *testing.T) {\n\t\t_, err := testDBService.GetUserByID(testInstanceID, testUser.ID.Hex()+\"1\")\n\t\tif err == nil {\n\t\t\tt.Errorf(\"user should not be found\")\n\t\t\treturn\n\t\t}\n\t})\n\n\tt.Run(\"Testing find existing user by email\", func(t *testing.T) {\n\t\tuser, err := testDBService.GetUserByAccountID(testInstanceID, testUser.Account.AccountID)\n\t\tif err != nil {\n\t\t\tt.Errorf(err.Error())\n\t\t\treturn\n\t\t}\n\t\tif user.Account.AccountID != testUser.Account.AccountID {\n\t\t\tt.Errorf(\"found user is not matching test user\")\n\t\t\treturn\n\t\t}\n\t})\n\n\tt.Run(\"Testing find not existing user by email\", func(t *testing.T) {\n\t\t_, err := testDBService.GetUserByAccountID(testInstanceID, testUser.Account.AccountID+\"1\")\n\t\tif err == nil {\n\t\t\tt.Errorf(\"user should not be found\")\n\t\t\treturn\n\t\t}\n\t})\n\n\tt.Run(\"Testing updating existing user's attributes\", func(t *testing.T) {\n\t\ttestUser.Account.AccountConfirmedAt = time.Now().Unix()\n\t\t_, err := testDBService.UpdateUser(testInstanceID, testUser)\n\t\tif err != nil {\n\t\t\tt.Errorf(err.Error())\n\t\t\treturn\n\t\t}\n\t})\n\n\tt.Run(\"Testing updating not existing user's attributes\", func(t *testing.T) {\n\t\ttestUser.Account.AccountConfirmedAt = time.Now().Unix()\n\t\tcurrentUser := testUser\n\t\twrongID := testUser.ID.Hex()[:len(testUser.ID.Hex())-2] + \"00\"\n\t\tid, err := primitive.ObjectIDFromHex(wrongID)\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t\treturn\n\t\t}\n\t\tcurrentUser.ID = id\n\t\t_, err = testDBService.UpdateUser(testInstanceID, currentUser)\n\t\tif err == nil {\n\t\t\tt.Errorf(\"cannot update not existing user\")\n\t\t\treturn\n\t\t}\n\t})\n\n\tt.Run(\"Testing counting recently added users\", func(t *testing.T) {\n\t\tcount, err := testDBService.CountRecentlyCreatedUsers(testInstanceID, 20)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"unexpected error: %v\", err)\n\t\t\treturn\n\n\t\t}\n\t\tlogger.Debug.Println(count)\n\t\tif count < 1 {\n\t\t\tt.Error(\"at least one user should be found\")\n\t\t}\n\t})\n\n\tt.Run(\"Testing deleting existing user\", func(t *testing.T) {\n\t\terr := testDBService.DeleteUser(testInstanceID, testUser.ID.Hex())\n\t\tif err != nil {\n\t\t\tt.Errorf(err.Error())\n\t\t\treturn\n\t\t}\n\t})\n\n\tt.Run(\"Testing deleting not existing user\", func(t *testing.T) {\n\t\terr := testDBService.DeleteUser(testInstanceID, testUser.ID.Hex()+\"1\")\n\t\tif err == nil {\n\t\t\tt.Errorf(\"user should not be found - error expected\")\n\t\t\treturn\n\t\t}\n\t})\n}", "func (m *MockAccessToken) Create(token api.AccessToken) (api.AccessToken, error) {\n\tret := m.ctrl.Call(m, \"Create\", token)\n\tret0, _ := ret[0].(api.AccessToken)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func mockAuthenticationComponent(log *zap.Logger, serviceName string) *AuthenticationComponent {\n\thttpTimeout := 300 * time.Millisecond\n\n\treturn NewAuthenticationComponent(&AuthenticationParams{\n\t\tAuthConfig: &core_auth_sdk.Config{\n\t\t\tIssuer: issuer,\n\t\t\tPrivateBaseURL: privateBaseUrl,\n\t\t\tAudience: audience,\n\t\t\tUsername: username,\n\t\t\tPassword: password,\n\t\t\tKeychainTTL: 0,\n\t\t},\n\t\tAuthConnectionConfig: &core_auth_sdk.RetryConfig{\n\t\t\tMaxRetries: 1,\n\t\t\tMinRetryWaitTime: 200 * time.Millisecond,\n\t\t\tMaxRetryWaitTime: 300 * time.Millisecond,\n\t\t\tRequestTimeout: 500 * time.Millisecond,\n\t\t},\n\t\tLogger: log,\n\t\tOrigin: origin,\n\t}, serviceName, httpTimeout)\n}", "func FakeManager(failingControllers int) *Manager {\n\tm := &Manager{\n\t\tcontrollers: controllerMap{},\n\t}\n\n\tfor i := 0; i < failingControllers; i++ {\n\t\tctrl := &Controller{\n\t\t\tname: fmt.Sprintf(\"controller-%d\", i),\n\t\t\tuuid: fmt.Sprintf(\"%d\", i),\n\t\t\tstop: make(chan struct{}),\n\t\t\tupdate: make(chan struct{}, 1),\n\t\t\ttrigger: make(chan struct{}, 1),\n\t\t\tterminated: make(chan struct{}),\n\t\t\tlastError: fmt.Errorf(\"controller failed\"),\n\t\t\tfailureCount: 1,\n\t\t\tconsecutiveErrors: 1,\n\t\t}\n\n\t\tctrl.ctxDoFunc, ctrl.cancelDoFunc = context.WithCancel(context.Background())\n\t\tm.controllers[ctrl.name] = ctrl\n\t}\n\n\treturn m\n}", "func (m *MockDelegateActor) AuthenticateGetInbox(c context.Context, w http.ResponseWriter, r *http.Request) (context.Context, bool, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"AuthenticateGetInbox\", c, w, r)\n\tret0, _ := ret[0].(context.Context)\n\tret1, _ := ret[1].(bool)\n\tret2, _ := ret[2].(error)\n\treturn ret0, ret1, ret2\n}", "func MockOnGetManagerVirtualMedia(ctx context.Context, mockAPI *redfishMocks.RedfishAPI,\n\tmanagerID string, virtualMediaID string, virtualMedia redfishClient.VirtualMedia,\n\thttpResponse *http.Response, err error) {\n\tmediaRequest := redfishClient.ApiGetManagerVirtualMediaRequest{}\n\tmockAPI.On(\"GetManagerVirtualMedia\", ctx, managerID, virtualMediaID).Return(mediaRequest).Times(1)\n\tmockAPI.On(\"GetManagerVirtualMediaExecute\", mock.Anything).Return(virtualMedia, httpResponse, err).Times(1)\n}", "func (m *MockCAClient) GetIdentity(arg0, arg1 string) (*api.IdentityResponse, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetIdentity\", arg0, arg1)\n\tret0, _ := ret[0].(*api.IdentityResponse)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func TestManager(t *testing.T) {\n\tsuite.Run(t, &TestManagerSuite{})\n}", "func newAuthorizationMocks(t *testing.T, resource, action string) (\n\tauthn.AuthenticationServiceClient, authz.AuthorizationServiceClient) {\n\tvar (\n\t\tctrl = gomock.NewController(t)\n\t\tmockAuthClient = authn.NewMockAuthenticationServiceClient(ctrl)\n\t\tmockAuthzClient = authz.NewMockAuthorizationServiceClient(ctrl)\n\t)\n\n\t// Mocking AuthN Calls\n\tmockAuthClient.EXPECT().Authenticate(gomock.Any(), gomock.Any()).DoAndReturn(\n\t\tfunc(_ context.Context, _ *authn.AuthenticateRequest) (*authn.AuthenticateResponse, error) {\n\t\t\treturn &authn.AuthenticateResponse{Subject: \"mock\", Teams: []string{}}, nil\n\t\t})\n\n\t// Mocking AuthZ Calls\n\tmockAuthzClient.EXPECT().ProjectsAuthorized(\n\t\tgomock.Any(),\n\t\t&authz.ProjectsAuthorizedReq{\n\t\t\tSubjects: []string{\"mock\"},\n\t\t\tResource: resource,\n\t\t\tAction: action,\n\t\t\tProjectsFilter: []string{},\n\t\t},\n\t).DoAndReturn(\n\t\tfunc(_ context.Context, _ *authz.ProjectsAuthorizedReq) (*authz.ProjectsAuthorizedResp, error) {\n\t\t\treturn &authz.ProjectsAuthorizedResp{Projects: []string{\"any\"}}, nil\n\t\t},\n\t)\n\n\treturn mockAuthClient, mockAuthzClient\n}", "func (m *MockDao) UID(steamID int64) (*model.Info, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"UID\", steamID)\n\tret0, _ := ret[0].(*model.Info)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func TestAssetSysCC_InvalidateToken(t *testing.T) {\n\n\tfmt.Println(\"-----------------------------------\")\n\tfmt.Println(\"Test3: invalidateToken\")\n\n\t//fmt.Println(\"******test string to big.newInt\")\n\t//str := \"12321\"\n\t//strInt := big.NewInt(0)\n\t//strInt.SetString(str,10)\n\t//fmt.Println(strInt.String())\n\t//fmt.Println(\"*******************************\")\n\n\tascc := new(AssetSysCC)\n\tstub := shim.NewMockStub(\"ascc\", ascc)\n\tcheckInit(t, stub, [][]byte{[]byte(\"\")})\n\n\tres_test3 := stub.MockInvoke(\"1\", [][]byte{[]byte(\"issueToken\"), []byte(\"SSToken\"), []byte(\"250\"), []byte(\"18\"), []byte(MAddress[:])})\n\n\tif res_test3.Status != shim.OK {\n\t\tfmt.Println(\"Register token failed\", string(res_test3.Message))\n\t\tt.FailNow()\n\t}\n\n\t////query token quantity\n\t//res1 := stub.MockInvoke(\"2\", [][]byte{[]byte(\"getBalance\"), []byte(MAddress[:]), []byte(\"SSToken\")});\n\t//if res1.Status != shim.OK {\n\t//\tfmt.Println(\"Query failed\", string(res1.Message))\n\t//\tt.FailNow()\n\t//}\n\t//amount,_ := strconv.Atoi(string(res1.Payload))\n\t//if amount != 250 {\n\t//\tfmt.Printf(\"Query result error! %v\", amount )\n\t//\tt.FailNow()\n\t//}\n\n\t//beging to invalidate this token\n\tcheckQueryInfo(t, stub, [][]byte{[]byte(\"getTokenInfo\"), []byte(\"SSToken\")})\n\n\ttestInvalidate := stub.MockInvoke(\"4\", [][]byte{[]byte(\"invalidateToken\"), []byte(\"SSToken\")});\n\tif testInvalidate.Status != shim.OK {\n\t\tfmt.Println(\"Query failed\", string(testInvalidate.Message))\n\t\tt.FailNow()\n\t}\n\n\tcheckQueryInfo(t, stub, [][]byte{[]byte(\"getTokenInfo\"), []byte(\"SSToken\")})\n}", "func (m *MockOauthAccessTokenRepository) Create(ktx kontext.Context, data entity.OauthAccessTokenInsertable, tx db.TX) (int, exception.Exception) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Create\", ktx, data, tx)\n\tret0, _ := ret[0].(int)\n\tret1, _ := ret[1].(exception.Exception)\n\treturn ret0, ret1\n}", "func (mr *MockProvidersMockRecorder) IdentityManager(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"IdentityManager\", reflect.TypeOf((*MockProviders)(nil).IdentityManager), arg0)\n}", "func (m *MockStore) GetUserById(arg0 context.Context, arg1 uuid.UUID) (db.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUserById\", arg0, arg1)\n\tret0, _ := ret[0].(db.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockCandidatePropertyGetter) Id() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Id\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func (m *CommunicationsIdentitySet) SetAssertedIdentity(value Identityable)() {\n err := m.GetBackingStore().Set(\"assertedIdentity\", value)\n if err != nil {\n panic(err)\n }\n}", "func (m *MockUsersRepoInterface) Authorize(arg0, arg1 string) (*user.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Authorize\", arg0, arg1)\n\tret0, _ := ret[0].(*user.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func TestMemIdmAll(t *testing.T) {\n\tidm := memidm.New()\n\tsidm := test.NewSuiteIdm(t, idm)\n\tsidm.TestAll(t)\n}", "func (m *MockClient) SigningManager() core.SigningManager {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"SigningManager\")\n\tret0, _ := ret[0].(core.SigningManager)\n\treturn ret0\n}", "func InitializeMockAuthenticationComponent() *AuthenticationComponent {\n\tlogInstance := core_logging.New(\"info\")\n\tdefer logInstance.ConfigureLogger()\n\tlog := logInstance.Logger\n\n\treturn mockAuthenticationComponent(log, svcName)\n}", "func mockClientFactoryGenerator(setupFn ...func(c istioclient.Interface)) func() (istioclient.Interface, error) {\n\toutFactory := func() (istioclient.Interface, error) {\n\t\tc := kube.NewFakeClient().Istio()\n\t\tfor _, f := range setupFn {\n\t\t\tf(c)\n\t\t}\n\t\treturn c, nil\n\t}\n\n\treturn outFactory\n}", "func (m *MockCAClient) CreateIdentity(arg0 *api.IdentityRequest) (*api.IdentityResponse, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"CreateIdentity\", arg0)\n\tret0, _ := ret[0].(*api.IdentityResponse)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func TestAssetSysCC_IssueToken(t *testing.T) {\n\n\tfmt.Println(\"-----------------------------------\")\n\tfmt.Println(\"Test2: issueToken\")\n\n\tascc := new(AssetSysCC)\n\tstub := shim.NewMockStub(\"ascc\", ascc)\n\tcheckInit(t, stub, [][]byte{[]byte(\"\")})\n\n\n\tres_test2 := stub.MockInvoke(\"1\", [][]byte{[]byte(\"registerToken\"), []byte(\"SSToken\"), []byte(\"250\"), []byte(\"18\"), []byte(MAddress[:])})\n\n\tif res_test2.Status != shim.OK {\n\t\tfmt.Println(\"Register token failed\", string(res_test2.Message))\n\t\tt.FailNow()\n\t}\n\n\tres_test3 := stub.MockInvoke(\"1\", [][]byte{[]byte(\"issueToken\"), []byte(\"SSToken\"), []byte(\"250\"), []byte(\"18\"), []byte(MAddress[:])})\n\n\tif res_test3.Status != shim.OK {\n\t\tfmt.Println(\"Register token failed\", string(res_test3.Message))\n\t\tt.FailNow()\n\t}\n\tcheckQueryInfo(t, stub, [][]byte{[]byte(\"getTokenInfo\"), []byte(\"SSToken\")})\n\n\t////query token quantity\n\t//\tres1 := stub.MockInvoke(\"2\", [][]byte{[]byte(\"getBalance\"), []byte(MAddress[:]), []byte(\"SSToken\")});\n\t//\tif res1.Status != shim.OK {\n\t//\t\tfmt.Println(\"Query failed\", string(res1.Message))\n\t//\t\tt.FailNow()\n\t//\t}\n\t//\tamount,_ := strconv.Atoi(string(res1.Payload))\n\t//\tif amount != 250 {\n\t//\t\tfmt.Printf(\"Query result error! %v\", amount )\n\t//\t\tt.FailNow()\n\t//\t}\n\n\tfmt.Println(\"Test issueToken for a registered one Success!\")\n\n\tres_test4 := stub.MockInvoke(\"2\", [][]byte{[]byte(\"issueToken\"), []byte(\"MToken\"), []byte(\"888\"), []byte(\"20\"), []byte(testAddress[:])})\n\tif res_test4.Status != shim.OK {\n\t\tfmt.Println(\"Register token failed\", string(res_test3.Message))\n\t\tt.FailNow()\n\t}\n\tcheckQueryInfo(t, stub, [][]byte{[]byte(\"getTokenInfo\"), []byte(\"MToken\")})\n\n\t////query token quantity\n\t//res2 := stub.MockInvoke(\"2\", [][]byte{[]byte(\"getBalance\"), []byte(testAddress[:]), []byte(\"CMBToken\")});\n\t//if res1.Status != shim.OK {\n\t//\tfmt.Println(\"Query failed\", string(res2.Message))\n\t//\tt.FailNow()\n\t//}\n\t//amount2,_ := strconv.Atoi(string(res2.Payload))\n\t//if amount2 != 888 {\n\t//\tfmt.Printf(\"Query result error! %v\", amount2 )\n\t//\tt.FailNow()\n\t//}\n\n\tfmt.Println(\"Test issueToken for an un registered one Success!\")\n}", "func (mmForID *mStorageMockForID) Expect(ctx context.Context, pulse insolar.PulseNumber, recordID insolar.ID) *mStorageMockForID {\n\tif mmForID.mock.funcForID != nil {\n\t\tmmForID.mock.t.Fatalf(\"StorageMock.ForID mock is already set by Set\")\n\t}\n\n\tif mmForID.defaultExpectation == nil {\n\t\tmmForID.defaultExpectation = &StorageMockForIDExpectation{}\n\t}\n\n\tmmForID.defaultExpectation.params = &StorageMockForIDParams{ctx, pulse, recordID}\n\tfor _, e := range mmForID.expectations {\n\t\tif minimock.Equal(e.params, mmForID.defaultExpectation.params) {\n\t\t\tmmForID.mock.t.Fatalf(\"Expectation set by When has same params: %#v\", *mmForID.defaultExpectation.params)\n\t\t}\n\t}\n\n\treturn mmForID\n}", "func (m *MockAccessResponder) SetAccessToken(arg0 string) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"SetAccessToken\", arg0)\n}", "func (mmAuther *mGatewayMockAuther) Expect() *mGatewayMockAuther {\n\tif mmAuther.mock.funcAuther != nil {\n\t\tmmAuther.mock.t.Fatalf(\"GatewayMock.Auther mock is already set by Set\")\n\t}\n\n\tif mmAuther.defaultExpectation == nil {\n\t\tmmAuther.defaultExpectation = &GatewayMockAutherExpectation{}\n\t}\n\n\treturn mmAuther\n}", "func (m *MockUCAuth) GetByID(ctx context.Context, userID uint) (*models.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetByID\", ctx, userID)\n\tret0, _ := ret[0].(*models.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func TestAuthRequestGetters(t *testing.T) {\n\trunTest(t, func(s *res.Service) {\n\t\ts.Handle(\"model\", res.Auth(\"foo\", func(r res.AuthRequest) {\n\t\t\trestest.AssertEqualJSON(t, \"Method\", r.Method(), \"foo\")\n\t\t\trestest.AssertEqualJSON(t, \"CID\", r.CID(), mock.CID)\n\t\t\trestest.AssertEqualJSON(t, \"Header\", r.Header(), mock.Header)\n\t\t\trestest.AssertEqualJSON(t, \"Host\", r.Host(), mock.Host)\n\t\t\trestest.AssertEqualJSON(t, \"RemoteAddr\", r.RemoteAddr(), mock.RemoteAddr)\n\t\t\trestest.AssertEqualJSON(t, \"URI\", r.URI(), mock.URI)\n\t\t\tr.NotFound()\n\t\t}))\n\t}, func(s *restest.Session) {\n\t\ts.Auth(\"test.model\", \"foo\", nil).\n\t\t\tResponse().\n\t\t\tAssertError(res.ErrNotFound)\n\t})\n}", "func (mmGetByID *mPaymentRepositoryMockGetByID) Expect(ctx context.Context, id int64) *mPaymentRepositoryMockGetByID {\n\tif mmGetByID.mock.funcGetByID != nil {\n\t\tmmGetByID.mock.t.Fatalf(\"PaymentRepositoryMock.GetByID mock is already set by Set\")\n\t}\n\n\tif mmGetByID.defaultExpectation == nil {\n\t\tmmGetByID.defaultExpectation = &PaymentRepositoryMockGetByIDExpectation{}\n\t}\n\n\tmmGetByID.defaultExpectation.params = &PaymentRepositoryMockGetByIDParams{ctx, id}\n\tfor _, e := range mmGetByID.expectations {\n\t\tif minimock.Equal(e.params, mmGetByID.defaultExpectation.params) {\n\t\t\tmmGetByID.mock.t.Fatalf(\"Expectation set by When has same params: %#v\", *mmGetByID.defaultExpectation.params)\n\t\t}\n\t}\n\n\treturn mmGetByID\n}" ]
[ "0.65093976", "0.62010235", "0.60594493", "0.59081554", "0.5871026", "0.56601584", "0.55710304", "0.55710304", "0.5517578", "0.54584026", "0.5454241", "0.5450888", "0.54272795", "0.54178536", "0.5386579", "0.5373759", "0.5366716", "0.5348325", "0.5348325", "0.53374684", "0.53184766", "0.526019", "0.5187925", "0.5186036", "0.51803756", "0.51411355", "0.5134938", "0.51194453", "0.5113945", "0.51088315", "0.51037765", "0.50710183", "0.5064166", "0.50587714", "0.5057225", "0.5045967", "0.50422835", "0.50390327", "0.5013322", "0.5005937", "0.50021166", "0.499911", "0.49973473", "0.49803483", "0.4976903", "0.4976903", "0.49712214", "0.4951434", "0.4943098", "0.49349347", "0.49338442", "0.49198052", "0.49192414", "0.491123", "0.49093854", "0.49077988", "0.4906535", "0.48915085", "0.48858482", "0.48715866", "0.4862432", "0.48616114", "0.4856791", "0.48554894", "0.48543903", "0.48486477", "0.48466757", "0.48452756", "0.48430553", "0.48395836", "0.48364154", "0.48266608", "0.48234698", "0.48153293", "0.48120758", "0.48079056", "0.4803098", "0.4797482", "0.47956985", "0.47841594", "0.4775253", "0.47737193", "0.4769936", "0.47666356", "0.4759764", "0.47570384", "0.47567487", "0.47542664", "0.47480327", "0.47480235", "0.4745551", "0.47436145", "0.47431594", "0.4738007", "0.4737665", "0.47236526", "0.47233874", "0.47210532", "0.47185427", "0.47132775" ]
0.6485713
1
IdentityManager indicates an expected call of IdentityManager
func (mr *MockProvidersMockRecorder) IdentityManager(arg0 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "IdentityManager", reflect.TypeOf((*MockProviders)(nil).IdentityManager), arg0) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (mr *MockClientMockRecorder) IdentityManager(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"IdentityManager\", reflect.TypeOf((*MockClient)(nil).IdentityManager), arg0)\n}", "func (c *Provider) IdentityManager(orgName string) (msp.IdentityManager, bool) {\n\treturn c.idMgmtProvider.IdentityManager(orgName)\n}", "func (e AuthorizationFailedError) Identity() UserIdentityInfo { return e.identity }", "func (e AuthorizationDeniedError) Identity() UserIdentityInfo { return e.identity }", "func (mr *MockChoriaProviderMockRecorder) Identity() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Identity\", reflect.TypeOf((*MockChoriaProvider)(nil).Identity))\n}", "func (rest *TestTokenStorageREST) TestRetrieveExternalTokenIdentityNotPresent() {\n\t// using an Identity which does not exist in the database.\n\tidentity := account.Identity{\n\t\tID: uuid.NewV4(),\n\t\tUsername: \"TestDeveloper\",\n\t}\n\n\tservice, controller := rest.SecuredControllerWithIdentity(identity)\n\ttest.RetrieveTokenUnauthorized(rest.T(), service.Context, service, controller, \"https://github.com/a/b\", nil)\n\ttest.RetrieveTokenUnauthorized(rest.T(), service.Context, service, controller, \"github\", nil)\n\ttest.RetrieveTokenUnauthorized(rest.T(), service.Context, service, controller, \"https://api.starter-us-east-2.openshift.com\", nil)\n\ttest.RetrieveTokenUnauthorized(rest.T(), service.Context, service, controller, \"openshift\", nil)\n}", "func (mr *MockMachineMockRecorder) Identity() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Identity\", reflect.TypeOf((*MockMachine)(nil).Identity))\n}", "func (m *MockProviders) IdentityManager(arg0 string) (msp.IdentityManager, bool) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"IdentityManager\", arg0)\n\tret0, _ := ret[0].(msp.IdentityManager)\n\tret1, _ := ret[1].(bool)\n\treturn ret0, ret1\n}", "func (m *MockClient) IdentityManager(arg0 string) (msp.IdentityManager, bool) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"IdentityManager\", arg0)\n\tret0, _ := ret[0].(msp.IdentityManager)\n\tret1, _ := ret[1].(bool)\n\treturn ret0, ret1\n}", "func (mr *MockClientMockRecorder) IdentityConfig() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"IdentityConfig\", reflect.TypeOf((*MockClient)(nil).IdentityConfig))\n}", "func (mr *MockProvidersMockRecorder) IdentityConfig() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"IdentityConfig\", reflect.TypeOf((*MockProviders)(nil).IdentityConfig))\n}", "func TestNewIdentityManager(t *testing.T) {\n\tt.Run(\"success\", func(t *testing.T) {\n\t\tepCfg := &mocks.EndpointConfig{}\n\t\tepCfg.NetworkConfigReturns(&fab.NetworkConfig{\n\t\t\tOrganizations: map[string]fab.OrganizationConfig{\"org1msp\": {}},\n\t\t})\n\n\t\tm, err := newIdentityManager(\"org1MSP\", &mocks.CryptoSuite{}, epCfg, \"./msp\")\n\t\trequire.NoError(t, err)\n\t\trequire.NotNil(t, m)\n\t})\n\n\tt.Run(\"No endpoint config -> error\", func(t *testing.T) {\n\t\tm, err := newIdentityManager(\"org1MSP\", &mocks.CryptoSuite{}, nil, \"./msp\")\n\t\trequire.EqualError(t, err, \"endpoint config is required\")\n\t\trequire.Nil(t, m)\n\t})\n\n\tt.Run(\"No org name -> error\", func(t *testing.T) {\n\t\tm, err := newIdentityManager(\"\", nil, &mocks.EndpointConfig{}, \"./msp\")\n\t\trequire.EqualError(t, err, \"orgName is required\")\n\t\trequire.Nil(t, m)\n\t})\n\n\tt.Run(\"No crypto suite -> error\", func(t *testing.T) {\n\t\tm, err := newIdentityManager(\"org1MSP\", nil, &mocks.EndpointConfig{}, \"./msp\")\n\t\trequire.EqualError(t, err, \"cryptoProvider is required\")\n\t\trequire.Nil(t, m)\n\t})\n\n\tt.Run(\"Org not found -> error\", func(t *testing.T) {\n\t\tepCfg := &mocks.EndpointConfig{}\n\t\tepCfg.NetworkConfigReturns(&fab.NetworkConfig{})\n\n\t\tm, err := newIdentityManager(\"org1MSP\", &mocks.CryptoSuite{}, epCfg, \"./msp\")\n\t\trequire.EqualError(t, err, \"org config retrieval failed\")\n\t\trequire.Nil(t, m)\n\t})\n\n\tt.Run(\"MSP config path not provided -> error\", func(t *testing.T) {\n\t\tepCfg := &mocks.EndpointConfig{}\n\t\tepCfg.NetworkConfigReturns(&fab.NetworkConfig{\n\t\t\tOrganizations: map[string]fab.OrganizationConfig{\"org1msp\": {}},\n\t\t})\n\n\t\tm, err := newIdentityManager(\"org1MSP\", &mocks.CryptoSuite{}, epCfg, \"\")\n\t\trequire.EqualError(t, err, \"either mspConfigPath or an embedded list of users is required\")\n\t\trequire.Nil(t, m)\n\t})\n}", "func TestGenerateIdentity(t *testing.T) {\n\tif _, err := GenerateIdentity(); err != nil {\n\t\tt.Fatalf(\"Failed to generate new identity: %v\", err)\n\t}\n}", "func TestGenerateIdentity(t *testing.T) {\n\tif _, err := GenerateIdentity(); err != nil {\n\t\tt.Fatalf(\"Failed to generate new identity: %v\", err)\n\t}\n}", "func (m *CommunicationsIdentitySet) SetAssertedIdentity(value Identityable)() {\n err := m.GetBackingStore().Set(\"assertedIdentity\", value)\n if err != nil {\n panic(err)\n }\n}", "func (mr *MockManagerClientMockRecorder) GetManagerByUserFromServer(id interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetManagerByUserFromServer\", reflect.TypeOf((*MockManagerClient)(nil).GetManagerByUserFromServer), id)\n}", "func (c *OAuth) Manager(idp idp.IdentityProvider, store *mongodb.Store, encoder jwt.Encoder) *oauth.Manager {\n\tfmt.Println(c)\n\tproviderMetadata := &openid.ProviderMetadata{\n\t\tIssuer: c.Issuer,\n\t\tAuthorizationEndpoint: c.UIAuthorizeEndpoint,\n\t\tTokenEndpoint: fmt.Sprintf(\"%s/v0/oauth/token\", c.Issuer),\n\t\tUserInfoEndpoint: fmt.Sprintf(\"%s/v0/openid/userinfo\", c.Issuer),\n\t\tJwksURI: fmt.Sprintf(\"%s/.well-known/jwks.json\", c.Issuer),\n\t\tRegistrationEndpoint: fmt.Sprintf(\"%s/v0/clients\", c.Issuer),\n\t\tScopesSupported: append(c.ScopesSupported, openid.OpenIDScope, openid.ProfileScope, openid.EmailScope),\n\t\tResponseTypesSupported: []string{string(model.CodeResponseType)},\n\t\tGrantTypesSupported: []string{string(model.AuthorizationCodeGrantType), string(model.PasswordGrantType), string(model.ClientCredentialsGrantType)},\n\t\tSubjectTypesSupported: []string{\"public\"},\n\t\tIDTokenSigningAlgValuesSupported: []string{string(jose.RS256)},\n\t\tTokenEndpointAuthMethodsSupported: []string{openid.ClientSecretPostTokenAuthMethod},\n\t\tCodeChallengeMethodsSupported: []string{string(model.PlainCodeChallengeMethod), string(model.S256CodeChallengeMethod)},\n\t}\n\treturn oauth.NewManager(idp, store, encoder, providerMetadata)\n}", "func (s *UserSuite) TestUserAttachedToRequestAuthenticatedNoUseridentifierHasBeenRegistered(c *C) {\n\thandler := u.Handler()\n\n\treq, _ := http.NewRequest(\"GET\", \"http://127.0.0.1:8000/auth-status\", nil)\n\tresp := httptest.NewRecorder()\n\thandler(resp, req)\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tc.Assert(err, IsNil)\n\tc.Assert(string(body), Equals, \"false\")\n}", "func (u *MockUser) Identity() ([]byte, error) {\n\treturn []byte(\"test\"), nil\n}", "func (m *AzureManagedControlPlane) validateIdentity(_ client.Client) error {\n\tvar allErrs field.ErrorList\n\n\tif m.Spec.Identity != nil {\n\t\tif m.Spec.Identity.Type == ManagedControlPlaneIdentityTypeUserAssigned {\n\t\t\tif m.Spec.Identity.UserAssignedIdentityResourceID == \"\" {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(\"Spec\", \"Identity\", \"UserAssignedIdentityResourceID\"), m.Spec.Identity.UserAssignedIdentityResourceID, \"cannot be empty if Identity.Type is UserAssigned\"))\n\t\t\t}\n\t\t} else {\n\t\t\tif m.Spec.Identity.UserAssignedIdentityResourceID != \"\" {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(\"Spec\", \"Identity\", \"UserAssignedIdentityResourceID\"), m.Spec.Identity.UserAssignedIdentityResourceID, \"should be empty if Identity.Type is SystemAssigned\"))\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(allErrs) > 0 {\n\t\treturn kerrors.NewAggregate(allErrs.ToAggregate().Errors())\n\t}\n\n\treturn nil\n}", "func (ctx *TestContext) IAmAManagerOfTheGroupWithID(group string) error {\n\treturn ctx.UserIsAManagerOfTheGroupWith(getParameterString(map[string]string{\n\t\t\"id\": group,\n\t\t\"user_id\": ctx.user,\n\t\t\"can_watch_members\": \"false\",\n\t}))\n}", "func (o *UserDisco) GetIdentityOk() (*FullIdentity, bool) {\n\tif o == nil || o.Identity == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Identity, true\n}", "func (suite *AuthSuite) TestAuthUnknownServiceMember() {\n\t// Set up: Prepare the session, goth.User, callback handler, http response\n\t// and request, landing URL, and pass them into authorizeUnknownUser\n\n\thandlerConfig := suite.HandlerConfig()\n\tappnames := handlerConfig.AppNames()\n\n\t// Prepare the session and session manager\n\tfakeToken := \"some_token\"\n\tsession := auth.Session{\n\t\tApplicationName: auth.MilApp,\n\t\tIDToken: fakeToken,\n\t\tHostname: appnames.MilServername,\n\t}\n\tsessionManager := handlerConfig.SessionManagers().Mil\n\tmockSender := setUpMockNotificationSender() // We should get an email for this activity\n\n\t// Prepare the goth.User to simulate the UUID and email that login.gov would\n\t// provide\n\tfakeUUID, _ := uuid.NewV4()\n\tuser := goth.User{\n\t\tUserID: fakeUUID.String(),\n\t\tEmail: \"new_service_member@example.com\",\n\t}\n\tctx := suite.SetupSessionContext(context.Background(), &session, sessionManager)\n\n\t// Call the function under test\n\tresult := authorizeUnknownUser(ctx, suite.AppContextWithSessionForTest(&session), user,\n\t\tsessionManager, mockSender)\n\tsuite.Equal(authorizationResultAuthorized, result)\n\tmockSender.(*mocks.NotificationSender).AssertNumberOfCalls(suite.T(), \"SendNotification\", 1)\n\n\t// Look up the user and service member in the test DB\n\tfoundUser, _ := models.GetUserFromEmail(suite.DB(), user.Email)\n\tserviceMemberID := session.ServiceMemberID\n\tserviceMember, _ := models.FetchServiceMemberForUser(suite.DB(), &session, serviceMemberID)\n\t// Look up the session token in the session store (this test uses the memory store)\n\tsessionStore := sessionManager.Store()\n\t_, existsBefore, _ := sessionStore.Find(foundUser.CurrentMilSessionID)\n\n\t// Verify service member exists and its ID is populated in the session\n\tsuite.NotEmpty(session.ServiceMemberID)\n\n\t// Verify session contains UserID that points to the newly-created user\n\tsuite.Equal(foundUser.ID, session.UserID)\n\n\t// Verify user's LoginGovEmail and LoginGovUUID match the values passed in\n\tsuite.Equal(user.Email, foundUser.LoginGovEmail)\n\tsuite.Equal(user.UserID, foundUser.LoginGovUUID.String())\n\n\t// Verify that the user's CurrentMilSessionID is not empty. The value is\n\t// generated randomly, so we can't test for a specific string. Any string\n\t// except an empty string is acceptable.\n\tsuite.NotEqual(\"\", foundUser.CurrentMilSessionID)\n\n\t// Verify the session token also exists in the session store\n\tsuite.Equal(true, existsBefore)\n\n\t// Verify the service member that was created is associated with the user\n\t// that was created\n\tsuite.Equal(foundUser.ID, serviceMember.UserID)\n}", "func (mr *MockCAClientMockRecorder) ModifyIdentity(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"ModifyIdentity\", reflect.TypeOf((*MockCAClient)(nil).ModifyIdentity), arg0)\n}", "func (ctx *TestContext) IAmAManagerOfTheGroup(group string) error {\n\treturn ctx.UserIsAManagerOfTheGroupWith(getParameterString(map[string]string{\n\t\t\"id\": group,\n\t\t\"user_id\": ctx.user,\n\t\t\"name\": group,\n\t\t\"can_watch_members\": \"false\",\n\t}))\n}", "func (f *FakeContext) RequestIDNotCalled() bool {\n\treturn len(f.RequestIDCalls) == 0\n}", "func (o *User) GetIdentitiesOk() ([]ObjectIdentity, bool) {\n\tif o == nil || o.Identities == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Identities, true\n}", "func (suite *HealthCheckTestSuite) TestModuleExecuteWithNilOnPremIdentity() {\n\t// Initialize the appconfigMock with HealthFrequencyMinutes as every five minute\n\tappconfigMock := &appconfig.SsmagentConfig{\n\t\tSsm: appconfig.SsmCfg{\n\t\t\tHealthFrequencyMinutes: appconfig.DefaultSsmHealthFrequencyMinutes,\n\t\t},\n\t}\n\n\tmockEC2Identity := &identityMock.IAgentIdentityInner{}\n\tnewEC2Identity = func(log log.T) identity.IAgentIdentityInner {\n\t\treturn mockEC2Identity\n\t}\n\n\tavailabilityZone := \"us-east-1a\"\n\tavailabilityZoneId := \"use1-az2\"\n\tmockEC2Identity.On(\"IsIdentityEnvironment\").Return(true)\n\tmockEC2Identity.On(\"AvailabilityZone\").Return(availabilityZone, nil)\n\tmockEC2Identity.On(\"AvailabilityZoneId\").Return(availabilityZoneId, nil)\n\n\tnewOnPremIdentity = func(log log.T, config *appconfig.SsmagentConfig) identity.IAgentIdentityInner {\n\t\treturn nil\n\t}\n\n\tmockECSIdentity := &identityMock.IAgentIdentityInner{}\n\tnewECSIdentity = func(log log.T) identity.IAgentIdentityInner {\n\t\treturn mockECSIdentity\n\t}\n\tmockECSIdentity.On(\"IsIdentityEnvironment\").Return(false)\n\n\tssmConnectionChannel := \"ssmmessages\"\n\tvar ableToOpenMGSConnection uint32\n\tatomic.StoreUint32(&ableToOpenMGSConnection, 1)\n\tssmconnectionchannel.SetConnectionChannel(&ableToOpenMGSConnection)\n\n\t// Turn on the mock method\n\tsuite.contextMock.On(\"AppConfig\").Return(*appconfigMock)\n\tsuite.serviceMock.On(\"UpdateInstanceInformation\", mock.Anything, version.Version, \"Active\", AgentName, availabilityZone, availabilityZoneId, ssmConnectionChannel).Return(nil, nil)\n\tsuite.healthCheck.ModuleExecute()\n\t// Because ModuleExecute will launch two new go routine, wait 100ms to make sure the updateHealth() has launched\n\ttime.Sleep(100 * time.Millisecond)\n\t// Assert the UpdateInstanceInformation get called in updateHealth() function, and the agent status is same as input.\n\tsuite.serviceMock.AssertCalled(suite.T(), \"UpdateInstanceInformation\", mock.Anything, version.Version, \"Active\", AgentName, availabilityZone, availabilityZoneId, ssmConnectionChannel)\n}", "func (c *Client) IDTokenUserinfoClaimsAssertion() bool {\n\treturn c.idTokenUserinfoClaimsAssertion\n}", "func (s *UserSuite) TestUserAttachedToRequestAuthenticatedRegisteredUseridentifierReturnsAnonymousUser(c *C) {\n\thandler := u.Handler()\n\n\tIdentifyUsersWith(FakeAuth)\n\treq, _ := http.NewRequest(\"GET\", \"http://127.0.0.1:8000/auth-status\", nil)\n\tresp := httptest.NewRecorder()\n\thandler(resp, req)\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tc.Assert(err, IsNil)\n\tc.Assert(string(body), Equals, \"false\")\n}", "func (idMap *IdentityMap) CheckIdentity(id string, login map[string]string) error {\n\tfor name, pattern := range *idMap {\n\t\tif !pattern.MatchString(id) {\n\t\t\tcontinue\n\t\t}\n\n\t\tlogin[name] = id\n\t\tlogin[\"type\"] = \"account\"\n\t\tlogin[\"verifyCode\"] = \"\"\n\n\t\treturn nil\n\t}\n\n\treturn ErrIdentity\n}", "func (e OAuthAccessTokenIdentifiersValidationError) Cause() error { return e.cause }", "func (mr *MockManagerClientMockRecorder) GetManagerFromServer(id interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetManagerFromServer\", reflect.TypeOf((*MockManagerClient)(nil).GetManagerFromServer), id)\n}", "func (m *GraphBaseServiceClient) IdentityProtection()(*i663c30678b300c2c4b619c4964b4326e471e4da61a44d7c39f752349da7a468e.IdentityProtectionRequestBuilder) {\n return i663c30678b300c2c4b619c4964b4326e471e4da61a44d7c39f752349da7a468e.NewIdentityProtectionRequestBuilderInternal(m.pathParameters, m.requestAdapter);\n}", "func (m *GraphBaseServiceClient) IdentityProtection()(*i663c30678b300c2c4b619c4964b4326e471e4da61a44d7c39f752349da7a468e.IdentityProtectionRequestBuilder) {\n return i663c30678b300c2c4b619c4964b4326e471e4da61a44d7c39f752349da7a468e.NewIdentityProtectionRequestBuilderInternal(m.pathParameters, m.requestAdapter);\n}", "func (m *GraphBaseServiceClient) Identity()(*i79ca23a9ac0659e1330dd29e049fe157787d5af6695ead2ff8263396db68d027.IdentityRequestBuilder) {\n return i79ca23a9ac0659e1330dd29e049fe157787d5af6695ead2ff8263396db68d027.NewIdentityRequestBuilderInternal(m.pathParameters, m.requestAdapter);\n}", "func (m *GraphBaseServiceClient) Identity()(*i79ca23a9ac0659e1330dd29e049fe157787d5af6695ead2ff8263396db68d027.IdentityRequestBuilder) {\n return i79ca23a9ac0659e1330dd29e049fe157787d5af6695ead2ff8263396db68d027.NewIdentityRequestBuilderInternal(m.pathParameters, m.requestAdapter);\n}", "func TestAzureBlobGetAppsListShouldFailInvalidIdentity(t *testing.T) {\n\tctx := context.TODO()\n\tappFrameworkRef := enterpriseApi.AppFrameworkSpec{\n\t\tDefaults: enterpriseApi.AppSourceDefaultSpec{\n\t\t\tVolName: \"azure_vol1\",\n\t\t\tScope: enterpriseApi.ScopeLocal,\n\t\t},\n\t\tVolList: []enterpriseApi.VolumeSpec{\n\t\t\t{\n\t\t\t\tName: \"azure_vol1\",\n\t\t\t\tEndpoint: \"https://mystorageaccount.blob.core.windows.net\",\n\t\t\t\tPath: \"appscontainer1\",\n\t\t\t\tType: \"blob\",\n\t\t\t\tProvider: \"azure\",\n\t\t\t},\n\t\t},\n\t\tAppSources: []enterpriseApi.AppSourceSpec{\n\t\t\t{\n\t\t\t\tName: \"adminApps\",\n\t\t\t\tLocation: \"adminAppsRepo\",\n\t\t\t\tAppSourceDefaultSpec: enterpriseApi.AppSourceDefaultSpec{\n\t\t\t\t\tVolName: \"azure_vol1\",\n\t\t\t\t\tScope: enterpriseApi.ScopeLocal,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\t// Initialize clients\n\tazureBlobClient := &AzureBlobClient{}\n\tmclient := spltest.MockHTTPClient{}\n\n\t// Identity call return a token - that means AKS cluster has an identity configured.\n\twantRequest, _ := http.NewRequest(\"GET\", \"http://169.254.169.254/metadata/identity/oauth2/token?api-version=2021-10-01&resource=https%3A%2F%2Fstorage.azure.com%2F\", nil)\n\trespTokenData := &TokenResponse{\n\t\tAccessToken: \"acctoken\",\n\t\tClientID: \"ClientId\",\n\t}\n\tmrespdata, _ := json.Marshal(respTokenData)\n\tmclient.AddHandler(wantRequest, 200, string(mrespdata), nil)\n\n\t// Add mock for the azure rest call for list apps\n\twantRequest, _ = http.NewRequest(\"GET\", \"https://mystorageaccount.blob.core.windows.net/appscontainer1?prefix=adminAppsRepo&restype=container&comp=list&include=snapshots&include=metadata\", nil)\n\n\t// Expect the identity does not have authorization to access the buckets\n\tmclient.AddHandler(wantRequest, 403, \"identity not authorized\", nil)\n\n\t// Get App source and volume from spec\n\tappSource := appFrameworkRef.AppSources[0]\n\tvol, err := GetAppSrcVolume(ctx, appSource, &appFrameworkRef)\n\tif err != nil {\n\t\tt.Errorf(\"Unable to get volume for app source : %s\", appSource.Name)\n\t}\n\n\t// Update the GetRemoteDataClient function pointer\n\tgetClientWrapper := RemoteDataClientsMap[vol.Provider]\n\tgetClientWrapper.SetRemoteDataClientFuncPtr(ctx, vol.Provider, NewMockAzureBlobClient)\n\n\t// Update the GetRemoteDataClientInit function pointer\n\tinitFn := func(ctx context.Context, region, accessKeyID, secretAccessKey string) interface{} {\n\t\treturn &mclient\n\t}\n\tgetClientWrapper.SetRemoteDataClientInitFuncPtr(ctx, vol.Provider, initFn)\n\n\t// Init azure blob client\n\tgetRemoteDataClientFn := getClientWrapper.GetRemoteDataClientInitFuncPtr(ctx)\n\tazureBlobClient.HTTPClient = getRemoteDataClientFn(ctx, \"us-west-2\", \"abcd\", \"1234\").(*spltest.MockHTTPClient)\n\tazureBlobClient.BucketName = vol.Path\n\tazureBlobClient.Prefix = appSource.Location\n\tazureBlobClient.Endpoint = vol.Endpoint\n\n\trespList, err := azureBlobClient.GetAppsList(ctx)\n\tif err == nil {\n\t\tt.Errorf(\"GetAppsList should return err\")\n\t}\n\n\tif err.Error() != \"error authorizing the rest call. check your IAM/secret configuration\" {\n\t\tt.Errorf(\"GetAppsList should return authorization error\")\n\t}\n\n\t// authorizing the rest call. check your IAM/secret configuration\n\n\tif len(respList.Objects) != 0 {\n\t\tt.Errorf(\"GetAppsList should not return any response objects\")\n\t}\n\tmclient.RemoveHandlers()\n}", "func testSystemAssignedIdentity(msiEndpoint string) (*adal.Token, error) {\n\tspt, err := adal.NewServicePrincipalTokenFromMSI(msiEndpoint, azure.PublicCloud.ResourceManagerEndpoint)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"Failed to acquire a token using the MSI VM extension\")\n\t}\n\n\tif err := spt.Refresh(); err != nil {\n\t\treturn nil, errors.Wrapf(err, \"Failed to refresh ServicePrincipalTokenFromMSI using the MSI VM extension, msiEndpoint(%s)\", msiEndpoint)\n\t}\n\n\ttoken := spt.Token()\n\tif token.IsZero() {\n\t\treturn nil, errors.Errorf(\"No token found, MSI VM extension, msiEndpoint(%s)\", msiEndpoint)\n\t}\n\n\tklog.Infof(\"successfully acquired a token using the MSI, msiEndpoint(%s)\", msiEndpoint)\n\treturn &token, nil\n}", "func (mr *MockCAClientMockRecorder) GetIdentity(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetIdentity\", reflect.TypeOf((*MockCAClient)(nil).GetIdentity), arg0, arg1)\n}", "func (adminAPIOp) SkipVerification() bool { return true }", "func (o *VirtualizationBaseHostPciDeviceAllOf) GetIdentityOk() (*string, bool) {\n\tif o == nil || o.Identity == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Identity, true\n}", "func AnonOperationNotAloneMessage() string {\n\treturn \"This anonymous operation must be the only defined operation.\"\n}", "func (suite *HealthCheckTestSuite) TestModuleExecuteWithOnPremIdentity() {\n\t// Initialize the appconfigMock with HealthFrequencyMinutes as every five minute\n\tappconfigMock := &appconfig.SsmagentConfig{\n\t\tSsm: appconfig.SsmCfg{\n\t\t\tHealthFrequencyMinutes: appconfig.DefaultSsmHealthFrequencyMinutes,\n\t\t},\n\t}\n\n\tmockEC2Identity := &identityMock.IAgentIdentityInner{}\n\tnewEC2Identity = func(log log.T) identity.IAgentIdentityInner {\n\t\treturn mockEC2Identity\n\t}\n\n\tavailabilityZone := \"us-east-1a\"\n\tavailabilityZoneId := \"use1-az2\"\n\tmockEC2Identity.On(\"IsIdentityEnvironment\").Return(true)\n\tmockEC2Identity.On(\"AvailabilityZone\").Return(availabilityZone, nil)\n\tmockEC2Identity.On(\"AvailabilityZoneId\").Return(availabilityZoneId, nil)\n\n\tmockOnPremIdentity := &identityMock.IAgentIdentityInner{}\n\tnewOnPremIdentity = func(log log.T, config *appconfig.SsmagentConfig) identity.IAgentIdentityInner {\n\t\treturn mockOnPremIdentity\n\t}\n\tmockOnPremIdentity.On(\"IsIdentityEnvironment\").Return(true)\n\n\tmockECSIdentity := &identityMock.IAgentIdentityInner{}\n\tnewECSIdentity = func(log log.T) identity.IAgentIdentityInner {\n\t\treturn mockECSIdentity\n\t}\n\tmockECSIdentity.On(\"IsIdentityEnvironment\").Return(false)\n\n\tssmConnectionChannel := \"ssmmessages\"\n\tvar ableToOpenMGSConnection uint32\n\tatomic.StoreUint32(&ableToOpenMGSConnection, 1)\n\tssmconnectionchannel.SetConnectionChannel(&ableToOpenMGSConnection)\n\n\t// Turn on the mock method\n\tsuite.contextMock.On(\"AppConfig\").Return(*appconfigMock)\n\tsuite.serviceMock.On(\"UpdateInstanceInformation\", mock.Anything, version.Version, \"Active\", AgentName, \"\", \"\", ssmConnectionChannel).Return(nil, nil)\n\tsuite.healthCheck.ModuleExecute()\n\t// Because ModuleExecute will launch two new go routine, wait 100ms to make sure the updateHealth() has launched\n\ttime.Sleep(100 * time.Millisecond)\n\t// Assert the UpdateInstanceInformation get called in updateHealth() function, and the agent status is same as input.\n\tsuite.serviceMock.AssertCalled(suite.T(), \"UpdateInstanceInformation\", mock.Anything, version.Version, \"Active\", AgentName, \"\", \"\", ssmConnectionChannel)\n\tsuite.serviceMock.AssertNotCalled(suite.T(), \"IsIdentityEnvironment\", true)\n}", "func (m *CommunicationsIdentitySet) GetAssertedIdentity()(Identityable) {\n val, err := m.GetBackingStore().Get(\"assertedIdentity\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(Identityable)\n }\n return nil\n}", "func (mr *MockHostMockRecorder) ConnManager() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"ConnManager\", reflect.TypeOf((*MockHost)(nil).ConnManager))\n}", "func (c *Client) Identity(id string, token string) {\n\tvar identityMessage *IdentityRequestMessage\n\n\tif len(id) <= 0 || len(token) <= 0 {\n\t\tidentityMessage = &IdentityRequestMessage{}\n\t}\n\n\tidentityMessage = &IdentityRequestMessage{id, token}\n\tinput := knot.NewFrame(\"identity\", identityMessage)\n\n\treq := IdentityRequest{Request: c.NewRequest(input), Frame: input}\n\treq.Send()\n}", "func ManagedClusterPodIdentityExceptionGenerator() gopter.Gen {\n\tif managedClusterPodIdentityExceptionGenerator != nil {\n\t\treturn managedClusterPodIdentityExceptionGenerator\n\t}\n\n\tgenerators := make(map[string]gopter.Gen)\n\tAddIndependentPropertyGeneratorsForManagedClusterPodIdentityException(generators)\n\tmanagedClusterPodIdentityExceptionGenerator = gen.Struct(reflect.TypeOf(ManagedClusterPodIdentityException{}), generators)\n\n\treturn managedClusterPodIdentityExceptionGenerator\n}", "func TestAuthRequestNilTokenEvent(t *testing.T) {\n\trunTest(t, func(s *res.Service) {\n\t\ts.Handle(\"model\", res.Auth(\"method\", func(r res.AuthRequest) {\n\t\t\tr.TokenEvent(nil)\n\t\t\tr.OK(nil)\n\t\t}))\n\t}, func(s *restest.Session) {\n\t\treq := s.Auth(\"test.model\", \"method\", nil)\n\t\ts.GetMsg().\n\t\t\tAssertTokenEvent(mock.CID, nil)\n\t\treq.Response().\n\t\t\tAssertResult(nil)\n\t})\n}", "func (m *AospDeviceOwnerDeviceConfiguration) SetPasswordSignInFailureCountBeforeFactoryReset(value *int32)() {\n err := m.GetBackingStore().Set(\"passwordSignInFailureCountBeforeFactoryReset\", value)\n if err != nil {\n panic(err)\n }\n}", "func (m *AospDeviceOwnerDeviceConfiguration) GetPasswordSignInFailureCountBeforeFactoryReset()(*int32) {\n val, err := m.GetBackingStore().Get(\"passwordSignInFailureCountBeforeFactoryReset\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*int32)\n }\n return nil\n}", "func (o *UserDisco) HasIdentity() bool {\n\tif o != nil && o.Identity != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (m *AndroidWorkProfileGeneralDeviceConfiguration) SetPasswordSignInFailureCountBeforeFactoryReset(value *int32)() {\n m.passwordSignInFailureCountBeforeFactoryReset = value\n}", "func (m *User) GetIdentities()([]ObjectIdentityable) {\n return m.identities\n}", "func (mr *MockRegionUserInfoDaoMockRecorder) GetTokenByEid(eid interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetTokenByEid\", reflect.TypeOf((*MockRegionUserInfoDao)(nil).GetTokenByEid), eid)\n}", "func (f *FakeContext) WithRequestIDNotCalled() bool {\n\treturn len(f.WithRequestIDCalls) == 0\n}", "func (adminAPIOp) SkipMFASetup() bool { return true }", "func (s *UsersService) Identity() *UsersIdentityCall {\n\tvar call UsersIdentityCall\n\tcall.service = s\n\treturn &call\n}", "func NewIdentityManager(orgName string, userStore msp.UserStore, cryptoSuite core.CryptoSuite, endpointConfig fab.EndpointConfig) (*IdentityManager, error) {\n\n\tnetConfig := endpointConfig.NetworkConfig()\n\t// viper keys are case insensitive\n\torgConfig, ok := netConfig.Organizations[strings.ToLower(orgName)]\n\tif !ok {\n\t\treturn nil, errors.New(\"org config retrieval failed\")\n\t}\n\n\tif orgConfig.CryptoPath == \"\" && len(orgConfig.Users) == 0 {\n\t\treturn nil, errors.New(\"Either a cryptopath or an embedded list of users is required\")\n\t}\n\n\tvar mspPrivKeyStore core.KVStore\n\tvar mspCertStore core.KVStore\n\n\torgCryptoPathTemplate := orgConfig.CryptoPath\n\tif orgCryptoPathTemplate != \"\" {\n\t\tvar err error\n\t\tif !filepath.IsAbs(orgCryptoPathTemplate) {\n\t\t\torgCryptoPathTemplate = filepath.Join(endpointConfig.CryptoConfigPath(), orgCryptoPathTemplate)\n\t\t}\n\t\tmspPrivKeyStore, err = NewFileKeyStore(orgCryptoPathTemplate)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"creating a private key store failed\")\n\t\t}\n\t\tmspCertStore, err = NewFileCertStore(orgCryptoPathTemplate)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"creating a cert store failed\")\n\t\t}\n\t} else {\n\t\tlogger.Warnf(\"Cryptopath not provided for organization [%s], MSP stores not created\", orgName)\n\t}\n\n\tmgr := &IdentityManager{\n\t\torgName: orgName,\n\t\torgMSPID: orgConfig.MSPID,\n\t\tconfig: endpointConfig,\n\t\tcryptoSuite: cryptoSuite,\n\t\tmspPrivKeyStore: mspPrivKeyStore,\n\t\tmspCertStore: mspCertStore,\n\t\tembeddedUsers: orgConfig.Users,\n\t\tuserStore: userStore,\n\t\t// CA Client state is created lazily, when (if) needed\n\t}\n\treturn mgr, nil\n}", "func (c *context) Identity() entity.Identity {\n\treturn c.id.AgentIdentity()\n}", "func (mr *MockClientMockRecorder) SigningManager() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"SigningManager\", reflect.TypeOf((*MockClient)(nil).SigningManager))\n}", "func (e PlmnIdentityValidationError) Cause() error { return e.cause }", "func (mr *MockProvidersMockRecorder) SigningManager() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"SigningManager\", reflect.TypeOf((*MockProviders)(nil).SigningManager))\n}", "func (mr *MockManagerClientMockRecorder) CreateManagerOnServer(userId, companyId interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"CreateManagerOnServer\", reflect.TypeOf((*MockManagerClient)(nil).CreateManagerOnServer), userId, companyId)\n}", "func (m *User) SetIdentities(value []ObjectIdentityable)() {\n m.identities = value\n}", "func TestHandler_URLMappingShowRecapSalesFailIDWrong(t *testing.T) {\n\t// melakukan proses login\n\tuser := model.DummyUserPriviledgeWithUsergroup(1)\n\tsd, _ := auth.Login(user)\n\ttoken := \"Bearer \" + sd.Token\n\tng := tester.New()\n\tng.SetHeader(tester.H{\"Authorization\": token})\n\tng.Method = \"GET\"\n\tng.Path = \"/v1/recap-sales/asas\"\n\tng.Run(test.Router(), func(res tester.HTTPResponse, req tester.HTTPRequest) {\n\t\tassert.Equal(t, int(400), res.Code, fmt.Sprintf(\"Should has 'endpoint %s' with method '%s'\", \"/v1/recap-sales/asas\", \"GET\"))\n\t})\n}", "func (o *ComputeBladeIdentityAllOf) GetManagerSlotIdOk() (*int64, bool) {\n\tif o == nil || o.ManagerSlotId == nil {\n\t\treturn nil, false\n\t}\n\treturn o.ManagerSlotId, true\n}", "func (m *AtomicRecordStorageMock) MinimockForIDInspect() {\n\tfor _, e := range m.ForIDMock.expectations {\n\t\tif mm_atomic.LoadUint64(&e.Counter) < 1 {\n\t\t\tm.t.Errorf(\"Expected call to AtomicRecordStorageMock.ForID with params: %#v\", *e.params)\n\t\t}\n\t}\n\n\t// if default expectation was set then invocations count should be greater than zero\n\tif m.ForIDMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterForIDCounter) < 1 {\n\t\tif m.ForIDMock.defaultExpectation.params == nil {\n\t\t\tm.t.Error(\"Expected call to AtomicRecordStorageMock.ForID\")\n\t\t} else {\n\t\t\tm.t.Errorf(\"Expected call to AtomicRecordStorageMock.ForID with params: %#v\", *m.ForIDMock.defaultExpectation.params)\n\t\t}\n\t}\n\t// if func was set then invocations count should be greater than zero\n\tif m.funcForID != nil && mm_atomic.LoadUint64(&m.afterForIDCounter) < 1 {\n\t\tm.t.Error(\"Expected call to AtomicRecordStorageMock.ForID\")\n\t}\n}", "func (mr *MockCAClientMockRecorder) CreateIdentity(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"CreateIdentity\", reflect.TypeOf((*MockCAClient)(nil).CreateIdentity), arg0)\n}", "func ValidateIdentity(attribute string, identity string) error {\n\n\ti := Manager().IdentityFromAny(identity)\n\tif i.IsEmpty() {\n\t\treturn makeValidationError(attribute, fmt.Sprintf(\"Invalid identity '%s': unknown\", identity))\n\t}\n\n\treturn nil\n}", "func TestEmployeeManagerMap_Valid(t *testing.T) {\n\templyMgrMap := getTestEmployeeManagerMap()\n\tassert.Nil(t, emplyMgrMap.Valid())\n}", "func (mr *MockVerifierMockRecorder) VerifyIDToken(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"VerifyIDToken\", reflect.TypeOf((*MockVerifier)(nil).VerifyIDToken), arg0, arg1)\n}", "func (mr *MockAtomicLogicMockRecorder) SetTicketManager(tm interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"SetTicketManager\", reflect.TypeOf((*MockAtomicLogic)(nil).SetTicketManager), tm)\n}", "func (_f60 *FakeContext) WithRequestIDCalledOnceWith(ident1 string) bool {\n\tvar count int\n\tfor _, call := range _f60.WithRequestIDCalls {\n\t\tif reflect.DeepEqual(call.Parameters.Ident1, ident1) {\n\t\t\tcount++\n\t\t}\n\t}\n\n\treturn count == 1\n}", "func testIATBHOriginatorIdentification(t testing.TB) {\n\tbh := mockIATBatchHeaderFF()\n\tbh.OriginatorIdentification = \"\"\n\terr := bh.Validate()\n\tif !base.Match(err, ErrFieldInclusion) {\n\t\tt.Errorf(\"%T: %s\", err, err)\n\t}\n}", "func (o *IdentityCredentialIdentifierOidcProperties) GetInitialAccessTokenOk() (*string, bool) {\n\tif o == nil || o.InitialAccessToken == nil {\n\t\treturn nil, false\n\t}\n\treturn o.InitialAccessToken, true\n}", "func (m *AndroidWorkProfileGeneralDeviceConfiguration) SetWorkProfilePasswordSignInFailureCountBeforeFactoryReset(value *int32)() {\n m.workProfilePasswordSignInFailureCountBeforeFactoryReset = value\n}", "func (mr *MockLogicMockRecorder) SetTicketManager(tm interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"SetTicketManager\", reflect.TypeOf((*MockLogic)(nil).SetTicketManager), tm)\n}", "func (m *PlmnIdentity) Validate() error {\n\treturn m.validate(false)\n}", "func (f *FakeContext) RequestIDCalled() bool {\n\treturn len(f.RequestIDCalls) != 0\n}", "func ERROR_AUTH_SEED_NOT_SET(w http.ResponseWriter, pl string) {\n\tbuildForeignError(w, http.StatusForbidden, \"ERROR_AUTH_SEED_NOT_SET\", pl)\n}", "func (o *authImpl) Admit(ctx context.Context, req identity.Requestor) (authentication.Identity, bool) {\n\n\t// @step: verify the authorization token\n\tbearer, found := utils.GetBearerToken(req.Headers().Get(\"Authorization\"))\n\tif !found {\n\t\treturn nil, false\n\t}\n\n\tid, err := func() (authentication.Identity, error) {\n\t\t// @step: validate the token\n\t\tclaims := struct {\n\t\t\tEmail string `json:\"email\"`\n\t\t\tUsername string `json:\"username\"`\n\t\t\tjwt.StandardClaims\n\t\t}{}\n\t\t_, err := jwt.ParseWithClaims(bearer, &claims, func(token *jwt.Token) (interface{}, error) {\n\t\t\t// Don't forget to validate the alg is what you expect:\n\t\t\tif _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {\n\t\t\t\treturn nil, fmt.Errorf(\"Unexpected signing method: %v\", token.Header[\"alg\"])\n\t\t\t}\n\t\t\tpubKeyBytes, err := base64.StdEncoding.DecodeString(o.config.PublicKey)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"Unable to parse public key from config: %v\", err)\n\t\t\t}\n\t\t\tpubKey, err := x509.ParsePKIXPublicKey(pubKeyBytes)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"Unable to parse public key from config: %v\", err)\n\t\t\t}\n\t\t\treturn pubKey, nil\n\t\t})\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tusername := claims.Username\n\t\tif username == \"\" {\n\t\t\treturn nil, errors.New(\"issued token does not contain the username claim\")\n\t\t}\n\n\t\tid, found, err := o.GetUserIdentity(ctx, username)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif !found {\n\t\t\treturn nil, errors.New(\"user not found in the kore\")\n\t\t}\n\n\t\treturn id, nil\n\t}()\n\tif err != nil {\n\t\treturn nil, false\n\t}\n\n\treturn id, true\n}", "func (o *APICheck) Identity() elemental.Identity {\n\n\treturn APICheckIdentity\n}", "func (mr *MockpatcherMockRecorder) EnsureManagerRoleIsAllowedToUpload(bucketName interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"EnsureManagerRoleIsAllowedToUpload\", reflect.TypeOf((*Mockpatcher)(nil).EnsureManagerRoleIsAllowedToUpload), bucketName)\n}", "func (m *StorageMock) MinimockForIDInspect() {\n\tfor _, e := range m.ForIDMock.expectations {\n\t\tif mm_atomic.LoadUint64(&e.Counter) < 1 {\n\t\t\tm.t.Errorf(\"Expected call to StorageMock.ForID with params: %#v\", *e.params)\n\t\t}\n\t}\n\n\t// if default expectation was set then invocations count should be greater than zero\n\tif m.ForIDMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterForIDCounter) < 1 {\n\t\tif m.ForIDMock.defaultExpectation.params == nil {\n\t\t\tm.t.Error(\"Expected call to StorageMock.ForID\")\n\t\t} else {\n\t\t\tm.t.Errorf(\"Expected call to StorageMock.ForID with params: %#v\", *m.ForIDMock.defaultExpectation.params)\n\t\t}\n\t}\n\t// if func was set then invocations count should be greater than zero\n\tif m.funcForID != nil && mm_atomic.LoadUint64(&m.afterForIDCounter) < 1 {\n\t\tm.t.Error(\"Expected call to StorageMock.ForID\")\n\t}\n}", "func (app *MgmtApp) defaultNotifyClientAuthenticatedFailed(client Client) {\n loge.Info(\"User failed login: %v\", client.Username())\n}", "func (p *Provider) ValidateIdentityParams(ctx context.Context, code, cookie, state string) (t *Token, err error) {\n\tt, _, err = p.ValidateIdentityParamsWithUserdata(ctx, code, cookie, state)\n\treturn\n}", "func (ctr *Controller) GetUserIdsManagedByManager(c echo.Context) error {\n\tuserProfile := c.Get(\"user_profile\").(m.User)\n\trecords, err := ctr.UserProjectRepo.SelectUserIdsManagedByManager(userProfile.OrganizationID, userProfile.UserProfile.UserID)\n\tif err != nil {\n\t\tif err.Error() == pg.ErrNoRows.Error() {\n\t\t\treturn c.JSON(http.StatusOK, cf.JsonResponse{\n\t\t\t\tStatus: cf.FailResponseCode,\n\t\t\t\tMessage: \"There are no users to manage.\",\n\t\t\t})\n\t\t}\n\n\t\treturn c.JSON(http.StatusInternalServerError, cf.JsonResponse{\n\t\t\tStatus: cf.FailResponseCode,\n\t\t\tMessage: \"System Error\",\n\t\t\tData: err,\n\t\t})\n\t}\n\n\tvar userIds []int\n\tfor _, record := range records {\n\t\tuserIds = append(userIds, record.UserId)\n\t}\n\n\treturn c.JSON(http.StatusOK, cf.JsonResponse{\n\t\tStatus: cf.SuccessResponseCode,\n\t\tMessage: \"Get user ids successfully.\",\n\t\tData: userIds,\n\t})\n}", "func (mr *MockBeanMockRecorder) GetMetadataManager() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetMetadataManager\", reflect.TypeOf((*MockBean)(nil).GetMetadataManager))\n}", "func (rest *TestTokenStorageREST) TestStatusExternalTokenValidOnForcePullInternalError() {\n\tidentity, err := testsupport.CreateTestIdentity(rest.DB, uuid.NewV4().String(), \"KC\")\n\trequire.Nil(rest.T(), err)\n\trest.checkStatusExternalTokenValidOnForcePullInternalError(identity, \"https://github.com/a/b\", \"https://github.com\")\n\trest.checkStatusExternalTokenValidOnForcePullInternalError(identity, \"github\", \"https://github.com\")\n\trest.checkStatusExternalTokenValidOnForcePullInternalError(identity, \"openshift\", \"https://api.starter-us-east-2.openshift.com/\")\n\trest.checkStatusExternalTokenValidOnForcePullInternalError(identity, \"https://api.starter-us-east-2.openshift.com\", \"https://api.starter-us-east-2.openshift.com/\")\n}", "func (mmVerify *DelegationTokenFactoryMock) VerifyBeforeCounter() uint64 {\n\treturn mm_atomic.LoadUint64(&mmVerify.beforeVerifyCounter)\n}", "func (_m *AuthServer) mustEmbedUnimplementedAuthServer() {\n\t_m.Called()\n}", "func (o *ActionDTO) GetUserIdentityOk() (*string, bool) {\n\tif o == nil || o.UserIdentity == nil {\n\t\treturn nil, false\n\t}\n\treturn o.UserIdentity, true\n}", "func (m *MockProviders) IdentityConfig() msp.IdentityConfig {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"IdentityConfig\")\n\tret0, _ := ret[0].(msp.IdentityConfig)\n\treturn ret0\n}", "func TestHandler_URLMappingShowRecapSalesFailIDNotExist(t *testing.T) {\n\t// melakukan proses login\n\tuser := model.DummyUserPriviledgeWithUsergroup(1)\n\tsd, _ := auth.Login(user)\n\ttoken := \"Bearer \" + sd.Token\n\tng := tester.New()\n\tng.SetHeader(tester.H{\"Authorization\": token})\n\tng.Method = \"GET\"\n\tng.Path = \"/v1/recap-sales/999999\"\n\tng.Run(test.Router(), func(res tester.HTTPResponse, req tester.HTTPRequest) {\n\t\tassert.Equal(t, int(404), res.Code, fmt.Sprintf(\"Should has 'endpoint %s' with method '%s'\", \"/v1/recap-sales/999999\", \"GET\"))\n\t})\n}", "func (t *CarInsuranceChaincode) verifyUserIdentity(stub shim.ChaincodeStubInterface, id string) ([]byte, error) {\n\tvar claimData Claim\n\tvar jsonResp string\n\tvar userData []User\n\tvar claimUser User\n\tvar log string = \"\"\n\tuserData = GetUserData()\n\tdata, err := stub.GetState(id)\n\n\tif err != nil {\n\t\tjsonResp = \"{\\\"Error\\\":\\\"Failed to retrieve claim details\\\"}\"\n\t\treturn nil, errors.New(jsonResp)\n\t}\n\n\terr = json.Unmarshal(data, &claimData)\n\tif err != nil {\n\t\tjsonResp = \"{\\\"Error\\\":\\\"Failed to UnMarshal claim data\\\"}\"\n\t\treturn nil, errors.New(jsonResp)\n\t}\n\n\tclaimUser = claimData.UserDetails\n\n\tfor i := 0; i < len(userData); i++ {\n\t\tif userData[i].FirstName == claimUser.FirstName && userData[i].LastName == claimUser.LastName && userData[i].BirthDate == claimUser.BirthDate && userData[i].Email == claimUser.Email && userData[i].LicencePlateNumber == claimUser.LicencePlateNumber && userData[i].PolicyId == claimUser.PolicyId && userData[i].SSN == claimUser.SSN && userData[i].VIN == claimUser.VIN {\n\t\t\tlog = log + \"User Details Verified!\"\n\t\t\t//var updatedClaim = NewClaimWithState(claimData.Id, claimData.IncidentDate, claimData.Amount, claimUser, STATE_IDENTITY_INSPECTION)\n\t\t\tclaimData.Status = STATE_IDENTITY_INSPECTION\n\t\t\tt.updateClaimStatus(stub, claimData)\n\t\t\tbreak\n\t\t} else {\n\t\t\tjsonResp = \"{\\\"Error\\\":\\\"User Identity authentication failed\\\"}\"\n\t\t\treturn nil, errors.New(jsonResp)\n\t\t}\n\t}\n\n\tdata, err = json.Marshal(log)\n\n\tif err != nil {\n\t\treturn nil, errors.New(\"Error creating log\")\n\t}\n\n\treturn data, nil\n\n}", "func (s *InMemoryDocumentSessionOperations) RememberEntityForDocumentIdGeneration(entity Object) {\n\terr := NewNotImplementedException(\"You cannot set GenerateDocumentIdsOnStore to false without implementing RememberEntityForDocumentIdGeneration\")\n\tmust(err)\n}", "func IdentityFilter(request *restful.Request, response *restful.Response, chain *restful.FilterChain) {\n\tchain.ProcessFilter(request, response)\n}", "func TestAuthResource_WithInvalidRID_CausesPanic(t *testing.T) {\n\trunTest(t, func(s *res.Service) {\n\t\ts.Handle(\"model\", res.Auth(\"method\", func(r res.AuthRequest) {\n\t\t\trestest.AssertPanicNoRecover(t, func() {\n\t\t\t\tr.Resource(\"test..foo\")\n\t\t\t})\n\t\t}))\n\t}, func(s *restest.Session) {\n\t\ts.Auth(\"test.model\", \"method\", nil).\n\t\t\tResponse().\n\t\t\tAssertErrorCode(res.CodeInternalError)\n\t})\n}", "func (mr *MockIDistributedEnforcerMockRecorder) SetRoleManager(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"SetRoleManager\", reflect.TypeOf((*MockIDistributedEnforcer)(nil).SetRoleManager), arg0)\n}" ]
[ "0.6893613", "0.62998694", "0.5792427", "0.57147837", "0.550829", "0.5505529", "0.5474895", "0.5283069", "0.5260831", "0.5145219", "0.51250386", "0.5115499", "0.5110014", "0.5110014", "0.5074017", "0.49268156", "0.49200475", "0.49072677", "0.4907088", "0.490103", "0.4892025", "0.48862773", "0.48690385", "0.48458758", "0.48349786", "0.47964332", "0.47856918", "0.47540897", "0.4747332", "0.4734482", "0.47252202", "0.4704152", "0.46564436", "0.46399468", "0.46399468", "0.463981", "0.463981", "0.4636833", "0.46359205", "0.46315196", "0.46113026", "0.46081066", "0.46074238", "0.45985124", "0.4596818", "0.45751676", "0.45659968", "0.45647758", "0.45581794", "0.4552412", "0.45326856", "0.45147908", "0.4502679", "0.44984144", "0.44846398", "0.44826132", "0.44822776", "0.44813898", "0.4481156", "0.44723946", "0.44706315", "0.44694883", "0.44598576", "0.4457083", "0.4444011", "0.44401503", "0.44354936", "0.4424148", "0.4419265", "0.44187915", "0.44081625", "0.44046894", "0.43966955", "0.4381609", "0.43741825", "0.4371499", "0.43708694", "0.4370459", "0.43665943", "0.43627143", "0.43600744", "0.43568134", "0.43534836", "0.4347535", "0.4341237", "0.43345776", "0.43325916", "0.43260175", "0.43248498", "0.4323696", "0.431871", "0.43143895", "0.4313772", "0.43071127", "0.42928118", "0.428945", "0.42778656", "0.42735994", "0.42673093", "0.42662108" ]
0.68559355
1
InfraProvider mocks base method
func (m *MockProviders) InfraProvider() fab.InfraProvider { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "InfraProvider") ret0, _ := ret[0].(fab.InfraProvider) return ret0 }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (m *MockClient) InfraProvider() fab.InfraProvider {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"InfraProvider\")\n\tret0, _ := ret[0].(fab.InfraProvider)\n\treturn ret0\n}", "func (m *MockProvider) Provide(arg0 string) blobclient.Client {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Provide\", arg0)\n\tret0, _ := ret[0].(blobclient.Client)\n\treturn ret0\n}", "func Test_Provider(t *testing.T) {\n\t// SetLogLevel(\"TRACE\")\n\t// CheckVersion()\n\n\t// Start provider API in the background\n\tgo InitProvider()\n\t// err := InitProvider()\n\t// if err != nil {\n\t// \tlog.Fatalf(\"Error initializing Provider %+v\", err)\n\t// }\n\n\tverifier := HTTPVerifier{}\n\t// Authorization middleware\n\t// This is your chance to modify the request before it hits your provider\n\t// NOTE: this should be used very carefully, as it has the potential to\n\t// _change_ the contract\n\t// f := func(next http.Handler) http.Handler {\n\t// \treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t// \t\tlog.Println(\"[DEBUG] HOOK request filter\")\n\t// \t\t// r.Header.Add(\"Authorization\", \"Bearer 1234-dynamic-value\")\n\t// \t\tnext.ServeHTTP(w, r)\n\t// \t})\n\t// }\n\n\t// Verify the Provider with local Pact Files\n\terr := verifier.VerifyProvider(t, VerifyRequest{\n\t\tProviderBaseURL: \"http://localhost:9000\",\n\t\tBrokerURL: \"http://localhost:9292\",\n\t\tProvider: \"GreetingAPI\",\n\t\tProviderVersion: \"1.0.0\",\n\t\tPublishVerificationResults: true,\n\t\t// PactFiles: []string{\n\t\t// \tfilepath.ToSlash(fmt.Sprintf(\"%s/GreetingAPIConsumer-GreetingAPI.json\", pactDir)),\n\t\t// },\n\t\t// RequestFilter: f,\n\t\t// BeforeEach: func() error {\n\t\t// \tlog.Println(\"[DEBUG] HOOK before each\")\n\t\t// \treturn nil\n\t\t// },\n\t\t// AfterEach: func() error {\n\t\t// \tlog.Println(\"[DEBUG] HOOK after each\")\n\t\t// \treturn nil\n\t\t// },\n\t\t// StateHandlers: StateHandlers{\n\t\t// \t\"User foo exists\": func(setup bool, s ProviderStateV3) (ProviderStateV3Response, error) {\n\n\t\t// \t\tif setup {\n\t\t// \t\t\tlog.Println(\"[DEBUG] HOOK calling user foo exists state handler\", s)\n\t\t// \t\t} else {\n\t\t// \t\t\tlog.Println(\"[DEBUG] HOOK teardown the 'User foo exists' state\")\n\t\t// \t\t}\n\n\t\t// \t\t// ... do something, such as create \"foo\" in the database\n\n\t\t// \t\t// Optionally (if there are generators in the pact) return provider state values to be used in the verification\n\t\t// \t\treturn ProviderStateV3Response{\"uuid\": \"1234\"}, nil\n\t\t// \t},\n\t\t// },\n\t})\n\n\tassert.NoError(t, err)\n}", "func mockedGranter(kubeutil *kube.Kube, app *v1.RadixRegistration, namespace string, serviceAccount *corev1.ServiceAccount) error {\n\treturn nil\n}", "func (m *MockBootstrapperProvider) Provide() (Bootstrapper, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Provide\")\n\tret0, _ := ret[0].(Bootstrapper)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockProcessProvider) BootstrapperProvider() BootstrapperProvider {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"BootstrapperProvider\")\n\tret0, _ := ret[0].(BootstrapperProvider)\n\treturn ret0\n}", "func (m *MockHostEvent) GetInfraEnvId() strfmt.UUID {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetInfraEnvId\")\n\tret0, _ := ret[0].(strfmt.UUID)\n\treturn ret0\n}", "func (m *MockChoriaProvider) MainCollective() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"MainCollective\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func TestGetCloudProvider(t *testing.T) {\n\tfakeCredFile := \"fake-cred-file.json\"\n\tfakeKubeConfig := \"fake-kube-config\"\n\temptyKubeConfig := \"empty-kube-config\"\n\tfakeContent := `\napiVersion: v1\nclusters:\n- cluster:\n server: https://localhost:8080\n name: foo-cluster\ncontexts:\n- context:\n cluster: foo-cluster\n user: foo-user\n namespace: bar\n name: foo-context\ncurrent-context: foo-context\nkind: Config\nusers:\n- name: foo-user\n user:\n exec:\n apiVersion: client.authentication.k8s.io/v1alpha1\n args:\n - arg-1\n - arg-2\n command: foo-command\n`\n\n\terr := createTestFile(emptyKubeConfig)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tdefer func() {\n\t\tif err := os.Remove(emptyKubeConfig); err != nil {\n\t\t\tt.Error(err)\n\t\t}\n\t}()\n\n\ttests := []struct {\n\t\tdesc string\n\t\tcreateFakeCredFile bool\n\t\tcreateFakeKubeConfig bool\n\t\tkubeconfig string\n\t\tnodeID string\n\t\tuserAgent string\n\t\tallowEmptyCloudConfig bool\n\t\texpectedErr error\n\t}{\n\t\t{\n\t\t\tdesc: \"out of cluster, no kubeconfig, no credential file\",\n\t\t\tkubeconfig: \"\",\n\t\t\tnodeID: \"\",\n\t\t\tallowEmptyCloudConfig: true,\n\t\t\texpectedErr: nil,\n\t\t},\n\t\t{\n\t\t\tdesc: \"[failure][disallowEmptyCloudConfig] out of cluster, no kubeconfig, no credential file\",\n\t\t\tkubeconfig: \"\",\n\t\t\tnodeID: \"\",\n\t\t\tallowEmptyCloudConfig: false,\n\t\t\texpectedErr: nil,\n\t\t},\n\t\t{\n\t\t\tdesc: \"[failure] out of cluster & in cluster, specify a non-exist kubeconfig, no credential file\",\n\t\t\tkubeconfig: \"/tmp/non-exist.json\",\n\t\t\tnodeID: \"\",\n\t\t\tallowEmptyCloudConfig: true,\n\t\t\texpectedErr: nil,\n\t\t},\n\t\t{\n\t\t\tdesc: \"[failure] out of cluster & in cluster, specify a empty kubeconfig, no credential file\",\n\t\t\tkubeconfig: emptyKubeConfig,\n\t\t\tnodeID: \"\",\n\t\t\tallowEmptyCloudConfig: true,\n\t\t\texpectedErr: fmt.Errorf(\"failed to get KubeClient: invalid configuration: no configuration has been provided, try setting KUBERNETES_MASTER environment variable\"),\n\t\t},\n\t\t{\n\t\t\tdesc: \"[failure] out of cluster & in cluster, specify a fake kubeconfig, no credential file\",\n\t\t\tcreateFakeKubeConfig: true,\n\t\t\tkubeconfig: fakeKubeConfig,\n\t\t\tnodeID: \"\",\n\t\t\tallowEmptyCloudConfig: true,\n\t\t\texpectedErr: nil,\n\t\t},\n\t\t{\n\t\t\tdesc: \"[success] out of cluster & in cluster, no kubeconfig, a fake credential file\",\n\t\t\tcreateFakeCredFile: true,\n\t\t\tkubeconfig: \"\",\n\t\t\tnodeID: \"\",\n\t\t\tuserAgent: \"useragent\",\n\t\t\tallowEmptyCloudConfig: true,\n\t\t\texpectedErr: nil,\n\t\t},\n\t}\n\n\tfor _, test := range tests {\n\t\tif test.createFakeKubeConfig {\n\t\t\tif err := createTestFile(fakeKubeConfig); err != nil {\n\t\t\t\tt.Error(err)\n\t\t\t}\n\t\t\tdefer func() {\n\t\t\t\tif err := os.Remove(fakeKubeConfig); err != nil {\n\t\t\t\t\tt.Error(err)\n\t\t\t\t}\n\t\t\t}()\n\n\t\t\tif err := os.WriteFile(fakeKubeConfig, []byte(fakeContent), 0666); err != nil {\n\t\t\t\tt.Error(err)\n\t\t\t}\n\t\t}\n\t\tif test.createFakeCredFile {\n\t\t\tif err := createTestFile(fakeCredFile); err != nil {\n\t\t\t\tt.Error(err)\n\t\t\t}\n\t\t\tdefer func() {\n\t\t\t\tif err := os.Remove(fakeCredFile); err != nil {\n\t\t\t\t\tt.Error(err)\n\t\t\t\t}\n\t\t\t}()\n\n\t\t\toriginalCredFile, ok := os.LookupEnv(DefaultAzureCredentialFileEnv)\n\t\t\tif ok {\n\t\t\t\tdefer os.Setenv(DefaultAzureCredentialFileEnv, originalCredFile)\n\t\t\t} else {\n\t\t\t\tdefer os.Unsetenv(DefaultAzureCredentialFileEnv)\n\t\t\t}\n\t\t\tos.Setenv(DefaultAzureCredentialFileEnv, fakeCredFile)\n\t\t}\n\t\tcloud, err := getCloudProvider(test.kubeconfig, test.nodeID, \"\", \"\", test.userAgent, test.allowEmptyCloudConfig, 25.0, 50)\n\t\tif !reflect.DeepEqual(err, test.expectedErr) && test.expectedErr != nil && !strings.Contains(err.Error(), test.expectedErr.Error()) {\n\t\t\tt.Errorf(\"desc: %s,\\n input: %q, GetCloudProvider err: %v, expectedErr: %v\", test.desc, test.kubeconfig, err, test.expectedErr)\n\t\t}\n\t\tif cloud == nil {\n\t\t\tt.Errorf(\"return value of getCloudProvider should not be nil even there is error\")\n\t\t} else {\n\t\t\tassert.Equal(t, cloud.Environment.StorageEndpointSuffix, storage.DefaultBaseURL)\n\t\t\tassert.Equal(t, cloud.UserAgent, test.userAgent)\n\t\t}\n\t}\n}", "func testInMemoryDataStore() IDataStore {\n return NewInMemoryDataStore();\n}", "func ProviderTest(initial Initial, observer invoker.Observer, settings Settings) (Configurator, func(), error) {\n\tc, e := NewMockConfigurator(initial, observer, settings)\n\treturn c, func() {}, e\n}", "func MockedProvider(t *testing.T, c *config.Config, callback string) (*config.Config, goth.Provider) {\n\tconst (\n\t\ttestClientKey = \"provider-test-client-key\"\n\t\ttestSecret = \"provider-test-secret\"\n\t\ttestCallback = \"http://auth.exmaple.com/test/callback\"\n\t)\n\tmp := newMockProvider(t, callback)\n\tp := provider.Name(mp.Name())\n\tprovider.AddExternal(p)\n\tt.Cleanup(func() {\n\t\tdelete(provider.External, p)\n\t})\n\tif callback == \"\" {\n\t\tcallback = testCallback\n\t}\n\tc.Authorization.Providers[p] = config.Provider{\n\t\tClientKey: testClientKey,\n\t\tSecret: testSecret,\n\t\tCallbackURL: callback,\n\t}\n\treturn c, mp\n}", "func (m *MockInfraEnvEvent) GetInfraEnvId() strfmt.UUID {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetInfraEnvId\")\n\tret0, _ := ret[0].(strfmt.UUID)\n\treturn ret0\n}", "func providerConfigure(d *schema.ResourceData) (interface{}, error) {\n\tif d.Get(\"url\") == nil {\n\t\treturn nil, fmt.Errorf(\"url cannot be nil\")\n\t}\n\n\tusername := d.Get(\"username\").(string)\n\tpassword := d.Get(\"password\").(string)\n\tapiKey := d.Get(\"api_key\").(string)\n\taccessToken := d.Get(\"access_token\").(string)\n\n\tlog.SetLogger(log.NewLogger(log.INFO, nil))\n\n\tvar client *http.Client\n\tdetails := auth.NewArtifactoryDetails()\n\n\turl := d.Get(\"url\").(string)\n\tif url[len(url)-1] != '/' {\n\t\turl += \"/\"\n\t}\n\tdetails.SetUrl(url)\n\n\tif username != \"\" && password != \"\" {\n\t\tdetails.SetUser(username)\n\t\tdetails.SetPassword(password)\n\t\ttp := transport.BasicAuth{\n\t\t\tUsername: username,\n\t\t\tPassword: password,\n\t\t}\n\t\tclient = tp.Client()\n\t} else if apiKey != \"\" {\n\t\tdetails.SetApiKey(apiKey)\n\t\ttp := &transport.ApiKeyAuth{\n\t\t\tApiKey: apiKey,\n\t\t}\n\t\tclient = tp.Client()\n\t} else if accessToken != \"\" {\n\t\tdetails.SetAccessToken(accessToken)\n\t\ttp := &transport.AccessTokenAuth{\n\t\t\tAccessToken: accessToken,\n\t\t}\n\t\tclient = tp.Client()\n\t} else {\n\t\treturn nil, fmt.Errorf(\"either [username, password] or [api_key] or [access_token] must be set to use provider\")\n\t}\n\n\tconfig, err := config.NewConfigBuilder().\n\t\tSetServiceDetails(details).\n\t\tSetDryRun(false).\n\t\tBuild()\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trtold, err := artifactoryold.NewClient(d.Get(\"url\").(string), client)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trtnew, err := artifactorynew.New(&details, config)\n\n\tif err != nil {\n\t\treturn nil, err\n\t} else if _, resp, err := rtold.V1.System.Ping(context.Background()); err != nil {\n\t\treturn nil, err\n\t} else if resp.StatusCode != 200 {\n\t\treturn nil, fmt.Errorf(\"failed to ping server. Got %d\", resp.StatusCode)\n\t} else if _, err := rtnew.Ping(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tproductid := \"terraform-provider-artifactory/\" + ProviderVersion\n\tcommandid := \"Terraform/\" + version.Version\n\tusage.SendReportUsage(productid, commandid, rtnew)\n\n\trt := &ArtClient{\n\t\tArtOld: rtold,\n\t\tArtNew: rtnew,\n\t}\n\n\treturn rt, nil\n}", "func (c *Provider) InfraProvider() fab.InfraProvider {\n\treturn c.infraProvider\n}", "func TestBaseImage(t *testing.T) {\n\tctx, err := controllerPrepare()\n\tif err != nil {\n\t\tt.Fatal(\"Fail in controller prepare: \", err)\n\t}\n\teveBaseRef := os.Getenv(\"EVE_BASE_REF\")\n\tif len(eveBaseRef) == 0 {\n\t\teveBaseRef = \"4.10.0\"\n\t}\n\tzArch := os.Getenv(\"ZARCH\")\n\tif len(eveBaseRef) == 0 {\n\t\tzArch = \"amd64\"\n\t}\n\tHV := os.Getenv(\"HV\")\n\tif HV == \"xen\" {\n\t\tHV = \"\"\n\t}\n\tvar baseImageTests = []struct {\n\t\tdataStoreID string\n\t\timageID string\n\t\tbaseID string\n\t\timageRelativePath string\n\t\timageFormat config.Format\n\t\teveBaseRef string\n\t\tzArch string\n\t\tHV string\n\t}{\n\t\t{eServerDataStoreID,\n\n\t\t\t\"1ab8761b-5f89-4e0b-b757-4b87a9fa93ec\",\n\n\t\t\t\"22b8761b-5f89-4e0b-b757-4b87a9fa93ec\",\n\n\t\t\t\"baseos.qcow2\",\n\t\t\tconfig.Format_QCOW2,\n\t\t\teveBaseRef,\n\t\t\tzArch,\n\t\t\tHV,\n\t\t},\n\t}\n\tfor _, tt := range baseImageTests {\n\t\tbaseOSVersion := fmt.Sprintf(\"%s-%s\", tt.eveBaseRef, tt.zArch)\n\t\tif tt.HV != \"\" {\n\t\t\tbaseOSVersion = fmt.Sprintf(\"%s-%s-%s\", tt.eveBaseRef, tt.zArch, tt.HV)\n\t\t}\n\t\tt.Run(baseOSVersion, func(t *testing.T) {\n\n\t\t\terr = prepareBaseImageLocal(ctx, tt.dataStoreID, tt.imageID, tt.baseID, tt.imageRelativePath, tt.imageFormat, baseOSVersion)\n\n\t\t\tif err != nil {\n\t\t\t\tt.Fatal(\"Fail in prepare base image from local file: \", err)\n\t\t\t}\n\t\t\tdeviceCtx, err := ctx.GetDeviceFirst()\n\t\t\tif err != nil {\n\t\t\t\tt.Fatal(\"Fail in get first device: \", err)\n\t\t\t}\n\t\t\tdeviceCtx.SetBaseOSConfig([]string{tt.baseID})\n\t\t\tdevUUID := deviceCtx.GetID()\n\t\t\terr = ctx.ConfigSync(deviceCtx)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatal(\"Fail in sync config with controller: \", err)\n\t\t\t}\n\t\t\tt.Run(\"Started\", func(t *testing.T) {\n\t\t\t\terr := ctx.InfoChecker(devUUID, map[string]string{\"devId\": devUUID.String(), \"shortVersion\": baseOSVersion}, einfo.ZInfoDevSW, 300)\n\t\t\t\tif err != nil {\n\t\t\t\t\tt.Fatal(\"Fail in waiting for base image update init: \", err)\n\t\t\t\t}\n\t\t\t})\n\t\t\tt.Run(\"Downloaded\", func(t *testing.T) {\n\t\t\t\terr := ctx.InfoChecker(devUUID, map[string]string{\"devId\": devUUID.String(), \"shortVersion\": baseOSVersion, \"downloadProgress\": \"100\"}, einfo.ZInfoDevSW, 1500)\n\t\t\t\tif err != nil {\n\t\t\t\t\tt.Fatal(\"Fail in waiting for base image download progress: \", err)\n\t\t\t\t}\n\t\t\t})\n\t\t\tt.Run(\"Logs\", func(t *testing.T) {\n\t\t\t\tif !checkLogs {\n\t\t\t\t\tt.Skip(\"no LOGS flag set - skipped\")\n\t\t\t\t}\n\t\t\t\terr = ctx.LogChecker(devUUID, map[string]string{\"devId\": devUUID.String(), \"eveVersion\": baseOSVersion}, 1200)\n\t\t\t\tif err != nil {\n\t\t\t\t\tt.Fatal(\"Fail in waiting for base image logs: \", err)\n\t\t\t\t}\n\t\t\t})\n\t\t\ttimeout := time.Duration(1200)\n\n\t\t\tif !checkLogs {\n\t\t\t\ttimeout = 2400\n\t\t\t}\n\t\t\tt.Run(\"Active\", func(t *testing.T) {\n\t\t\t\terr = ctx.InfoChecker(devUUID, map[string]string{\"devId\": devUUID.String(), \"shortVersion\": baseOSVersion, \"status\": \"INSTALLED\", \"partitionState\": \"(inprogress|active)\"}, einfo.ZInfoDevSW, timeout)\n\t\t\t\tif err != nil {\n\t\t\t\t\tt.Fatal(\"Fail in waiting for base image installed status: \", err)\n\t\t\t\t}\n\t\t\t})\n\t\t})\n\t}\n\n}", "func mockChildPackages() {\n\n\t// Fake an AWS credentials file so that the mfile package will nehave as if it is happy\n\tsetFakeCredentials()\n\n\t// Fake out the creds package into using an apparently credentials response from AWS\n\tcreds.SetGetSessionTokenFunc(func(awsService *sts.STS, input *sts.GetSessionTokenInput) (*sts.GetSessionTokenOutput, error) {\n\t\treturn getSessionTokenOutput, nil\n\t})\n\n}", "func NewMockInfra(ctrl *gomock.Controller) *MockInfra {\n\tmock := &MockInfra{ctrl: ctrl}\n\tmock.recorder = &MockInfraMockRecorder{mock}\n\treturn mock\n}", "func TestConjur_Provider(t *testing.T) {\n\tvar err error\n\tvar provider plugin_v1.Provider\n\tname := \"conjur\"\n\n\toptions := plugin_v1.ProviderOptions{\n\t\tName: name,\n\t}\n\n\tt.Run(\"Can create the Conjur provider\", func(t *testing.T) {\n\t\tprovider, err = providers.ProviderFactories[name](options)\n\t\tassert.NoError(t, err)\n\t})\n\n\tt.Run(\"Has the expected provider name\", func(t *testing.T) {\n\t\tassert.Equal(t, \"conjur\", provider.GetName())\n\t})\n\n\tt.Run(\"Can provide an access token\", func(t *testing.T) {\n\t\tid := \"accessToken\"\n\t\tvalues, err := provider.GetValues(id)\n\n\t\tassert.NoError(t, err)\n\t\tassert.NotNil(t, values[id])\n\t\tassert.NoError(t, values[id].Error)\n\t\tassert.NotNil(t, values[id].Value)\n\n\t\ttoken := make(map[string]string)\n\t\terr = json.Unmarshal(values[id].Value, &token)\n\t\tassert.NoError(t, err)\n\t\tassert.NotNil(t, token[\"protected\"])\n\t\tassert.NotNil(t, token[\"payload\"])\n\t})\n\n\tt.Run(\"Reports an unknown value\",\n\t\ttestutils.Reports(\n\t\t\tprovider,\n\t\t\t\"foobar\",\n\t\t\t\"404 Not Found. CONJ00076E Variable dev:variable:foobar is empty or not found..\",\n\t\t),\n\t)\n\n\tt.Run(\"Provides\", func(t *testing.T) {\n\t\tfor _, testCase := range canProvideTestCases {\n\t\t\tt.Run(testCase.Description, testutils.CanProvide(provider, testCase.ID, testCase.ExpectedValue))\n\t\t}\n\t})\n}", "func providerFactory(_ io.Reader) (cloudprovider.Interface, error) {\n\tlog := klogr.NewWithOptions(klogr.WithFormat(klogr.FormatKlog))\n\tc, err := loadConfig(envconfig.OsLookuper())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tapiUrl := katapult.DefaultURL\n\tif c.APIHost != \"\" {\n\t\tlog.Info(\"default API base URL overrided\",\n\t\t\t\"url\", c.APIHost)\n\t\tapiUrl, err = url.Parse(c.APIHost)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to parse provided api url: %w\", err)\n\t\t}\n\t}\n\n\trm, err := katapult.New(\n\t\tkatapult.WithAPIKey(c.APIKey),\n\t\tkatapult.WithBaseURL(apiUrl),\n\t\tkatapult.WithUserAgent(\"kce-ccm\"), // TODO: Add version.\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tclient := core.New(rm)\n\n\treturn &provider{\n\t\tlog: log,\n\t\tkatapult: client,\n\t\tconfig: *c,\n\t\tloadBalancer: &loadBalancerManager{\n\t\t\tlog: log,\n\t\t\tconfig: *c,\n\t\t\tloadBalancerController: client.LoadBalancers,\n\t\t\tloadBalancerRuleController: client.LoadBalancerRules,\n\t\t},\n\t}, nil\n}", "func (mdhth *MockDHTHandler) Provider(string, bool) error {\n\treturn nil\n}", "func TestCustomAnchoreConfigProvider_GetConfiguration(t *testing.T) {\n\tintegratedServiceRepository := integratedservices.NewInMemoryIntegratedServiceRepository(map[uint][]integratedservices.IntegratedService{\n\t\t1: {\n\t\t\t{\n\t\t\t\tName: \"securityscan\",\n\t\t\t\tSpec: map[string]interface{}{\n\t\t\t\t\t\"customAnchore\": map[string]interface{}{\n\t\t\t\t\t\t\"enabled\": true,\n\t\t\t\t\t\t\"url\": \"https://anchore.example.com\",\n\t\t\t\t\t\t\"secretId\": \"secretId\",\n\t\t\t\t\t\t\"insecure\": true,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tOutput: nil,\n\t\t\t\tStatus: integratedservices.IntegratedServiceStatusActive,\n\t\t\t},\n\t\t},\n\t})\n\n\tsecretStore := new(SecretStore)\n\tsecretStore.On(\"GetSecretValues\", mock.Anything, \"secretId\").Return(\n\t\tmap[string]string{\n\t\t\t\"username\": \"user\",\n\t\t\t\"password\": \"password\",\n\t\t},\n\t\tnil,\n\t)\n\n\tconfigProvider := NewCustomAnchoreConfigProvider(integratedServiceRepository, secretStore, services.NoopLogger{})\n\n\tconfig, err := configProvider.GetConfiguration(context.Background(), 1)\n\trequire.NoError(t, err)\n\n\tassert.Equal(\n\t\tt,\n\t\tanchore.Config{\n\t\t\tEndpoint: \"https://anchore.example.com\",\n\t\t\tUser: \"user\",\n\t\t\tPassword: \"password\",\n\t\t\tInsecure: true,\n\t\t},\n\t\tconfig,\n\t)\n\n\tsecretStore.AssertExpectations(t)\n}", "func providerConfigure(ctx context.Context, d *schema.ResourceData) (interface{}, diag.Diagnostics) {\n\n\tvar diags diag.Diagnostics\n\tbearerToken := d.Get(\"bearer_token\").(string)\n\n\tvar host string\n\thVal, ok := d.GetOk(\"host\")\n\tif ok {\n\t\ttempHost := hVal.(string)\n\t\thost = tempHost\n\t}\n\n\tc := NewClient(host, bearerToken, &http.Client{})\n\treturn c, diags\n}", "func TestDontWaitForOtherProvidersIfWeGotError(t *testing.T) {\n\tstart := time.Now()\n\n\tappCustom := App{\n\t\tContentProvider: NewContentProviderService(\n\t\t\tmap[Provider]Client{\n\t\t\t\tProvider1: &ClientMock{\n\t\t\t\t\tGetContentFn: func(userIP string, count int) ([]*ContentItem, error) {\n\t\t\t\t\t\treturn []*ContentItem{}, errors.New(\"some error from provider 1\")\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tProvider2: &ClientMock{\n\t\t\t\t\tGetContentFn: func(userIP string, count int) ([]*ContentItem, error) {\n\t\t\t\t\t\treturn []*ContentItem{}, errors.New(\"some error from provider 2\")\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tProvider3: &ClientMock{\n\t\t\t\t\tGetContentFn: func(userIP string, count int) ([]*ContentItem, error) {\n\t\t\t\t\t\t// let's imitate some pending request to provider\n\t\t\t\t\t\ttime.Sleep(5 * time.Second)\n\t\t\t\t\t\treturn []*ContentItem{{\n\t\t\t\t\t\t\tSource: \"3\",\n\t\t\t\t\t\t}}, nil\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tDefaultConfig,\n\t\t\tWithTimeOut(500*time.Millisecond),\n\t\t),\n\t}\n\n\tcontent := runRequest(t, appCustom, SimpleContentRequest)\n\n\tif len(content) != 0 {\n\t\tt.Fatalf(\"Got %d items back, want 0\", len(content))\n\t}\n\n\texecTime := time.Since(start)\n\tif execTime > time.Second {\n\t\tt.Fatalf(\"test time should be less then 1 second, got: %s\", execTime)\n\t}\n}", "func (m *MockChoriaProvider) Identity() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Identity\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func (m *MockProvider) OnEndpointsSynced() {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"OnEndpointsSynced\")\n}", "func (m *MockProcessProvider) SetBootstrapperProvider(bootstrapper BootstrapperProvider) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"SetBootstrapperProvider\", bootstrapper)\n}", "func TestCNContainer_Base(t *testing.T) {\n\tassert := assert.New(t)\n\n\tcn, err := cnTestInit()\n\trequire.Nil(t, err)\n\n\tdockerPlugin, err := startDockerPlugin(t)\n\trequire.Nil(t, err)\n\n\t//From YAML on instance init\n\t//Two VNICs on the same tenant subnet\n\tmac, _ := net.ParseMAC(\"CA:FE:00:01:02:03\")\n\tmac2, _ := net.ParseMAC(\"CA:FE:00:02:02:03\")\n\t_, tnet, _ := net.ParseCIDR(\"192.168.111.0/24\")\n\ttip := net.ParseIP(\"192.168.111.100\")\n\ttip2 := net.ParseIP(\"192.168.111.102\")\n\tcip := net.ParseIP(\"192.168.200.200\")\n\n\tvnicCfg := &VnicConfig{\n\t\tVnicRole: TenantContainer,\n\t\tVnicIP: tip,\n\t\tConcIP: cip,\n\t\tVnicMAC: mac,\n\t\tSubnet: *tnet,\n\t\tSubnetKey: 0xF,\n\t\tVnicID: \"vuuid\",\n\t\tInstanceID: \"iuuid\",\n\t\tTenantID: \"tuuid\",\n\t\tSubnetID: \"suuid\",\n\t\tConcID: \"cnciuuid\",\n\t}\n\n\tvnicCfg2 := &VnicConfig{\n\t\tVnicRole: TenantContainer,\n\t\tVnicIP: tip2,\n\t\tConcIP: cip,\n\t\tVnicMAC: mac2,\n\t\tSubnet: *tnet,\n\t\tSubnetKey: 0xF,\n\t\tVnicID: \"vuuid2\",\n\t\tInstanceID: \"iuuid2\",\n\t\tTenantID: \"tuuid\",\n\t\tSubnetID: \"suuid\",\n\t\tConcID: \"cnciuuid\",\n\t}\n\n\tvar subnetID, iface string //Used to check that they match\n\n\t// Create a VNIC: Should create bridge and tunnels\n\tif vnic, ssntpEvent, cInfo, err := cn.CreateVnic(vnicCfg); err != nil {\n\t\tt.Error(err)\n\t} else {\n\t\t// expected SSNTP Event\n\t\tif assert.NotNil(ssntpEvent) {\n\t\t\tassert.Equal(ssntpEvent.Event, SsntpTunAdd)\n\t\t}\n\t\t// expected Container Event\n\t\tif assert.NotNil(cInfo) {\n\t\t\tassert.Equal(cInfo.CNContainerEvent, ContainerNetworkAdd)\n\t\t\tassert.NotEqual(cInfo.SubnetID, \"\")\n\t\t\tassert.NotEqual(cInfo.Subnet.String(), \"\")\n\t\t\tassert.NotEqual(cInfo.Gateway.String(), \"\")\n\t\t\tassert.NotEqual(cInfo.Bridge, \"\")\n\t\t}\n\t\tassert.Nil(validSsntpEvent(ssntpEvent, vnicCfg))\n\n\t\t//Cache the first subnet ID we see. All subsequent should have the same\n\t\tsubnetID = cInfo.SubnetID\n\t\tiface = vnic.InterfaceName()\n\t\tassert.NotEqual(iface, \"\")\n\n\t\t//Launcher will attach to this name and send out the event\n\t\t//Launcher will also create the logical docker network\n\t\tdebugPrint(t, \"VNIC created =\", vnic.LinkName, ssntpEvent, cInfo)\n\t\tassert.Nil(linkDump(t))\n\n\t\t//Now kick off the docker commands\n\t\tassert.Nil(dockerNetCreate(cInfo.Subnet, cInfo.Gateway, cInfo.Bridge, cInfo.SubnetID))\n\t\tassert.Nil(dockerNetInfo(cInfo.SubnetID))\n\t\tassert.Nil(dockerRunVerify(vnicCfg.VnicIP.String(), vnicCfg.VnicIP, vnicCfg.VnicMAC, cInfo.SubnetID))\n\t\tassert.Nil(dockerContainerDelete(vnicCfg.VnicIP.String()))\n\t}\n\n\t//Duplicate VNIC creation\n\tif vnic, ssntpEvent, cInfo, err := cn.CreateVnic(vnicCfg); err != nil {\n\t\tt.Error(err)\n\t} else {\n\t\tassert.Nil(ssntpEvent, \"ERROR: DUP unexpected event\")\n\t\tif assert.NotNil(cInfo) {\n\t\t\tassert.Equal(cInfo.SubnetID, subnetID)\n\t\t\tassert.Equal(cInfo.CNContainerEvent, ContainerNetworkInfo)\n\t\t\tassert.Equal(iface, vnic.InterfaceName())\n\t\t}\n\t}\n\n\t//Second VNIC creation - Should succeed\n\tif vnic, ssntpEvent, cInfo, err := cn.CreateVnic(vnicCfg2); err != nil {\n\t\tt.Error(err)\n\t} else {\n\t\tassert.Nil(ssntpEvent)\n\t\tif assert.NotNil(cInfo) {\n\t\t\tassert.Equal(cInfo.SubnetID, subnetID)\n\t\t\tassert.Equal(cInfo.CNContainerEvent, ContainerNetworkInfo)\n\t\t}\n\t\tiface = vnic.InterfaceName()\n\t\tassert.NotEqual(iface, \"\")\n\t\tassert.Nil(dockerRunVerify(vnicCfg2.VnicIP.String(), vnicCfg2.VnicIP,\n\t\t\tvnicCfg2.VnicMAC, cInfo.SubnetID))\n\t\tassert.Nil(dockerContainerDelete(vnicCfg2.VnicIP.String()))\n\t}\n\n\t//Duplicate VNIC creation\n\tif vnic, ssntpEvent, cInfo, err := cn.CreateVnic(vnicCfg2); err != nil {\n\t\tt.Error(err)\n\t} else {\n\t\tassert.Nil(ssntpEvent)\n\t\tif assert.NotNil(cInfo) {\n\t\t\tassert.Equal(cInfo.SubnetID, subnetID)\n\t\t\tassert.Equal(cInfo.CNContainerEvent, ContainerNetworkInfo)\n\t\t\tassert.Equal(iface, vnic.InterfaceName())\n\t\t}\n\t}\n\n\t//Destroy the first one\n\tif ssntpEvent, cInfo, err := cn.DestroyVnic(vnicCfg); err != nil {\n\t\tt.Error(err)\n\t} else {\n\t\tassert.Nil(ssntpEvent)\n\t\tassert.Nil(cInfo)\n\t}\n\n\t//Destroy it again\n\tif ssntpEvent, cInfo, err := cn.DestroyVnic(vnicCfg); err != nil {\n\t\tt.Error(err)\n\t} else {\n\t\tassert.Nil(ssntpEvent)\n\t\tassert.Nil(cInfo)\n\t}\n\n\t// Try and destroy - should work - cInfo should be reported\n\tif ssntpEvent, cInfo, err := cn.DestroyVnic(vnicCfg2); err != nil {\n\t\tt.Error(err)\n\t} else {\n\t\tassert.NotNil(ssntpEvent)\n\t\tif assert.NotNil(cInfo) {\n\t\t\tassert.Equal(cInfo.SubnetID, subnetID)\n\t\t\tassert.Equal(cInfo.CNContainerEvent, ContainerNetworkDel)\n\t\t}\n\t}\n\n\t//Has to be called after the VNIC has been deleted\n\tassert.Nil(dockerNetDelete(subnetID))\n\tassert.Nil(dockerNetList())\n\n\t//Destroy it again\n\tif ssntpEvent, cInfo, err := cn.DestroyVnic(vnicCfg2); err != nil {\n\t\tt.Error(err)\n\t} else {\n\t\tassert.Nil(ssntpEvent)\n\t\tassert.Nil(cInfo)\n\t}\n\n\tassert.Nil(stopDockerPlugin(dockerPlugin))\n}", "func newExecProvider() ExecProvider {\n\treturn realExecProvider{}\n}", "func (m *MockecsDescriber) Platform() (*ecs.ContainerPlatform, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Platform\")\n\tret0, _ := ret[0].(*ecs.ContainerPlatform)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func getTestDriverA(env string) (*OVTest, *ov.OVClient) {\n\t// os.Setenv(\"DEBUG\", \"true\") // remove comment to debug logs\n\tvar ot *OVTest\n\tvar tc *testconfig.TestConfig\n\tot = &OVTest{Tc: tc.NewTestConfig(), Env: env}\n\tot.GetEnvironment(env)\n\tot.Tc.GetTestingConfiguration(os.Getenv(\"ONEVIEW_TEST_DATA\"))\n\tot.Client = &ov.OVClient{Client: rest.Client{\n\t\tUser: os.Getenv(\"ONEVIEW_OV_USER\"),\n\t\tPassword: os.Getenv(\"ONEVIEW_OV_PASSWORD\"),\n\t\tDomain: os.Getenv(\"ONEVIEW_OV_DOMAIN\"),\n\t\tEndpoint: os.Getenv(\"ONEVIEW_OV_ENDPOINT\"),\n\t\t// ConfigDir:\n\t\tSSLVerify: false,\n\t\tAPIKey: \"none\",\n\t},\n\t}\n\terr := ot.Client.RefreshVersion()\n\tif err != nil {\n\t\tlog.Errorf(\"Problem with getting api version refreshed : %+v\", err)\n\t}\n\t// fmt.Println(\"Setting up test with getTestDriverA\")\n\treturn ot, ot.Client\n}", "func TestNewIdentityManager(t *testing.T) {\n\tt.Run(\"success\", func(t *testing.T) {\n\t\tepCfg := &mocks.EndpointConfig{}\n\t\tepCfg.NetworkConfigReturns(&fab.NetworkConfig{\n\t\t\tOrganizations: map[string]fab.OrganizationConfig{\"org1msp\": {}},\n\t\t})\n\n\t\tm, err := newIdentityManager(\"org1MSP\", &mocks.CryptoSuite{}, epCfg, \"./msp\")\n\t\trequire.NoError(t, err)\n\t\trequire.NotNil(t, m)\n\t})\n\n\tt.Run(\"No endpoint config -> error\", func(t *testing.T) {\n\t\tm, err := newIdentityManager(\"org1MSP\", &mocks.CryptoSuite{}, nil, \"./msp\")\n\t\trequire.EqualError(t, err, \"endpoint config is required\")\n\t\trequire.Nil(t, m)\n\t})\n\n\tt.Run(\"No org name -> error\", func(t *testing.T) {\n\t\tm, err := newIdentityManager(\"\", nil, &mocks.EndpointConfig{}, \"./msp\")\n\t\trequire.EqualError(t, err, \"orgName is required\")\n\t\trequire.Nil(t, m)\n\t})\n\n\tt.Run(\"No crypto suite -> error\", func(t *testing.T) {\n\t\tm, err := newIdentityManager(\"org1MSP\", nil, &mocks.EndpointConfig{}, \"./msp\")\n\t\trequire.EqualError(t, err, \"cryptoProvider is required\")\n\t\trequire.Nil(t, m)\n\t})\n\n\tt.Run(\"Org not found -> error\", func(t *testing.T) {\n\t\tepCfg := &mocks.EndpointConfig{}\n\t\tepCfg.NetworkConfigReturns(&fab.NetworkConfig{})\n\n\t\tm, err := newIdentityManager(\"org1MSP\", &mocks.CryptoSuite{}, epCfg, \"./msp\")\n\t\trequire.EqualError(t, err, \"org config retrieval failed\")\n\t\trequire.Nil(t, m)\n\t})\n\n\tt.Run(\"MSP config path not provided -> error\", func(t *testing.T) {\n\t\tepCfg := &mocks.EndpointConfig{}\n\t\tepCfg.NetworkConfigReturns(&fab.NetworkConfig{\n\t\t\tOrganizations: map[string]fab.OrganizationConfig{\"org1msp\": {}},\n\t\t})\n\n\t\tm, err := newIdentityManager(\"org1MSP\", &mocks.CryptoSuite{}, epCfg, \"\")\n\t\trequire.EqualError(t, err, \"either mspConfigPath or an embedded list of users is required\")\n\t\trequire.Nil(t, m)\n\t})\n}", "func NewProvider() *ProviderConfig {\n\tproviderConfig := &ProviderConfig{\n\t\tAlibaba: make(map[string]*models.AlibabaCloudSpec),\n\t\tAnexia: make(map[string]*models.AnexiaCloudSpec),\n\t\tAws: make(map[string]*models.AWSCloudSpec),\n\t\tAzure: make(map[string]*models.AzureCloudSpec),\n\t\tDigitalocean: make(map[string]*models.DigitaloceanCloudSpec),\n\t\tFake: make(map[string]*models.FakeCloudSpec),\n\t\tGcp: make(map[string]*models.GCPCloudSpec),\n\t\tHetzner: make(map[string]*models.HetznerCloudSpec),\n\t\tKubevirt: make(map[string]*models.KubevirtCloudSpec),\n\t\tOpenstack: make(map[string]*models.OpenstackCloudSpec),\n\t\tPacket: make(map[string]*models.PacketCloudSpec),\n\t\tVsphere: make(map[string]*models.VSphereCloudSpec),\n\t}\n\n\tproviderConfig.Alibaba[\"Alibaba\"] = newAlibabaCloudSpec()\n\tproviderConfig.Anexia[\"Anexia\"] = newAnexiaCloudSpec()\n\tproviderConfig.Aws[\"Aws\"] = newAWSCloudSpec()\n\tproviderConfig.Azure[\"Azure\"] = newAzureCloudSpec()\n\tproviderConfig.Digitalocean[\"Digitalocean\"] = newDigitaloceanCloudSpec()\n\tproviderConfig.Fake[\"Fake\"] = newFakeCloudSpec()\n\tproviderConfig.Gcp[\"Gcp\"] = newGCPCloudSpec()\n\tproviderConfig.Hetzner[\"Hetzner\"] = newHetznerCloudSpec()\n\tproviderConfig.Kubevirt[\"Kubevirt\"] = newKubevirtCloudSpec()\n\tproviderConfig.Openstack[\"Openstack\"] = newOpenstackCloudSpec()\n\tproviderConfig.Packet[\"Packet\"] = newPacketCloudSpec()\n\tproviderConfig.Vsphere[\"Vsphere\"] = newVSphereCloudSpec()\n\n\treturn providerConfig\n}", "func (m *MockResolver) EvictSelf() error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"EvictSelf\")\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func Provider() tfbridge.ProviderInfo {\n\t// Instantiate the Terraform provider\n\tp := shimv2.NewProvider(shim.NewProvider())\n\n\t// Create a Pulumi provider mapping\n\tprov := tfbridge.ProviderInfo{\n\t\tP: p,\n\t\tName: \"azuread\",\n\t\tDisplayName: \"Azure Active Directory (Azure AD)\",\n\t\tDescription: \"A Pulumi package for creating and managing Azure Active Directory (Azure AD) cloud resources.\",\n\t\tKeywords: []string{\"pulumi\", \"azuread\"},\n\t\tLicense: \"Apache-2.0\",\n\t\tHomepage: \"https://pulumi.io\",\n\t\tGitHubOrg: \"hashicorp\",\n\t\tRepository: \"https://github.com/pulumi/pulumi-azuread\",\n\t\tConfig: map[string]*tfbridge.SchemaInfo{\n\t\t\t\"environment\": {\n\t\t\t\tDefault: &tfbridge.DefaultInfo{\n\t\t\t\t\tValue: \"public\",\n\t\t\t\t\tEnvVars: []string{\"ARM_ENVIRONMENT\"},\n\t\t\t\t},\n\t\t\t},\n\t\t\t\"msi_endpoint\": {\n\t\t\t\tDefault: &tfbridge.DefaultInfo{\n\t\t\t\t\tEnvVars: []string{\"ARM_MSI_ENDPOINT\"},\n\t\t\t\t},\n\t\t\t},\n\t\t\t\"use_msi\": {\n\t\t\t\tDefault: &tfbridge.DefaultInfo{\n\t\t\t\t\tValue: false,\n\t\t\t\t\tEnvVars: []string{\"ARM_USE_MSI\"},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tPreConfigureCallback: preConfigureCallback,\n\t\tResources: map[string]*tfbridge.ResourceInfo{\n\t\t\t\"azuread_application\": {Tok: makeResource(mainMod, \"Application\")},\n\t\t\t\"azuread_application_password\": {Tok: makeResource(mainMod, \"ApplicationPassword\")},\n\t\t\t\"azuread_group\": {Tok: makeResource(mainMod, \"Group\")},\n\t\t\t\"azuread_service_principal\": {Tok: makeResource(mainMod, \"ServicePrincipal\")},\n\t\t\t\"azuread_service_principal_password\": {Tok: makeResource(mainMod, \"ServicePrincipalPassword\")},\n\t\t\t\"azuread_service_principal_delegated_permission_grant\": {\n\t\t\t\tTok: makeResource(mainMod, \"ServicePrincipalDelegatedPermissionGrant\"),\n\t\t\t},\n\t\t\t\"azuread_user\": {Tok: makeResource(mainMod, \"User\")},\n\t\t\t\"azuread_group_member\": {Tok: makeResource(mainMod, \"GroupMember\")},\n\t\t\t\"azuread_application_certificate\": {Tok: makeResource(mainMod, \"ApplicationCertificate\")},\n\t\t\t\"azuread_service_principal_certificate\": {Tok: makeResource(mainMod, \"ServicePrincipalCertificate\")},\n\t\t\t\"azuread_service_principal_token_signing_certificate\": {\n\t\t\t\tTok: makeResource(mainMod, \"ServicePrincipalTokenSigningCertificate\"),\n\t\t\t},\n\t\t\t\"azuread_application_pre_authorized\": {Tok: makeResource(mainMod, \"ApplicationPreAuthorized\")},\n\t\t\t\"azuread_invitation\": {Tok: makeResource(mainMod, \"Invitation\")},\n\t\t\t\"azuread_conditional_access_policy\": {Tok: makeResource(mainMod, \"ConditionalAccessPolicy\")},\n\t\t\t\"azuread_named_location\": {Tok: makeResource(mainMod, \"NamedLocation\")},\n\t\t\t\"azuread_directory_role\": {Tok: makeResource(mainMod, \"DirectoryRole\")},\n\t\t\t\"azuread_directory_role_member\": {Tok: makeResource(mainMod, \"DirectoryRoleMember\")},\n\t\t\t\"azuread_app_role_assignment\": {Tok: makeResource(mainMod, \"AppRoleAssignment\")},\n\t\t\t\"azuread_administrative_unit\": {Tok: makeResource(mainMod, \"AdministrativeUnit\")},\n\t\t\t\"azuread_administrative_unit_member\": {Tok: makeResource(mainMod, \"AdministrativeUnitMember\")},\n\t\t\t\"azuread_application_federated_identity_credential\": {\n\t\t\t\tTok: makeResource(mainMod, \"ApplicationFederatedIdentityCredential\"),\n\t\t\t},\n\t\t\t\"azuread_custom_directory_role\": {Tok: makeResource(mainMod, \"CustomDirectoryRole\")},\n\t\t\t\"azuread_claims_mapping_policy\": {Tok: makeResource(mainMod, \"ClaimsMappingPolicy\")},\n\t\t\t\"azuread_directory_role_assignment\": {Tok: makeResource(mainMod, \"DirectoryRoleAssignment\")},\n\t\t\t\"azuread_service_principal_claims_mapping_policy_assignment\": {\n\t\t\t\tTok: makeResource(mainMod, \"ServicePrincipalClaimsMappingPolicyAssignment\"),\n\t\t\t},\n\t\t\t\"azuread_synchronization_job\": {Tok: makeResource(mainMod, \"SynchronizationJob\")},\n\t\t\t\"azuread_synchronization_secret\": {Tok: makeResource(mainMod, \"SynchronizationSecret\")},\n\t\t\t\"azuread_access_package\": {Tok: makeResource(mainMod, \"AccessPackage\")},\n\t\t\t\"azuread_access_package_assignment_policy\": {Tok: makeResource(mainMod, \"AccessPackageAssignmentPolicy\")},\n\t\t\t\"azuread_access_package_catalog\": {Tok: makeResource(mainMod, \"AccessPackageCatalog\")},\n\t\t\t\"azuread_access_package_resource_catalog_association\": {\n\t\t\t\tTok: makeResource(mainMod, \"AccessPackageResourceCatalogAssociation\"),\n\t\t\t},\n\t\t\t\"azuread_access_package_resource_package_association\": {\n\t\t\t\tTok: makeResource(mainMod, \"AccessPackageResourcePackageAssociation\"),\n\t\t\t},\n\t\t\t\"azuread_administrative_unit_role_member\": {Tok: makeResource(mainMod, \"AdministrativeUnitRoleMember\")},\n\t\t\t\"azuread_user_flow_attribute\": {Tok: makeResource(mainMod, \"UserFlowAttribute\")},\n\t\t},\n\t\tDataSources: map[string]*tfbridge.DataSourceInfo{\n\t\t\t\"azuread_client_config\": {Tok: makeDataSource(mainMod, \"getClientConfig\")},\n\t\t\t\"azuread_application_published_app_ids\": {Tok: makeDataSource(mainMod, \"getApplicationPublishedAppIds\")},\n\t\t\t\"azuread_application_template\": {Tok: makeDataSource(mainMod, \"getApplicationTemplate\")},\n\t\t\t\"azuread_service_principals\": {Tok: makeDataSource(mainMod, \"getServicePrincipals\")},\n\t\t\t\"azuread_administrative_unit\": {Tok: makeDataSource(mainMod, \"getAdministrativeUnit\")},\n\t\t\t\"azuread_directory_object\": {Tok: makeDataSource(mainMod, \"getDirectoryObject\")},\n\t\t\t\"azuread_directory_roles\": {Tok: makeDataSource(mainMod, \"getDirectoryRoles\")},\n\t\t\t\"azuread_access_package\": {Tok: makeDataSource(mainMod, \"getAccessPackage\")},\n\t\t\t\"azuread_access_package_catalog\": {Tok: makeDataSource(mainMod, \"getAccessPackageCatalog\")},\n\t\t},\n\t\tJavaScript: &tfbridge.JavaScriptInfo{\n\t\t\t// List any npm dependencies and their versions\n\t\t\tDependencies: map[string]string{\n\t\t\t\t\"@pulumi/pulumi\": \"^3.0.0\",\n\t\t\t},\n\t\t\tDevDependencies: map[string]string{\n\t\t\t\t\"@types/node\": \"^10.0.0\", // so we can access strongly typed node definitions.\n\t\t\t\t\"@types/mime\": \"^2.0.0\",\n\t\t\t},\n\t\t},\n\t\tPython: &tfbridge.PythonInfo{\n\t\t\tRequires: map[string]string{\n\t\t\t\t\"pulumi\": \">=3.0.0,<4.0.0\",\n\t\t\t},\n\t\t},\n\t\tGolang: &tfbridge.GolangInfo{\n\t\t\tImportBasePath: filepath.Join(\n\t\t\t\tfmt.Sprintf(\"github.com/pulumi/pulumi-%[1]s/sdk/\", mainPkg),\n\t\t\t\ttfbridge.GetModuleMajorVersion(version.Version),\n\t\t\t\t\"go\",\n\t\t\t\tmainPkg,\n\t\t\t),\n\t\t\tGenerateResourceContainerTypes: true,\n\t\t},\n\t\tCSharp: &tfbridge.CSharpInfo{\n\t\t\tPackageReferences: map[string]string{\n\t\t\t\t\"Pulumi\": \"3.*\",\n\t\t\t},\n\t\t\tNamespaces: map[string]string{\n\t\t\t\t\"azuread\": \"AzureAD\",\n\t\t\t},\n\t\t}, MetadataInfo: tfbridge.NewProviderMetadata(metadata),\n\t}\n\n\tprov.MustComputeTokens(tfbridgetokens.SingleModule(\"azuread_\", mainMod,\n\t\ttfbridgetokens.MakeStandard(mainPkg)))\n\tprov.SetAutonaming(255, \"-\")\n\tprov.MustApplyAutoAliases()\n\n\treturn prov\n}", "func (m *MockInfra) Region() string {\n\tret := m.ctrl.Call(m, \"Region\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func TestTimeoutToProviders(t *testing.T) {\n\tstart := time.Now()\n\n\tappCustom := App{\n\t\tContentProvider: NewContentProviderService(\n\t\t\tmap[Provider]Client{\n\t\t\t\tProvider1: SampleContentProvider{Source: Provider1},\n\t\t\t\tProvider2: SampleContentProvider{Source: Provider2},\n\t\t\t\tProvider3: &ClientMock{\n\t\t\t\t\tGetContentFn: func(userIP string, count int) ([]*ContentItem, error) {\n\t\t\t\t\t\t// let's imitate some pending request to provider\n\t\t\t\t\t\ttime.Sleep(5 * time.Second)\n\t\t\t\t\t\treturn []*ContentItem{{\n\t\t\t\t\t\t\tSource: \"3\",\n\t\t\t\t\t\t}}, nil\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tDefaultConfig,\n\t\t\tWithTimeOut(500*time.Millisecond),\n\t\t),\n\t}\n\n\tcontent := runRequest(t, appCustom, SimpleContentRequest)\n\tif len(content) != 4 {\n\t\tt.Fatalf(\"Got %d items back, want 4\", len(content))\n\t}\n\n\texecTime := time.Since(start)\n\tif execTime > time.Second {\n\t\tt.Fatalf(\"test time should be less then 1 second, got: %s\", execTime)\n\t}\n}", "func Test_provider_doTaskReporter(t *testing.T) {\n\tctrl := gomock.NewController(t)\n\tdefer ctrl.Finish()\n\tlogger := NewMockLogger(ctrl)\n\n\tlogger.EXPECT().Infof(\"begin do task report, taskID: %d\", uint64(1)).Return()\n\n\tvar (\n\t\tbdl *bundle.Bundle\n\t\tdbClient *dbclient.Client\n\t)\n\tmonkey.PatchInstanceMethod(reflect.TypeOf(bdl), \"PipelineCallback\",\n\t\tfunc(_ *bundle.Bundle, _ apistructs.PipelineCallbackRequest, openapiAddr, token string) error {\n\t\t\treturn nil\n\t\t})\n\tmonkey.PatchInstanceMethod(reflect.TypeOf(dbClient), \"GetPipelineTask\",\n\t\tfunc(_ *dbclient.Client, _ interface{}) (spec.PipelineTask, error) {\n\t\t\treturn spec.PipelineTask{ID: 1}, nil\n\t\t})\n\tdefer monkey.UnpatchAll()\n\n\ttype fields struct {\n\t\tbdl *bundle.Bundle\n\t\tdbClient *db.Client\n\t\tLog logs.Logger\n\t\tconfig *config\n\t}\n\ttype args struct {\n\t\tctx context.Context\n\t\ttaskID uint64\n\t}\n\ttests := []struct {\n\t\tname string\n\t\tfields fields\n\t\targs args\n\t\twantErr bool\n\t}{\n\t\t{\n\t\t\tname: \"test doTaskReporter\",\n\t\t\tfields: fields{\n\t\t\t\tbdl: bdl,\n\t\t\t\tdbClient: &db.Client{Client: dbClient},\n\t\t\t\tLog: logger,\n\t\t\t\tconfig: &config{},\n\t\t\t},\n\t\t\targs: args{\n\t\t\t\tctx: context.Background(),\n\t\t\t\ttaskID: 1,\n\t\t\t},\n\t\t\twantErr: false,\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tp := &provider{\n\t\t\t\tbdl: tt.fields.bdl,\n\t\t\t\tdbClient: tt.fields.dbClient,\n\t\t\t\tLog: tt.fields.Log,\n\t\t\t\tCfg: tt.fields.config,\n\t\t\t\tEdgeRegister: &edgepipeline_register.MockEdgeRegister{},\n\t\t\t}\n\t\t\tif err := p.doTaskReporter(tt.args.ctx, tt.args.taskID); (err != nil) != tt.wantErr {\n\t\t\t\tt.Errorf(\"doTaskReporter() error = %v, wantErr %v\", err, tt.wantErr)\n\t\t\t}\n\t\t})\n\t}\n}", "func (m *MockMachine) MainCollective() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"MainCollective\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func NewIdentityProviderBase()(*IdentityProviderBase) {\n m := &IdentityProviderBase{\n Entity: *NewEntity(),\n }\n return m\n}", "func (ts *Tester) Provider() string {\n\treturn \"eks\"\n}", "func (p *Provider) newGCPProviderSpec(windowsServerVersion windows.ServerVersion) (*mapi.GCPMachineProviderSpec, error) {\n\tlistOptions := meta.ListOptions{LabelSelector: \"machine.openshift.io/cluster-api-machine-role=worker\"}\n\tmachines, err := p.oc.Machine.Machines(clusterinfo.MachineAPINamespace).List(context.TODO(), listOptions)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(machines.Items) == 0 {\n\t\treturn nil, fmt.Errorf(\"found 0 worker role machines\")\n\t}\n\tfoundSpec := &mapi.GCPMachineProviderSpec{}\n\terr = json.Unmarshal(machines.Items[0].Spec.ProviderSpec.Value.Raw, foundSpec)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to unmarshal raw machine provider spec: %v\", err)\n\t}\n\n\treturn &mapi.GCPMachineProviderSpec{\n\t\tTypeMeta: meta.TypeMeta{\n\t\t\tAPIVersion: \"machine.openshift.io/v1beta1\",\n\t\t\tKind: \"GCPMachineProviderSpec\",\n\t\t},\n\t\tObjectMeta: meta.ObjectMeta{},\n\t\tUserDataSecret: &core.LocalObjectReference{\n\t\t\tName: clusterinfo.UserDataSecretName,\n\t\t},\n\t\tCredentialsSecret: &core.LocalObjectReference{\n\t\t\tName: foundSpec.CredentialsSecret.Name,\n\t\t},\n\t\tCanIPForward: false,\n\t\tDeletionProtection: false,\n\t\tDisks: []*mapi.GCPDisk{{\n\t\t\tAutoDelete: true,\n\t\t\tBoot: true,\n\t\t\tSizeGB: 128,\n\t\t\tType: \"pd-ssd\",\n\t\t\tImage: getImage(windowsServerVersion),\n\t\t}},\n\t\tNetworkInterfaces: foundSpec.NetworkInterfaces,\n\t\tServiceAccounts: foundSpec.ServiceAccounts,\n\t\tTags: foundSpec.Tags,\n\t\tMachineType: foundSpec.MachineType,\n\t\tRegion: foundSpec.Region,\n\t\tZone: foundSpec.Zone,\n\t\tProjectID: foundSpec.ProjectID,\n\t}, nil\n}", "func (m *MockBootstrapperProvider) String() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"String\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func (m *MockFileInfo) Sys() interface{} {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Sys\")\n\tret0, _ := ret[0].(interface{})\n\treturn ret0\n}", "func IgrenoreTestP2PServiceRunAddPeer(t *testing.T) {\n\tmockActor := new(MockActorService)\n\tdummyBlock := types.Block{Hash: dummyBlockHash, Header: &types.BlockHeader{BlockNo: dummyBlockHeight}}\n\tmockActor.On(\"CallRequest\", mock.Anything, mock.Anything).Return(message.GetBlockRsp{Block: &dummyBlock}, nil)\n\t//mockMF := new(MockMoFactory)\n\ttarget := &networkTransport{conf: config.NewServerContext(\"\", \"\").GetDefaultConfig().(*config.Config).P2P,\n\t\tlogger:log.NewLogger(\"test.p2p\") }\n\n\ttarget.Host = &mockHost{peerstore.NewPeerstore(pstoremem.NewKeyBook(), pstoremem.NewAddrBook(), pstoremem.NewPeerMetadata())}\n\ttarget.selfMeta.ID = peer.ID(\"gwegw\")\n\n\tsampleAddr1 := PeerMeta{ID: \"ddd\", IPAddress: \"192.168.0.1\", Port: 33888, Outbound: true}\n\tsampleAddr2 := PeerMeta{ID: \"fff\", IPAddress: \"192.168.0.2\", Port: 33888, Outbound: true}\n\ttarget.GetOrCreateStream(sampleAddr1, aergoP2PSub)\n\ttarget.GetOrCreateStream(sampleAddr1, aergoP2PSub)\n\ttime.Sleep(time.Second)\n\tif len(target.Peerstore().Peers()) != 1 {\n\t\tt.Errorf(\"Peer count : Expected %d, Actually %d\", 1, len(target.Peerstore().Peers()))\n\t}\n\ttarget.GetOrCreateStream(sampleAddr2, aergoP2PSub)\n\ttime.Sleep(time.Second * 1)\n\tif len(target.Peerstore().Peers()) != 2 {\n\t\tt.Errorf(\"Peer count : Expected %d, Actually %d\", 2, len(target.Peerstore().Peers()))\n\t}\n}", "func TestRestOfInternalCode(t *testing.T) {\n\n\t// In this case unit testing will not help as we need to actually corever\n\t// this package with test. Because real functions hide under internal structures\n\t// which we do not expose, so our previous approach will no longer works.\n\t// Well it works but coverage does not detect that we are testing actual\n\t// implementation\n\n\t// In order to cover this part we will need to either pretend that we are\n\t// testing something or create real integration tests and ensure that mongod\n\t// process is running. In my case I will just fake my testing and do not use\n\t// assert. This way my test will pass either way\n\n\t// Create database context. I use real database, but it is possible to mock\n\t// database and configuration through interfaces.\n\tconf := config.GetConfig()\n\tclient, _ := databases.NewClient(conf)\n\tclient.StartSession()\n\n\tdb := databases.NewDatabase(conf, client)\n\tclient.Connect()\n\tdb.Client()\n\tvar result interface{}\n\t// because we do not care for actual results, we just quickly timeout the\n\t// call and we use incorrect call method\n\ttimeoutCtx, _ := context.WithTimeout(context.Background(), 1*time.Microsecond)\n\tdb.Collection(\"non-fake-existing-collection\").FindOne(timeoutCtx, \"incorrect-value\").Decode(&result)\n\n\t// insert and delete functions seems to panic instead of returning and error.\n\t// I did not investigate anything in this case as this is not our main goal.\n\t// Just define assert panic function and use this panicing function in it.\n\tvar mongoPanics assert.PanicTestFunc\n\n\tmongoPanics = func() {\n\t\tdb.Collection(\"non-fake-existing-collection\").InsertOne(timeoutCtx, result)\n\t}\n\tassert.Panics(t, mongoPanics)\n\n\tmongoPanics = func() {\n\t\tdb.Collection(\"non-fake-existing-collection\").DeleteOne(timeoutCtx, result)\n\t}\n\tassert.Panics(t, mongoPanics)\n\n\t// And it is done. We do not need to have mongo running and our code is\n\t// covered 100%. Well the actual implementation is faked, but it should be\n\t// tested via integration tests, not unit tests.\n\n}", "func (m *MockAPI) HostMonitoring() {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"HostMonitoring\")\n}", "func providerConfigure(data *schema.ResourceData) (interface{}, error) {\n\tlog.Println(\"[INFO] Initializing Client\")\n\n\tconfig := Config{\n\t\tAPIKey: data.Get(\"api_key\").(string),\n\t\tAPIURL: data.Get(\"api_url\").(string),\n\t}\n\n\treturn config.Client()\n}", "func (m *MockProcessProvider) Provide() (Process, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Provide\")\n\tret0, _ := ret[0].(Process)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockProvider) OnEndpointsAdd(arg0 *v1.Endpoints) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"OnEndpointsAdd\", arg0)\n}", "func getProvider(id string) *provider {\n\tif mockGetProviderValue != nil {\n\t\treturn mockGetProviderValue\n\t}\n\tp, _ := auth.GetProviderByConfigID(auth.ProviderConfigID{Type: providerType, ID: id}).(*provider)\n\treturn p\n}", "func (a *Application) RegisterProvider() {\n\n}", "func Provider() tfbridge.ProviderInfo {\n\t// Instantiate the Terraform provider\n\tp := shimv2.NewProvider(xyz.Provider())\n\n\t// Create a Pulumi provider mapping\n\tprov := tfbridge.ProviderInfo{\n\t\tP: p,\n\t\tName: \"xyz\",\n\t\t// DisplayName is a way to be able to change the casing of the provider\n\t\t// name when being displayed on the Pulumi registry\n\t\tDisplayName: \"\",\n\t\t// The default publisher for all packages is Pulumi.\n\t\t// Change this to your personal name (or a company name) that you\n\t\t// would like to be shown in the Pulumi Registry if this package is published\n\t\t// there.\n\t\tPublisher: \"Pulumi\",\n\t\t// LogoURL is optional but useful to help identify your package in the Pulumi Registry\n\t\t// if this package is published there.\n\t\t//\n\t\t// You may host a logo on a domain you control or add an SVG logo for your package\n\t\t// in your repository and use the raw content URL for that file as your logo URL.\n\t\tLogoURL: \"\",\n\t\t// PluginDownloadURL is an optional URL used to download the Provider\n\t\t// for use in Pulumi programs\n\t\t// e.g https://github.com/org/pulumi-provider-name/releases/\n\t\tPluginDownloadURL: \"\",\n\t\tDescription: \"A Pulumi package for creating and managing xyz cloud resources.\",\n\t\t// category/cloud tag helps with categorizing the package in the Pulumi Registry.\n\t\t// For all available categories, see `Keywords` in\n\t\t// https://www.pulumi.com/docs/guides/pulumi-packages/schema/#package.\n\t\tKeywords: []string{\"pulumi\", \"xyz\", \"category/cloud\"},\n\t\tLicense: \"Apache-2.0\",\n\t\tHomepage: \"https://www.pulumi.com\",\n\t\tRepository: \"https://github.com/pulumi/pulumi-xyz\",\n\t\t// The GitHub Org for the provider - defaults to `terraform-providers`. Note that this\n\t\t// should match the TF provider module's require directive, not any replace directives.\n\t\tGitHubOrg: \"\",\n\t\tConfig: map[string]*tfbridge.SchemaInfo{\n\t\t\t// Add any required configuration here, or remove the example below if\n\t\t\t// no additional points are required.\n\t\t\t// \"region\": {\n\t\t\t// \tType: tfbridge.MakeType(\"region\", \"Region\"),\n\t\t\t// \tDefault: &tfbridge.DefaultInfo{\n\t\t\t// \t\tEnvVars: []string{\"AWS_REGION\", \"AWS_DEFAULT_REGION\"},\n\t\t\t// \t},\n\t\t\t// },\n\t\t},\n\t\tPreConfigureCallback: preConfigureCallback,\n\t\tResources: map[string]*tfbridge.ResourceInfo{\n\t\t\t// Map each resource in the Terraform provider to a Pulumi type. Two examples\n\t\t\t// are below - the single line form is the common case. The multi-line form is\n\t\t\t// needed only if you wish to override types or other default options.\n\t\t\t//\n\t\t\t// \"aws_iam_role\": {Tok: tfbridge.MakeResource(mainPkg, mainMod, \"IamRole\")}\n\t\t\t//\n\t\t\t// \"aws_acm_certificate\": {\n\t\t\t// \tTok: tfbridge.MakeResource(mainPkg, mainMod, \"Certificate\"),\n\t\t\t// \tFields: map[string]*tfbridge.SchemaInfo{\n\t\t\t// \t\t\"tags\": {Type: tfbridge.MakeType(mainPkg, \"Tags\")},\n\t\t\t// \t},\n\t\t\t// },\n\t\t},\n\t\tDataSources: map[string]*tfbridge.DataSourceInfo{\n\t\t\t// Map each resource in the Terraform provider to a Pulumi function. An example\n\t\t\t// is below.\n\t\t\t// \"aws_ami\": {Tok: tfbridge.MakeDataSource(mainPkg, mainMod, \"getAmi\")},\n\t\t},\n\t\tJavaScript: &tfbridge.JavaScriptInfo{\n\t\t\t// List any npm dependencies and their versions\n\t\t\tDependencies: map[string]string{\n\t\t\t\t\"@pulumi/pulumi\": \"^3.0.0\",\n\t\t\t},\n\t\t\tDevDependencies: map[string]string{\n\t\t\t\t\"@types/node\": \"^10.0.0\", // so we can access strongly typed node definitions.\n\t\t\t\t\"@types/mime\": \"^2.0.0\",\n\t\t\t},\n\t\t\t// See the documentation for tfbridge.OverlayInfo for how to lay out this\n\t\t\t// section, or refer to the AWS provider. Delete this section if there are\n\t\t\t// no overlay files.\n\t\t\t//Overlay: &tfbridge.OverlayInfo{},\n\t\t},\n\t\tPython: &tfbridge.PythonInfo{\n\t\t\t// List any Python dependencies and their version ranges\n\t\t\tRequires: map[string]string{\n\t\t\t\t\"pulumi\": \">=3.0.0,<4.0.0\",\n\t\t\t},\n\t\t},\n\t\tGolang: &tfbridge.GolangInfo{\n\t\t\tImportBasePath: filepath.Join(\n\t\t\t\tfmt.Sprintf(\"github.com/pulumi/pulumi-%[1]s/sdk/\", mainPkg),\n\t\t\t\ttfbridge.GetModuleMajorVersion(version.Version),\n\t\t\t\t\"go\",\n\t\t\t\tmainPkg,\n\t\t\t),\n\t\t\tGenerateResourceContainerTypes: true,\n\t\t},\n\t\tCSharp: &tfbridge.CSharpInfo{\n\t\t\tPackageReferences: map[string]string{\n\t\t\t\t\"Pulumi\": \"3.*\",\n\t\t\t},\n\t\t},\n\t}\n\n\t// These are new API's that you may opt to use to automatically compute resource tokens,\n\t// and apply auto aliasing for full backwards compatibility.\n\t// For more information, please reference: https://pkg.go.dev/github.com/pulumi/pulumi-terraform-bridge/v3/pkg/tfbridge#ProviderInfo.ComputeTokens\n\tprov.MustComputeTokens(tokens.SingleModule(\"xyz_\", mainMod,\n\t\ttokens.MakeStandard(mainPkg)))\n\tprov.MustApplyAutoAliasing()\n\tprov.SetAutonaming(255, \"-\")\n\n\treturn prov\n}", "func ToMockProvider(p goth.Provider) *MockProvider {\n\treturn p.(*MockProvider)\n}", "func (m *MockCandidatePropertyGetter) Cloudprovider() *models.SCloudprovider {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Cloudprovider\")\n\tret0, _ := ret[0].(*models.SCloudprovider)\n\treturn ret0\n}", "func (m *MockisCryptoApiRequest_CryptoApiReq) isCryptoApiRequest_CryptoApiReq() {\n\tm.ctrl.Call(m, \"isCryptoApiRequest_CryptoApiReq\")\n}", "func (m *MockProvider) OnServiceSynced() {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"OnServiceSynced\")\n}", "func SetupProvider(mgr ctrl.Manager, o controller.Options) error {\n\tname := \"packages/\" + strings.ToLower(v1.ProviderGroupKind)\n\tnp := func() v1.Package { return &v1.Provider{} }\n\tnr := func() v1.PackageRevision { return &v1.ProviderRevision{} }\n\tnrl := func() v1.PackageRevisionList { return &v1.ProviderRevisionList{} }\n\n\tcs, err := kubernetes.NewForConfig(mgr.GetConfig())\n\tif err != nil {\n\t\treturn errors.Wrap(err, errCreateK8sClient)\n\t}\n\tf, err := xpkg.NewK8sFetcher(cs, append(o.FetcherOptions, xpkg.WithNamespace(o.Namespace), xpkg.WithServiceAccount(o.ServiceAccount))...)\n\tif err != nil {\n\t\treturn errors.Wrap(err, errBuildFetcher)\n\t}\n\n\topts := []ReconcilerOption{\n\t\tWithNewPackageFn(np),\n\t\tWithNewPackageRevisionFn(nr),\n\t\tWithNewPackageRevisionListFn(nrl),\n\t\tWithRevisioner(NewPackageRevisioner(f, WithDefaultRegistry(o.DefaultRegistry))),\n\t\tWithLogger(o.Logger.WithValues(\"controller\", name)),\n\t\tWithRecorder(event.NewAPIRecorder(mgr.GetEventRecorderFor(name))),\n\t}\n\tif o.WebhookTLSSecretName != \"\" {\n\t\topts = append(opts, WithWebhookTLSSecretName(o.WebhookTLSSecretName))\n\t}\n\tif o.ESSOptions != nil && o.ESSOptions.TLSSecretName != nil {\n\t\topts = append(opts, WithESSTLSSecretName(o.ESSOptions.TLSSecretName))\n\t}\n\tif o.TLSServerSecretName != \"\" {\n\t\topts = append(opts, WithTLSServerSecretName(&o.TLSServerSecretName))\n\t}\n\tif o.TLSClientSecretName != \"\" {\n\t\topts = append(opts, WithTLSClientSecretName(&o.TLSClientSecretName))\n\t}\n\n\treturn ctrl.NewControllerManagedBy(mgr).\n\t\tNamed(name).\n\t\tFor(&v1.Provider{}).\n\t\tOwns(&v1.ProviderRevision{}).\n\t\tWithOptions(o.ForControllerRuntime()).\n\t\tComplete(ratelimiter.NewReconciler(name, NewReconciler(mgr, opts...), o.GlobalRateLimiter))\n}", "func (m *MockEnvironment) Fetch() map[string]interface{} {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Fetch\")\n\tret0, _ := ret[0].(map[string]interface{})\n\treturn ret0\n}", "func NewMockInterfaceProvider(managedInterfacesRegexp string, autoRefresh bool) (nt.InterfaceProvider,\n\tchan time.Time, error) {\n\tch := make(chan time.Time)\n\tip, err := nt.NewChanInterfaceProvider(ch, &MockInterfaceLister{}, managedInterfacesRegexp,\n\t\tautoRefresh)\n\treturn ip, ch, err\n}", "func (m *MockClusterScoper) BaseURI() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"BaseURI\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func (m *MockisCryptoApiResponse_CryptoApiResp) isCryptoApiResponse_CryptoApiResp() {\n\tm.ctrl.Call(m, \"isCryptoApiResponse_CryptoApiResp\")\n}", "func (m *MockProviderClient) Configure(arg0 context.Context, arg1 *tfplugin5.Configure_Request, arg2 ...grpc.CallOption) (*tfplugin5.Configure_Response, error) {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{arg0, arg1}\n\tfor _, a := range arg2 {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"Configure\", varargs...)\n\tret0, _ := ret[0].(*tfplugin5.Configure_Response)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (p *TestProvider) Provide(addr string) Client {\n\tc, ok := p.clients[addr]\n\tif !ok {\n\t\tlog.Panicf(\"addr %s not found\", addr)\n\t}\n\treturn c\n}", "func TestingBase(c context.Context) Base {\n\treturn func(h Handler) httprouter.Handle {\n\t\treturn func(rw http.ResponseWriter, r *http.Request, p httprouter.Params) {\n\t\t\th(c, rw, r, p)\n\t\t}\n\t}\n}", "func (m *MockSystemContract) Exec() error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Exec\")\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockClient) ForPlugin(plugin string) github.Client {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ForPlugin\", plugin)\n\tret0, _ := ret[0].(github.Client)\n\treturn ret0\n}", "func (m *MockSystemContract) Init(arg0 core.Keepers, arg1 types1.BaseTx, arg2 uint64) core.SystemContract {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Init\", arg0, arg1, arg2)\n\tret0, _ := ret[0].(core.SystemContract)\n\treturn ret0\n}", "func (m *MockBootstrapperProvider) EXPECT() *MockBootstrapperProviderMockRecorder {\n\treturn m.recorder\n}", "func Provider() terraform.ResourceProvider {\n\tvar p *schema.Provider\n\tp = &schema.Provider{\n\t\tSchema: map[string]*schema.Schema{\n\t\t\t\"subscription_id\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"ARM_SUBSCRIPTION_ID\", \"\"),\n\t\t\t},\n\n\t\t\t\"client_id\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"ARM_CLIENT_ID\", \"\"),\n\t\t\t},\n\n\t\t\t\"client_secret\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"ARM_CLIENT_SECRET\", \"\"),\n\t\t\t},\n\n\t\t\t\"tenant_id\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"ARM_TENANT_ID\", \"\"),\n\t\t\t},\n\n\t\t\t\"environment\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"ARM_ENVIRONMENT\", \"public\"),\n\t\t\t},\n\n\t\t\t\"skip_provider_registration\": {\n\t\t\t\tType: schema.TypeBool,\n\t\t\t\tOptional: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"ARM_SKIP_PROVIDER_REGISTRATION\", false),\n\t\t\t},\n\t\t},\n\n\t\tDataSourcesMap: map[string]*schema.Resource{\n\t\t\t\"azurerm_client_config\": dataSourceArmClientConfig(),\n\t\t},\n\n\t\tResourcesMap: map[string]*schema.Resource{\n\t\t\t// These resources use the Azure ARM SDK\n\t\t\t\"azurerm_availability_set\": resourceArmAvailabilitySet(),\n\t\t\t\"azurerm_cdn_endpoint\": resourceArmCdnEndpoint(),\n\t\t\t\"azurerm_cdn_profile\": resourceArmCdnProfile(),\n\t\t\t\"azurerm_container_registry\": resourceArmContainerRegistry(),\n\t\t\t\"azurerm_container_service\": resourceArmContainerService(),\n\n\t\t\t\"azurerm_eventhub\": resourceArmEventHub(),\n\t\t\t\"azurerm_eventhub_authorization_rule\": resourceArmEventHubAuthorizationRule(),\n\t\t\t\"azurerm_eventhub_consumer_group\": resourceArmEventHubConsumerGroup(),\n\t\t\t\"azurerm_eventhub_namespace\": resourceArmEventHubNamespace(),\n\n\t\t\t\"azurerm_lb\": resourceArmLoadBalancer(),\n\t\t\t\"azurerm_lb_backend_address_pool\": resourceArmLoadBalancerBackendAddressPool(),\n\t\t\t\"azurerm_lb_nat_rule\": resourceArmLoadBalancerNatRule(),\n\t\t\t\"azurerm_lb_nat_pool\": resourceArmLoadBalancerNatPool(),\n\t\t\t\"azurerm_lb_probe\": resourceArmLoadBalancerProbe(),\n\t\t\t\"azurerm_lb_rule\": resourceArmLoadBalancerRule(),\n\n\t\t\t\"azurerm_managed_disk\": resourceArmManagedDisk(),\n\n\t\t\t\"azurerm_key_vault\": resourceArmKeyVault(),\n\t\t\t\"azurerm_local_network_gateway\": resourceArmLocalNetworkGateway(),\n\t\t\t\"azurerm_network_interface\": resourceArmNetworkInterface(),\n\t\t\t\"azurerm_network_security_group\": resourceArmNetworkSecurityGroup(),\n\t\t\t\"azurerm_network_security_rule\": resourceArmNetworkSecurityRule(),\n\t\t\t\"azurerm_public_ip\": resourceArmPublicIp(),\n\t\t\t\"azurerm_redis_cache\": resourceArmRedisCache(),\n\t\t\t\"azurerm_route\": resourceArmRoute(),\n\t\t\t\"azurerm_route_table\": resourceArmRouteTable(),\n\t\t\t\"azurerm_servicebus_namespace\": resourceArmServiceBusNamespace(),\n\t\t\t\"azurerm_servicebus_subscription\": resourceArmServiceBusSubscription(),\n\t\t\t\"azurerm_servicebus_topic\": resourceArmServiceBusTopic(),\n\t\t\t\"azurerm_storage_account\": resourceArmStorageAccount(),\n\t\t\t\"azurerm_storage_blob\": resourceArmStorageBlob(),\n\t\t\t\"azurerm_storage_container\": resourceArmStorageContainer(),\n\t\t\t\"azurerm_storage_share\": resourceArmStorageShare(),\n\t\t\t\"azurerm_storage_queue\": resourceArmStorageQueue(),\n\t\t\t\"azurerm_storage_table\": resourceArmStorageTable(),\n\t\t\t\"azurerm_subnet\": resourceArmSubnet(),\n\t\t\t\"azurerm_template_deployment\": resourceArmTemplateDeployment(),\n\t\t\t\"azurerm_traffic_manager_endpoint\": resourceArmTrafficManagerEndpoint(),\n\t\t\t\"azurerm_traffic_manager_profile\": resourceArmTrafficManagerProfile(),\n\t\t\t\"azurerm_virtual_machine_extension\": resourceArmVirtualMachineExtensions(),\n\t\t\t\"azurerm_virtual_machine\": resourceArmVirtualMachine(),\n\t\t\t\"azurerm_virtual_machine_scale_set\": resourceArmVirtualMachineScaleSet(),\n\t\t\t\"azurerm_virtual_network\": resourceArmVirtualNetwork(),\n\t\t\t\"azurerm_virtual_network_peering\": resourceArmVirtualNetworkPeering(),\n\n\t\t\t// These resources use the Riviera SDK\n\t\t\t\"azurerm_dns_a_record\": resourceArmDnsARecord(),\n\t\t\t\"azurerm_dns_aaaa_record\": resourceArmDnsAAAARecord(),\n\t\t\t\"azurerm_dns_cname_record\": resourceArmDnsCNameRecord(),\n\t\t\t\"azurerm_dns_mx_record\": resourceArmDnsMxRecord(),\n\t\t\t\"azurerm_dns_ns_record\": resourceArmDnsNsRecord(),\n\t\t\t\"azurerm_dns_srv_record\": resourceArmDnsSrvRecord(),\n\t\t\t\"azurerm_dns_txt_record\": resourceArmDnsTxtRecord(),\n\t\t\t\"azurerm_dns_zone\": resourceArmDnsZone(),\n\t\t\t\"azurerm_resource_group\": resourceArmResourceGroup(),\n\t\t\t\"azurerm_search_service\": resourceArmSearchService(),\n\t\t\t\"azurerm_sql_database\": resourceArmSqlDatabase(),\n\t\t\t\"azurerm_sql_firewall_rule\": resourceArmSqlFirewallRule(),\n\t\t\t\"azurerm_sql_server\": resourceArmSqlServer(),\n\t\t},\n\t}\n\n\tp.ConfigureFunc = providerConfigure(p)\n\n\treturn p\n}", "func (m *MockRepo) Host() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Host\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func (m *MockrepoProvider) EXPECT() *MockrepoProviderMockRecorder {\n\treturn m.recorder\n}", "func (m *MockLocalConfigProvider) GetApplication() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetApplication\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func TestTrunkENI_CreateAndAssociateBranchENIs(t *testing.T) {\n\tctrl := gomock.NewController(t)\n\tdefer ctrl.Finish()\n\n\ttrunkENI, mockEC2APIHelper, mockInstance := getMockHelperInstanceAndTrunkObject(ctrl)\n\ttrunkENI.trunkENIId = trunkId\n\n\tmockInstance.EXPECT().Type().Return(InstanceType)\n\tmockInstance.EXPECT().SubnetID().Return(SubnetId).Times(2)\n\tmockInstance.EXPECT().SubnetCidrBlock().Return(SubnetCidrBlock).Times(2)\n\n\tmockEC2APIHelper.EXPECT().CreateNetworkInterface(&BranchEniDescription, &SubnetId, SecurityGroups,\n\t\tvlan1Tag, 0, nil).Return(BranchInterface1, nil)\n\tmockEC2APIHelper.EXPECT().AssociateBranchToTrunk(&trunkId, &Branch1Id, VlanId1).Return(nil, nil)\n\tmockEC2APIHelper.EXPECT().CreateNetworkInterface(&BranchEniDescription, &SubnetId, SecurityGroups, vlan2Tag,\n\t\t0, nil).Return(BranchInterface2, nil)\n\tmockEC2APIHelper.EXPECT().AssociateBranchToTrunk(&trunkId, &Branch2Id, VlanId2).Return(nil, nil)\n\n\teniDetails, err := trunkENI.CreateAndAssociateBranchENIs(MockPod2, SecurityGroups, 2)\n\texpectedENIDetails := []*ENIDetails{EniDetails1, EniDetails2}\n\n\tassert.NoError(t, err)\n\t// VLan ID are marked as used\n\tassert.True(t, trunkENI.usedVlanIds[VlanId1])\n\tassert.True(t, trunkENI.usedVlanIds[VlanId2])\n\t// The returned content is as expected\n\tassert.Equal(t, expectedENIDetails, eniDetails)\n\tassert.Equal(t, expectedENIDetails, trunkENI.uidToBranchENIMap[PodUID2])\n}", "func (m *MockUnsafeTodoServiceServer) mustEmbedUnimplementedTodoServiceServer() {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"mustEmbedUnimplementedTodoServiceServer\")\n}", "func (_m *MockEncoderPool) Init(alloc EncoderAllocate) {\n\t_m.ctrl.Call(_m, \"Init\", alloc)\n}", "func testSetup(t *testing.T) (ins c.Instance, loc *time.Location, appCfg c.AppConfig) {\n\n\tins = mock.Instance{\n\t\tApp: \"myapp\",\n\t\tAccount: \"prod\",\n\t\tStack: \"mystack\",\n\t\tCluster: \"mycluster\",\n\t\tRegion: \"us-east-1\",\n\t\tASG: \"myapp-mystack-mycluster-V123\",\n\t\tInstanceID: \"i-a96a0166\",\n\t}\n\n\tloc, err := time.LoadLocation(\"America/Los_Angeles\")\n\tif err != nil {\n\t\tt.Fatalf(err.Error())\n\t}\n\n\tappCfg = c.AppConfig{\n\t\tEnabled: true,\n\t\tRegionsAreIndependent: true,\n\t\tMeanTimeBetweenKillsInWorkDays: 5,\n\t\tMinTimeBetweenKillsInWorkDays: 1,\n\t\tGrouping: c.Cluster,\n\t\tExceptions: nil,\n\t}\n\n\treturn\n\n}", "func (p *ProviderConfig) GetProviderCloudSpec(providerName string, datacenter string, routerID string) *models.CloudSpec {\n\tcs := &models.CloudSpec{\n\t\tDatacenterName: datacenter,\n\t}\n\n\tproviderAlibaba, ok := p.Alibaba[providerName]\n\tif ok {\n\t\tcs.Alibaba = providerAlibaba\n\t}\n\tproviderAnexia, ok := p.Anexia[providerName]\n\tif ok {\n\t\tcs.Anexia = providerAnexia\n\t}\n\tproviderAws, ok := p.Aws[providerName]\n\tif ok {\n\t\tcs.Aws = providerAws\n\t}\n\tproviderAzure, ok := p.Azure[providerName]\n\tif ok {\n\t\tcs.Azure = providerAzure\n\t}\n\tproviderDigitalocean, ok := p.Digitalocean[providerName]\n\tif ok {\n\t\tcs.Digitalocean = providerDigitalocean\n\t}\n\tproviderFake, ok := p.Fake[providerName]\n\tif ok {\n\t\tcs.Fake = providerFake\n\t}\n\tproviderGcp, ok := p.Gcp[providerName]\n\tif ok {\n\t\tcs.Gcp = providerGcp\n\t}\n\tproviderHetzner, ok := p.Hetzner[providerName]\n\tif ok {\n\t\tcs.Hetzner = providerHetzner\n\t}\n\tproviderKubevirt, ok := p.Kubevirt[providerName]\n\tif ok {\n\t\tcs.Kubevirt = providerKubevirt\n\t}\n\tproviderOpenstack, ok := p.Openstack[providerName]\n\tif ok {\n\t\tcs.Openstack = providerOpenstack\n\t\tcs.Openstack.RouterID = routerID\n\t}\n\tproviderPacket, ok := p.Packet[providerName]\n\tif ok {\n\t\tcs.Packet = providerPacket\n\t}\n\tproviderVsphere, ok := p.Vsphere[providerName]\n\tif ok {\n\t\tcs.Vsphere = providerVsphere\n\t}\n\n\treturn cs\n}", "func NewFakeProvider(t *testing.T) *FakeProvider {\n\tbuilder := chain.NewBuilder(t, address.Address{})\n\treturn &FakeProvider{\n\t\tBuilder: builder,\n\t\tt: t,\n\t\tactors: make(map[address.Address]*types.Actor)}\n}", "func (m *MockProvider) GetEntrecote(weight int) (int, error) {\n\tret := m.ctrl.Call(m, \"GetEntrecote\", weight)\n\tret0, _ := ret[0].(int)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockClusterDescriber) BaseURI() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"BaseURI\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func initTestCase(f *framework.Framework, c clientset.Interface, pvConfig framework.PersistentVolumeConfig, pvcConfig framework.PersistentVolumeClaimConfig, ns, nodeName string) (*v1.Pod, *v1.PersistentVolume, *v1.PersistentVolumeClaim) {\n\tpv, pvc, err := framework.CreatePVPVC(c, pvConfig, pvcConfig, ns, false)\n\tdefer func() {\n\t\tif err != nil {\n\t\t\tframework.DeletePersistentVolumeClaim(c, pvc.Name, ns)\n\t\t\tframework.DeletePersistentVolume(c, pv.Name)\n\t\t}\n\t}()\n\tExpect(err).NotTo(HaveOccurred())\n\tpod := framework.MakePod(ns, []*v1.PersistentVolumeClaim{pvc}, true, \"\")\n\tpod.Spec.NodeName = nodeName\n\tframework.Logf(\"Creating NFS client pod.\")\n\tpod, err = c.CoreV1().Pods(ns).Create(pod)\n\tframework.Logf(\"NFS client Pod %q created on Node %q\", pod.Name, nodeName)\n\tExpect(err).NotTo(HaveOccurred())\n\tdefer func() {\n\t\tif err != nil {\n\t\t\tframework.DeletePodWithWait(f, c, pod)\n\t\t}\n\t}()\n\terr = framework.WaitForPodRunningInNamespace(c, pod)\n\tExpect(err).NotTo(HaveOccurred(), fmt.Sprintf(\"Pod %q timed out waiting for phase: Running\", pod.Name))\n\t// Return created api objects\n\tpod, err = c.CoreV1().Pods(ns).Get(pod.Name, metav1.GetOptions{})\n\tExpect(err).NotTo(HaveOccurred())\n\tpvc, err = c.CoreV1().PersistentVolumeClaims(ns).Get(pvc.Name, metav1.GetOptions{})\n\tExpect(err).NotTo(HaveOccurred())\n\tpv, err = c.CoreV1().PersistentVolumes().Get(pv.Name, metav1.GetOptions{})\n\tExpect(err).NotTo(HaveOccurred())\n\treturn pod, pv, pvc\n}", "func (m *MockProvider) Run(arg0 <-chan struct{}) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"Run\", arg0)\n}", "func (m *MockProvider) Service(arg0 string) (interface{}, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Service\", arg0)\n\tret0, _ := ret[0].(interface{})\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func newProviderImpl(name string) (Provider, error) {\n\tif name == LOCAL {\n\t\treturn &LocalProvider{}, nil\n\t}\n\n\tif name == AWS {\n\t\treturn &AwsProvider{}, nil\n\t}\n\n\treturn nil, errors.New(fmt.Sprintf(\"Provider '%s' doesn't exist\", name))\n}", "func TestNewBeerService_ReturnsBeerInteractor(t *testing.T) {\n\tt.Parallel()\n\tinteractor := &mocks.BeerInteractor{}\n\tassert.NotNil(t, adapters.NewBeerService(interactor))\n}", "func TestInternalFritzAPI(t *testing.T) {\n\ttestCases := []struct {\n\t\ttc func(t *testing.T, internal Internal)\n\t}{\n\t\t{testListLanDevices},\n\t\t{testListLogs},\n\t\t{testInetStats},\n\t\t{testBoxInfo},\n\t}\n\tfor _, testCase := range testCases {\n\t\tt.Run(fmt.Sprintf(\"Test aha api %s\", runtime.FuncForPC(reflect.ValueOf(testCase.tc).Pointer()).Name()), func(t *testing.T) {\n\t\t\tsrv := mock.New().Start()\n\t\t\tdefer srv.Close()\n\t\t\tinternal := setUpClient(t, srv)\n\t\t\tassert.NotNil(t, internal)\n\t\t\ttestCase.tc(t, internal)\n\t\t})\n\t}\n}", "func (_m *AppFunctionContext) PushToCore(event dtos.Event) (common.BaseWithIdResponse, error) {\n\tret := _m.Called(event)\n\n\tvar r0 common.BaseWithIdResponse\n\tif rf, ok := ret.Get(0).(func(dtos.Event) common.BaseWithIdResponse); ok {\n\t\tr0 = rf(event)\n\t} else {\n\t\tr0 = ret.Get(0).(common.BaseWithIdResponse)\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(dtos.Event) error); ok {\n\t\tr1 = rf(event)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (m *MockAuthorizer) CloudEnvironment() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"CloudEnvironment\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func (m *MockHandler) SendInfraEnvEvent(ctx context.Context, event InfraEnvEvent) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"SendInfraEnvEvent\", ctx, event)\n}", "func newKeyServerWithMocking(user upspin.UserName, ref string, data []byte) (*server, *storagetest.ExpectDownloadCapturePut) {\n\tmockGCP := &storagetest.ExpectDownloadCapturePut{\n\t\tRef: []string{ref},\n\t\tData: [][]byte{data},\n\t\tPutContents: make([][]byte, 0, 1),\n\t\tPutRef: make([]string, 0, 1),\n\t}\n\ts := &server{\n\t\tstorage: mockGCP,\n\t\tuser: user,\n\t\tlookupTXT: mockLookupTXT,\n\t\tlogger: &noopLogger{},\n\t\tcache: cache.NewLRU(10),\n\t\tnegCache: cache.NewLRU(10),\n\t}\n\treturn s, mockGCP\n}", "func (m *MockProvider) OnServiceAdd(arg0 *v1.Service) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"OnServiceAdd\", arg0)\n}", "func (m *MockProcessOptions) TopologyMapProvider() topology.MapProvider {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"TopologyMapProvider\")\n\tret0, _ := ret[0].(topology.MapProvider)\n\treturn ret0\n}", "func (achieveRepo *mockAchieveRepo) Initialize(ctx context.Context, db *sql.DB) {}", "func (m *MockManagedClusterScoper) BaseURI() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"BaseURI\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func (m *MockProviderManager) GetProviders(arg0 string) ([]*resource.ResourceProvider, error) {\n\tret := m.ctrl.Call(m, \"GetProviders\", arg0)\n\tret0, _ := ret[0].([]*resource.ResourceProvider)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockClient) LocalDiscoveryProvider() fab.LocalDiscoveryProvider {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"LocalDiscoveryProvider\")\n\tret0, _ := ret[0].(fab.LocalDiscoveryProvider)\n\treturn ret0\n}", "func (m *MockPrompt) forPlatformType() (string, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"forPlatformType\")\n\tret0, _ := ret[0].(string)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func Provider() terraform.ResourceProvider {\n\treturn &schema.Provider{\n\t\tSchema: map[string]*schema.Schema{\n\t\t\t\"public_key\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"UCLOUD_PUBLIC_KEY\", nil),\n\t\t\t\tDescription: descriptions[\"public_key\"],\n\t\t\t},\n\n\t\t\t\"private_key\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"UCLOUD_PRIVATE_KEY\", nil),\n\t\t\t\tDescription: descriptions[\"private_key\"],\n\t\t\t},\n\n\t\t\t\"region\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"UCLOUD_REGION\", nil),\n\t\t\t\tDescription: descriptions[\"region\"],\n\t\t\t},\n\n\t\t\t\"project_id\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"UCLOUD_PROJECT_ID\", nil),\n\t\t\t\tDescription: descriptions[\"project_id\"],\n\t\t\t},\n\n\t\t\t\"max_retries\": {\n\t\t\t\tType: schema.TypeInt,\n\t\t\t\tOptional: true,\n\t\t\t\tDefault: DefaultMaxRetries,\n\t\t\t\tDescription: descriptions[\"max_retries\"],\n\t\t\t},\n\n\t\t\t\"insecure\": {\n\t\t\t\tType: schema.TypeBool,\n\t\t\t\tOptional: true,\n\t\t\t\tDefault: DefaultInSecure,\n\t\t\t\tDescription: descriptions[\"insecure\"],\n\t\t\t},\n\t\t},\n\n\t\tDataSourcesMap: map[string]*schema.Resource{\n\t\t\t\"ucloud_instances\": dataSourceUCloudInstances(),\n\t\t\t\"ucloud_projects\": dataSourceUCloudProjects(),\n\t\t\t\"ucloud_images\": dataSourceUCloudImages(),\n\t\t\t\"ucloud_zones\": dataSourceUCloudZones(),\n\t\t\t\"ucloud_eips\": dataSourceUCloudEips(),\n\t\t},\n\t\tResourcesMap: map[string]*schema.Resource{\n\t\t\t\"ucloud_instance\": resourceUCloudInstance(),\n\t\t\t\"ucloud_eip\": resourceUCloudEIP(),\n\t\t\t\"ucloud_eip_association\": resourceUCloudEIPAssociation(),\n\t\t\t\"ucloud_vpc\": resourceUCloudVPC(),\n\t\t\t\"ucloud_subnet\": resourceUCloudSubnet(),\n\t\t\t\"ucloud_vpc_peering_connection\": resourceUCloudVPCPeeringConnection(),\n\t\t\t\"ucloud_lb\": resourceUCloudLB(),\n\t\t\t\"ucloud_lb_listener\": resourceUCloudLBListener(),\n\t\t\t\"ucloud_lb_attachment\": resourceUCloudLBAttachment(),\n\t\t\t\"ucloud_lb_rule\": resourceUCloudLBRule(),\n\t\t\t\"ucloud_disk\": resourceUCloudDisk(),\n\t\t\t\"ucloud_disk_attachment\": resourceUCloudDiskAttachment(),\n\t\t\t\"ucloud_security_group\": resourceUCloudSecurityGroup(),\n\t\t},\n\t\tConfigureFunc: providerConfigure,\n\t}\n}", "func (m *MockisKey_KeyInfo) isKey_KeyInfo() {\n\tm.ctrl.Call(m, \"isKey_KeyInfo\")\n}" ]
[ "0.680102", "0.61172336", "0.5651182", "0.5620679", "0.5540909", "0.5528276", "0.54399544", "0.53394455", "0.53289324", "0.5326502", "0.53053826", "0.5295907", "0.5289515", "0.52590674", "0.5251287", "0.5249962", "0.52412957", "0.52379525", "0.51799697", "0.51713246", "0.5155932", "0.5145608", "0.5144195", "0.5138", "0.51276004", "0.5097182", "0.50903016", "0.5087548", "0.5068389", "0.50678015", "0.50607324", "0.50512064", "0.5048093", "0.50399464", "0.503411", "0.50300765", "0.5018892", "0.501024", "0.5010031", "0.4997261", "0.49823028", "0.49766088", "0.49665582", "0.49597958", "0.4956144", "0.4955618", "0.49500763", "0.49493417", "0.4949065", "0.49489698", "0.49472514", "0.49424955", "0.4939421", "0.49246833", "0.49198568", "0.4916341", "0.49071294", "0.4895889", "0.48820263", "0.4880439", "0.48755202", "0.4874325", "0.48659423", "0.48652476", "0.48588735", "0.48563534", "0.485597", "0.48492727", "0.48479217", "0.48398605", "0.48354605", "0.48336884", "0.48320982", "0.48264006", "0.4821987", "0.4819229", "0.48178384", "0.48136464", "0.48019865", "0.48013958", "0.4799529", "0.4798486", "0.479633", "0.4795281", "0.47950435", "0.47925833", "0.47912613", "0.4784728", "0.4783957", "0.478131", "0.47787452", "0.47759667", "0.47756046", "0.47713786", "0.47706047", "0.47691014", "0.47598657", "0.47538313", "0.47534677", "0.4751679" ]
0.66950154
1
InfraProvider indicates an expected call of InfraProvider
func (mr *MockProvidersMockRecorder) InfraProvider() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "InfraProvider", reflect.TypeOf((*MockProviders)(nil).InfraProvider)) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (mr *MockClientMockRecorder) InfraProvider() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"InfraProvider\", reflect.TypeOf((*MockClient)(nil).InfraProvider))\n}", "func (c *Provider) InfraProvider() fab.InfraProvider {\n\treturn c.infraProvider\n}", "func (m *MockClient) InfraProvider() fab.InfraProvider {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"InfraProvider\")\n\tret0, _ := ret[0].(fab.InfraProvider)\n\treturn ret0\n}", "func (m *MockProviders) InfraProvider() fab.InfraProvider {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"InfraProvider\")\n\tret0, _ := ret[0].(fab.InfraProvider)\n\treturn ret0\n}", "func (o *KubernetesNodeGroupProfile) GetInfraProviderOk() (*KubernetesBaseInfrastructureProviderRelationship, bool) {\n\tif o == nil || o.InfraProvider == nil {\n\t\treturn nil, false\n\t}\n\treturn o.InfraProvider, true\n}", "func (o *KubernetesNodeGroupProfile) HasInfraProvider() bool {\n\tif o != nil && o.InfraProvider != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func infraFailure(err error) *build.InfraFailure {\n\tfailure := &build.InfraFailure{\n\t\tText: err.Error(),\n\t}\n\tif errors.Unwrap(err) == context.Canceled {\n\t\tfailure.Type = build.InfraFailure_CANCELED\n\t} else {\n\t\tfailure.Type = build.InfraFailure_BOOTSTRAPPER_ERROR\n\t\tfailure.BootstrapperCallStack = errors.RenderStack(err)\n\t}\n\n\treturn failure\n}", "func (o InfraAlertConditionOutput) IntegrationProvider() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *InfraAlertCondition) pulumi.StringPtrOutput { return v.IntegrationProvider }).(pulumi.StringPtrOutput)\n}", "func (ts *Tester) Provider() string {\n\treturn \"eks\"\n}", "func (u *UnknownProvider) GetProviderString() string {\n\treturn \"unknown\"\n}", "func (me TxsdNodeRoleSimpleContentExtensionCategory) IsInfra() bool { return me.String() == \"infra\" }", "func testAccSpinnakerApplication_cloudProvider(rName string, provider string) string {\n\treturn fmt.Sprintf(`\nresource \"spinnaker_application\" \"test\" {\n\tname = %q\n\temail = \"acceptance@test.com\"\n\tcloud_providers = [%q]\n}\n`, rName, provider)\n}", "func (a *Application) RegisterProvider() {\n\n}", "func Provider() terraform.ResourceProvider {\n\treturn &schema.Provider{\n\t\tSchema: map[string]*schema.Schema{\n\t\t\t\"access_key\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tDefault: \"\",\n\t\t\t\tDescription: \"The access key for API operations.\",\n\t\t\t},\n\t\t\t\"secret_key\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tDefault: \"\",\n\t\t\t\tDescription: \"The secret key for API operations.\",\n\t\t\t},\n\t\t\t\"endpoint\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tDescription: \"The endpoint for API operations.\",\n\t\t\t},\n\t\t\t\"region\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tDescription: \"The region where Nifcloud operations will take place.\",\n\t\t\t},\n\t\t},\n\n\t\tDataSourcesMap: map[string]*schema.Resource{\n\t\t\t// \"nifcloud_instance\": dataSourceInstance(),\n\t\t},\n\t\tResourcesMap: map[string]*schema.Resource{\n\t\t\t\"nifcloud_instance\": resourceNifcloudInstance(),\n\t\t\t\"nifcloud_network\": resourceNifcloudNetwork(),\n\t\t\t\"nifcloud_volume\": resourceNifcloudVolume(),\n\t\t\t\"nifcloud_securitygroup\": resourceNifcloudSecurityGroup(),\n\t\t\t\"nifcloud_securitygroup_rule\": resourceNifcloudSecurityGroupRule(),\n\t\t\t\"nifcloud_keypair\": resourceNifcloudKeyPair(),\n\t\t\t\"nifcloud_instancebackup_rule\": resourceNifcloudInstanceBackupRule(),\n\t\t\t\"nifcloud_image\": resourceNifcloudImage(),\n\t\t\t\"nifcloud_customer_gateway\": resourceNifcloudCustomerGateway(),\n\t\t\t\"nifcloud_vpn_gateway\": resourceNifcloudVpnGateway(),\n\t\t\t\"nifcloud_vpn_connection\": resourceNifcloudVpnConnection(),\n\t\t\t\"nifcloud_db_parameter_group\": resourceNifcloudDbParameterGroup(),\n\t\t\t\"nifcloud_db_security_group\": resourceNifcloudDbSecurityGroup(),\n\t\t\t\"nifcloud_db_instance\": resourceNifcloudDbInstance(),\n\t\t\t\"nifcloud_router\": resourceNifcloudRouter(),\n\t\t\t\"nifcloud_route_table\": resourceNifcloudRouteTable(),\n\t\t\t\"nifcloud_route\": resourceNifcloudRoute(),\n\t\t\t\"nifcloud_route_table_association\": resourceNifcloudRouteTableAssociation(),\n\t\t\t\"nifcloud_route_table_association_with_vpn_gateway\": resourceNifcloudRouteTableAssociationWithVpnGateway(),\n\t\t\t\"nifcloud_lb\": resourceNifcloudLb(),\n\t\t\t\"nifcloud_lb_port\": resourceNifcloudLbPort(),\n\t\t\t\"nifcloud_eip\": resourceNifcloudEip(),\n\t\t},\n\t\tConfigureFunc: providerConfigure,\n\t}\n}", "func Provider() tfbridge.ProviderInfo {\n\t// Instantiate the Terraform provider\n\tp := shimv2.NewProvider(xyz.Provider())\n\n\t// Create a Pulumi provider mapping\n\tprov := tfbridge.ProviderInfo{\n\t\tP: p,\n\t\tName: \"xyz\",\n\t\t// DisplayName is a way to be able to change the casing of the provider\n\t\t// name when being displayed on the Pulumi registry\n\t\tDisplayName: \"\",\n\t\t// The default publisher for all packages is Pulumi.\n\t\t// Change this to your personal name (or a company name) that you\n\t\t// would like to be shown in the Pulumi Registry if this package is published\n\t\t// there.\n\t\tPublisher: \"Pulumi\",\n\t\t// LogoURL is optional but useful to help identify your package in the Pulumi Registry\n\t\t// if this package is published there.\n\t\t//\n\t\t// You may host a logo on a domain you control or add an SVG logo for your package\n\t\t// in your repository and use the raw content URL for that file as your logo URL.\n\t\tLogoURL: \"\",\n\t\t// PluginDownloadURL is an optional URL used to download the Provider\n\t\t// for use in Pulumi programs\n\t\t// e.g https://github.com/org/pulumi-provider-name/releases/\n\t\tPluginDownloadURL: \"\",\n\t\tDescription: \"A Pulumi package for creating and managing xyz cloud resources.\",\n\t\t// category/cloud tag helps with categorizing the package in the Pulumi Registry.\n\t\t// For all available categories, see `Keywords` in\n\t\t// https://www.pulumi.com/docs/guides/pulumi-packages/schema/#package.\n\t\tKeywords: []string{\"pulumi\", \"xyz\", \"category/cloud\"},\n\t\tLicense: \"Apache-2.0\",\n\t\tHomepage: \"https://www.pulumi.com\",\n\t\tRepository: \"https://github.com/pulumi/pulumi-xyz\",\n\t\t// The GitHub Org for the provider - defaults to `terraform-providers`. Note that this\n\t\t// should match the TF provider module's require directive, not any replace directives.\n\t\tGitHubOrg: \"\",\n\t\tConfig: map[string]*tfbridge.SchemaInfo{\n\t\t\t// Add any required configuration here, or remove the example below if\n\t\t\t// no additional points are required.\n\t\t\t// \"region\": {\n\t\t\t// \tType: tfbridge.MakeType(\"region\", \"Region\"),\n\t\t\t// \tDefault: &tfbridge.DefaultInfo{\n\t\t\t// \t\tEnvVars: []string{\"AWS_REGION\", \"AWS_DEFAULT_REGION\"},\n\t\t\t// \t},\n\t\t\t// },\n\t\t},\n\t\tPreConfigureCallback: preConfigureCallback,\n\t\tResources: map[string]*tfbridge.ResourceInfo{\n\t\t\t// Map each resource in the Terraform provider to a Pulumi type. Two examples\n\t\t\t// are below - the single line form is the common case. The multi-line form is\n\t\t\t// needed only if you wish to override types or other default options.\n\t\t\t//\n\t\t\t// \"aws_iam_role\": {Tok: tfbridge.MakeResource(mainPkg, mainMod, \"IamRole\")}\n\t\t\t//\n\t\t\t// \"aws_acm_certificate\": {\n\t\t\t// \tTok: tfbridge.MakeResource(mainPkg, mainMod, \"Certificate\"),\n\t\t\t// \tFields: map[string]*tfbridge.SchemaInfo{\n\t\t\t// \t\t\"tags\": {Type: tfbridge.MakeType(mainPkg, \"Tags\")},\n\t\t\t// \t},\n\t\t\t// },\n\t\t},\n\t\tDataSources: map[string]*tfbridge.DataSourceInfo{\n\t\t\t// Map each resource in the Terraform provider to a Pulumi function. An example\n\t\t\t// is below.\n\t\t\t// \"aws_ami\": {Tok: tfbridge.MakeDataSource(mainPkg, mainMod, \"getAmi\")},\n\t\t},\n\t\tJavaScript: &tfbridge.JavaScriptInfo{\n\t\t\t// List any npm dependencies and their versions\n\t\t\tDependencies: map[string]string{\n\t\t\t\t\"@pulumi/pulumi\": \"^3.0.0\",\n\t\t\t},\n\t\t\tDevDependencies: map[string]string{\n\t\t\t\t\"@types/node\": \"^10.0.0\", // so we can access strongly typed node definitions.\n\t\t\t\t\"@types/mime\": \"^2.0.0\",\n\t\t\t},\n\t\t\t// See the documentation for tfbridge.OverlayInfo for how to lay out this\n\t\t\t// section, or refer to the AWS provider. Delete this section if there are\n\t\t\t// no overlay files.\n\t\t\t//Overlay: &tfbridge.OverlayInfo{},\n\t\t},\n\t\tPython: &tfbridge.PythonInfo{\n\t\t\t// List any Python dependencies and their version ranges\n\t\t\tRequires: map[string]string{\n\t\t\t\t\"pulumi\": \">=3.0.0,<4.0.0\",\n\t\t\t},\n\t\t},\n\t\tGolang: &tfbridge.GolangInfo{\n\t\t\tImportBasePath: filepath.Join(\n\t\t\t\tfmt.Sprintf(\"github.com/pulumi/pulumi-%[1]s/sdk/\", mainPkg),\n\t\t\t\ttfbridge.GetModuleMajorVersion(version.Version),\n\t\t\t\t\"go\",\n\t\t\t\tmainPkg,\n\t\t\t),\n\t\t\tGenerateResourceContainerTypes: true,\n\t\t},\n\t\tCSharp: &tfbridge.CSharpInfo{\n\t\t\tPackageReferences: map[string]string{\n\t\t\t\t\"Pulumi\": \"3.*\",\n\t\t\t},\n\t\t},\n\t}\n\n\t// These are new API's that you may opt to use to automatically compute resource tokens,\n\t// and apply auto aliasing for full backwards compatibility.\n\t// For more information, please reference: https://pkg.go.dev/github.com/pulumi/pulumi-terraform-bridge/v3/pkg/tfbridge#ProviderInfo.ComputeTokens\n\tprov.MustComputeTokens(tokens.SingleModule(\"xyz_\", mainMod,\n\t\ttokens.MakeStandard(mainPkg)))\n\tprov.MustApplyAutoAliasing()\n\tprov.SetAutonaming(255, \"-\")\n\n\treturn prov\n}", "func Test_Provider(t *testing.T) {\n\t// SetLogLevel(\"TRACE\")\n\t// CheckVersion()\n\n\t// Start provider API in the background\n\tgo InitProvider()\n\t// err := InitProvider()\n\t// if err != nil {\n\t// \tlog.Fatalf(\"Error initializing Provider %+v\", err)\n\t// }\n\n\tverifier := HTTPVerifier{}\n\t// Authorization middleware\n\t// This is your chance to modify the request before it hits your provider\n\t// NOTE: this should be used very carefully, as it has the potential to\n\t// _change_ the contract\n\t// f := func(next http.Handler) http.Handler {\n\t// \treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t// \t\tlog.Println(\"[DEBUG] HOOK request filter\")\n\t// \t\t// r.Header.Add(\"Authorization\", \"Bearer 1234-dynamic-value\")\n\t// \t\tnext.ServeHTTP(w, r)\n\t// \t})\n\t// }\n\n\t// Verify the Provider with local Pact Files\n\terr := verifier.VerifyProvider(t, VerifyRequest{\n\t\tProviderBaseURL: \"http://localhost:9000\",\n\t\tBrokerURL: \"http://localhost:9292\",\n\t\tProvider: \"GreetingAPI\",\n\t\tProviderVersion: \"1.0.0\",\n\t\tPublishVerificationResults: true,\n\t\t// PactFiles: []string{\n\t\t// \tfilepath.ToSlash(fmt.Sprintf(\"%s/GreetingAPIConsumer-GreetingAPI.json\", pactDir)),\n\t\t// },\n\t\t// RequestFilter: f,\n\t\t// BeforeEach: func() error {\n\t\t// \tlog.Println(\"[DEBUG] HOOK before each\")\n\t\t// \treturn nil\n\t\t// },\n\t\t// AfterEach: func() error {\n\t\t// \tlog.Println(\"[DEBUG] HOOK after each\")\n\t\t// \treturn nil\n\t\t// },\n\t\t// StateHandlers: StateHandlers{\n\t\t// \t\"User foo exists\": func(setup bool, s ProviderStateV3) (ProviderStateV3Response, error) {\n\n\t\t// \t\tif setup {\n\t\t// \t\t\tlog.Println(\"[DEBUG] HOOK calling user foo exists state handler\", s)\n\t\t// \t\t} else {\n\t\t// \t\t\tlog.Println(\"[DEBUG] HOOK teardown the 'User foo exists' state\")\n\t\t// \t\t}\n\n\t\t// \t\t// ... do something, such as create \"foo\" in the database\n\n\t\t// \t\t// Optionally (if there are generators in the pact) return provider state values to be used in the verification\n\t\t// \t\treturn ProviderStateV3Response{\"uuid\": \"1234\"}, nil\n\t\t// \t},\n\t\t// },\n\t})\n\n\tassert.NoError(t, err)\n}", "func (o *KubernetesNodeGroupProfile) SetInfraProvider(v KubernetesBaseInfrastructureProviderRelationship) {\n\to.InfraProvider = &v\n}", "func TestOverlayIOPExhaustiveness(t *testing.T) {\n\twellknownProviders := map[string]struct{}{\n\t\t\"prometheus\": {},\n\t\t\"envoy_file_access_log\": {},\n\t\t\"stackdriver\": {},\n\t\t\"envoy_otel_als\": {},\n\t\t\"envoy_ext_authz_http\": {},\n\t\t\"envoy_ext_authz_grpc\": {},\n\t\t\"zipkin\": {},\n\t\t\"lightstep\": {},\n\t\t\"datadog\": {},\n\t\t\"opencensus\": {},\n\t\t\"skywalking\": {},\n\t\t\"envoy_http_als\": {},\n\t\t\"envoy_tcp_als\": {},\n\t\t\"opentelemetry\": {},\n\t}\n\n\tunexpectedProviders := make([]string, 0)\n\n\tmsg := &meshconfig.MeshConfig_ExtensionProvider{}\n\tpb := msg.ProtoReflect()\n\tmd := pb.Descriptor()\n\n\tof := md.Oneofs().Get(0)\n\tfor i := 0; i < of.Fields().Len(); i++ {\n\t\to := of.Fields().Get(i)\n\t\tn := string(o.Name())\n\t\tif _, ok := wellknownProviders[n]; ok {\n\t\t\tdelete(wellknownProviders, n)\n\t\t} else {\n\t\t\tunexpectedProviders = append(unexpectedProviders, n)\n\t\t}\n\t}\n\n\tif len(wellknownProviders) != 0 || len(unexpectedProviders) != 0 {\n\t\tt.Errorf(\"unexpected provider not implemented in OverlayIOP, wellknownProviders: %v unexpectedProviders: %v\", wellknownProviders, unexpectedProviders)\n\t\tt.Fail()\n\t}\n}", "func NewProvider() *ProviderConfig {\n\tproviderConfig := &ProviderConfig{\n\t\tAlibaba: make(map[string]*models.AlibabaCloudSpec),\n\t\tAnexia: make(map[string]*models.AnexiaCloudSpec),\n\t\tAws: make(map[string]*models.AWSCloudSpec),\n\t\tAzure: make(map[string]*models.AzureCloudSpec),\n\t\tDigitalocean: make(map[string]*models.DigitaloceanCloudSpec),\n\t\tFake: make(map[string]*models.FakeCloudSpec),\n\t\tGcp: make(map[string]*models.GCPCloudSpec),\n\t\tHetzner: make(map[string]*models.HetznerCloudSpec),\n\t\tKubevirt: make(map[string]*models.KubevirtCloudSpec),\n\t\tOpenstack: make(map[string]*models.OpenstackCloudSpec),\n\t\tPacket: make(map[string]*models.PacketCloudSpec),\n\t\tVsphere: make(map[string]*models.VSphereCloudSpec),\n\t}\n\n\tproviderConfig.Alibaba[\"Alibaba\"] = newAlibabaCloudSpec()\n\tproviderConfig.Anexia[\"Anexia\"] = newAnexiaCloudSpec()\n\tproviderConfig.Aws[\"Aws\"] = newAWSCloudSpec()\n\tproviderConfig.Azure[\"Azure\"] = newAzureCloudSpec()\n\tproviderConfig.Digitalocean[\"Digitalocean\"] = newDigitaloceanCloudSpec()\n\tproviderConfig.Fake[\"Fake\"] = newFakeCloudSpec()\n\tproviderConfig.Gcp[\"Gcp\"] = newGCPCloudSpec()\n\tproviderConfig.Hetzner[\"Hetzner\"] = newHetznerCloudSpec()\n\tproviderConfig.Kubevirt[\"Kubevirt\"] = newKubevirtCloudSpec()\n\tproviderConfig.Openstack[\"Openstack\"] = newOpenstackCloudSpec()\n\tproviderConfig.Packet[\"Packet\"] = newPacketCloudSpec()\n\tproviderConfig.Vsphere[\"Vsphere\"] = newVSphereCloudSpec()\n\n\treturn providerConfig\n}", "func (o *KubernetesNodeGroupProfile) GetInfraProvider() KubernetesBaseInfrastructureProviderRelationship {\n\tif o == nil || o.InfraProvider == nil {\n\t\tvar ret KubernetesBaseInfrastructureProviderRelationship\n\t\treturn ret\n\t}\n\treturn *o.InfraProvider\n}", "func (o *StorageNetAppCloudTargetAllOf) GetProviderTypeOk() (*string, bool) {\n\tif o == nil || o.ProviderType == nil {\n\t\treturn nil, false\n\t}\n\treturn o.ProviderType, true\n}", "func shouldIncludeOIDCProvider(provider oidcProvider, excludeAfter time.Time, configObj config.Config) bool {\n\tif excludeAfter.Before(aws.TimeValue(provider.CreateTime)) {\n\t\treturn false\n\t}\n\n\treturn config.ShouldInclude(\n\t\taws.StringValue(provider.ProviderURL),\n\t\tconfigObj.OIDCProvider.IncludeRule.NamesRegExp,\n\t\tconfigObj.OIDCProvider.ExcludeRule.NamesRegExp,\n\t)\n}", "func (o *ClusterMetricsNodes) GetInfraOk() (*float64, bool) {\n\tif o == nil || o.Infra == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Infra, true\n}", "func (fi *FabricInterface) SupportsProvider(provider string) bool {\n\tif fi == nil {\n\t\treturn false\n\t}\n\n\t// format: [lib+]prov[,prov2,...]\n\tvar prefix string\n\tprovPieces := strings.Split(provider, \"+\")\n\tproviders := provPieces[0]\n\tif len(provPieces) > 1 {\n\t\tprefix = provPieces[0] + \"+\"\n\t\tproviders = provPieces[1]\n\t}\n\n\tfor _, prov := range strings.Split(providers, \",\") {\n\t\tprov = prefix + prov\n\t\tif !fi.Providers.Has(prov) {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}", "func TestConjur_Provider(t *testing.T) {\n\tvar err error\n\tvar provider plugin_v1.Provider\n\tname := \"conjur\"\n\n\toptions := plugin_v1.ProviderOptions{\n\t\tName: name,\n\t}\n\n\tt.Run(\"Can create the Conjur provider\", func(t *testing.T) {\n\t\tprovider, err = providers.ProviderFactories[name](options)\n\t\tassert.NoError(t, err)\n\t})\n\n\tt.Run(\"Has the expected provider name\", func(t *testing.T) {\n\t\tassert.Equal(t, \"conjur\", provider.GetName())\n\t})\n\n\tt.Run(\"Can provide an access token\", func(t *testing.T) {\n\t\tid := \"accessToken\"\n\t\tvalues, err := provider.GetValues(id)\n\n\t\tassert.NoError(t, err)\n\t\tassert.NotNil(t, values[id])\n\t\tassert.NoError(t, values[id].Error)\n\t\tassert.NotNil(t, values[id].Value)\n\n\t\ttoken := make(map[string]string)\n\t\terr = json.Unmarshal(values[id].Value, &token)\n\t\tassert.NoError(t, err)\n\t\tassert.NotNil(t, token[\"protected\"])\n\t\tassert.NotNil(t, token[\"payload\"])\n\t})\n\n\tt.Run(\"Reports an unknown value\",\n\t\ttestutils.Reports(\n\t\t\tprovider,\n\t\t\t\"foobar\",\n\t\t\t\"404 Not Found. CONJ00076E Variable dev:variable:foobar is empty or not found..\",\n\t\t),\n\t)\n\n\tt.Run(\"Provides\", func(t *testing.T) {\n\t\tfor _, testCase := range canProvideTestCases {\n\t\t\tt.Run(testCase.Description, testutils.CanProvide(provider, testCase.ID, testCase.ExpectedValue))\n\t\t}\n\t})\n}", "func (b *ClusterNodesBuilder) Infra(value int) *ClusterNodesBuilder {\n\tb.infra = &value\n\treturn b\n}", "func CheckProvider(provider string) (string, error) {\n\tprovider = strings.ToLower(provider)\n\tif provider == ProviderAWS {\n\t\treturn provider, nil\n\t}\n\n\treturn provider, fmt.Errorf(\"unsupported provider %s\", provider)\n}", "func (d *Deployment) EnsureProvider(provider string) error {\n\tif provider == \"\" {\n\t\treturn nil\n\t}\n\n\tproviderRef, err := providers.ParseReference(provider)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"invalid provider reference %v: %w\", provider, err)\n\t}\n\t_, has := d.GetProvider(providerRef)\n\tif !has {\n\t\t// We need to create the provider in the registry, find its old state and just \"Same\" it.\n\t\tvar providerResource *resource.State\n\t\tfor _, r := range d.prev.Resources {\n\t\t\tif r.URN == providerRef.URN() && r.ID == providerRef.ID() {\n\t\t\t\tproviderResource = r\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif providerResource == nil {\n\t\t\treturn fmt.Errorf(\"could not find provider %v\", providerRef)\n\t\t}\n\n\t\terr := d.SameProvider(providerResource)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"could not create provider %v: %w\", providerRef, err)\n\t\t}\n\t}\n\n\treturn nil\n}", "func ProviderIs(providers ...string) bool {\n\tfor _, provider := range providers {\n\t\tif strings.EqualFold(provider, TestContext.Provider) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func NewRegisterInfraEnvNotImplemented() *RegisterInfraEnvNotImplemented {\n\n\treturn &RegisterInfraEnvNotImplemented{}\n}", "func ec2Provider(providers []ProviderPayload) *ProviderPayload {\n\tfor _, provider := range providers {\n\t\tif provider.Name == providerEc2 {\n\t\t\treturn &provider\n\t\t}\n\t}\n\tlog.Fatal(\"ec2 provider is missing\")\n\treturn nil\n}", "func (mdhth *MockDHTHandler) Provider(string, bool) error {\n\treturn nil\n}", "func ProviderTestKOSeal() (configstore.ItemList, error) {\n\tret := configstore.ItemList{\n\t\tItems: []configstore.Item{\n\t\t\tconfigstore.NewItem(\n\t\t\t\tkeyloader.EncryptionKeyConfigName,\n\t\t\t\t`{\"key\":\"5fdb8af280b007a46553dfddb3f42bc10619dcabca8d4fdf5239b09445ab1a41\",\"identifier\":\"test\",\"sealed\":false,\"timestamp\":10,\"cipher\":\"aes-gcm\"}`,\n\t\t\t\t1,\n\t\t\t),\n\t\t\tconfigstore.NewItem(\n\t\t\t\tkeyloader.EncryptionKeyConfigName,\n\t\t\t\t`{\"key\":\"QXdDW4N/jmJzpMu7i1zu4YF1opTn7H+eOk9CLFGBSFg=\",\"identifier\":\"test\",\"sealed\":true,\"timestamp\":1,\"cipher\":\"xchacha20-poly1305\"}`,\n\t\t\t\t1,\n\t\t\t),\n\t\t},\n\t}\n\treturn ret, nil\n}", "func (p *ProviderConfig) GetProviderCloudSpec(providerName string, datacenter string, routerID string) *models.CloudSpec {\n\tcs := &models.CloudSpec{\n\t\tDatacenterName: datacenter,\n\t}\n\n\tproviderAlibaba, ok := p.Alibaba[providerName]\n\tif ok {\n\t\tcs.Alibaba = providerAlibaba\n\t}\n\tproviderAnexia, ok := p.Anexia[providerName]\n\tif ok {\n\t\tcs.Anexia = providerAnexia\n\t}\n\tproviderAws, ok := p.Aws[providerName]\n\tif ok {\n\t\tcs.Aws = providerAws\n\t}\n\tproviderAzure, ok := p.Azure[providerName]\n\tif ok {\n\t\tcs.Azure = providerAzure\n\t}\n\tproviderDigitalocean, ok := p.Digitalocean[providerName]\n\tif ok {\n\t\tcs.Digitalocean = providerDigitalocean\n\t}\n\tproviderFake, ok := p.Fake[providerName]\n\tif ok {\n\t\tcs.Fake = providerFake\n\t}\n\tproviderGcp, ok := p.Gcp[providerName]\n\tif ok {\n\t\tcs.Gcp = providerGcp\n\t}\n\tproviderHetzner, ok := p.Hetzner[providerName]\n\tif ok {\n\t\tcs.Hetzner = providerHetzner\n\t}\n\tproviderKubevirt, ok := p.Kubevirt[providerName]\n\tif ok {\n\t\tcs.Kubevirt = providerKubevirt\n\t}\n\tproviderOpenstack, ok := p.Openstack[providerName]\n\tif ok {\n\t\tcs.Openstack = providerOpenstack\n\t\tcs.Openstack.RouterID = routerID\n\t}\n\tproviderPacket, ok := p.Packet[providerName]\n\tif ok {\n\t\tcs.Packet = providerPacket\n\t}\n\tproviderVsphere, ok := p.Vsphere[providerName]\n\tif ok {\n\t\tcs.Vsphere = providerVsphere\n\t}\n\n\treturn cs\n}", "func (scnb *SupplyChainNodeBuilder) requireProvider() bool {\n\tif scnb.currentProvider == nil {\n\t\treturn false\n\t}\n\treturn true\n}", "func SetupProvider(mgr ctrl.Manager, o controller.Options) error {\n\tname := \"packages/\" + strings.ToLower(v1.ProviderGroupKind)\n\tnp := func() v1.Package { return &v1.Provider{} }\n\tnr := func() v1.PackageRevision { return &v1.ProviderRevision{} }\n\tnrl := func() v1.PackageRevisionList { return &v1.ProviderRevisionList{} }\n\n\tcs, err := kubernetes.NewForConfig(mgr.GetConfig())\n\tif err != nil {\n\t\treturn errors.Wrap(err, errCreateK8sClient)\n\t}\n\tf, err := xpkg.NewK8sFetcher(cs, append(o.FetcherOptions, xpkg.WithNamespace(o.Namespace), xpkg.WithServiceAccount(o.ServiceAccount))...)\n\tif err != nil {\n\t\treturn errors.Wrap(err, errBuildFetcher)\n\t}\n\n\topts := []ReconcilerOption{\n\t\tWithNewPackageFn(np),\n\t\tWithNewPackageRevisionFn(nr),\n\t\tWithNewPackageRevisionListFn(nrl),\n\t\tWithRevisioner(NewPackageRevisioner(f, WithDefaultRegistry(o.DefaultRegistry))),\n\t\tWithLogger(o.Logger.WithValues(\"controller\", name)),\n\t\tWithRecorder(event.NewAPIRecorder(mgr.GetEventRecorderFor(name))),\n\t}\n\tif o.WebhookTLSSecretName != \"\" {\n\t\topts = append(opts, WithWebhookTLSSecretName(o.WebhookTLSSecretName))\n\t}\n\tif o.ESSOptions != nil && o.ESSOptions.TLSSecretName != nil {\n\t\topts = append(opts, WithESSTLSSecretName(o.ESSOptions.TLSSecretName))\n\t}\n\tif o.TLSServerSecretName != \"\" {\n\t\topts = append(opts, WithTLSServerSecretName(&o.TLSServerSecretName))\n\t}\n\tif o.TLSClientSecretName != \"\" {\n\t\topts = append(opts, WithTLSClientSecretName(&o.TLSClientSecretName))\n\t}\n\n\treturn ctrl.NewControllerManagedBy(mgr).\n\t\tNamed(name).\n\t\tFor(&v1.Provider{}).\n\t\tOwns(&v1.ProviderRevision{}).\n\t\tWithOptions(o.ForControllerRuntime()).\n\t\tComplete(ratelimiter.NewReconciler(name, NewReconciler(mgr, opts...), o.GlobalRateLimiter))\n}", "func Provider() tfbridge.ProviderInfo {\n\t// Instantiate the Terraform provider\n\tp := shimv2.NewProvider(shim.NewProvider())\n\n\t// Create a Pulumi provider mapping\n\tprov := tfbridge.ProviderInfo{\n\t\tP: p,\n\t\tName: \"azuread\",\n\t\tDisplayName: \"Azure Active Directory (Azure AD)\",\n\t\tDescription: \"A Pulumi package for creating and managing Azure Active Directory (Azure AD) cloud resources.\",\n\t\tKeywords: []string{\"pulumi\", \"azuread\"},\n\t\tLicense: \"Apache-2.0\",\n\t\tHomepage: \"https://pulumi.io\",\n\t\tGitHubOrg: \"hashicorp\",\n\t\tRepository: \"https://github.com/pulumi/pulumi-azuread\",\n\t\tConfig: map[string]*tfbridge.SchemaInfo{\n\t\t\t\"environment\": {\n\t\t\t\tDefault: &tfbridge.DefaultInfo{\n\t\t\t\t\tValue: \"public\",\n\t\t\t\t\tEnvVars: []string{\"ARM_ENVIRONMENT\"},\n\t\t\t\t},\n\t\t\t},\n\t\t\t\"msi_endpoint\": {\n\t\t\t\tDefault: &tfbridge.DefaultInfo{\n\t\t\t\t\tEnvVars: []string{\"ARM_MSI_ENDPOINT\"},\n\t\t\t\t},\n\t\t\t},\n\t\t\t\"use_msi\": {\n\t\t\t\tDefault: &tfbridge.DefaultInfo{\n\t\t\t\t\tValue: false,\n\t\t\t\t\tEnvVars: []string{\"ARM_USE_MSI\"},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tPreConfigureCallback: preConfigureCallback,\n\t\tResources: map[string]*tfbridge.ResourceInfo{\n\t\t\t\"azuread_application\": {Tok: makeResource(mainMod, \"Application\")},\n\t\t\t\"azuread_application_password\": {Tok: makeResource(mainMod, \"ApplicationPassword\")},\n\t\t\t\"azuread_group\": {Tok: makeResource(mainMod, \"Group\")},\n\t\t\t\"azuread_service_principal\": {Tok: makeResource(mainMod, \"ServicePrincipal\")},\n\t\t\t\"azuread_service_principal_password\": {Tok: makeResource(mainMod, \"ServicePrincipalPassword\")},\n\t\t\t\"azuread_service_principal_delegated_permission_grant\": {\n\t\t\t\tTok: makeResource(mainMod, \"ServicePrincipalDelegatedPermissionGrant\"),\n\t\t\t},\n\t\t\t\"azuread_user\": {Tok: makeResource(mainMod, \"User\")},\n\t\t\t\"azuread_group_member\": {Tok: makeResource(mainMod, \"GroupMember\")},\n\t\t\t\"azuread_application_certificate\": {Tok: makeResource(mainMod, \"ApplicationCertificate\")},\n\t\t\t\"azuread_service_principal_certificate\": {Tok: makeResource(mainMod, \"ServicePrincipalCertificate\")},\n\t\t\t\"azuread_service_principal_token_signing_certificate\": {\n\t\t\t\tTok: makeResource(mainMod, \"ServicePrincipalTokenSigningCertificate\"),\n\t\t\t},\n\t\t\t\"azuread_application_pre_authorized\": {Tok: makeResource(mainMod, \"ApplicationPreAuthorized\")},\n\t\t\t\"azuread_invitation\": {Tok: makeResource(mainMod, \"Invitation\")},\n\t\t\t\"azuread_conditional_access_policy\": {Tok: makeResource(mainMod, \"ConditionalAccessPolicy\")},\n\t\t\t\"azuread_named_location\": {Tok: makeResource(mainMod, \"NamedLocation\")},\n\t\t\t\"azuread_directory_role\": {Tok: makeResource(mainMod, \"DirectoryRole\")},\n\t\t\t\"azuread_directory_role_member\": {Tok: makeResource(mainMod, \"DirectoryRoleMember\")},\n\t\t\t\"azuread_app_role_assignment\": {Tok: makeResource(mainMod, \"AppRoleAssignment\")},\n\t\t\t\"azuread_administrative_unit\": {Tok: makeResource(mainMod, \"AdministrativeUnit\")},\n\t\t\t\"azuread_administrative_unit_member\": {Tok: makeResource(mainMod, \"AdministrativeUnitMember\")},\n\t\t\t\"azuread_application_federated_identity_credential\": {\n\t\t\t\tTok: makeResource(mainMod, \"ApplicationFederatedIdentityCredential\"),\n\t\t\t},\n\t\t\t\"azuread_custom_directory_role\": {Tok: makeResource(mainMod, \"CustomDirectoryRole\")},\n\t\t\t\"azuread_claims_mapping_policy\": {Tok: makeResource(mainMod, \"ClaimsMappingPolicy\")},\n\t\t\t\"azuread_directory_role_assignment\": {Tok: makeResource(mainMod, \"DirectoryRoleAssignment\")},\n\t\t\t\"azuread_service_principal_claims_mapping_policy_assignment\": {\n\t\t\t\tTok: makeResource(mainMod, \"ServicePrincipalClaimsMappingPolicyAssignment\"),\n\t\t\t},\n\t\t\t\"azuread_synchronization_job\": {Tok: makeResource(mainMod, \"SynchronizationJob\")},\n\t\t\t\"azuread_synchronization_secret\": {Tok: makeResource(mainMod, \"SynchronizationSecret\")},\n\t\t\t\"azuread_access_package\": {Tok: makeResource(mainMod, \"AccessPackage\")},\n\t\t\t\"azuread_access_package_assignment_policy\": {Tok: makeResource(mainMod, \"AccessPackageAssignmentPolicy\")},\n\t\t\t\"azuread_access_package_catalog\": {Tok: makeResource(mainMod, \"AccessPackageCatalog\")},\n\t\t\t\"azuread_access_package_resource_catalog_association\": {\n\t\t\t\tTok: makeResource(mainMod, \"AccessPackageResourceCatalogAssociation\"),\n\t\t\t},\n\t\t\t\"azuread_access_package_resource_package_association\": {\n\t\t\t\tTok: makeResource(mainMod, \"AccessPackageResourcePackageAssociation\"),\n\t\t\t},\n\t\t\t\"azuread_administrative_unit_role_member\": {Tok: makeResource(mainMod, \"AdministrativeUnitRoleMember\")},\n\t\t\t\"azuread_user_flow_attribute\": {Tok: makeResource(mainMod, \"UserFlowAttribute\")},\n\t\t},\n\t\tDataSources: map[string]*tfbridge.DataSourceInfo{\n\t\t\t\"azuread_client_config\": {Tok: makeDataSource(mainMod, \"getClientConfig\")},\n\t\t\t\"azuread_application_published_app_ids\": {Tok: makeDataSource(mainMod, \"getApplicationPublishedAppIds\")},\n\t\t\t\"azuread_application_template\": {Tok: makeDataSource(mainMod, \"getApplicationTemplate\")},\n\t\t\t\"azuread_service_principals\": {Tok: makeDataSource(mainMod, \"getServicePrincipals\")},\n\t\t\t\"azuread_administrative_unit\": {Tok: makeDataSource(mainMod, \"getAdministrativeUnit\")},\n\t\t\t\"azuread_directory_object\": {Tok: makeDataSource(mainMod, \"getDirectoryObject\")},\n\t\t\t\"azuread_directory_roles\": {Tok: makeDataSource(mainMod, \"getDirectoryRoles\")},\n\t\t\t\"azuread_access_package\": {Tok: makeDataSource(mainMod, \"getAccessPackage\")},\n\t\t\t\"azuread_access_package_catalog\": {Tok: makeDataSource(mainMod, \"getAccessPackageCatalog\")},\n\t\t},\n\t\tJavaScript: &tfbridge.JavaScriptInfo{\n\t\t\t// List any npm dependencies and their versions\n\t\t\tDependencies: map[string]string{\n\t\t\t\t\"@pulumi/pulumi\": \"^3.0.0\",\n\t\t\t},\n\t\t\tDevDependencies: map[string]string{\n\t\t\t\t\"@types/node\": \"^10.0.0\", // so we can access strongly typed node definitions.\n\t\t\t\t\"@types/mime\": \"^2.0.0\",\n\t\t\t},\n\t\t},\n\t\tPython: &tfbridge.PythonInfo{\n\t\t\tRequires: map[string]string{\n\t\t\t\t\"pulumi\": \">=3.0.0,<4.0.0\",\n\t\t\t},\n\t\t},\n\t\tGolang: &tfbridge.GolangInfo{\n\t\t\tImportBasePath: filepath.Join(\n\t\t\t\tfmt.Sprintf(\"github.com/pulumi/pulumi-%[1]s/sdk/\", mainPkg),\n\t\t\t\ttfbridge.GetModuleMajorVersion(version.Version),\n\t\t\t\t\"go\",\n\t\t\t\tmainPkg,\n\t\t\t),\n\t\t\tGenerateResourceContainerTypes: true,\n\t\t},\n\t\tCSharp: &tfbridge.CSharpInfo{\n\t\t\tPackageReferences: map[string]string{\n\t\t\t\t\"Pulumi\": \"3.*\",\n\t\t\t},\n\t\t\tNamespaces: map[string]string{\n\t\t\t\t\"azuread\": \"AzureAD\",\n\t\t\t},\n\t\t}, MetadataInfo: tfbridge.NewProviderMetadata(metadata),\n\t}\n\n\tprov.MustComputeTokens(tfbridgetokens.SingleModule(\"azuread_\", mainMod,\n\t\ttfbridgetokens.MakeStandard(mainPkg)))\n\tprov.SetAutonaming(255, \"-\")\n\tprov.MustApplyAutoAliases()\n\n\treturn prov\n}", "func (r DeliveryResource) CloudProvider() string {\n\t// Kind is like ec2/cluster@v1 or titus/cluster@v1\n\t// but CloudProvider needs to be \"aws\" for \"ec2\"\n\t// so make that mapping here\n\tparts := strings.SplitN(r.Kind, \"/\", 2)\n\tif len(parts) == 0 {\n\t\treturn \"unknown-cloud-provider\"\n\t}\n\tif parts[0] == \"ec2\" {\n\t\treturn \"aws\"\n\t}\n\treturn parts[0]\n}", "func isInfraContainer(netNS string) bool {\n\treturn true\n}", "func Provider() terraform.ResourceProvider {\n\treturn &schema.Provider{\n\t\tSchema: map[string]*schema.Schema{\n\t\t\t\"public_key\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"UCLOUD_PUBLIC_KEY\", nil),\n\t\t\t\tDescription: descriptions[\"public_key\"],\n\t\t\t},\n\n\t\t\t\"private_key\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"UCLOUD_PRIVATE_KEY\", nil),\n\t\t\t\tDescription: descriptions[\"private_key\"],\n\t\t\t},\n\n\t\t\t\"region\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"UCLOUD_REGION\", nil),\n\t\t\t\tDescription: descriptions[\"region\"],\n\t\t\t},\n\n\t\t\t\"project_id\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"UCLOUD_PROJECT_ID\", nil),\n\t\t\t\tDescription: descriptions[\"project_id\"],\n\t\t\t},\n\n\t\t\t\"max_retries\": {\n\t\t\t\tType: schema.TypeInt,\n\t\t\t\tOptional: true,\n\t\t\t\tDefault: DefaultMaxRetries,\n\t\t\t\tDescription: descriptions[\"max_retries\"],\n\t\t\t},\n\n\t\t\t\"insecure\": {\n\t\t\t\tType: schema.TypeBool,\n\t\t\t\tOptional: true,\n\t\t\t\tDefault: DefaultInSecure,\n\t\t\t\tDescription: descriptions[\"insecure\"],\n\t\t\t},\n\t\t},\n\n\t\tDataSourcesMap: map[string]*schema.Resource{\n\t\t\t\"ucloud_instances\": dataSourceUCloudInstances(),\n\t\t\t\"ucloud_projects\": dataSourceUCloudProjects(),\n\t\t\t\"ucloud_images\": dataSourceUCloudImages(),\n\t\t\t\"ucloud_zones\": dataSourceUCloudZones(),\n\t\t\t\"ucloud_eips\": dataSourceUCloudEips(),\n\t\t},\n\t\tResourcesMap: map[string]*schema.Resource{\n\t\t\t\"ucloud_instance\": resourceUCloudInstance(),\n\t\t\t\"ucloud_eip\": resourceUCloudEIP(),\n\t\t\t\"ucloud_eip_association\": resourceUCloudEIPAssociation(),\n\t\t\t\"ucloud_vpc\": resourceUCloudVPC(),\n\t\t\t\"ucloud_subnet\": resourceUCloudSubnet(),\n\t\t\t\"ucloud_vpc_peering_connection\": resourceUCloudVPCPeeringConnection(),\n\t\t\t\"ucloud_lb\": resourceUCloudLB(),\n\t\t\t\"ucloud_lb_listener\": resourceUCloudLBListener(),\n\t\t\t\"ucloud_lb_attachment\": resourceUCloudLBAttachment(),\n\t\t\t\"ucloud_lb_rule\": resourceUCloudLBRule(),\n\t\t\t\"ucloud_disk\": resourceUCloudDisk(),\n\t\t\t\"ucloud_disk_attachment\": resourceUCloudDiskAttachment(),\n\t\t\t\"ucloud_security_group\": resourceUCloudSecurityGroup(),\n\t\t},\n\t\tConfigureFunc: providerConfigure,\n\t}\n}", "func Provider() terraform.ResourceProvider {\n\treturn &schema.Provider{\n\t\tSchema: map[string]*schema.Schema{\n\t\t\t\"api_token\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tSensitive: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"AIVEN_TOKEN\", nil),\n\t\t\t\tDescription: \"Aiven Authentication Token\",\n\t\t\t},\n\t\t},\n\n\t\tDataSourcesMap: map[string]*schema.Resource{\n\t\t\t\"aiven_connection_pool\": datasourceConnectionPool(),\n\t\t\t\"aiven_database\": datasourceDatabase(),\n\t\t\t\"aiven_kafka_acl\": datasourceKafkaACL(),\n\t\t\t\"aiven_kafka_topic\": datasourceKafkaTopic(),\n\t\t\t\"aiven_kafka_connector\": datasourceKafkaConnector(),\n\t\t\t\"aiven_kafka_schema\": datasourceKafkaSchema(),\n\t\t\t\"aiven_kafka_schema_configuration\": datasourceKafkaSchemaConfiguration(),\n\t\t\t\"aiven_elasticsearch_acl\": datasourceElasticsearchACL(),\n\t\t\t\"aiven_project\": datasourceProject(),\n\t\t\t\"aiven_project_user\": datasourceProjectUser(),\n\t\t\t\"aiven_project_vpc\": datasourceProjectVPC(),\n\t\t\t\"aiven_vpc_peering_connection\": datasourceVPCPeeringConnection(),\n\t\t\t\"aiven_service\": datasourceService(),\n\t\t\t\"aiven_service_integration\": datasourceServiceIntegration(),\n\t\t\t\"aiven_service_integration_endpoint\": datasourceServiceIntegrationEndpoint(),\n\t\t\t\"aiven_service_user\": datasourceServiceUser(),\n\t\t\t\"aiven_account\": datasourceAccount(),\n\t\t\t\"aiven_account_team\": datasourceAccountTeam(),\n\t\t\t\"aiven_account_team_project\": datasourceAccountTeamProject(),\n\t\t\t\"aiven_account_team_member\": datasourceAccountTeamMember(),\n\t\t\t\"aiven_mirrormaker_replication_flow\": datasourceMirrorMakerReplicationFlowTopic(),\n\t\t\t\"aiven_account_authentication\": datasourceAccountAuthentication(),\n\t\t\t\"aiven_kafka\": datasourceKafka(),\n\t\t\t\"aiven_kafka_connect\": datasourceKafkaConnect(),\n\t\t\t\"aiven_kafka_mirrormaker\": datasourceKafkaMirrormaker(),\n\t\t\t\"aiven_pg\": datasourcePG(),\n\t\t\t\"aiven_mysql\": datasourceMySQL(),\n\t\t\t\"aiven_cassandra\": datasourceCassandra(),\n\t\t\t\"aiven_elasticsearch\": datasourceElasticsearch(),\n\t\t\t\"aiven_grafana\": datasourceGrafana(),\n\t\t\t\"aiven_influxdb\": datasourceInfluxDB(),\n\t\t\t\"aiven_redis\": datasourceRedis(),\n\t\t},\n\n\t\tResourcesMap: map[string]*schema.Resource{\n\t\t\t\"aiven_connection_pool\": resourceConnectionPool(),\n\t\t\t\"aiven_database\": resourceDatabase(),\n\t\t\t\"aiven_kafka_acl\": resourceKafkaACL(),\n\t\t\t\"aiven_kafka_topic\": resourceKafkaTopic(),\n\t\t\t\"aiven_kafka_connector\": resourceKafkaConnector(),\n\t\t\t\"aiven_kafka_schema\": resourceKafkaSchema(),\n\t\t\t\"aiven_kafka_schema_configuration\": resourceKafkaSchemaConfiguration(),\n\t\t\t\"aiven_elasticsearch_acl\": resourceElasticsearchACL(),\n\t\t\t\"aiven_project\": resourceProject(),\n\t\t\t\"aiven_project_user\": resourceProjectUser(),\n\t\t\t\"aiven_project_vpc\": resourceProjectVPC(),\n\t\t\t\"aiven_vpc_peering_connection\": resourceVPCPeeringConnection(),\n\t\t\t\"aiven_service\": resourceService(),\n\t\t\t\"aiven_service_integration\": resourceServiceIntegration(),\n\t\t\t\"aiven_service_integration_endpoint\": resourceServiceIntegrationEndpoint(),\n\t\t\t\"aiven_service_user\": resourceServiceUser(),\n\t\t\t\"aiven_account\": resourceAccount(),\n\t\t\t\"aiven_account_team\": resourceAccountTeam(),\n\t\t\t\"aiven_account_team_project\": resourceAccountTeamProject(),\n\t\t\t\"aiven_account_team_member\": resourceAccountTeamMember(),\n\t\t\t\"aiven_mirrormaker_replication_flow\": resourceMirrorMakerReplicationFlow(),\n\t\t\t\"aiven_account_authentication\": resourceAccountAuthentication(),\n\t\t\t\"aiven_kafka\": resourceKafka(),\n\t\t\t\"aiven_kafka_connect\": resourceKafkaConnect(),\n\t\t\t\"aiven_kafka_mirrormaker\": resourceKafkaMirrormaker(),\n\t\t\t\"aiven_pg\": resourcePG(),\n\t\t\t\"aiven_mysql\": resourceMySQL(),\n\t\t\t\"aiven_cassandra\": resourceCassandra(),\n\t\t\t\"aiven_elasticsearch\": resourceElasticsearch(),\n\t\t\t\"aiven_grafana\": resourceGrafana(),\n\t\t\t\"aiven_influxdb\": resourceInfluxDB(),\n\t\t\t\"aiven_redis\": resourceRedis(),\n\t\t},\n\n\t\tConfigureFunc: func(d *schema.ResourceData) (interface{}, error) {\n\t\t\t_ = cache.NewTopicCache()\n\n\t\t\treturn aiven.NewTokenClient(d.Get(\"api_token\").(string), \"terraform-provider-aiven/\")\n\t\t},\n\t}\n}", "func TestDontWaitForOtherProvidersIfWeGotError(t *testing.T) {\n\tstart := time.Now()\n\n\tappCustom := App{\n\t\tContentProvider: NewContentProviderService(\n\t\t\tmap[Provider]Client{\n\t\t\t\tProvider1: &ClientMock{\n\t\t\t\t\tGetContentFn: func(userIP string, count int) ([]*ContentItem, error) {\n\t\t\t\t\t\treturn []*ContentItem{}, errors.New(\"some error from provider 1\")\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tProvider2: &ClientMock{\n\t\t\t\t\tGetContentFn: func(userIP string, count int) ([]*ContentItem, error) {\n\t\t\t\t\t\treturn []*ContentItem{}, errors.New(\"some error from provider 2\")\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tProvider3: &ClientMock{\n\t\t\t\t\tGetContentFn: func(userIP string, count int) ([]*ContentItem, error) {\n\t\t\t\t\t\t// let's imitate some pending request to provider\n\t\t\t\t\t\ttime.Sleep(5 * time.Second)\n\t\t\t\t\t\treturn []*ContentItem{{\n\t\t\t\t\t\t\tSource: \"3\",\n\t\t\t\t\t\t}}, nil\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tDefaultConfig,\n\t\t\tWithTimeOut(500*time.Millisecond),\n\t\t),\n\t}\n\n\tcontent := runRequest(t, appCustom, SimpleContentRequest)\n\n\tif len(content) != 0 {\n\t\tt.Fatalf(\"Got %d items back, want 0\", len(content))\n\t}\n\n\texecTime := time.Since(start)\n\tif execTime > time.Second {\n\t\tt.Fatalf(\"test time should be less then 1 second, got: %s\", execTime)\n\t}\n}", "func (cf *Config) IsCloudProviderEnabled(cloudProviderName string) bool {\n\tcloudProviderFromConfig := cf.CloudProviderMetadata\n\n\tfor _, cloudName := range cloudProviderFromConfig {\n\t\tif strings.ToLower(cloudName) == strings.ToLower(cloudProviderName) {\n\t\t\tklog.V(5).Infof(\"cloudProviderMetadata is set to %s in agent configuration, trying endpoints for %s Cloud Provider\",\n\t\t\t\tcloudProviderFromConfig,\n\t\t\t\tcloudProviderName)\n\t\t\treturn true\n\t\t}\n\t}\n\n\tklog.V(5).Infof(\"cloudProviderMetadata is set to %s in agent configuration, skipping %s Cloud Provider\",\n\t\tcloudProviderFromConfig,\n\t\tcloudProviderName)\n\treturn false\n}", "func Provider() *schema.Provider {\n\tprovider := &schema.Provider{\n\t\tDataSourcesMap: map[string]*schema.Resource{\n\t\t\t\"ucodecov_settings\": dataSourceCodecovSettings(),\n\t\t},\n\t}\n\treturn provider\n}", "func providerConfigure(ctx context.Context, d *schema.ResourceData) (interface{}, diag.Diagnostics) {\n\n\tvar diags diag.Diagnostics\n\tbearerToken := d.Get(\"bearer_token\").(string)\n\n\tvar host string\n\thVal, ok := d.GetOk(\"host\")\n\tif ok {\n\t\ttempHost := hVal.(string)\n\t\thost = tempHost\n\t}\n\n\tc := NewClient(host, bearerToken, &http.Client{})\n\treturn c, diags\n}", "func Provider() terraform.ResourceProvider {\n\tprovider := &schema.Provider{\n\t\tSchema: map[string]*schema.Schema{\n\t\t\t\"auth_url\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"OS_AUTH_URL\", \"\"),\n\t\t\t\tDescription: descriptions[\"auth_url\"],\n\t\t\t},\n\n\t\t\t\"region\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tDescription: descriptions[\"region\"],\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"OS_REGION_NAME\", \"\"),\n\t\t\t},\n\n\t\t\t\"user_name\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"OS_USERNAME\", \"\"),\n\t\t\t\tDescription: descriptions[\"user_name\"],\n\t\t\t},\n\n\t\t\t\"user_id\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"OS_USER_ID\", \"\"),\n\t\t\t\tDescription: descriptions[\"user_name\"],\n\t\t\t},\n\n\t\t\t\"application_credential_id\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"OS_APPLICATION_CREDENTIAL_ID\", \"\"),\n\t\t\t\tDescription: descriptions[\"application_credential_id\"],\n\t\t\t},\n\n\t\t\t\"application_credential_name\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"OS_APPLICATION_CREDENTIAL_NAME\", \"\"),\n\t\t\t\tDescription: descriptions[\"application_credential_name\"],\n\t\t\t},\n\n\t\t\t\"application_credential_secret\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"OS_APPLICATION_CREDENTIAL_SECRET\", \"\"),\n\t\t\t\tDescription: descriptions[\"application_credential_secret\"],\n\t\t\t},\n\n\t\t\t\"tenant_id\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tDefaultFunc: schema.MultiEnvDefaultFunc([]string{\n\t\t\t\t\t\"OS_TENANT_ID\",\n\t\t\t\t\t\"OS_PROJECT_ID\",\n\t\t\t\t}, \"\"),\n\t\t\t\tDescription: descriptions[\"tenant_id\"],\n\t\t\t},\n\n\t\t\t\"tenant_name\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tDefaultFunc: schema.MultiEnvDefaultFunc([]string{\n\t\t\t\t\t\"OS_TENANT_NAME\",\n\t\t\t\t\t\"OS_PROJECT_NAME\",\n\t\t\t\t}, \"\"),\n\t\t\t\tDescription: descriptions[\"tenant_name\"],\n\t\t\t},\n\n\t\t\t\"password\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tSensitive: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"OS_PASSWORD\", \"\"),\n\t\t\t\tDescription: descriptions[\"password\"],\n\t\t\t},\n\n\t\t\t\"token\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tDefaultFunc: schema.MultiEnvDefaultFunc([]string{\n\t\t\t\t\t\"OS_TOKEN\",\n\t\t\t\t\t\"OS_AUTH_TOKEN\",\n\t\t\t\t}, \"\"),\n\t\t\t\tDescription: descriptions[\"token\"],\n\t\t\t},\n\n\t\t\t\"user_domain_name\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"OS_USER_DOMAIN_NAME\", \"\"),\n\t\t\t\tDescription: descriptions[\"user_domain_name\"],\n\t\t\t},\n\n\t\t\t\"user_domain_id\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"OS_USER_DOMAIN_ID\", \"\"),\n\t\t\t\tDescription: descriptions[\"user_domain_id\"],\n\t\t\t},\n\n\t\t\t\"project_domain_name\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"OS_PROJECT_DOMAIN_NAME\", \"\"),\n\t\t\t\tDescription: descriptions[\"project_domain_name\"],\n\t\t\t},\n\n\t\t\t\"project_domain_id\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"OS_PROJECT_DOMAIN_ID\", \"\"),\n\t\t\t\tDescription: descriptions[\"project_domain_id\"],\n\t\t\t},\n\n\t\t\t\"domain_id\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"OS_DOMAIN_ID\", \"\"),\n\t\t\t\tDescription: descriptions[\"domain_id\"],\n\t\t\t},\n\n\t\t\t\"domain_name\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"OS_DOMAIN_NAME\", \"\"),\n\t\t\t\tDescription: descriptions[\"domain_name\"],\n\t\t\t},\n\n\t\t\t\"default_domain\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"OS_DEFAULT_DOMAIN\", \"default\"),\n\t\t\t\tDescription: descriptions[\"default_domain\"],\n\t\t\t},\n\n\t\t\t\"insecure\": {\n\t\t\t\tType: schema.TypeBool,\n\t\t\t\tOptional: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"OS_INSECURE\", nil),\n\t\t\t\tDescription: descriptions[\"insecure\"],\n\t\t\t},\n\n\t\t\t\"endpoint_type\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"OS_ENDPOINT_TYPE\", \"\"),\n\t\t\t},\n\n\t\t\t\"cacert_file\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"OS_CACERT\", \"\"),\n\t\t\t\tDescription: descriptions[\"cacert_file\"],\n\t\t\t},\n\n\t\t\t\"cert\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"OS_CERT\", \"\"),\n\t\t\t\tDescription: descriptions[\"cert\"],\n\t\t\t},\n\n\t\t\t\"key\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"OS_KEY\", \"\"),\n\t\t\t\tDescription: descriptions[\"key\"],\n\t\t\t},\n\n\t\t\t\"swauth\": {\n\t\t\t\tType: schema.TypeBool,\n\t\t\t\tOptional: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"OS_SWAUTH\", false),\n\t\t\t\tDescription: descriptions[\"swauth\"],\n\t\t\t},\n\n\t\t\t\"use_octavia\": {\n\t\t\t\tType: schema.TypeBool,\n\t\t\t\tOptional: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"OS_USE_OCTAVIA\", false),\n\t\t\t\tDescription: descriptions[\"use_octavia\"],\n\t\t\t},\n\n\t\t\t\"delayed_auth\": {\n\t\t\t\tType: schema.TypeBool,\n\t\t\t\tOptional: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"OS_DELAYED_AUTH\", true),\n\t\t\t\tDescription: descriptions[\"delayed_auth\"],\n\t\t\t},\n\n\t\t\t\"allow_reauth\": {\n\t\t\t\tType: schema.TypeBool,\n\t\t\t\tOptional: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"OS_ALLOW_REAUTH\", true),\n\t\t\t\tDescription: descriptions[\"allow_reauth\"],\n\t\t\t},\n\n\t\t\t\"cloud\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"OS_CLOUD\", \"\"),\n\t\t\t\tDescription: descriptions[\"cloud\"],\n\t\t\t},\n\n\t\t\t\"max_retries\": {\n\t\t\t\tType: schema.TypeInt,\n\t\t\t\tOptional: true,\n\t\t\t\tDefault: 0,\n\t\t\t\tDescription: descriptions[\"max_retries\"],\n\t\t\t},\n\n\t\t\t\"endpoint_overrides\": {\n\t\t\t\tType: schema.TypeMap,\n\t\t\t\tOptional: true,\n\t\t\t\tDescription: descriptions[\"endpoint_overrides\"],\n\t\t\t},\n\n\t\t\t\"disable_no_cache_header\": {\n\t\t\t\tType: schema.TypeBool,\n\t\t\t\tOptional: true,\n\t\t\t\tDefault: false,\n\t\t\t\tDescription: descriptions[\"disable_no_cache_header\"],\n\t\t\t},\n\t\t},\n\n\t\tDataSourcesMap: map[string]*schema.Resource{\n\t\t\t\"ironic_introspection\": dataSourceIronicIntrospection(),\n\t\t},\n\t\t//DataSourcesMap: map[string]*schema.Resource{\n\t\t//\t\"openstack_blockstorage_availability_zones_v3\": dataSourceBlockStorageAvailabilityZonesV3(),\n\t\t//\t\"openstack_blockstorage_snapshot_v2\": dataSourceBlockStorageSnapshotV2(),\n\t\t//\t\"openstack_blockstorage_snapshot_v3\": dataSourceBlockStorageSnapshotV3(),\n\t\t//\t\"openstack_blockstorage_volume_v2\": dataSourceBlockStorageVolumeV2(),\n\t\t//\t\"openstack_blockstorage_volume_v3\": dataSourceBlockStorageVolumeV3(),\n\t\t//\t\"openstack_compute_availability_zones_v2\": dataSourceComputeAvailabilityZonesV2(),\n\t\t//\t\"openstack_compute_instance_v2\": dataSourceComputeInstanceV2(),\n\t\t//\t\"openstack_compute_flavor_v2\": dataSourceComputeFlavorV2(),\n\t\t//\t\"openstack_compute_keypair_v2\": dataSourceComputeKeypairV2(),\n\t\t//\t\"openstack_containerinfra_clustertemplate_v1\": dataSourceContainerInfraClusterTemplateV1(),\n\t\t//\t\"openstack_containerinfra_cluster_v1\": dataSourceContainerInfraCluster(),\n\t\t//\t\"openstack_dns_zone_v2\": dataSourceDNSZoneV2(),\n\t\t//\t\"openstack_fw_policy_v1\": dataSourceFWPolicyV1(),\n\t\t//\t\"openstack_identity_role_v3\": dataSourceIdentityRoleV3(),\n\t\t//\t\"openstack_identity_project_v3\": dataSourceIdentityProjectV3(),\n\t\t//\t\"openstack_identity_user_v3\": dataSourceIdentityUserV3(),\n\t\t//\t\"openstack_identity_auth_scope_v3\": dataSourceIdentityAuthScopeV3(),\n\t\t//\t\"openstack_identity_endpoint_v3\": dataSourceIdentityEndpointV3(),\n\t\t//\t\"openstack_identity_service_v3\": dataSourceIdentityServiceV3(),\n\t\t//\t\"openstack_identity_group_v3\": dataSourceIdentityGroupV3(),\n\t\t//\t\"openstack_images_image_v2\": dataSourceImagesImageV2(),\n\t\t//\t\"openstack_networking_addressscope_v2\": dataSourceNetworkingAddressScopeV2(),\n\t\t//\t\"openstack_networking_network_v2\": dataSourceNetworkingNetworkV2(),\n\t\t//\t\"openstack_networking_qos_bandwidth_limit_rule_v2\": dataSourceNetworkingQoSBandwidthLimitRuleV2(),\n\t\t//\t\"openstack_networking_qos_dscp_marking_rule_v2\": dataSourceNetworkingQoSDSCPMarkingRuleV2(),\n\t\t//\t\"openstack_networking_qos_minimum_bandwidth_rule_v2\": dataSourceNetworkingQoSMinimumBandwidthRuleV2(),\n\t\t//\t\"openstack_networking_qos_policy_v2\": dataSourceNetworkingQoSPolicyV2(),\n\t\t//\t\"openstack_networking_subnet_v2\": dataSourceNetworkingSubnetV2(),\n\t\t//\t\"openstack_networking_secgroup_v2\": dataSourceNetworkingSecGroupV2(),\n\t\t//\t\"openstack_networking_subnetpool_v2\": dataSourceNetworkingSubnetPoolV2(),\n\t\t//\t\"openstack_networking_floatingip_v2\": dataSourceNetworkingFloatingIPV2(),\n\t\t//\t\"openstack_networking_router_v2\": dataSourceNetworkingRouterV2(),\n\t\t//\t\"openstack_networking_port_v2\": dataSourceNetworkingPortV2(),\n\t\t//\t\"openstack_networking_port_ids_v2\": dataSourceNetworkingPortIDsV2(),\n\t\t//\t\"openstack_networking_trunk_v2\": dataSourceNetworkingTrunkV2(),\n\t\t//\t\"openstack_sharedfilesystem_availability_zones_v2\": dataSourceSharedFilesystemAvailabilityZonesV2(),\n\t\t//\t\"openstack_sharedfilesystem_sharenetwork_v2\": dataSourceSharedFilesystemShareNetworkV2(),\n\t\t//\t\"openstack_sharedfilesystem_share_v2\": dataSourceSharedFilesystemShareV2(),\n\t\t//\t\"openstack_sharedfilesystem_snapshot_v2\": dataSourceSharedFilesystemSnapshotV2(),\n\t\t//\t\"openstack_keymanager_secret_v1\": dataSourceKeyManagerSecretV1(),\n\t\t//\t\"openstack_keymanager_container_v1\": dataSourceKeyManagerContainerV1(),\n\t\t//},\n\n\t\tResourcesMap: map[string]*schema.Resource{\n\t\t\t\"ironic_node_v1\": resourceNodeV1(),\n\t\t\t\"ironic_port_v1\": resourcePortV1(),\n\t\t\t\"ironic_allocation_v1\": resourceAllocationV1(),\n\t\t\t\"ironic_deployment\": resourceDeployment(),\n\t\t},\n\t\t//ResourcesMap: map[string]*schema.Resource{\n\t\t//\t\"openstack_blockstorage_quotaset_v2\": resourceBlockStorageQuotasetV2(),\n\t\t//\t\"openstack_blockstorage_quotaset_v3\": resourceBlockStorageQuotasetV3(),\n\t\t//\t\"openstack_blockstorage_volume_v1\": resourceBlockStorageVolumeV1(),\n\t\t//\t\"openstack_blockstorage_volume_v2\": resourceBlockStorageVolumeV2(),\n\t\t//\t\"openstack_blockstorage_volume_v3\": resourceBlockStorageVolumeV3(),\n\t\t//\t\"openstack_blockstorage_volume_attach_v2\": resourceBlockStorageVolumeAttachV2(),\n\t\t//\t\"openstack_blockstorage_volume_attach_v3\": resourceBlockStorageVolumeAttachV3(),\n\t\t//\t\"openstack_compute_flavor_v2\": resourceComputeFlavorV2(),\n\t\t//\t\"openstack_compute_flavor_access_v2\": resourceComputeFlavorAccessV2(),\n\t\t//\t\"openstack_compute_instance_v2\": resourceComputeInstanceV2(),\n\t\t//\t\"openstack_compute_interface_attach_v2\": resourceComputeInterfaceAttachV2(),\n\t\t//\t\"openstack_compute_keypair_v2\": resourceComputeKeypairV2(),\n\t\t//\t\"openstack_compute_secgroup_v2\": resourceComputeSecGroupV2(),\n\t\t//\t\"openstack_compute_servergroup_v2\": resourceComputeServerGroupV2(),\n\t\t//\t\"openstack_compute_quotaset_v2\": resourceComputeQuotasetV2(),\n\t\t//\t\"openstack_compute_floatingip_v2\": resourceComputeFloatingIPV2(),\n\t\t//\t\"openstack_compute_floatingip_associate_v2\": resourceComputeFloatingIPAssociateV2(),\n\t\t//\t\"openstack_compute_volume_attach_v2\": resourceComputeVolumeAttachV2(),\n\t\t//\t\"openstack_containerinfra_clustertemplate_v1\": resourceContainerInfraClusterTemplateV1(),\n\t\t//\t\"openstack_containerinfra_cluster_v1\": resourceContainerInfraClusterV1(),\n\t\t//\t\"openstack_db_instance_v1\": resourceDatabaseInstanceV1(),\n\t\t//\t\"openstack_db_user_v1\": resourceDatabaseUserV1(),\n\t\t//\t\"openstack_db_configuration_v1\": resourceDatabaseConfigurationV1(),\n\t\t//\t\"openstack_db_database_v1\": resourceDatabaseDatabaseV1(),\n\t\t//\t\"openstack_dns_recordset_v2\": resourceDNSRecordSetV2(),\n\t\t//\t\"openstack_dns_zone_v2\": resourceDNSZoneV2(),\n\t\t//\t\"openstack_fw_firewall_v1\": resourceFWFirewallV1(),\n\t\t//\t\"openstack_fw_policy_v1\": resourceFWPolicyV1(),\n\t\t//\t\"openstack_fw_rule_v1\": resourceFWRuleV1(),\n\t\t//\t\"openstack_identity_endpoint_v3\": resourceIdentityEndpointV3(),\n\t\t//\t\"openstack_identity_project_v3\": resourceIdentityProjectV3(),\n\t\t//\t\"openstack_identity_role_v3\": resourceIdentityRoleV3(),\n\t\t//\t\"openstack_identity_role_assignment_v3\": resourceIdentityRoleAssignmentV3(),\n\t\t//\t\"openstack_identity_service_v3\": resourceIdentityServiceV3(),\n\t\t//\t\"openstack_identity_user_v3\": resourceIdentityUserV3(),\n\t\t//\t\"openstack_identity_application_credential_v3\": resourceIdentityApplicationCredentialV3(),\n\t\t//\t\"openstack_images_image_v2\": resourceImagesImageV2(),\n\t\t//\t\"openstack_images_image_access_v2\": resourceImagesImageAccessV2(),\n\t\t//\t\"openstack_images_image_access_accept_v2\": resourceImagesImageAccessAcceptV2(),\n\t\t//\t\"openstack_lb_member_v1\": resourceLBMemberV1(),\n\t\t//\t\"openstack_lb_monitor_v1\": resourceLBMonitorV1(),\n\t\t//\t\"openstack_lb_pool_v1\": resourceLBPoolV1(),\n\t\t//\t\"openstack_lb_vip_v1\": resourceLBVipV1(),\n\t\t//\t\"openstack_lb_loadbalancer_v2\": resourceLoadBalancerV2(),\n\t\t//\t\"openstack_lb_listener_v2\": resourceListenerV2(),\n\t\t//\t\"openstack_lb_pool_v2\": resourcePoolV2(),\n\t\t//\t\"openstack_lb_member_v2\": resourceMemberV2(),\n\t\t//\t\"openstack_lb_members_v2\": resourceMembersV2(),\n\t\t//\t\"openstack_lb_monitor_v2\": resourceMonitorV2(),\n\t\t//\t\"openstack_lb_l7policy_v2\": resourceL7PolicyV2(),\n\t\t//\t\"openstack_lb_l7rule_v2\": resourceL7RuleV2(),\n\t\t//\t\"openstack_networking_floatingip_v2\": resourceNetworkingFloatingIPV2(),\n\t\t//\t\"openstack_networking_floatingip_associate_v2\": resourceNetworkingFloatingIPAssociateV2(),\n\t\t//\t\"openstack_networking_network_v2\": resourceNetworkingNetworkV2(),\n\t\t//\t\"openstack_networking_port_v2\": resourceNetworkingPortV2(),\n\t\t//\t\"openstack_networking_rbac_policy_v2\": resourceNetworkingRBACPolicyV2(),\n\t\t//\t\"openstack_networking_port_secgroup_associate_v2\": resourceNetworkingPortSecGroupAssociateV2(),\n\t\t//\t\"openstack_networking_qos_bandwidth_limit_rule_v2\": resourceNetworkingQoSBandwidthLimitRuleV2(),\n\t\t//\t\"openstack_networking_qos_dscp_marking_rule_v2\": resourceNetworkingQoSDSCPMarkingRuleV2(),\n\t\t//\t\"openstack_networking_qos_minimum_bandwidth_rule_v2\": resourceNetworkingQoSMinimumBandwidthRuleV2(),\n\t\t//\t\"openstack_networking_qos_policy_v2\": resourceNetworkingQoSPolicyV2(),\n\t\t//\t\"openstack_networking_quota_v2\": resourceNetworkingQuotaV2(),\n\t\t//\t\"openstack_networking_router_v2\": resourceNetworkingRouterV2(),\n\t\t//\t\"openstack_networking_router_interface_v2\": resourceNetworkingRouterInterfaceV2(),\n\t\t//\t\"openstack_networking_router_route_v2\": resourceNetworkingRouterRouteV2(),\n\t\t//\t\"openstack_networking_secgroup_v2\": resourceNetworkingSecGroupV2(),\n\t\t//\t\"openstack_networking_secgroup_rule_v2\": resourceNetworkingSecGroupRuleV2(),\n\t\t//\t\"openstack_networking_subnet_v2\": resourceNetworkingSubnetV2(),\n\t\t//\t\"openstack_networking_subnet_route_v2\": resourceNetworkingSubnetRouteV2(),\n\t\t//\t\"openstack_networking_subnetpool_v2\": resourceNetworkingSubnetPoolV2(),\n\t\t//\t\"openstack_networking_addressscope_v2\": resourceNetworkingAddressScopeV2(),\n\t\t//\t\"openstack_networking_trunk_v2\": resourceNetworkingTrunkV2(),\n\t\t//\t\"openstack_objectstorage_container_v1\": resourceObjectStorageContainerV1(),\n\t\t//\t\"openstack_objectstorage_object_v1\": resourceObjectStorageObjectV1(),\n\t\t//\t\"openstack_objectstorage_tempurl_v1\": resourceObjectstorageTempurlV1(),\n\t\t//\t\"openstack_orchestration_stack_v1\": resourceOrchestrationStackV1(),\n\t\t//\t\"openstack_vpnaas_ipsec_policy_v2\": resourceIPSecPolicyV2(),\n\t\t//\t\"openstack_vpnaas_service_v2\": resourceServiceV2(),\n\t\t//\t\"openstack_vpnaas_ike_policy_v2\": resourceIKEPolicyV2(),\n\t\t//\t\"openstack_vpnaas_endpoint_group_v2\": resourceEndpointGroupV2(),\n\t\t//\t\"openstack_vpnaas_site_connection_v2\": resourceSiteConnectionV2(),\n\t\t//\t\"openstack_sharedfilesystem_securityservice_v2\": resourceSharedFilesystemSecurityServiceV2(),\n\t\t//\t\"openstack_sharedfilesystem_sharenetwork_v2\": resourceSharedFilesystemShareNetworkV2(),\n\t\t//\t\"openstack_sharedfilesystem_share_v2\": resourceSharedFilesystemShareV2(),\n\t\t//\t\"openstack_sharedfilesystem_share_access_v2\": resourceSharedFilesystemShareAccessV2(),\n\t\t//\t\"openstack_keymanager_secret_v1\": resourceKeyManagerSecretV1(),\n\t\t//\t\"openstack_keymanager_container_v1\": resourceKeyManagerContainerV1(),\n\t\t//\t\"openstack_keymanager_order_v1\": resourceKeyManagerOrderV1(),\n\t\t//},\n\t}\n\n\tprovider.ConfigureFunc = func(d *schema.ResourceData) (interface{}, error) {\n\t\tterraformVersion := provider.TerraformVersion\n\t\tif terraformVersion == \"\" {\n\t\t\t// Terraform 0.12 introduced this field to the protocol\n\t\t\t// We can therefore assume that if it's missing it's 0.10 or 0.11\n\t\t\tterraformVersion = \"0.11+compatible\"\n\t\t}\n\t\treturn configureProvider(d, terraformVersion)\n\t}\n\n\treturn provider\n}", "func (a *FixedAllocateAction) queryEniFromCloud() (pbcommon.ErrCode, string) {\n\teni, err := a.cloudIf.QueryEni(a.req.EniID)\n\tif err != nil {\n\t\treturn pbcommon.ErrCode_ERROR_CLOUD_NETSERVICE_CLOUDAPI_QUERY_ENI_FAILED, err.Error()\n\t}\n\tif a.req.VpcID != eni.VpcID ||\n\t\ta.req.Region != eni.Region ||\n\t\ta.req.SubnetID != eni.SubnetID {\n\n\t\treturn pbcommon.ErrCode_ERROR_CLOUD_NETSERVICE_CLOUDAPI_ENI_INFO_NOTMATCH, \"eni info not match request info\"\n\t}\n\n\treturn pbcommon.ErrCode_ERROR_OK, \"\"\n}", "func validateProviderInfo(provider register.ProviderRegistrar) bool {\n\t// All of the fields must have a value in them.\n\tif provider.GetNodeID() == \"\" {\n\t\tlogging.Warn(\"Provider registration issue: NodeID not set\")\n\t\treturn false\n\t}\n\tif provider.GetAddress() == \"\" {\n\t\tlogging.Warn(\"Provider registration issue: Provider IP address or domain name not set\")\n\t\treturn false\n\t}\n\tif provider.GetNetworkInfoGateway() == \"\" {\n\t\tlogging.Warn(\"Provider registration issue: Port for Gateway to Provider communications not set\")\n\t\treturn false\n\t}\n\tif provider.GetNetworkInfoClient() == \"\" {\n\t\tlogging.Warn(\"Provider registration issue: Port for Client to Provider communications not set\")\n\t\treturn false\n\t}\n\tif provider.GetNetworkInfoAdmin() == \"\" {\n\t\tlogging.Warn(\"Provider registration issue: Port for Admin to Provider communications not set\")\n\t\treturn false\n\t}\n\tif provider.GetRegionCode() == \"\" {\n\t\tlogging.Warn(\"Provider registration issue: Region Code not set\")\n\t\treturn false\n\t}\n\t_, err := provider.GetRootSigningKey()\n\tif err != nil {\n\t\tlogging.Warn(\"Provider registration issue: Root Signing Public Key error: %+v\", err)\n\t\treturn false\n\t}\n\t_, err = provider.GetSigningKey()\n\tif err != nil {\n\t\tlogging.Warn(\"Provider registration issue: Retrieval Signing Key error: %+v\", err)\n\t\treturn false\n\t}\n\treturn true\n}", "func (o *SuperKeyRequest) GetProviderOk() (*string, bool) {\n\tif o == nil || o.Provider == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Provider, true\n}", "func (mr *MockCandidatePropertyGetterMockRecorder) Cloudprovider() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Cloudprovider\", reflect.TypeOf((*MockCandidatePropertyGetter)(nil).Cloudprovider))\n}", "func (v *Provider) Diagnose() {\n\trr, err := v.rr()\n\tif err != nil {\n\t\treturn\n\t}\n\n\ttw := tabwriter.NewWriter(os.Stdout, 0, 0, 1, ' ', 0)\n\n\tsort.Slice(rr.OperationList.ServiceInfo, func(i, j int) bool {\n\t\treturn rr.OperationList.ServiceInfo[i].ServiceId < rr.OperationList.ServiceInfo[j].ServiceId\n\t})\n\n\tfor _, si := range rr.OperationList.ServiceInfo {\n\t\tif si.InvocationUrl.Content != \"\" {\n\t\t\tfmt.Fprintf(tw, \"%s:\\t%s\\n\", si.ServiceId, si.InvocationUrl.Content)\n\t\t}\n\t}\n\n\t// list remaining service\n\tservices := lo.FilterMap(rr.OperationList.ServiceInfo, func(si ServiceInfo, _ int) (string, bool) {\n\t\treturn si.ServiceId, si.InvocationUrl.Content == \"\"\n\t})\n\n\tfmt.Fprintf(tw, \"without uri:\\t%s\\n\", strings.Join(services, \",\"))\n\n\ttw.Flush()\n}", "func infra(b *specs.TasksCfgBuilder, name string) string {\n\tb.MustAddTask(name, &specs.TaskSpec{\n\t\tCipdPackages: []*specs.CipdPackage{b.MustGetCipdPackageFromAsset(\"go\")},\n\t\tDimensions: []string{\n\t\t\t\"pool:Skia\",\n\t\t\tfmt.Sprintf(\"os:%s\", DEFAULT_OS_LINUX),\n\t\t\t\"gpu:none\",\n\t\t},\n\t\tExtraArgs: []string{\n\t\t\t\"--workdir\", \"../../..\", \"swarm_infra\",\n\t\t\tfmt.Sprintf(\"repository=%s\", specs.PLACEHOLDER_REPO),\n\t\t\tfmt.Sprintf(\"buildername=%s\", name),\n\t\t\t\"mastername=fake-master\",\n\t\t\t\"buildnumber=2\",\n\t\t\t\"slavename=fake-buildslave\",\n\t\t\t\"nobuildbot=True\",\n\t\t\tfmt.Sprintf(\"swarm_out_dir=%s\", specs.PLACEHOLDER_ISOLATED_OUTDIR),\n\t\t\tfmt.Sprintf(\"revision=%s\", specs.PLACEHOLDER_REVISION),\n\t\t\tfmt.Sprintf(\"patch_storage=%s\", specs.PLACEHOLDER_PATCH_STORAGE),\n\t\t\tfmt.Sprintf(\"patch_issue=%s\", specs.PLACEHOLDER_ISSUE),\n\t\t\tfmt.Sprintf(\"patch_set=%s\", specs.PLACEHOLDER_PATCHSET),\n\t\t},\n\t\tIsolate: \"swarm_recipe.isolate\",\n\t\tPriority: 0.8,\n\t})\n\treturn name\n}", "func TestGetCloudProvider(t *testing.T) {\n\tfakeCredFile := \"fake-cred-file.json\"\n\tfakeKubeConfig := \"fake-kube-config\"\n\temptyKubeConfig := \"empty-kube-config\"\n\tfakeContent := `\napiVersion: v1\nclusters:\n- cluster:\n server: https://localhost:8080\n name: foo-cluster\ncontexts:\n- context:\n cluster: foo-cluster\n user: foo-user\n namespace: bar\n name: foo-context\ncurrent-context: foo-context\nkind: Config\nusers:\n- name: foo-user\n user:\n exec:\n apiVersion: client.authentication.k8s.io/v1alpha1\n args:\n - arg-1\n - arg-2\n command: foo-command\n`\n\n\terr := createTestFile(emptyKubeConfig)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tdefer func() {\n\t\tif err := os.Remove(emptyKubeConfig); err != nil {\n\t\t\tt.Error(err)\n\t\t}\n\t}()\n\n\ttests := []struct {\n\t\tdesc string\n\t\tcreateFakeCredFile bool\n\t\tcreateFakeKubeConfig bool\n\t\tkubeconfig string\n\t\tnodeID string\n\t\tuserAgent string\n\t\tallowEmptyCloudConfig bool\n\t\texpectedErr error\n\t}{\n\t\t{\n\t\t\tdesc: \"out of cluster, no kubeconfig, no credential file\",\n\t\t\tkubeconfig: \"\",\n\t\t\tnodeID: \"\",\n\t\t\tallowEmptyCloudConfig: true,\n\t\t\texpectedErr: nil,\n\t\t},\n\t\t{\n\t\t\tdesc: \"[failure][disallowEmptyCloudConfig] out of cluster, no kubeconfig, no credential file\",\n\t\t\tkubeconfig: \"\",\n\t\t\tnodeID: \"\",\n\t\t\tallowEmptyCloudConfig: false,\n\t\t\texpectedErr: nil,\n\t\t},\n\t\t{\n\t\t\tdesc: \"[failure] out of cluster & in cluster, specify a non-exist kubeconfig, no credential file\",\n\t\t\tkubeconfig: \"/tmp/non-exist.json\",\n\t\t\tnodeID: \"\",\n\t\t\tallowEmptyCloudConfig: true,\n\t\t\texpectedErr: nil,\n\t\t},\n\t\t{\n\t\t\tdesc: \"[failure] out of cluster & in cluster, specify a empty kubeconfig, no credential file\",\n\t\t\tkubeconfig: emptyKubeConfig,\n\t\t\tnodeID: \"\",\n\t\t\tallowEmptyCloudConfig: true,\n\t\t\texpectedErr: fmt.Errorf(\"failed to get KubeClient: invalid configuration: no configuration has been provided, try setting KUBERNETES_MASTER environment variable\"),\n\t\t},\n\t\t{\n\t\t\tdesc: \"[failure] out of cluster & in cluster, specify a fake kubeconfig, no credential file\",\n\t\t\tcreateFakeKubeConfig: true,\n\t\t\tkubeconfig: fakeKubeConfig,\n\t\t\tnodeID: \"\",\n\t\t\tallowEmptyCloudConfig: true,\n\t\t\texpectedErr: nil,\n\t\t},\n\t\t{\n\t\t\tdesc: \"[success] out of cluster & in cluster, no kubeconfig, a fake credential file\",\n\t\t\tcreateFakeCredFile: true,\n\t\t\tkubeconfig: \"\",\n\t\t\tnodeID: \"\",\n\t\t\tuserAgent: \"useragent\",\n\t\t\tallowEmptyCloudConfig: true,\n\t\t\texpectedErr: nil,\n\t\t},\n\t}\n\n\tfor _, test := range tests {\n\t\tif test.createFakeKubeConfig {\n\t\t\tif err := createTestFile(fakeKubeConfig); err != nil {\n\t\t\t\tt.Error(err)\n\t\t\t}\n\t\t\tdefer func() {\n\t\t\t\tif err := os.Remove(fakeKubeConfig); err != nil {\n\t\t\t\t\tt.Error(err)\n\t\t\t\t}\n\t\t\t}()\n\n\t\t\tif err := os.WriteFile(fakeKubeConfig, []byte(fakeContent), 0666); err != nil {\n\t\t\t\tt.Error(err)\n\t\t\t}\n\t\t}\n\t\tif test.createFakeCredFile {\n\t\t\tif err := createTestFile(fakeCredFile); err != nil {\n\t\t\t\tt.Error(err)\n\t\t\t}\n\t\t\tdefer func() {\n\t\t\t\tif err := os.Remove(fakeCredFile); err != nil {\n\t\t\t\t\tt.Error(err)\n\t\t\t\t}\n\t\t\t}()\n\n\t\t\toriginalCredFile, ok := os.LookupEnv(DefaultAzureCredentialFileEnv)\n\t\t\tif ok {\n\t\t\t\tdefer os.Setenv(DefaultAzureCredentialFileEnv, originalCredFile)\n\t\t\t} else {\n\t\t\t\tdefer os.Unsetenv(DefaultAzureCredentialFileEnv)\n\t\t\t}\n\t\t\tos.Setenv(DefaultAzureCredentialFileEnv, fakeCredFile)\n\t\t}\n\t\tcloud, err := getCloudProvider(test.kubeconfig, test.nodeID, \"\", \"\", test.userAgent, test.allowEmptyCloudConfig, 25.0, 50)\n\t\tif !reflect.DeepEqual(err, test.expectedErr) && test.expectedErr != nil && !strings.Contains(err.Error(), test.expectedErr.Error()) {\n\t\t\tt.Errorf(\"desc: %s,\\n input: %q, GetCloudProvider err: %v, expectedErr: %v\", test.desc, test.kubeconfig, err, test.expectedErr)\n\t\t}\n\t\tif cloud == nil {\n\t\t\tt.Errorf(\"return value of getCloudProvider should not be nil even there is error\")\n\t\t} else {\n\t\t\tassert.Equal(t, cloud.Environment.StorageEndpointSuffix, storage.DefaultBaseURL)\n\t\t\tassert.Equal(t, cloud.UserAgent, test.userAgent)\n\t\t}\n\t}\n}", "func TestEndpointCase84(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"us-iso-west-1\"),\n\t\tUseFIPS: ptr.Bool(true),\n\t\tUseDualStack: ptr.Bool(true),\n\t\tConsumerARN: ptr.String(\"arn:aws-iso:kinesis:us-iso-west-1:123456789012:stream/testStream/consumer/test-consumer:1525898737\"),\n\t\tOperationType: ptr.String(\"control\"),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err == nil {\n\t\tt.Fatalf(\"expect error, got none\")\n\t}\n\tif e, a := \"FIPS and DualStack are enabled, but this partition does not support one or both\", err.Error(); !strings.Contains(a, e) {\n\t\tt.Errorf(\"expect %v error in %v\", e, a)\n\t}\n}", "func Provider() terraform.ResourceProvider {\n\tvar p *schema.Provider\n\tp = &schema.Provider{\n\t\tSchema: map[string]*schema.Schema{\n\t\t\t\"subscription_id\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"ARM_SUBSCRIPTION_ID\", \"\"),\n\t\t\t},\n\n\t\t\t\"client_id\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"ARM_CLIENT_ID\", \"\"),\n\t\t\t},\n\n\t\t\t\"client_secret\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"ARM_CLIENT_SECRET\", \"\"),\n\t\t\t},\n\n\t\t\t\"tenant_id\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"ARM_TENANT_ID\", \"\"),\n\t\t\t},\n\n\t\t\t\"environment\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"ARM_ENVIRONMENT\", \"public\"),\n\t\t\t},\n\n\t\t\t\"skip_provider_registration\": {\n\t\t\t\tType: schema.TypeBool,\n\t\t\t\tOptional: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"ARM_SKIP_PROVIDER_REGISTRATION\", false),\n\t\t\t},\n\t\t},\n\n\t\tDataSourcesMap: map[string]*schema.Resource{\n\t\t\t\"azurerm_client_config\": dataSourceArmClientConfig(),\n\t\t},\n\n\t\tResourcesMap: map[string]*schema.Resource{\n\t\t\t// These resources use the Azure ARM SDK\n\t\t\t\"azurerm_availability_set\": resourceArmAvailabilitySet(),\n\t\t\t\"azurerm_cdn_endpoint\": resourceArmCdnEndpoint(),\n\t\t\t\"azurerm_cdn_profile\": resourceArmCdnProfile(),\n\t\t\t\"azurerm_container_registry\": resourceArmContainerRegistry(),\n\t\t\t\"azurerm_container_service\": resourceArmContainerService(),\n\n\t\t\t\"azurerm_eventhub\": resourceArmEventHub(),\n\t\t\t\"azurerm_eventhub_authorization_rule\": resourceArmEventHubAuthorizationRule(),\n\t\t\t\"azurerm_eventhub_consumer_group\": resourceArmEventHubConsumerGroup(),\n\t\t\t\"azurerm_eventhub_namespace\": resourceArmEventHubNamespace(),\n\n\t\t\t\"azurerm_lb\": resourceArmLoadBalancer(),\n\t\t\t\"azurerm_lb_backend_address_pool\": resourceArmLoadBalancerBackendAddressPool(),\n\t\t\t\"azurerm_lb_nat_rule\": resourceArmLoadBalancerNatRule(),\n\t\t\t\"azurerm_lb_nat_pool\": resourceArmLoadBalancerNatPool(),\n\t\t\t\"azurerm_lb_probe\": resourceArmLoadBalancerProbe(),\n\t\t\t\"azurerm_lb_rule\": resourceArmLoadBalancerRule(),\n\n\t\t\t\"azurerm_managed_disk\": resourceArmManagedDisk(),\n\n\t\t\t\"azurerm_key_vault\": resourceArmKeyVault(),\n\t\t\t\"azurerm_local_network_gateway\": resourceArmLocalNetworkGateway(),\n\t\t\t\"azurerm_network_interface\": resourceArmNetworkInterface(),\n\t\t\t\"azurerm_network_security_group\": resourceArmNetworkSecurityGroup(),\n\t\t\t\"azurerm_network_security_rule\": resourceArmNetworkSecurityRule(),\n\t\t\t\"azurerm_public_ip\": resourceArmPublicIp(),\n\t\t\t\"azurerm_redis_cache\": resourceArmRedisCache(),\n\t\t\t\"azurerm_route\": resourceArmRoute(),\n\t\t\t\"azurerm_route_table\": resourceArmRouteTable(),\n\t\t\t\"azurerm_servicebus_namespace\": resourceArmServiceBusNamespace(),\n\t\t\t\"azurerm_servicebus_subscription\": resourceArmServiceBusSubscription(),\n\t\t\t\"azurerm_servicebus_topic\": resourceArmServiceBusTopic(),\n\t\t\t\"azurerm_storage_account\": resourceArmStorageAccount(),\n\t\t\t\"azurerm_storage_blob\": resourceArmStorageBlob(),\n\t\t\t\"azurerm_storage_container\": resourceArmStorageContainer(),\n\t\t\t\"azurerm_storage_share\": resourceArmStorageShare(),\n\t\t\t\"azurerm_storage_queue\": resourceArmStorageQueue(),\n\t\t\t\"azurerm_storage_table\": resourceArmStorageTable(),\n\t\t\t\"azurerm_subnet\": resourceArmSubnet(),\n\t\t\t\"azurerm_template_deployment\": resourceArmTemplateDeployment(),\n\t\t\t\"azurerm_traffic_manager_endpoint\": resourceArmTrafficManagerEndpoint(),\n\t\t\t\"azurerm_traffic_manager_profile\": resourceArmTrafficManagerProfile(),\n\t\t\t\"azurerm_virtual_machine_extension\": resourceArmVirtualMachineExtensions(),\n\t\t\t\"azurerm_virtual_machine\": resourceArmVirtualMachine(),\n\t\t\t\"azurerm_virtual_machine_scale_set\": resourceArmVirtualMachineScaleSet(),\n\t\t\t\"azurerm_virtual_network\": resourceArmVirtualNetwork(),\n\t\t\t\"azurerm_virtual_network_peering\": resourceArmVirtualNetworkPeering(),\n\n\t\t\t// These resources use the Riviera SDK\n\t\t\t\"azurerm_dns_a_record\": resourceArmDnsARecord(),\n\t\t\t\"azurerm_dns_aaaa_record\": resourceArmDnsAAAARecord(),\n\t\t\t\"azurerm_dns_cname_record\": resourceArmDnsCNameRecord(),\n\t\t\t\"azurerm_dns_mx_record\": resourceArmDnsMxRecord(),\n\t\t\t\"azurerm_dns_ns_record\": resourceArmDnsNsRecord(),\n\t\t\t\"azurerm_dns_srv_record\": resourceArmDnsSrvRecord(),\n\t\t\t\"azurerm_dns_txt_record\": resourceArmDnsTxtRecord(),\n\t\t\t\"azurerm_dns_zone\": resourceArmDnsZone(),\n\t\t\t\"azurerm_resource_group\": resourceArmResourceGroup(),\n\t\t\t\"azurerm_search_service\": resourceArmSearchService(),\n\t\t\t\"azurerm_sql_database\": resourceArmSqlDatabase(),\n\t\t\t\"azurerm_sql_firewall_rule\": resourceArmSqlFirewallRule(),\n\t\t\t\"azurerm_sql_server\": resourceArmSqlServer(),\n\t\t},\n\t}\n\n\tp.ConfigureFunc = providerConfigure(p)\n\n\treturn p\n}", "func ForProvider(p providerconfigtypes.CloudProvider, cvr *providerconfig.ConfigVarResolver) (cloudprovidertypes.Provider, error) {\n\tif p, found := providers[p]; found {\n\t\treturn NewValidationCacheWrappingCloudProvider(p(cvr)), nil\n\t}\n\tif p, found := communityProviders[p]; found {\n\t\treturn NewValidationCacheWrappingCloudProvider(p(cvr)), nil\n\t}\n\treturn nil, ErrProviderNotFound\n}", "func (scnb *SupplyChainNodeBuilder) Provider(provider proto.EntityDTO_EntityType, pType proto.Provider_ProviderType) *SupplyChainNodeBuilder {\n\tif scnb.err != nil {\n\t\treturn scnb\n\t}\n\tif hasTemplate := scnb.requireEntityTemplate(); !hasTemplate {\n\t\tscnb.err = fmt.Errorf(\"EntityTemplate is not found. Must set before call Provider().\")\n\t\treturn scnb\n\t}\n\n\tif pType == proto.Provider_LAYERED_OVER {\n\t\tmaxCardinality := int32(math.MaxInt32)\n\t\tminCardinality := int32(0)\n\t\tscnb.currentProvider = &proto.Provider{\n\t\t\tTemplateClass: &provider,\n\t\t\tProviderType: &pType,\n\t\t\tCardinalityMax: &maxCardinality,\n\t\t\tCardinalityMin: &minCardinality,\n\t\t}\n\t} else {\n\t\thostCardinality := int32(1)\n\t\tscnb.currentProvider = &proto.Provider{\n\t\t\tTemplateClass: &provider,\n\t\t\tProviderType: &pType,\n\t\t\tCardinalityMax: &hostCardinality,\n\t\t\tCardinalityMin: &hostCardinality,\n\t\t}\n\t}\n\n\treturn scnb\n}", "func ProviderSpec() *ProviderSpecApplyConfiguration {\n\treturn &ProviderSpecApplyConfiguration{}\n}", "func (fw IPtables) Provider() string {\n\treturn \"iptables\"\n}", "func CapaProviderFn(thread *starlark.Thread, _ *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {\n\n\tvar (\n\t\tworkloadCluster, namespace string\n\t\tnames, labels *starlark.List\n\t\tsshConfig, mgmtKubeConfig *starlarkstruct.Struct\n\t)\n\n\terr := starlark.UnpackArgs(\"capa_provider\", args, kwargs,\n\t\t\"ssh_config\", &sshConfig,\n\t\t\"mgmt_kube_config\", &mgmtKubeConfig,\n\t\t\"workload_cluster?\", &workloadCluster,\n\t\t\"namespace?\", &namespace,\n\t\t\"labels?\", &labels,\n\t\t\"nodes?\", &names)\n\tif err != nil {\n\t\treturn starlark.None, errors.Wrap(err, \"failed to unpack input arguments\")\n\t}\n\n\tctx, ok := thread.Local(identifiers.scriptCtx).(context.Context)\n\tif !ok || ctx == nil {\n\t\treturn starlark.None, fmt.Errorf(\"script context not found\")\n\t}\n\n\tif sshConfig == nil || mgmtKubeConfig == nil {\n\t\treturn starlark.None, errors.New(\"capa_provider requires the name of the management cluster, the ssh configuration and the management cluster kubeconfig\")\n\t}\n\n\tif mgmtKubeConfig == nil {\n\t\tmgmtKubeConfig = thread.Local(identifiers.kubeCfg).(*starlarkstruct.Struct)\n\t}\n\tmgmtKubeConfigPath, err := getKubeConfigPathFromStruct(mgmtKubeConfig)\n\tif err != nil {\n\t\treturn starlark.None, errors.Wrap(err, \"failed to extract management kubeconfig\")\n\t}\n\n\t// if workload cluster is not supplied, then the resources for the management cluster\n\t// should be enumerated\n\tclusterName := workloadCluster\n\tif clusterName == \"\" {\n\t\tconfig, err := k8s.LoadKubeCfg(mgmtKubeConfigPath)\n\t\tif err != nil {\n\t\t\treturn starlark.None, errors.Wrap(err, \"failed to load kube config\")\n\t\t}\n\t\tclusterName, err = config.GetClusterName()\n\t\tif err != nil {\n\t\t\treturn starlark.None, errors.Wrap(err, \"cannot find cluster with name \"+workloadCluster)\n\t\t}\n\t}\n\n\tbastionIpAddr, err := k8s.FetchBastionIpAddress(clusterName, namespace, mgmtKubeConfigPath)\n\tif err != nil {\n\t\treturn starlark.None, errors.Wrap(err, \"could not fetch jump host addresses\")\n\t}\n\n\tproviderConfigPath, err := provider.KubeConfig(mgmtKubeConfigPath, clusterName, namespace)\n\tif err != nil {\n\t\treturn starlark.None, err\n\t}\n\n\tnodeAddresses, err := k8s.GetNodeAddresses(ctx, providerConfigPath, toSlice(names), toSlice(labels))\n\tif err != nil {\n\t\treturn starlark.None, errors.Wrap(err, \"could not fetch host addresses\")\n\t}\n\n\t// dictionary for capa provider struct\n\tcapaProviderDict := starlark.StringDict{\n\t\t\"kind\": starlark.String(identifiers.capaProvider),\n\t\t\"transport\": starlark.String(\"ssh\"),\n\t\t\"kube_config\": starlark.String(providerConfigPath),\n\t}\n\n\t// add node info to dictionary\n\tvar nodeIps []starlark.Value\n\tfor _, node := range nodeAddresses {\n\t\tnodeIps = append(nodeIps, starlark.String(node))\n\t}\n\tcapaProviderDict[\"hosts\"] = starlark.NewList(nodeIps)\n\n\tsshConfigDict := starlark.StringDict{}\n\tsshConfig.ToStringDict(sshConfigDict)\n\n\t// modify ssh config jump credentials, if not specified\n\tif _, err := sshConfig.Attr(\"jump_host\"); err != nil {\n\t\tsshConfigDict[\"jump_host\"] = starlark.String(bastionIpAddr)\n\t}\n\tif _, err := sshConfig.Attr(\"jump_user\"); err != nil {\n\t\tsshConfigDict[\"jump_user\"] = starlark.String(\"ubuntu\")\n\t}\n\tcapaProviderDict[identifiers.sshCfg] = starlarkstruct.FromStringDict(starlark.String(identifiers.sshCfg), sshConfigDict)\n\n\treturn starlarkstruct.FromStringDict(starlark.String(identifiers.capaProvider), capaProviderDict), nil\n}", "func WithInfraProvider(infraProvider fab.InfraProvider) SDKContextParams {\n\treturn func(ctx *Provider) {\n\t\tctx.infraProvider = infraProvider\n\t}\n}", "func (mr *MockBootstrapperProviderMockRecorder) Provide() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Provide\", reflect.TypeOf((*MockBootstrapperProvider)(nil).Provide))\n}", "func NewACIProvider(config string, operatingSystem string, image string, deploymentFile string) (*ACIProvider, error) {\n\tvar p ACIProvider\n\tvar err error\n\n\tp.aciClient, err = CreateACIClient()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif config != \"\" {\n\t\tf, err := os.Open(config)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tdefer f.Close()\n\n\t\tif err := p.loadConfig(f); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tif rg := os.Getenv(\"ACI_RESOURCE_GROUP\"); rg != \"\" {\n\t\tp.resourceGroup = rg\n\t}\n\tif p.resourceGroup == \"\" {\n\t\treturn nil, errors.New(\"Resource group can not be empty please set ACI_RESOURCE_GROUP\")\n\t}\n\n\tif r := os.Getenv(\"ACI_REGION\"); r != \"\" {\n\t\tp.region = r\n\t}\n\tif p.region == \"\" {\n\t\treturn nil, errors.New(\"Region can not be empty please set ACI_REGION\")\n\t}\n\tif r := p.region; !isValidACIRegion(r) {\n\t\tunsupportedRegionMessage := fmt.Sprintf(\"Region %s is invalid. Current supported regions are: %s\",\n\t\t\tr, strings.Join(validAciRegions, \", \"))\n\n\t\treturn nil, errors.New(unsupportedRegionMessage)\n\t}\n\n\tregion := os.Getenv(\"ACI_REGION\")\n\tif region == \"\" {\n\t\treturn nil, errors.New(\"Region can not be empty please set ACI_REGION\")\n\t}\n\n\tp.cpu = \"20\"\n\tp.memory = \"100Gi\"\n\tp.cinstances = \"20\"\n\n\t//If a single image is given, create a basic worker instance\n\tif image != \"\" {\n\t\tcg, err := GetSingleImageContainerGroup(image, region, operatingSystem)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tp.workerInstance = cg\n\t} else if deploymentFile != \"\" {\n\t\treturn nil, errors.New(\"Currently do not support K8s deployment files.\")\n\t\t// deployment, err := GetDeploymentFromFile(deploymentFile)\n\t\t// if err != nil{\n\t\t// \treturn nil, err\n\t\t// }\n\t\t// cg, err := GetACIFromK8sPod(pod, region, operatingSystem)\n\t\t// p.workerInstance = cg\n\n\t\t// // Make sure the KIRIX_WORK env varible was added to one container\n\t\t// err = p.AddWork(\"\")\n\t\t// if err != nil {\n\t\t// \treturn nil, err\n\t\t// }\n\t} else {\n\t\treturn nil, errors.New(\"Must supply either an image or Kubernetes deployment spec.\")\n\t}\n\n\treturn &p, err\n}", "func providerFactory(_ io.Reader) (cloudprovider.Interface, error) {\n\tlog := klogr.NewWithOptions(klogr.WithFormat(klogr.FormatKlog))\n\tc, err := loadConfig(envconfig.OsLookuper())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tapiUrl := katapult.DefaultURL\n\tif c.APIHost != \"\" {\n\t\tlog.Info(\"default API base URL overrided\",\n\t\t\t\"url\", c.APIHost)\n\t\tapiUrl, err = url.Parse(c.APIHost)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to parse provided api url: %w\", err)\n\t\t}\n\t}\n\n\trm, err := katapult.New(\n\t\tkatapult.WithAPIKey(c.APIKey),\n\t\tkatapult.WithBaseURL(apiUrl),\n\t\tkatapult.WithUserAgent(\"kce-ccm\"), // TODO: Add version.\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tclient := core.New(rm)\n\n\treturn &provider{\n\t\tlog: log,\n\t\tkatapult: client,\n\t\tconfig: *c,\n\t\tloadBalancer: &loadBalancerManager{\n\t\t\tlog: log,\n\t\t\tconfig: *c,\n\t\t\tloadBalancerController: client.LoadBalancers,\n\t\t\tloadBalancerRuleController: client.LoadBalancerRules,\n\t\t},\n\t}, nil\n}", "func validateProvider(provider string) (string, error) {\n\tswitch sanitize(provider) {\n\tcase \"\":\n\t\treturn \"cloudflare\", nil\n\tcase \"cloudflare\":\n\t\treturn \"cloudflare\", nil\n\tcase \"dryrun\":\n\t\treturn \"dryrun\", nil\n\tdefault:\n\t\treturn \"\", fmt.Errorf(\"Invalid provider `%s` specified. Available providers: [`cloudflare`, `dryrun`]\", provider)\n\t}\n}", "func Provider(v interface{}) Annotation {\n\treturn &providerType{v}\n}", "func discriminateErrCtx(err error) error {\n\tif _, ok := err.(*runtime.APIError); ok {\n\t\t// the service can be reached\n\t\treturn emperror.With(err, cloudInfoService)\n\t}\n\t// handle other cloud info errors here\n\n\t// probably connectivity error (should it be analized further?!)\n\treturn emperror.With(err, cloudInfoClientComponent)\n}", "func (e ApplicationPubSub_NATSProviderValidationError) Cause() error { return e.cause }", "func (o *Okta) provider() *oidc.Provider {\n\tif o.myProvider == nil {\n\t\tctx := oidc.ClientContext(context.Background(), o.client())\n\t\tissuerURL := o.IssuerURL()\n\t\tprovider, err := oidc.NewProvider(ctx, issuerURL)\n\t\tif err != nil {\n\t\t\tpanic(fmt.Errorf(\"Failed to query provider %q: %v\", issuerURL, err))\n\t\t}\n\t\to.myProvider = provider\n\n\t}\n\treturn o.myProvider\n}", "func (c *MockAzureCloud) ProviderID() kops.CloudProviderID {\n\treturn kops.CloudProviderAzure\n}", "func (adminAPIOp) SkipVerification() bool { return true }", "func Provider() *schema.Provider {\n\tp := &schema.Provider{\n\t\tSchema: map[string]*schema.Schema{\n\t\t\t\"api_token\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tSensitive: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"IPINFO_TOKEN\", nil),\n\t\t\t\tDescription: \"ipinfo.io Authentication Token\",\n\t\t\t},\n\t\t},\n\n\t\tDataSourcesMap: map[string]*schema.Resource{\n\t\t\t\"ipinfo\": datasourceIPInfo(),\n\t\t},\n\t}\n\n\tp.ConfigureContextFunc = func(_ context.Context, d *schema.ResourceData) (interface{}, diag.Diagnostics) {\n\t\tterraformVersion := p.TerraformVersion\n\t\tif terraformVersion == \"\" {\n\t\t\t// Terraform 0.12 introduced this field to the protocol\n\t\t\t// We can therefore assume that if it's missing it's 0.10 or 0.11\n\t\t\tterraformVersion = \"0.11+compatible\"\n\t\t}\n\n\t\t// Get access token by signing up a free account at https://ipinfo.io/signup\n\t\tclient := ipinfo.NewClient(nil, nil, d.Get(\"api_token\").(string))\n\n\t\treturn client, nil\n\t}\n\n\treturn p\n}", "func MissingProviderSuggestion(ctx context.Context, addr addrs.Provider, source Source, reqs Requirements) addrs.Provider {\n\tif !addr.IsDefault() {\n\t\treturn addr\n\t}\n\n\t// Before possibly looking up legacy naming, see if the user has another provider\n\t// named in their requirements that is of the same type, and offer that\n\t// as a suggestion\n\tfor req := range reqs {\n\t\tif req != addr && req.Type == addr.Type {\n\t\t\treturn req\n\t\t}\n\t}\n\n\t// Our strategy here, for a default provider, is to use the default\n\t// registry's special API for looking up \"legacy\" providers and try looking\n\t// for a legacy provider whose type name matches the type of the given\n\t// provider. This should then find a suitable answer for any provider\n\t// that was originally auto-installable in v0.12 and earlier but moved\n\t// into a non-default namespace as part of introducing the hierarchical\n\t// provider namespace.\n\t//\n\t// To achieve that, we need to find the direct registry client in\n\t// particular from the given source, because that is the only Source\n\t// implementation that can actually handle a legacy provider lookup.\n\tregSource := findLegacyProviderLookupSource(addr.Hostname, source)\n\tif regSource == nil {\n\t\t// If there's no direct registry source in the installation config\n\t\t// then we can't provide a renaming suggestion.\n\t\treturn addr\n\t}\n\n\tdefaultNS, redirectNS, err := regSource.lookupLegacyProviderNamespace(ctx, addr.Hostname, addr.Type)\n\tif err != nil {\n\t\treturn addr\n\t}\n\n\tswitch {\n\tcase redirectNS != \"\":\n\t\treturn addrs.Provider{\n\t\t\tHostname: addr.Hostname,\n\t\t\tNamespace: redirectNS,\n\t\t\tType: addr.Type,\n\t\t}\n\tdefault:\n\t\treturn addrs.Provider{\n\t\t\tHostname: addr.Hostname,\n\t\t\tNamespace: defaultNS,\n\t\t\tType: addr.Type,\n\t\t}\n\t}\n}", "func (o *ClusterMetricsNodes) HasInfra() bool {\n\tif o != nil && o.Infra != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func NewProvider(ctx *pulumi.Context,\n\tname string, args *ProviderArgs, opts ...pulumi.ResourceOption) (*Provider, error) {\n\tif args == nil {\n\t\targs = &ProviderArgs{}\n\t}\n\n\tif args.AllowReauth == nil {\n\t\targs.AllowReauth = pulumi.BoolPtr(getEnvOrDefault(false, parseEnvBool, \"OS_ALLOW_REAUTH\").(bool))\n\t}\n\tif args.Cloud == nil {\n\t\targs.Cloud = pulumi.StringPtr(getEnvOrDefault(\"\", nil, \"OS_CLOUD\").(string))\n\t}\n\tif args.DelayedAuth == nil {\n\t\targs.DelayedAuth = pulumi.BoolPtr(getEnvOrDefault(false, parseEnvBool, \"OS_DELAYED_AUTH\").(bool))\n\t}\n\tif args.EndpointType == nil {\n\t\targs.EndpointType = pulumi.StringPtr(getEnvOrDefault(\"\", nil, \"OS_ENDPOINT_TYPE\").(string))\n\t}\n\tif args.Insecure == nil {\n\t\targs.Insecure = pulumi.BoolPtr(getEnvOrDefault(false, parseEnvBool, \"OS_INSECURE\").(bool))\n\t}\n\tif args.Region == nil {\n\t\targs.Region = pulumi.StringPtr(getEnvOrDefault(\"\", nil, \"OS_REGION_NAME\").(string))\n\t}\n\tif args.Swauth == nil {\n\t\targs.Swauth = pulumi.BoolPtr(getEnvOrDefault(false, parseEnvBool, \"OS_SWAUTH\").(bool))\n\t}\n\tif args.UseOctavia == nil {\n\t\targs.UseOctavia = pulumi.BoolPtr(getEnvOrDefault(false, parseEnvBool, \"OS_USE_OCTAVIA\").(bool))\n\t}\n\tvar resource Provider\n\terr := ctx.RegisterResource(\"pulumi:providers:openstack\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func TestENITrunkingEnabled(t *testing.T) {\n\tdefer setTestRegion()()\n\tdefer setTestEnv(\"ECS_ENABLE_TASK_ENI\", \"true\")()\n\tcfg, err := NewConfig(ec2.NewBlackholeEC2MetadataClient())\n\trequire.NoError(t, err)\n\n\tcfg.platformOverrides()\n\tassert.True(t, cfg.ENITrunkingEnabled.Enabled(), \"ENI trunking should be enabled\")\n}", "func TraceProvider() trace.Provider {\n\tif gp := globalTracer.Load(); gp != nil {\n\t\treturn gp.(traceProvider).tp\n\t}\n\treturn trace.NoopProvider{}\n}", "func (e Error) IsInfrastructure() bool {\n\treturn e.group == infrastructure\n}", "func (mr *MockProcessProviderMockRecorder) BootstrapperProvider() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"BootstrapperProvider\", reflect.TypeOf((*MockProcessProvider)(nil).BootstrapperProvider))\n}", "func detectProvider(format string) (string, error) {\n\tswitch {\n\tcase format == FORMAT_SYSTEMD:\n\t\treturn FORMAT_SYSTEMD, nil\n\tcase format == FORMAT_UPSTART:\n\t\treturn FORMAT_UPSTART, nil\n\tcase os.Args[0] == \"systemd-exporter\":\n\t\treturn FORMAT_SYSTEMD, nil\n\tcase os.Args[0] == \"upstart-exporter\":\n\t\treturn FORMAT_UPSTART, nil\n\tcase env.Which(\"systemctl\") != \"\":\n\t\treturn FORMAT_SYSTEMD, nil\n\tcase env.Which(\"initctl\") != \"\":\n\t\treturn FORMAT_UPSTART, nil\n\tdefault:\n\t\treturn \"\", fmt.Errorf(\"Can't find init system provider\")\n\t}\n}", "func Provider() terraform.ResourceProvider {\n\treturn &schema.Provider{\n\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\"ip\": &schema.Schema{\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"VCD_IP\", nil),\n\t\t\t\tDescription: \"The vcd IP for vcd API operations.\",\n\t\t\t},\n\n\t\t\t\"user\": &schema.Schema{\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"VCD_USER\", nil),\n\t\t\t\tDescription: \"The user name for vcd API operations.\",\n\t\t\t},\n\n\t\t\t\"password\": &schema.Schema{\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"VCD_PASSWORD\", nil),\n\t\t\t\tDescription: \"The user password for vcd API operations.\",\n\t\t\t},\n\n\t\t\t\"org\": &schema.Schema{\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"VCD_ORG\", nil),\n\t\t\t\tDescription: \"The vcd org for API operations\",\n\t\t\t},\n\n\t\t\t\"use_vcd_cli_profile\": &schema.Schema{\n\t\t\t\tType: schema.TypeBool,\n\t\t\t\tOptional: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"VCD_USE_VCD_CLI_PROFILE\", false),\n\t\t\t\tDescription: \"If set, VCDClient will use vcd cli profile and token .\",\n\t\t\t},\n\n\t\t\t\"allow_unverified_ssl\": &schema.Schema{\n\t\t\t\tType: schema.TypeBool,\n\t\t\t\tOptional: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"VCD_ALLOW_UNVERIFIED_SSL\", false),\n\t\t\t\tDescription: \"If set, VCDClient will permit unverifiable SSL certificates.\",\n\t\t\t},\n\t\t},\n\n\t\tResourcesMap: map[string]*schema.Resource{\n\n\t\t\t\"vcloud-director_catalog\": resourceCatalog(),\n\t\t\t\"vcloud-director_catalog_item_media\": resourceCatalogItemMedia(),\n\t\t\t\"vcloud-director_catalog_item_ova\": resourceCatalogItemOva(),\n\t\t\t\"vcloud-director_vapp\": resourceVApp(),\n\t\t\t\"vcloud-director_independent_disk\": resourceIndependentDisk(),\n\t\t\t\"vcloud-director_org\": resourceOrg(),\n\t\t\t\"vcloud-director_disk\": resourceIndependentDisk(),\n\t\t\t\"vcloud-director_user\": resourceUser(),\n\t\t\t\"vcloud-director_vdc\": resourceVdc(),\n\t\t\t\"vcloud-director_vapp_vm\": resourceVappVm(),\n\t\t},\n\n\t\tConfigureFunc: providerConfigure,\n\t}\n}", "func TestEndpointCase75(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"us-east-1\"),\n\t\tUseFIPS: ptr.Bool(false),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tConsumerARN: ptr.String(\"arn\"),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err == nil {\n\t\tt.Fatalf(\"expect error, got none\")\n\t}\n\tif e, a := \"Invalid ARN: Failed to parse ARN.\", err.Error(); !strings.Contains(a, e) {\n\t\tt.Errorf(\"expect %v error in %v\", e, a)\n\t}\n}", "func providerConfigure(d *schema.ResourceData) (interface{}, error) {\n\tif d.Get(\"url\") == nil {\n\t\treturn nil, fmt.Errorf(\"url cannot be nil\")\n\t}\n\n\tusername := d.Get(\"username\").(string)\n\tpassword := d.Get(\"password\").(string)\n\tapiKey := d.Get(\"api_key\").(string)\n\taccessToken := d.Get(\"access_token\").(string)\n\n\tlog.SetLogger(log.NewLogger(log.INFO, nil))\n\n\tvar client *http.Client\n\tdetails := auth.NewArtifactoryDetails()\n\n\turl := d.Get(\"url\").(string)\n\tif url[len(url)-1] != '/' {\n\t\turl += \"/\"\n\t}\n\tdetails.SetUrl(url)\n\n\tif username != \"\" && password != \"\" {\n\t\tdetails.SetUser(username)\n\t\tdetails.SetPassword(password)\n\t\ttp := transport.BasicAuth{\n\t\t\tUsername: username,\n\t\t\tPassword: password,\n\t\t}\n\t\tclient = tp.Client()\n\t} else if apiKey != \"\" {\n\t\tdetails.SetApiKey(apiKey)\n\t\ttp := &transport.ApiKeyAuth{\n\t\t\tApiKey: apiKey,\n\t\t}\n\t\tclient = tp.Client()\n\t} else if accessToken != \"\" {\n\t\tdetails.SetAccessToken(accessToken)\n\t\ttp := &transport.AccessTokenAuth{\n\t\t\tAccessToken: accessToken,\n\t\t}\n\t\tclient = tp.Client()\n\t} else {\n\t\treturn nil, fmt.Errorf(\"either [username, password] or [api_key] or [access_token] must be set to use provider\")\n\t}\n\n\tconfig, err := config.NewConfigBuilder().\n\t\tSetServiceDetails(details).\n\t\tSetDryRun(false).\n\t\tBuild()\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trtold, err := artifactoryold.NewClient(d.Get(\"url\").(string), client)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trtnew, err := artifactorynew.New(&details, config)\n\n\tif err != nil {\n\t\treturn nil, err\n\t} else if _, resp, err := rtold.V1.System.Ping(context.Background()); err != nil {\n\t\treturn nil, err\n\t} else if resp.StatusCode != 200 {\n\t\treturn nil, fmt.Errorf(\"failed to ping server. Got %d\", resp.StatusCode)\n\t} else if _, err := rtnew.Ping(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tproductid := \"terraform-provider-artifactory/\" + ProviderVersion\n\tcommandid := \"Terraform/\" + version.Version\n\tusage.SendReportUsage(productid, commandid, rtnew)\n\n\trt := &ArtClient{\n\t\tArtOld: rtold,\n\t\tArtNew: rtnew,\n\t}\n\n\treturn rt, nil\n}", "func TestConfigure_UseExistingASN(t *testing.T) {\n\tASNOnDevice := \"65001\"\n\tMockLeafDeviceAdapter := mock.DeviceAdapter{\n\t\tMockGetInterfaces: func(FabricID uint, DeviceID uint, DeviceIP string) ([]domain.Interface, error) {\n\n\t\t\treturn []domain.Interface{domain.Interface{FabricID: FabricID, DeviceID: DeviceID,\n\t\t\t\tIntType: \"ethernet\", IntName: \"1/11\", Mac: \"M1\", ConfigState: \"up\"}}, nil\n\n\t\t},\n\t\tMockGetLLDPs: func(FabricID uint, DeviceID uint, DeviceIP string) ([]domain.LLDP, error) {\n\n\t\t\treturn []domain.LLDP{domain.LLDP{FabricID: FabricID, DeviceID: DeviceID,\n\t\t\t\tLocalIntType: \"ethernet\", LocalIntName: \"1/11\", LocalIntMac: \"M1\",\n\t\t\t\tRemoteIntType: \"ethernet\", RemoteIntName: \"1/22\", RemoteIntMac: \"M2\"}}, nil\n\n\t\t},\n\t\tMockGetASN: func(FabricID uint, Device uint, DeviceIP string) (string, error) {\n\t\t\treturn ASNOnDevice, nil\n\t\t},\n\t}\n\n\tdatabase.Setup(constants.TESTDBLocation)\n\tdefer cleanupDB(database.GetWorkingInstance())\n\n\tDatabaseRepository := gateway.DatabaseRepository{Database: database.GetWorkingInstance()}\n\tdevUC := usecase.DeviceInteractor{Db: &DatabaseRepository, DeviceAdapterFactory: mock.GetDeviceAdapterFactory(MockLeafDeviceAdapter)}\n\tdevUC.AddFabric(context.Background(), MockFabricName)\n\n\tresp, err := devUC.AddDevices(context.Background(), MockFabricName, []string{MockLeaf1IP}, []string{},\n\t\tUserName, Password, false)\n\tassert.Contains(t, resp, usecase.AddDeviceResponse{FabricName: MockFabricName, FabricID: 1, IPAddress: MockLeaf1IP, Role: usecase.LeafRole})\n\n\tassert.Nil(t, err)\n\n\tswitchConfig, err := DatabaseRepository.GetSwitchConfigOnDeviceIP(MockFabricName, MockLeaf1IP)\n\tassert.Equal(t, ASNOnDevice, switchConfig.LocalAS)\n\t//Verify ASN is already on the Switch, so need to push\n\tassert.Equal(t, domain.ConfigNone, switchConfig.ASConfigType)\n\n\t//Next Call without Device having ASN\n\tMockLeafDeviceAdapterWithoutASN := mock.DeviceAdapter{\n\t\tMockGetInterfaces: func(FabricID uint, DeviceID uint, DeviceIP string) ([]domain.Interface, error) {\n\n\t\t\treturn []domain.Interface{domain.Interface{FabricID: FabricID, DeviceID: DeviceID,\n\t\t\t\tIntType: \"ethernet\", IntName: \"1/11\", Mac: \"M1\", ConfigState: \"up\"}}, nil\n\n\t\t},\n\t\tMockGetLLDPs: func(FabricID uint, DeviceID uint, DeviceIP string) ([]domain.LLDP, error) {\n\n\t\t\treturn []domain.LLDP{domain.LLDP{FabricID: FabricID, DeviceID: DeviceID,\n\t\t\t\tLocalIntType: \"ethernet\", LocalIntName: \"1/11\", LocalIntMac: \"M1\",\n\t\t\t\tRemoteIntType: \"ethernet\", RemoteIntName: \"1/22\", RemoteIntMac: \"M2\"}}, nil\n\n\t\t},\n\t}\n\tdevUC.DeviceAdapterFactory = mock.GetDeviceAdapterFactory(MockLeafDeviceAdapterWithoutASN)\n\tresp, err = devUC.AddDevices(context.Background(), MockFabricName, []string{MockLeaf1IP}, []string{},\n\t\tUserName, Password, false)\n\tassert.Contains(t, resp, usecase.AddDeviceResponse{FabricName: MockFabricName, FabricID: 1, IPAddress: MockLeaf1IP, Role: usecase.LeafRole})\n\n\tassert.Nil(t, err)\n\tswitchConfigSecond, err := DatabaseRepository.GetSwitchConfigOnDeviceIP(MockFabricName, MockLeaf1IP)\n\tassert.Equal(t, ASNOnDevice, switchConfigSecond.LocalAS)\n\t//Verify ASN is to be created\n\tassert.Equal(t, domain.ConfigCreate, switchConfigSecond.ASConfigType)\n}", "func IndirectlyTested() string {\n\treturn \"This function is tested via a function reference rather than a direct call\"\n}", "func (mr *MockProviderMockRecorder) Provide(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Provide\", reflect.TypeOf((*MockProvider)(nil).Provide), arg0)\n}", "func (p *Provider) newGCPProviderSpec(windowsServerVersion windows.ServerVersion) (*mapi.GCPMachineProviderSpec, error) {\n\tlistOptions := meta.ListOptions{LabelSelector: \"machine.openshift.io/cluster-api-machine-role=worker\"}\n\tmachines, err := p.oc.Machine.Machines(clusterinfo.MachineAPINamespace).List(context.TODO(), listOptions)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(machines.Items) == 0 {\n\t\treturn nil, fmt.Errorf(\"found 0 worker role machines\")\n\t}\n\tfoundSpec := &mapi.GCPMachineProviderSpec{}\n\terr = json.Unmarshal(machines.Items[0].Spec.ProviderSpec.Value.Raw, foundSpec)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to unmarshal raw machine provider spec: %v\", err)\n\t}\n\n\treturn &mapi.GCPMachineProviderSpec{\n\t\tTypeMeta: meta.TypeMeta{\n\t\t\tAPIVersion: \"machine.openshift.io/v1beta1\",\n\t\t\tKind: \"GCPMachineProviderSpec\",\n\t\t},\n\t\tObjectMeta: meta.ObjectMeta{},\n\t\tUserDataSecret: &core.LocalObjectReference{\n\t\t\tName: clusterinfo.UserDataSecretName,\n\t\t},\n\t\tCredentialsSecret: &core.LocalObjectReference{\n\t\t\tName: foundSpec.CredentialsSecret.Name,\n\t\t},\n\t\tCanIPForward: false,\n\t\tDeletionProtection: false,\n\t\tDisks: []*mapi.GCPDisk{{\n\t\t\tAutoDelete: true,\n\t\t\tBoot: true,\n\t\t\tSizeGB: 128,\n\t\t\tType: \"pd-ssd\",\n\t\t\tImage: getImage(windowsServerVersion),\n\t\t}},\n\t\tNetworkInterfaces: foundSpec.NetworkInterfaces,\n\t\tServiceAccounts: foundSpec.ServiceAccounts,\n\t\tTags: foundSpec.Tags,\n\t\tMachineType: foundSpec.MachineType,\n\t\tRegion: foundSpec.Region,\n\t\tZone: foundSpec.Zone,\n\t\tProjectID: foundSpec.ProjectID,\n\t}, nil\n}", "func Provider() terraform.ResourceProvider {\n\treturn &schema.Provider{\n\t\tSchema: map[string]*schema.Schema{\n\t\t\t\"url\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"APPGATE_ADDRESS\", \"\"),\n\t\t\t},\n\t\t\t\"username\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"APPGATE_USERNAME\", \"\"),\n\t\t\t},\n\t\t\t\"password\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"APPGATE_PASSWORD\", \"\"),\n\t\t\t},\n\t\t\t\"provider\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"APPGATE_PROVIDER\", \"local\"),\n\t\t\t},\n\t\t\t\"insecure\": {\n\t\t\t\tType: schema.TypeBool,\n\t\t\t\tRequired: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"APPGATE_INSECURE\", true),\n\t\t\t},\n\t\t\t\"debug\": {\n\t\t\t\tType: schema.TypeBool,\n\t\t\t\tOptional: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"APPGATE_HTTP_DEBUG\", false),\n\t\t\t},\n\t\t},\n\t\tDataSourcesMap: map[string]*schema.Resource{\n\t\t\t\"appgate_appliance\": dataSourceAppgateAppliance(),\n\t\t\t\"appgate_entitlement\": dataSourceAppgateEntitlement(),\n\t\t\t\"appgate_site\": dataSourceAppgateSite(),\n\t\t\t\"appgate_condition\": dataSourceAppgateCondition(),\n\t\t\t\"appgate_policy\": dataSourceAppgatePolicy(),\n\t\t\t\"appgate_ringfence_rule\": dataSourceAppgateRingfenceRule(),\n\t\t\t\"appgate_criteria_script\": dataSourceCriteriaScript(),\n\t\t\t\"appgate_entitlement_script\": dataSourceEntitlementScript(),\n\t\t\t\"appgate_device_script\": dataSourceDeviceScript(),\n\t\t\t\"appgate_appliance_customization\": dataSourceAppgateApplianceCustomization(),\n\t\t\t\"appgate_ip_pool\": dataSourceAppgateIPPool(),\n\t\t\t\"appgate_administrative_role\": dataSourceAppgateAdministrativeRole(),\n\t\t\t\"appgate_global_settings\": dataSourceGlobalSettings(),\n\t\t\t\"appgate_trusted_certificate\": dataSourceAppgateTrustedCertificate(),\n\t\t\t\"appgate_mfa_provider\": dataSourceAppgateMfaProvider(),\n\t\t\t\"appgate_local_user\": dataSourceAppgateLocalUser(),\n\t\t\t\"appgate_identity_provider\": dataSourceAppgateIdentityProvider(),\n\t\t},\n\t\tResourcesMap: map[string]*schema.Resource{\n\t\t\t\"appgate_appliance\": resourceAppgateAppliance(),\n\t\t\t\"appgate_entitlement\": resourceAppgateEntitlement(),\n\t\t\t\"appgate_site\": resourceAppgateSite(),\n\t\t\t\"appgate_ringfence_rule\": resourceAppgateRingfenceRule(),\n\t\t\t\"appgate_condition\": resourceAppgateCondition(),\n\t\t\t\"appgate_policy\": resourceAppgatePolicy(),\n\t\t\t\"appgate_criteria_script\": resourceAppgateCriteriaScript(),\n\t\t\t\"appgate_entitlement_script\": resourceAppgateEntitlementScript(),\n\t\t\t\"appgate_device_script\": resourceAppgateDeviceScript(),\n\t\t\t\"appgate_appliance_customization\": resourceAppgateApplianceCustomizations(),\n\t\t\t\"appgate_ip_pool\": resourceAppgateIPPool(),\n\t\t\t\"appgate_administrative_role\": resourceAppgateAdministrativeRole(),\n\t\t\t\"appgate_global_settings\": resourceGlobalSettings(),\n\t\t\t\"appgate_ldap_identity_provider\": resourceAppgateLdapProvider(),\n\t\t\t\"appgate_trusted_certificate\": resourceAppgateTrustedCertificate(),\n\t\t\t\"appgate_mfa_provider\": resourceAppgateMfaProvider(),\n\t\t\t\"appgate_local_user\": resourceAppgateLocalUser(),\n\t\t\t\"appgate_license\": resourceAppgateLicense(),\n\t\t\t\"appgate_admin_mfa_settings\": resourceAdminMfaSettings(),\n\t\t\t\"appgate_client_connections\": resourceClientConnections(),\n\t\t\t\"appgate_blacklist_user\": resourceAppgateBlacklistUser(),\n\t\t},\n\t\tConfigureFunc: providerConfigure,\n\t}\n}", "func (ind ErrInvalidNetworkDriver) BadRequest() {}", "func (m *Machine) GenerateProviderID() (string, error) {\n\tif m.vmiInstance == nil {\n\t\treturn \"\", errors.New(\"Underlying Kubevirt VM is NOT running\")\n\t}\n\n\tproviderID := fmt.Sprintf(\"kubevirt://%s\", m.machineContext.KubevirtMachine.Name)\n\n\treturn providerID, nil\n}", "func parseKogitoInfraResource(targetResourceType string) (*v1.InfraResource, error) {\n\tswitch targetResourceType {\n\t// case infrastructure.InfinispanKind:\n\t// \treturn &v1.InfraResource{APIVersion: infrastructure.InfinispanAPIVersion, Kind: infrastructure.InfinispanKind}, nil\n\tcase infrastructure.KafkaKind:\n\t\treturn &v1.InfraResource{APIVersion: infrastructure.KafkaAPIVersion, Kind: infrastructure.KafkaKind}, nil\n\t// case infrastructure.KeycloakKind:\n\t// \treturn &v1.InfraResource{APIVersion: infrastructure.KeycloakAPIVersion, Kind: infrastructure.KeycloakKind}, nil\n\t// case infrastructure.MongoDBKind:\n\t// \treturn &v1.InfraResource{APIVersion: infrastructure.MongoDBAPIVersion, Kind: infrastructure.MongoDBKind}, nil\n\t// case infrastructure.KnativeEventingBrokerKind:\n\t// \treturn &v1.InfraResource{APIVersion: infrastructure.KnativeEventingAPIVersion, Kind: infrastructure.KnativeEventingBrokerKind}, nil\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"Unknown KogitoInfra target resource type %s\", targetResourceType)\n\t}\n}", "func (e *ErrUnknownProvider) Is(target error) bool {\n\t_, ok := target.(*ErrUnknownProvider)\n\treturn ok\n}", "func (c *FilecoinRetrievalProviderAdmin) InitialiseProvider(providerRegistrar register.ProviderRegistrar, providerPrivKey *fcrcrypto.KeyPair, providerPrivKeyVer *fcrcrypto.KeyVersion) error {\n\terr := c.AdminApiCaller.RequestInitialiseKey(providerRegistrar, providerPrivKey, providerPrivKeyVer, c.Settings.providerAdminPrivateKey, c.Settings.providerAdminPrivateKeyVer)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Add this provider to the active providers list\n\tc.ActiveProvidersLock.Lock()\n\tc.ActiveProviders[providerRegistrar.GetNodeID()] = providerRegistrar\n\tc.ActiveProvidersLock.Unlock()\n\treturn nil\n}", "func (d *driver) Supported(\n\tctx types.Context,\n\topts types.Store) (bool, error) {\n\treturn utils.IsAzureInstance(ctx)\n}", "func TestConfigure_InvalidSpineASN(t *testing.T) {\n\tASNOnDevice := \"64519\"\n\tMockSpineDeviceAdapter := mock.DeviceAdapter{\n\t\tMockGetInterfaces: func(FabricID uint, DeviceID uint, DeviceIP string) ([]domain.Interface, error) {\n\n\t\t\treturn []domain.Interface{domain.Interface{FabricID: FabricID, DeviceID: DeviceID,\n\t\t\t\tIntType: \"ethernet\", IntName: \"1/11\", Mac: \"M1\", ConfigState: \"up\"}}, nil\n\n\t\t},\n\t\tMockGetLLDPs: func(FabricID uint, DeviceID uint, DeviceIP string) ([]domain.LLDP, error) {\n\n\t\t\treturn []domain.LLDP{domain.LLDP{FabricID: FabricID, DeviceID: DeviceID,\n\t\t\t\tLocalIntType: \"ethernet\", LocalIntName: \"1/11\", LocalIntMac: \"M1\",\n\t\t\t\tRemoteIntType: \"ethernet\", RemoteIntName: \"1/22\", RemoteIntMac: \"M2\"}}, nil\n\n\t\t},\n\t\tMockGetASN: func(FabricID uint, Device uint, DeviceIP string) (string, error) {\n\t\t\treturn ASNOnDevice, nil\n\t\t},\n\t}\n\n\tdatabase.Setup(constants.TESTDBLocation)\n\tdefer cleanupDB(database.GetWorkingInstance())\n\n\tDatabaseRepository := gateway.DatabaseRepository{Database: database.GetWorkingInstance()}\n\tdevUC := usecase.DeviceInteractor{Db: &DatabaseRepository, DeviceAdapterFactory: mock.GetDeviceAdapterFactory(MockSpineDeviceAdapter)}\n\tdevUC.AddFabric(context.Background(), MockFabricName)\n\n\tresp, err := devUC.AddDevices(context.Background(), MockFabricName, []string{}, []string{MockSpine1IP},\n\t\tUserName, Password, false)\n\tassert.Contains(t, resp, usecase.AddDeviceResponse{FabricName: MockFabricName, FabricID: 1, IPAddress: MockSpine1IP, Role: usecase.SpineRole,\n\t\tErrors: []error{errors.New(\"ASN 64519 not in range 64512\")}})\n\n\tassert.NotNil(t, err)\n\n}", "func TestLookupEndpointPanicsOnInvalidType(t *testing.T) {\n\tdefer func() {\n\t\tif r := recover(); r == nil {\n\t\t\tt.Error(\"lookupEndpoint should panic if an invalid conntype is specified.\")\n\t\t}\n\t}()\n\tlookupEndpoint(context.Background(), nil, nil, jid.JID{}, \"wssorbashorsomething\")\n}", "func Provider() terraform.ResourceProvider {\n\treturn &schema.Provider{\n\t\tSchema: map[string]*schema.Schema{\n\t\t\t\"apikey\": &schema.Schema{\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"NS1_APIKEY\", nil),\n\t\t\t\tDescription: descriptions[\"api_key\"],\n\t\t\t},\n\t\t\t\"endpoint\": &schema.Schema{\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"NS1_ENDPOINT\", nil),\n\t\t\t\tDescription: descriptions[\"endpoint\"],\n\t\t\t},\n\t\t\t\"ignore_ssl\": &schema.Schema{\n\t\t\t\tType: schema.TypeBool,\n\t\t\t\tOptional: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"NS1_IGNORE_SSL\", nil),\n\t\t\t\tDescription: descriptions[\"ignore_ssl\"],\n\t\t\t},\n\t\t},\n\t\tResourcesMap: map[string]*schema.Resource{\n\t\t\t\"ns1_zone\": zoneResource(),\n\t\t\t\"ns1_record\": recordResource(),\n\t\t\t\"ns1_datasource\": dataSourceResource(),\n\t\t\t\"ns1_datafeed\": dataFeedResource(),\n\t\t\t\"ns1_monitoringjob\": monitoringJobResource(),\n\t\t\t\"ns1_notifylist\": notifyListResource(),\n\t\t\t\"ns1_user\": userResource(),\n\t\t\t\"ns1_apikey\": apikeyResource(),\n\t\t\t\"ns1_team\": teamResource(),\n\t\t},\n\t\tConfigureFunc: ns1Configure,\n\t}\n}", "func providerConfigure(data *schema.ResourceData) (interface{}, error) {\n\tlog.Println(\"[INFO] Initializing Client\")\n\n\tconfig := Config{\n\t\tAPIKey: data.Get(\"api_key\").(string),\n\t\tAPIURL: data.Get(\"api_url\").(string),\n\t}\n\n\treturn config.Client()\n}", "func checkAllProviders(e2eFile string) error {\n\tcheckFailed := false\n\tinConformanceCode := false\n\n\tregStartConformance := regexp.MustCompile(patternStartConformance)\n\tregEndConformance := regexp.MustCompile(patternEndConformance)\n\tregSkip := regexp.MustCompile(patternSkip)\n\n\tfileInput, err := os.ReadFile(e2eFile)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to read file %s: %w\", e2eFile, err)\n\t}\n\tscanner := bufio.NewScanner(bytes.NewReader(fileInput))\n\tscanner.Split(bufio.ScanLines)\n\n\tfor scanner.Scan() {\n\t\tline := scanner.Text()\n\t\tif regStartConformance.MatchString(line) {\n\t\t\tif inConformanceCode {\n\t\t\t\treturn errors.New(\"Missed the end of previous conformance test. There might be a bug in this script.\")\n\t\t\t}\n\t\t\tinConformanceCode = true\n\t\t}\n\t\tif inConformanceCode {\n\t\t\tif regSkip.MatchString(line) {\n\t\t\t\t// To list all invalid places in a single operation of this tool, here doesn't return error and continues checking.\n\t\t\t\tfmt.Fprintf(os.Stderr, \"%v: Conformance test should not call any e2eskipper.Skip*()\\n\", e2eFile)\n\t\t\t\tcheckFailed = true\n\t\t\t}\n\t\t\tif regEndConformance.MatchString(line) {\n\t\t\t\tinConformanceCode = false\n\t\t\t}\n\t\t}\n\t}\n\tif inConformanceCode {\n\t\treturn errors.New(\"Missed the end of previous conformance test. There might be a bug in this script.\")\n\t}\n\tif checkFailed {\n\t\treturn errors.New(\"We need to fix the above errors.\")\n\t}\n\treturn nil\n}", "func (mr *MockHostEventMockRecorder) GetInfraEnvId() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetInfraEnvId\", reflect.TypeOf((*MockHostEvent)(nil).GetInfraEnvId))\n}" ]
[ "0.693289", "0.6662321", "0.6476766", "0.63881636", "0.61153394", "0.5661946", "0.56285894", "0.54785734", "0.5444923", "0.53784674", "0.53772527", "0.534679", "0.53375566", "0.5255437", "0.52410465", "0.52378464", "0.52251965", "0.5223927", "0.5214554", "0.5169369", "0.5103248", "0.5099115", "0.50802255", "0.5047766", "0.5014787", "0.500037", "0.49925166", "0.4981886", "0.49682713", "0.49474642", "0.49454272", "0.49182457", "0.49106047", "0.48998418", "0.48992407", "0.48827943", "0.4853908", "0.4840492", "0.48279625", "0.4819584", "0.48132038", "0.48126125", "0.48104617", "0.47890764", "0.4757852", "0.47573876", "0.47570863", "0.47565565", "0.47519723", "0.47504506", "0.4733425", "0.4732123", "0.47300613", "0.47259724", "0.4721239", "0.47129026", "0.4707523", "0.47040692", "0.47004753", "0.46987998", "0.4696343", "0.46934712", "0.4685733", "0.46790114", "0.4677129", "0.4669688", "0.46680433", "0.4659112", "0.46382907", "0.46371073", "0.46358335", "0.46336132", "0.4629408", "0.46187285", "0.4606787", "0.46036246", "0.46026108", "0.46014923", "0.46003056", "0.46001935", "0.45909837", "0.45904207", "0.4586924", "0.45793584", "0.4577275", "0.45745397", "0.45688084", "0.45542684", "0.45515954", "0.45432913", "0.45395678", "0.45220745", "0.45173663", "0.45156038", "0.4511053", "0.45103416", "0.45054534", "0.44998696", "0.4498753", "0.4496821" ]
0.6767527
1
LocalDiscoveryProvider mocks base method
func (m *MockProviders) LocalDiscoveryProvider() fab.LocalDiscoveryProvider { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "LocalDiscoveryProvider") ret0, _ := ret[0].(fab.LocalDiscoveryProvider) return ret0 }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (m *MockClient) LocalDiscoveryProvider() fab.LocalDiscoveryProvider {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"LocalDiscoveryProvider\")\n\tret0, _ := ret[0].(fab.LocalDiscoveryProvider)\n\treturn ret0\n}", "func (c *Provider) LocalDiscoveryProvider() fab.LocalDiscoveryProvider {\n\treturn c.localDiscoveryProvider\n}", "func (m *MockMemberList) LocalNode() discovery.Member {\n\tret := m.ctrl.Call(m, \"LocalNode\")\n\tret0, _ := ret[0].(discovery.Member)\n\treturn ret0\n}", "func NewMockDiscoveryProvider(err error, peers []fab.Peer) (*MockStaticDiscoveryProvider, error) {\n\treturn &MockStaticDiscoveryProvider{Error: err, Peers: peers}, nil\n}", "func TestLocalDomain_NetworkServiceRegistry(t *testing.T) {\n\tt.Cleanup(func() { goleak.VerifyNone(t) })\n\n\tctx, cancel := context.WithTimeout(context.Background(), time.Second)\n\tdefer cancel()\n\n\tdnsServer := sandbox.NewFakeResolver()\n\n\tdomain1 := sandbox.NewBuilder(ctx, t).\n\t\tSetNodesCount(0).\n\t\tSetDNSDomainName(\"cluster.local\").\n\t\tSetDNSResolver(dnsServer).\n\t\tBuild()\n\n\tclient1 := registryclient.NewNetworkServiceRegistryClient(ctx,\n\t\tregistryclient.WithDialOptions(grpc.WithTransportCredentials(insecure.NewCredentials())),\n\t\tregistryclient.WithClientURL(domain1.Registry.URL))\n\n\texpected, err := client1.Register(context.Background(), &registryapi.NetworkService{\n\t\tName: \"ns-1@\" + domain1.Name,\n\t})\n\n\trequire.Nil(t, err)\n\trequire.True(t, strings.Contains(expected.GetName(), \"@\"+domain1.Name))\n\n\tclient2 := registryclient.NewNetworkServiceRegistryClient(ctx,\n\t\tregistryclient.WithDialOptions(grpc.WithTransportCredentials(insecure.NewCredentials())),\n\t\tregistryclient.WithClientURL(domain1.Registry.URL))\n\n\tstream, err := client2.Find(context.Background(), &registryapi.NetworkServiceQuery{\n\t\tNetworkService: &registryapi.NetworkService{\n\t\t\tName: expected.Name,\n\t\t},\n\t})\n\n\trequire.Nil(t, err)\n\n\tlist := registryapi.ReadNetworkServiceList(stream)\n\n\trequire.Len(t, list, 1)\n\trequire.Equal(t, \"ns-1@cluster.local\", list[0].Name)\n}", "func Mock() Cluster { return mockCluster{} }", "func (_m *MockPlcDriver) SupportsDiscovery() bool {\n\tret := _m.Called()\n\n\tvar r0 bool\n\tif rf, ok := ret.Get(0).(func() bool); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tr0 = ret.Get(0).(bool)\n\t}\n\n\treturn r0\n}", "func mockedGranter(kubeutil *kube.Kube, app *v1.RadixRegistration, namespace string, serviceAccount *corev1.ServiceAccount) error {\n\treturn nil\n}", "func (dp *MockStaticDiscoveryProvider) CreateLocalDiscoveryService(mspID string) (fab.DiscoveryService, error) {\n\treturn &MockStaticDiscoveryService{Error: dp.Error, Peers: dp.Peers}, nil\n}", "func (c *Local) LocalDiscoveryService() fab.DiscoveryService {\n\treturn c.localDiscovery\n}", "func (m *MockService) Discovery() *idp.DiscoveryResponse {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Discovery\")\n\tret0, _ := ret[0].(*idp.DiscoveryResponse)\n\treturn ret0\n}", "func (m *MockInterface) Discovery() discovery.DiscoveryInterface {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Discovery\")\n\tret0, _ := ret[0].(discovery.DiscoveryInterface)\n\treturn ret0\n}", "func (m *MockEarlyConnection) LocalAddr() net.Addr {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"LocalAddr\")\n\tret0, _ := ret[0].(net.Addr)\n\treturn ret0\n}", "func newLocalService(config fab.EndpointConfig, mspID string, opts ...coptions.Opt) *LocalService {\n\tlogger.Debug(\"Creating new local discovery service\")\n\n\ts := &LocalService{mspID: mspID}\n\ts.service = newService(config, s.queryPeers, opts...)\n\treturn s\n}", "func (m *MockInformation) LocalLocation() *universe.View {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"LocalLocation\")\n\tret0, _ := ret[0].(*universe.View)\n\treturn ret0\n}", "func (l *Factory) CreateLocalDiscoveryProvider(config fabApi.EndpointConfig) (fabApi.LocalDiscoveryProvider, error) {\n\tlogger.Debug(\"create local Provider Impl\")\n\treturn &impl{config, l.LocalPeer, l.LocalPeerTLSCertPem}, nil\n}", "func newLocalProviderWithClock(t []string, clock clock.Clock) Provider {\n\tp := &localProvider{\n\t\ttags: t,\n\t\texpectedTags: t,\n\t}\n\n\tif config.IsExpectedTagsSet(coreConfig.Datadog) {\n\t\tp.expectedTags = append(p.tags, hostMetadataUtils.GetHostTags(context.TODO(), false, coreConfig.Datadog).System...)\n\n\t\t// expected tags deadline is based on the agent start time, which may have been earlier\n\t\t// than the current time.\n\t\texpectedTagsDeadline := coreConfig.StartTime.Add(coreConfig.Datadog.GetDuration(\"logs_config.expected_tags_duration\"))\n\n\t\t// reset submitExpectedTags after deadline elapsed\n\t\tclock.AfterFunc(expectedTagsDeadline.Sub(clock.Now()), func() {\n\t\t\tp.Lock()\n\t\t\tdefer p.Unlock()\n\t\t\tp.expectedTags = nil\n\t\t})\n\t}\n\n\treturn p\n}", "func TestExternalNameService(t *testing.T) {\n\trh, c, done := setup(t, enableExternalNameService(t))\n\tdefer done()\n\n\ts1 := fixture.NewService(\"kuard\").\n\t\tWithSpec(v1.ServiceSpec{\n\t\t\tPorts: []v1.ServicePort{{\n\t\t\t\tPort: 80,\n\t\t\t\tTargetPort: intstr.FromInt(8080),\n\t\t\t}},\n\t\t\tExternalName: \"foo.io\",\n\t\t\tType: v1.ServiceTypeExternalName,\n\t\t})\n\n\ti1 := &networking_v1.Ingress{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: \"kuard\",\n\t\t\tNamespace: s1.Namespace,\n\t\t},\n\t\tSpec: networking_v1.IngressSpec{\n\t\t\tDefaultBackend: featuretests.IngressBackend(s1),\n\t\t},\n\t}\n\trh.OnAdd(s1)\n\trh.OnAdd(i1)\n\n\tc.Request(routeType).Equals(&envoy_discovery_v3.DiscoveryResponse{\n\t\tResources: resources(t,\n\t\t\tenvoy_v3.RouteConfiguration(\"ingress_http\",\n\t\t\t\tenvoy_v3.VirtualHost(\"*\",\n\t\t\t\t\t&envoy_route_v3.Route{\n\t\t\t\t\t\tMatch: routePrefix(\"/\"),\n\t\t\t\t\t\tAction: routeCluster(\"default/kuard/80/da39a3ee5e\"),\n\t\t\t\t\t},\n\t\t\t\t),\n\t\t\t),\n\t\t),\n\t\tTypeUrl: routeType,\n\t})\n\n\tc.Request(clusterType).Equals(&envoy_discovery_v3.DiscoveryResponse{\n\t\tResources: resources(t,\n\t\t\texternalNameCluster(\"default/kuard/80/da39a3ee5e\", \"default/kuard\", \"default_kuard_80\", \"foo.io\", 80),\n\t\t),\n\t\tTypeUrl: clusterType,\n\t})\n\n\trh.OnDelete(i1)\n\n\trh.OnAdd(fixture.NewProxy(\"kuard\").\n\t\tWithFQDN(\"kuard.projectcontour.io\").\n\t\tWithSpec(contour_api_v1.HTTPProxySpec{\n\t\t\tRoutes: []contour_api_v1.Route{{\n\t\t\t\tServices: []contour_api_v1.Service{{\n\t\t\t\t\tName: s1.Name,\n\t\t\t\t\tPort: 80,\n\t\t\t\t}},\n\t\t\t}},\n\t\t}),\n\t)\n\n\tc.Request(routeType).Equals(&envoy_discovery_v3.DiscoveryResponse{\n\t\tResources: resources(t,\n\t\t\tenvoy_v3.RouteConfiguration(\"ingress_http\",\n\t\t\t\tenvoy_v3.VirtualHost(\"kuard.projectcontour.io\",\n\t\t\t\t\t&envoy_route_v3.Route{\n\t\t\t\t\t\tMatch: routePrefix(\"/\"),\n\t\t\t\t\t\tAction: routeCluster(\"default/kuard/80/a28d1ec01b\"),\n\t\t\t\t\t},\n\t\t\t\t),\n\t\t\t),\n\t\t),\n\t\tTypeUrl: routeType,\n\t})\n\n\tc.Request(clusterType).Equals(&envoy_discovery_v3.DiscoveryResponse{\n\t\tResources: resources(t,\n\t\t\texternalNameCluster(\"default/kuard/80/a28d1ec01b\", \"default/kuard\", \"default_kuard_80\", \"foo.io\", 80),\n\t\t),\n\t\tTypeUrl: clusterType,\n\t})\n\n\t// After we set the Host header, the cluster should remain\n\t// the same, but the Route should do update the Host header.\n\trh.OnDelete(fixture.NewProxy(\"kuard\").WithSpec(contour_api_v1.HTTPProxySpec{}))\n\trh.OnAdd(fixture.NewProxy(\"kuard\").\n\t\tWithFQDN(\"kuard.projectcontour.io\").\n\t\tWithSpec(contour_api_v1.HTTPProxySpec{\n\t\t\tRoutes: []contour_api_v1.Route{{\n\t\t\t\tServices: []contour_api_v1.Service{{\n\t\t\t\t\tName: s1.Name,\n\t\t\t\t\tPort: 80,\n\t\t\t\t}},\n\t\t\t\tRequestHeadersPolicy: &contour_api_v1.HeadersPolicy{\n\t\t\t\t\tSet: []contour_api_v1.HeaderValue{{\n\t\t\t\t\t\tName: \"Host\",\n\t\t\t\t\t\tValue: \"external.address\",\n\t\t\t\t\t}},\n\t\t\t\t},\n\t\t\t}},\n\t\t}),\n\t)\n\n\tc.Request(routeType).Equals(&envoy_discovery_v3.DiscoveryResponse{\n\t\tTypeUrl: routeType,\n\t\tResources: resources(t,\n\t\t\tenvoy_v3.RouteConfiguration(\"ingress_http\",\n\t\t\t\tenvoy_v3.VirtualHost(\"kuard.projectcontour.io\",\n\t\t\t\t\t&envoy_route_v3.Route{\n\t\t\t\t\t\tMatch: routePrefix(\"/\"),\n\t\t\t\t\t\tAction: routeHostRewrite(\"default/kuard/80/95e871afaf\", \"external.address\"),\n\t\t\t\t\t},\n\t\t\t\t),\n\t\t\t),\n\t\t),\n\t})\n\n\tc.Request(clusterType).Equals(&envoy_discovery_v3.DiscoveryResponse{\n\t\tTypeUrl: clusterType,\n\t\tResources: resources(t,\n\t\t\texternalNameCluster(\"default/kuard/80/95e871afaf\", \"default/kuard\", \"default_kuard_80\", \"foo.io\", 80),\n\t\t),\n\t})\n\n\t// Now try the same configuration, but enable HTTP/2. We\n\t// should still find that the same configuration applies, but\n\t// TLS is enabled and the SNI server name is overwritten from\n\t// the Host header.\n\trh.OnDelete(fixture.NewProxy(\"kuard\").WithSpec(contour_api_v1.HTTPProxySpec{}))\n\trh.OnAdd(fixture.NewProxy(\"kuard\").\n\t\tWithFQDN(\"kuard.projectcontour.io\").\n\t\tWithSpec(contour_api_v1.HTTPProxySpec{\n\t\t\tRoutes: []contour_api_v1.Route{{\n\t\t\t\tServices: []contour_api_v1.Service{{\n\t\t\t\t\tProtocol: ref.To(\"h2\"),\n\t\t\t\t\tName: s1.Name,\n\t\t\t\t\tPort: 80,\n\t\t\t\t}},\n\t\t\t\tRequestHeadersPolicy: &contour_api_v1.HeadersPolicy{\n\t\t\t\t\tSet: []contour_api_v1.HeaderValue{{\n\t\t\t\t\t\tName: \"Host\",\n\t\t\t\t\t\tValue: \"external.address\",\n\t\t\t\t\t}},\n\t\t\t\t},\n\t\t\t}},\n\t\t}),\n\t)\n\n\tc.Request(routeType).Equals(&envoy_discovery_v3.DiscoveryResponse{\n\t\tTypeUrl: routeType,\n\t\tResources: resources(t,\n\t\t\tenvoy_v3.RouteConfiguration(\"ingress_http\",\n\t\t\t\tenvoy_v3.VirtualHost(\"kuard.projectcontour.io\",\n\t\t\t\t\t&envoy_route_v3.Route{\n\t\t\t\t\t\tMatch: routePrefix(\"/\"),\n\t\t\t\t\t\tAction: routeHostRewrite(\"default/kuard/80/cdbf075ad8\", \"external.address\"),\n\t\t\t\t\t},\n\t\t\t\t),\n\t\t\t),\n\t\t),\n\t})\n\n\tc.Request(clusterType).Equals(&envoy_discovery_v3.DiscoveryResponse{\n\t\tTypeUrl: clusterType,\n\t\tResources: resources(t,\n\t\t\tDefaultCluster(\n\t\t\t\texternalNameCluster(\"default/kuard/80/cdbf075ad8\", \"default/kuard\", \"default_kuard_80\", \"foo.io\", 80),\n\t\t\t\t&envoy_cluster_v3.Cluster{\n\t\t\t\t\tTypedExtensionProtocolOptions: map[string]*anypb.Any{\n\t\t\t\t\t\t\"envoy.extensions.upstreams.http.v3.HttpProtocolOptions\": protobuf.MustMarshalAny(\n\t\t\t\t\t\t\t&envoy_extensions_upstream_http_v3.HttpProtocolOptions{\n\t\t\t\t\t\t\t\tUpstreamProtocolOptions: &envoy_extensions_upstream_http_v3.HttpProtocolOptions_ExplicitHttpConfig_{\n\t\t\t\t\t\t\t\t\tExplicitHttpConfig: &envoy_extensions_upstream_http_v3.HttpProtocolOptions_ExplicitHttpConfig{\n\t\t\t\t\t\t\t\t\t\tProtocolConfig: &envoy_extensions_upstream_http_v3.HttpProtocolOptions_ExplicitHttpConfig_Http2ProtocolOptions{},\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t&envoy_cluster_v3.Cluster{\n\t\t\t\t\tTransportSocket: envoy_v3.UpstreamTLSTransportSocket(\n\t\t\t\t\t\tenvoy_v3.UpstreamTLSContext(nil, \"external.address\", nil, \"h2\"),\n\t\t\t\t\t),\n\t\t\t\t},\n\t\t\t),\n\t\t),\n\t})\n\n\t// Now try the same configuration, but enable TLS (which\n\t// means HTTP/1.1 over TLS) rather than HTTP/2. We should get\n\t// TLS enabled with the overridden SNI name. but no HTTP/2\n\t// protocol config.\n\trh.OnDelete(fixture.NewProxy(\"kuard\").WithSpec(contour_api_v1.HTTPProxySpec{}))\n\trh.OnAdd(fixture.NewProxy(\"kuard\").\n\t\tWithFQDN(\"kuard.projectcontour.io\").\n\t\tWithSpec(contour_api_v1.HTTPProxySpec{\n\t\t\tRoutes: []contour_api_v1.Route{{\n\t\t\t\tServices: []contour_api_v1.Service{{\n\t\t\t\t\tProtocol: ref.To(\"tls\"),\n\t\t\t\t\tName: s1.Name,\n\t\t\t\t\tPort: 80,\n\t\t\t\t}},\n\t\t\t\tRequestHeadersPolicy: &contour_api_v1.HeadersPolicy{\n\t\t\t\t\tSet: []contour_api_v1.HeaderValue{{\n\t\t\t\t\t\tName: \"Host\",\n\t\t\t\t\t\tValue: \"external.address\",\n\t\t\t\t\t}},\n\t\t\t\t},\n\t\t\t}},\n\t\t}),\n\t)\n\n\tc.Request(routeType).Equals(&envoy_discovery_v3.DiscoveryResponse{\n\t\tTypeUrl: routeType,\n\t\tResources: resources(t,\n\t\t\tenvoy_v3.RouteConfiguration(\"ingress_http\",\n\t\t\t\tenvoy_v3.VirtualHost(\"kuard.projectcontour.io\",\n\t\t\t\t\t&envoy_route_v3.Route{\n\t\t\t\t\t\tMatch: routePrefix(\"/\"),\n\t\t\t\t\t\tAction: routeHostRewrite(\"default/kuard/80/f9439c1de8\", \"external.address\"),\n\t\t\t\t\t},\n\t\t\t\t),\n\t\t\t),\n\t\t),\n\t})\n\n\tc.Request(clusterType).Equals(&envoy_discovery_v3.DiscoveryResponse{\n\t\tTypeUrl: clusterType,\n\t\tResources: resources(t,\n\t\t\tDefaultCluster(\n\t\t\t\texternalNameCluster(\"default/kuard/80/f9439c1de8\", \"default/kuard\", \"default_kuard_80\", \"foo.io\", 80),\n\t\t\t\t&envoy_cluster_v3.Cluster{\n\t\t\t\t\tTransportSocket: envoy_v3.UpstreamTLSTransportSocket(\n\t\t\t\t\t\tenvoy_v3.UpstreamTLSContext(nil, \"external.address\", nil),\n\t\t\t\t\t),\n\t\t\t\t},\n\t\t\t),\n\t\t),\n\t})\n\n\tsec1 := &v1.Secret{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: \"secret\",\n\t\t\tNamespace: \"default\",\n\t\t},\n\t\tType: \"kubernetes.io/tls\",\n\t\tData: featuretests.Secretdata(featuretests.CERTIFICATE, featuretests.RSA_PRIVATE_KEY),\n\t}\n\n\t// Create TCPProxy with upstream protocol 'tls' to an externalName type service\n\t// and verify that the SNI on the upstream request matches the externalName value.\n\trh.OnDelete(fixture.NewProxy(\"kuard\").WithSpec(contour_api_v1.HTTPProxySpec{}))\n\trh.OnAdd(sec1)\n\trh.OnAdd(fixture.NewProxy(\"kuard\").\n\t\tWithFQDN(\"kuard.projectcontour.io\").\n\t\tWithCertificate(sec1.Name).\n\t\tWithSpec(contour_api_v1.HTTPProxySpec{\n\t\t\tTCPProxy: &contour_api_v1.TCPProxy{\n\t\t\t\tServices: []contour_api_v1.Service{{\n\t\t\t\t\tProtocol: ref.To(\"tls\"),\n\t\t\t\t\tName: s1.Name,\n\t\t\t\t\tPort: 80,\n\t\t\t\t}},\n\t\t\t},\n\t\t}),\n\t)\n\n\tc.Request(clusterType).Equals(&envoy_discovery_v3.DiscoveryResponse{\n\t\tTypeUrl: clusterType,\n\t\tResources: resources(t,\n\t\t\tDefaultCluster(\n\t\t\t\texternalNameCluster(\"default/kuard/80/7d449598f5\", \"default/kuard\", \"default_kuard_80\", \"foo.io\", 80),\n\t\t\t\t&envoy_cluster_v3.Cluster{\n\t\t\t\t\tTransportSocket: envoy_v3.UpstreamTLSTransportSocket(\n\t\t\t\t\t\tenvoy_v3.UpstreamTLSContext(nil, \"foo.io\", nil),\n\t\t\t\t\t),\n\t\t\t\t},\n\t\t\t),\n\t\t),\n\t})\n}", "func setupDiscovery(ctx context.Context, h host.Host) error {\n\t// setup mDNS discovery to find local peers\n\tdisc, err := discovery.NewMdnsService(ctx, h, DiscoveryInterval, DiscoveryServiceTag)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tn := discoveryNotifee{h: h}\n\tdisc.RegisterNotifee(&n)\n\treturn nil\n}", "func fakeDiscovery() discovery.DiscoveryInterface {\n\tfake := &fakediscovery.FakeDiscovery{Fake: &coretesting.Fake{}}\n\tapps := []metav1.APIResource{\n\t\t{Name: \"deployments\", Namespaced: true, Kind: \"Deployment\"},\n\t\t{Name: \"controllerrevisions\", Namespaced: true, Kind: \"ControllerRevision\"},\n\t\t{Name: \"daemonsets\", Namespaced: true, Kind: \"DaemonSet\"},\n\t\t{Name: \"replicasets\", Namespaced: true, Kind: \"ReplicaSet\"},\n\t\t{Name: \"statefulsets\", Namespaced: true, Kind: \"StatefulSet\"},\n\t}\n\tfake.Resources = []*metav1.APIResourceList{\n\t\t{\n\t\t\tGroupVersion: corev1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"bindings\", Namespaced: true, Kind: \"Binding\"},\n\t\t\t\t{Name: \"componentstatuses\", Kind: \"ComponentStatus\"},\n\t\t\t\t{Name: \"configmaps\", Namespaced: true, Kind: \"ConfigMap\"},\n\t\t\t\t{Name: \"endpoints\", Namespaced: true, Kind: \"Endpoints\"},\n\t\t\t\t{Name: \"events\", Namespaced: true, Kind: \"Event\"},\n\t\t\t\t{Name: \"limitranges\", Namespaced: true, Kind: \"LimitRange\"},\n\t\t\t\t{Name: \"namespaces\", Kind: \"Namespace\"},\n\t\t\t\t{Name: \"nodes\", Kind: \"Node\"},\n\t\t\t\t{Name: \"persistentvolumeclaims\", Namespaced: true, Kind: \"PersistentVolumeClaim\"},\n\t\t\t\t{Name: \"persistentvolumes\", Kind: \"PersistentVolume\"},\n\t\t\t\t{Name: \"pods\", Namespaced: true, Kind: \"Pod\"},\n\t\t\t\t{Name: \"podtemplates\", Namespaced: true, Kind: \"PodTemplate\"},\n\t\t\t\t{Name: \"replicationcontrollers\", Namespaced: true, Kind: \"ReplicationController\"},\n\t\t\t\t{Name: \"resourcequotas\", Namespaced: true, Kind: \"ResourceQuota\"},\n\t\t\t\t{Name: \"secrets\", Namespaced: true, Kind: \"Secret\"},\n\t\t\t\t{Name: \"serviceaccounts\", Namespaced: true, Kind: \"ServiceAccount\"},\n\t\t\t\t{Name: \"services\", Namespaced: true, Kind: \"Service\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: rbacv1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"clusterroles\", Kind: \"ClusterRole\"},\n\t\t\t\t{Name: \"clusterrolebindings\", Kind: \"ClusterRoleBinding\"},\n\t\t\t\t{Name: \"clusterroles\", Kind: \"ClusterRole\"},\n\t\t\t\t{Name: \"rolebindings\", Namespaced: true, Kind: \"RoleBinding\"},\n\t\t\t\t{Name: \"roles\", Namespaced: true, Kind: \"Role\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: appsv1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: apps,\n\t\t},\n\t\t{\n\t\t\tGroupVersion: appsv1beta1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: apps,\n\t\t},\n\t\t{\n\t\t\tGroupVersion: appsv1beta2.SchemeGroupVersion.String(),\n\t\t\tAPIResources: apps,\n\t\t},\n\t\t{\n\t\t\tGroupVersion: apiextensionsv1beta1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"customresourcedefinitions\", Kind: \"CustomResourceDefinition\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: apiextensionsv1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"customresourcedefinitions\", Kind: \"CustomResourceDefinition\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: storagev1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"storageclasses\", Kind: \"StorageClass\"},\n\t\t\t\t{Name: \"volumeattachments\", Kind: \"VolumeAttachment\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: storagev1beta1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"storageclasses\", Kind: \"StorageClass\"},\n\t\t\t\t{Name: \"volumeattachments\", Kind: \"VolumeAttachment\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: extensionsv1beta1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"ingresses\", Namespaced: true, Kind: \"Ingress\"},\n\t\t\t\t{Name: \"networkpolicies\", Namespaced: true, Kind: \"NetworkPolicy\"},\n\t\t\t\t{Name: \"podsecuritypolicies\", Kind: \"PodSecurityPolicy\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: networkingv1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"networkpolicies\", Namespaced: true, Kind: \"NetworkPolicy\"},\n\t\t\t\t{Name: \"ingresses\", Namespaced: true, Kind: \"Ingress\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: authenticationv1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"tokenreviews\", Kind: \"TokenReview\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: autoscalingv1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"horizontalpodautoscalers\", Kind: \"HorizontalPodAutoscaler\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: autoscalingv2beta1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"horizontalpodautoscalers\", Kind: \"HorizontalPodAutoscaler\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: autoscalingv2beta2.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"horizontalpodautoscalers\", Kind: \"HorizontalPodAutoscaler\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: policyv1beta1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"poddisruptionbudgets\", Namespaced: true, Kind: \"PodDisruptionBudget\"},\n\t\t\t\t{Name: \"podsecuritypolicies\", Kind: \"PodSecurityPolicy\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: rbacsyncv1alpha.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"clusterrbacsyncconfigs\", Kind: \"ClusterRBACSyncConfig\"},\n\t\t\t\t{Name: \"rbacsyncconfigs\", Namespaced: true, Kind: \"RBACSyncConfig\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: batchv1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"jobs\", Namespaced: true, Kind: \"Job\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: batchv1b1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"cronjobs\", Namespaced: true, Kind: \"CronJob\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: arkv1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"backups\", Namespaced: true, Kind: \"Backup\"},\n\t\t\t\t{Name: \"backupstoragelocations\", Namespaced: true, Kind: \"BackupStorageLocation\"},\n\t\t\t\t{Name: \"configs\", Namespaced: true, Kind: \"Config\"},\n\t\t\t\t{Name: \"deletebackuprequests\", Namespaced: true, Kind: \"DeleteBackupRequest\"},\n\t\t\t\t{Name: \"downloadrequests\", Namespaced: true, Kind: \"DownloadRequest\"},\n\t\t\t\t{Name: \"podvolumebackups\", Namespaced: true, Kind: \"PodVolumeBackup\"},\n\t\t\t\t{Name: \"podvolumerestores\", Namespaced: true, Kind: \"PodVolumeRestore\"},\n\t\t\t\t{Name: \"resticrepositories\", Namespaced: true, Kind: \"ResticRepository\"},\n\t\t\t\t{Name: \"restores\", Namespaced: true, Kind: \"Restore\"},\n\t\t\t\t{Name: \"schedules\", Namespaced: true, Kind: \"Schedule\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: istio.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"sidecar\", Namespaced: true, Kind: \"Sidecar\"},\n\t\t\t\t{Name: \"virtualservice\", Namespaced: true, Kind: \"VirtualService\"},\n\t\t\t\t{Name: \"destinationrule\", Namespaced: true, Kind: \"DestinationRule\"},\n\t\t\t\t{Name: \"gateway\", Namespaced: true, Kind: \"Gateway\"},\n\t\t\t\t{Name: \"serviceentry\", Kind: \"ServiceEntry\"},\n\t\t\t\t{Name: \"envoyfilter\", Namespaced: true, Kind: \"EnvoyFilter\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: istiov1b1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"sidecar\", Namespaced: true, Kind: \"Sidecar\"},\n\t\t\t\t{Name: \"virtualservice\", Namespaced: true, Kind: \"VirtualService\"},\n\t\t\t\t{Name: \"destinationrule\", Namespaced: true, Kind: \"DestinationRule\"},\n\t\t\t\t{Name: \"gateway\", Namespaced: true, Kind: \"Gateway\"},\n\t\t\t\t{Name: \"serviceentry\", Kind: \"ServiceEntry\"},\n\t\t\t\t{Name: \"envoyfilter\", Namespaced: true, Kind: \"EnvoyFilter\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: istiosecurityv1beta1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"authorizationpolicy\", Namespaced: true, Kind: \"AuthorizationPolicy\"},\n\t\t\t\t{Name: \"peerauthentication\", Namespaced: true, Kind: \"PeerAuthentication\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: csr.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"certificatesigningrequests\", Kind: \"CertificateSigningRequest\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: csrv1b1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"certificatesigningrequests\", Kind: \"CertificateSigningRequest\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: admissionregistrationv1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"validatingwebhookconfigurations\", Kind: \"ValidatingWebhookConfiguration\"},\n\t\t\t\t{Name: \"mutatingwebhookconfigurations\", Kind: \"MutatingWebhookConfiguration\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: admissionregistrationv1b1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"validatingwebhookconfigurations\", Kind: \"ValidatingWebhookConfiguration\"},\n\t\t\t\t{Name: \"mutatingwebhookconfigurations\", Kind: \"MutatingWebhookConfiguration\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: schedulingv1beta1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"priorityclass\", Kind: \"PriorityClass\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: schedulingv1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"priorityclass\", Kind: \"PriorityClass\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: apiregistrationv1b1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"apiservice\", Kind: \"APIService\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: apiregistrationv1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"apiservice\", Kind: \"APIService\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: vpav1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"verticalpodautoscalers\", Kind: \"VerticalPodAutoscaler\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: vpav1beta2.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"verticalpodautoscalers\", Kind: \"VerticalPodAutoscaler\"},\n\t\t\t},\n\t\t},\n\t}\n\treturn fake\n}", "func (m *MockPacketHandler) LocalAddr() net.Addr {\n\tret := m.ctrl.Call(m, \"LocalAddr\")\n\tret0, _ := ret[0].(net.Addr)\n\treturn ret0\n}", "func (r *EtcdResolver) JustForTest() {\n\tr.usedForTest = true\n}", "func (m *MockLocalConfigProvider) ListURLs() ([]LocalURL, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ListURLs\")\n\tret0, _ := ret[0].([]LocalURL)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func NewLocalProvider(t []string) Provider {\n\treturn newLocalProviderWithClock(t, clock.New())\n}", "func (sc *ShamClient) fallbackDiscovery() {\n\tif len(sc.localRegistry) == 0 {\n\t\tsc.setLocalRegistry(sc.serviceRegistry.Fallback)\n\t\tsc.logger.Infof(\"using Fallback registry for service %s: %+v\", sc.serviceName, sc.localRegistry)\n\t} else {\n\t\tsc.logger.Infof(\"continue using local registry for service %s: %+v\", sc.serviceName, sc.localRegistry)\n\t}\n}", "func InitLocalPilotTestEnv(t *testing.T) *bootstrap.Server {\n\tinitMutex.Lock()\n\tdefer initMutex.Unlock()\n\n\tports := testenv.NewPorts(testenv.XDSTest)\n\n\tserver := istiotestutil.EnsureTestServer()\n\n\tlocalIP = iputil.GetLocalIP()\n\n\t// Service and endpoints for hello.default - used in v1 pilot tests\n\thostname := model.Hostname(\"hello.default.svc.cluster.local\")\n\tserver.EnvoyXdsServer.MemRegistry.AddService(hostname, &model.Service{\n\t\tHostname: hostname,\n\t\tAddress: \"10.10.0.3\",\n\t\tPorts: testPorts(0),\n\t})\n\tserver.EnvoyXdsServer.MemRegistry.AddInstance(hostname, &model.ServiceInstance{\n\t\tEndpoint: model.NetworkEndpoint{\n\t\t\tAddress: \"127.0.0.1\",\n\t\t\tPort: int(ports.BackendPort),\n\t\t\tServicePort: &model.Port{\n\t\t\t\tName: \"http\",\n\t\t\t\tPort: 80,\n\t\t\t\tProtocol: model.ProtocolHTTP,\n\t\t\t},\n\t\t},\n\t\tAvailabilityZone: \"az\",\n\t})\n\n\t// \"local\" service points to the current host and the in-process mixer http test endpoint\n\tserver.EnvoyXdsServer.MemRegistry.AddService(\"local.default.svc.cluster.local\", &model.Service{\n\t\tHostname: \"local.default.svc.cluster.local\",\n\t\tAddress: \"10.10.0.4\",\n\t\tPorts: []*model.Port{\n\t\t\t{\n\t\t\t\tName: \"http\",\n\t\t\t\tPort: 80,\n\t\t\t\tProtocol: model.ProtocolHTTP,\n\t\t\t}},\n\t})\n\tserver.EnvoyXdsServer.MemRegistry.AddInstance(\"local.default.svc.cluster.local\", &model.ServiceInstance{\n\t\tEndpoint: model.NetworkEndpoint{\n\t\t\tAddress: localIP,\n\t\t\tPort: int(ports.BackendPort),\n\t\t\tServicePort: &model.Port{\n\t\t\t\tName: \"http\",\n\t\t\t\tPort: 80,\n\t\t\t\tProtocol: model.ProtocolHTTP,\n\t\t\t},\n\t\t},\n\t\tAvailabilityZone: \"az\",\n\t})\n\n\t// Explicit test service, in the v2 memory registry. Similar with mock.MakeService,\n\t// but easier to read.\n\tserver.EnvoyXdsServer.MemRegistry.AddService(\"service3.default.svc.cluster.local\", &model.Service{\n\t\tHostname: \"service3.default.svc.cluster.local\",\n\t\tAddress: \"10.10.0.1\",\n\t\tPorts: testPorts(0),\n\t})\n\n\tserver.EnvoyXdsServer.MemRegistry.AddInstance(\"service3.default.svc.cluster.local\", &model.ServiceInstance{\n\t\tEndpoint: model.NetworkEndpoint{\n\t\t\tAddress: app3Ip,\n\t\t\tPort: 2080,\n\t\t\tServicePort: &model.Port{\n\t\t\t\tName: \"http-main\",\n\t\t\t\tPort: 1080,\n\t\t\t\tProtocol: model.ProtocolHTTP,\n\t\t\t},\n\t\t},\n\t\tLabels: map[string]string{\"version\": \"v1\"},\n\t\tAvailabilityZone: \"az\",\n\t})\n\tserver.EnvoyXdsServer.MemRegistry.AddInstance(\"service3.default.svc.cluster.local\", &model.ServiceInstance{\n\t\tEndpoint: model.NetworkEndpoint{\n\t\t\tAddress: gatewayIP,\n\t\t\tPort: 2080,\n\t\t\tServicePort: &model.Port{\n\t\t\t\tName: \"http-main\",\n\t\t\t\tPort: 1080,\n\t\t\t\tProtocol: model.ProtocolHTTP,\n\t\t\t},\n\t\t},\n\t\tLabels: map[string]string{\"version\": \"v2\", \"app\": \"my-gateway-controller\"},\n\t\tAvailabilityZone: \"az\",\n\t})\n\n\t// Mock ingress service\n\tserver.EnvoyXdsServer.MemRegistry.AddService(\"istio-ingress.istio-system.svc.cluster.local\", &model.Service{\n\t\tHostname: \"istio-ingress.istio-system.svc.cluster.local\",\n\t\tAddress: \"10.10.0.2\",\n\t\tPorts: []*model.Port{\n\t\t\t{\n\t\t\t\tName: \"http\",\n\t\t\t\tPort: 80,\n\t\t\t\tProtocol: model.ProtocolHTTP,\n\t\t\t},\n\t\t\t{\n\t\t\t\tName: \"https\",\n\t\t\t\tPort: 443,\n\t\t\t\tProtocol: model.ProtocolHTTPS,\n\t\t\t},\n\t\t},\n\t})\n\tserver.EnvoyXdsServer.MemRegistry.AddInstance(\"istio-ingress.istio-system.svc.cluster.local\", &model.ServiceInstance{\n\t\tEndpoint: model.NetworkEndpoint{\n\t\t\tAddress: ingressIP,\n\t\t\tPort: 80,\n\t\t\tServicePort: &model.Port{\n\t\t\t\tName: \"http\",\n\t\t\t\tPort: 80,\n\t\t\t\tProtocol: model.ProtocolHTTP,\n\t\t\t},\n\t\t},\n\t\tLabels: model.IstioIngressWorkloadLabels,\n\t\tAvailabilityZone: \"az\",\n\t})\n\tserver.EnvoyXdsServer.MemRegistry.AddInstance(\"istio-ingress.istio-system.svc.cluster.local\", &model.ServiceInstance{\n\t\tEndpoint: model.NetworkEndpoint{\n\t\t\tAddress: ingressIP,\n\t\t\tPort: 443,\n\t\t\tServicePort: &model.Port{\n\t\t\t\tName: \"https\",\n\t\t\t\tPort: 443,\n\t\t\t\tProtocol: model.ProtocolHTTPS,\n\t\t\t},\n\t\t},\n\t\tLabels: model.IstioIngressWorkloadLabels,\n\t\tAvailabilityZone: \"az\",\n\t})\n\n\t//RouteConf Service4 is using port 80, to test that we generate multiple clusters (regression)\n\t// service4 has no endpoints\n\tserver.EnvoyXdsServer.MemRegistry.AddService(\"service4.default.svc.cluster.local\", &model.Service{\n\t\tHostname: \"service4.default.svc.cluster.local\",\n\t\tAddress: \"10.1.0.4\",\n\t\tPorts: []*model.Port{\n\t\t\t{\n\t\t\t\tName: \"http-main\",\n\t\t\t\tPort: 80,\n\t\t\t\tProtocol: model.ProtocolHTTP,\n\t\t\t},\n\t\t},\n\t})\n\n\t// Update cache\n\tserver.EnvoyXdsServer.ClearCacheFunc()()\n\n\treturn server\n}", "func testMdns(t *testing.T) {\n\tservice := \"_liqo._tcp\"\n\tdomain := \"local.\"\n\n\tgo clientCluster.discoveryCtrl.Register()\n\n\ttime.Sleep(1 * time.Second)\n\n\ttxts := []*discovery.TxtData{}\n\tclientCluster.discoveryCtrl.Resolve(service, domain, 3, &txts)\n\n\ttime.Sleep(1 * time.Second)\n\n\t// TODO: find better way to test mDNS, local IP is not always detected\n\tassert.Assert(t, len(txts) >= 0, \"If this line is reached test would be successful, no foreign packet can reach our testing environment at the moment\")\n}", "func InitializeForTest(apicClient apic.Client) {\n\tagent.apiMap = cache.New()\n\tagent.apicClient = apicClient\n}", "func TestNewIdentityManager(t *testing.T) {\n\tt.Run(\"success\", func(t *testing.T) {\n\t\tepCfg := &mocks.EndpointConfig{}\n\t\tepCfg.NetworkConfigReturns(&fab.NetworkConfig{\n\t\t\tOrganizations: map[string]fab.OrganizationConfig{\"org1msp\": {}},\n\t\t})\n\n\t\tm, err := newIdentityManager(\"org1MSP\", &mocks.CryptoSuite{}, epCfg, \"./msp\")\n\t\trequire.NoError(t, err)\n\t\trequire.NotNil(t, m)\n\t})\n\n\tt.Run(\"No endpoint config -> error\", func(t *testing.T) {\n\t\tm, err := newIdentityManager(\"org1MSP\", &mocks.CryptoSuite{}, nil, \"./msp\")\n\t\trequire.EqualError(t, err, \"endpoint config is required\")\n\t\trequire.Nil(t, m)\n\t})\n\n\tt.Run(\"No org name -> error\", func(t *testing.T) {\n\t\tm, err := newIdentityManager(\"\", nil, &mocks.EndpointConfig{}, \"./msp\")\n\t\trequire.EqualError(t, err, \"orgName is required\")\n\t\trequire.Nil(t, m)\n\t})\n\n\tt.Run(\"No crypto suite -> error\", func(t *testing.T) {\n\t\tm, err := newIdentityManager(\"org1MSP\", nil, &mocks.EndpointConfig{}, \"./msp\")\n\t\trequire.EqualError(t, err, \"cryptoProvider is required\")\n\t\trequire.Nil(t, m)\n\t})\n\n\tt.Run(\"Org not found -> error\", func(t *testing.T) {\n\t\tepCfg := &mocks.EndpointConfig{}\n\t\tepCfg.NetworkConfigReturns(&fab.NetworkConfig{})\n\n\t\tm, err := newIdentityManager(\"org1MSP\", &mocks.CryptoSuite{}, epCfg, \"./msp\")\n\t\trequire.EqualError(t, err, \"org config retrieval failed\")\n\t\trequire.Nil(t, m)\n\t})\n\n\tt.Run(\"MSP config path not provided -> error\", func(t *testing.T) {\n\t\tepCfg := &mocks.EndpointConfig{}\n\t\tepCfg.NetworkConfigReturns(&fab.NetworkConfig{\n\t\t\tOrganizations: map[string]fab.OrganizationConfig{\"org1msp\": {}},\n\t\t})\n\n\t\tm, err := newIdentityManager(\"org1MSP\", &mocks.CryptoSuite{}, epCfg, \"\")\n\t\trequire.EqualError(t, err, \"either mspConfigPath or an embedded list of users is required\")\n\t\trequire.Nil(t, m)\n\t})\n}", "func TestLogConfigInLocal(t *testing.T) {\n\t// Check if\n}", "func (l *impl) CreateLocalDiscoveryService(mspID string) (fabApi.DiscoveryService, error) {\n\treturn &localDiscoveryService{l.clientConfig, l.localPeer, l.localPeerTLSCertPem}, nil\n}", "func NewLocal(clientProvider context.ClientProvider) (*Local, error) {\n\tclient, err := clientProvider()\n\tif err != nil {\n\t\treturn nil, errors.WithMessage(err, \"failed to get client context to create local context\")\n\t}\n\n\tdiscoveryService, err := client.LocalDiscoveryProvider().CreateLocalDiscoveryService(client.Identifier().MSPID)\n\tif err != nil {\n\t\treturn nil, errors.WithMessage(err, \"failed to create local discovery service\")\n\t}\n\n\tlocal := &Local{\n\t\tClient: client,\n\t\tlocalDiscovery: discoveryService,\n\t}\n\n\tif ci, ok := discoveryService.(localServiceInit); ok {\n\t\tif err := ci.Initialize(local); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn local, nil\n}", "func (_e *MockPlcDriver_Expecter) SupportsDiscovery() *MockPlcDriver_SupportsDiscovery_Call {\n\treturn &MockPlcDriver_SupportsDiscovery_Call{Call: _e.mock.On(\"SupportsDiscovery\")}\n}", "func providerFactory(_ io.Reader) (cloudprovider.Interface, error) {\n\tlog := klogr.NewWithOptions(klogr.WithFormat(klogr.FormatKlog))\n\tc, err := loadConfig(envconfig.OsLookuper())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tapiUrl := katapult.DefaultURL\n\tif c.APIHost != \"\" {\n\t\tlog.Info(\"default API base URL overrided\",\n\t\t\t\"url\", c.APIHost)\n\t\tapiUrl, err = url.Parse(c.APIHost)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to parse provided api url: %w\", err)\n\t\t}\n\t}\n\n\trm, err := katapult.New(\n\t\tkatapult.WithAPIKey(c.APIKey),\n\t\tkatapult.WithBaseURL(apiUrl),\n\t\tkatapult.WithUserAgent(\"kce-ccm\"), // TODO: Add version.\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tclient := core.New(rm)\n\n\treturn &provider{\n\t\tlog: log,\n\t\tkatapult: client,\n\t\tconfig: *c,\n\t\tloadBalancer: &loadBalancerManager{\n\t\t\tlog: log,\n\t\t\tconfig: *c,\n\t\t\tloadBalancerController: client.LoadBalancers,\n\t\t\tloadBalancerRuleController: client.LoadBalancerRules,\n\t\t},\n\t}, nil\n}", "func TestPreparerInterface(t *testing.T) {\n\tt.Parallel()\n\n\tassert.Implements(t, (*resource.Resource)(nil), new(user.Preparer))\n}", "func TestSetupReplaceMock(t *testing.T) {\n\tt.SkipNow()\n\tstudent, mocks, err := MockCluster(false, nil, t)\n\tif err != nil {\n\t\tt.Error(\"Couldn't set up mock cluster\", err)\n\t}\n\n\t// Create a new impl for an rpc function\n\tdenyVote := func(ctx context.Context, req *RequestVoteRequest) (*RequestVoteReply, error) {\n\t\treturn &RequestVoteReply{Term: req.Term, VoteGranted: false}, nil\n\t}\n\n\t// replace the existing impl\n\tmocks[0].RequestVote = denyVote\n\tmocks[1].RequestVote = denyVote\n\n\tmocks[0].JoinCluster()\n\tmocks[1].JoinCluster()\n\n\ttime.Sleep(DefaultConfig().ElectionTimeout * 4)\n\n\tt.Log(\"Student node is:\", student.State)\n\n\tif student.State != CANDIDATE_STATE {\n\t\tt.Error(\"student state was not candidate, was:\", student.State)\n\t}\n\n\t// test as part of an rpc function\n\tmocks[0].RequestVote = func(ctx context.Context, req *RequestVoteRequest) (*RequestVoteReply, error) {\n\t\tt.Logf(\"Mock 0 recieved request vote: last_idx: %v term: %v\", req.GetLastLogIndex(), req.GetLastLogTerm())\n\t\tif req.GetLastLogIndex() != 0 || req.GetLastLogTerm() != 0 {\n\t\t\tt.Errorf(\"Student node failed to request vote correctly: last_idx: %v term: %v\", req.GetLastLogIndex(), req.GetLastLogTerm())\n\t\t}\n\n\t\tif term := student.GetCurrentTerm(); req.GetTerm() != term {\n\t\t\tt.Errorf(\"Student node sent the wrong term: (sent %v, expecting %v)\", req.GetTerm(), term)\n\t\t}\n\t\treturn denyVote(ctx, req)\n\t}\n\n\ttime.Sleep(DefaultConfig().ElectionTimeout * 5)\n}", "func (m *MockClient) InfraProvider() fab.InfraProvider {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"InfraProvider\")\n\tret0, _ := ret[0].(fab.InfraProvider)\n\treturn ret0\n}", "func (_m *Session) LocalAddr() net.Addr {\n\tret := _m.Called()\n\n\tvar r0 net.Addr\n\tif rf, ok := ret.Get(0).(func() net.Addr); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(net.Addr)\n\t\t}\n\t}\n\n\treturn r0\n}", "func (mr *MockClientMockRecorder) LocalDiscoveryProvider() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"LocalDiscoveryProvider\", reflect.TypeOf((*MockClient)(nil).LocalDiscoveryProvider))\n}", "func Test_Provider(t *testing.T) {\n\t// SetLogLevel(\"TRACE\")\n\t// CheckVersion()\n\n\t// Start provider API in the background\n\tgo InitProvider()\n\t// err := InitProvider()\n\t// if err != nil {\n\t// \tlog.Fatalf(\"Error initializing Provider %+v\", err)\n\t// }\n\n\tverifier := HTTPVerifier{}\n\t// Authorization middleware\n\t// This is your chance to modify the request before it hits your provider\n\t// NOTE: this should be used very carefully, as it has the potential to\n\t// _change_ the contract\n\t// f := func(next http.Handler) http.Handler {\n\t// \treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t// \t\tlog.Println(\"[DEBUG] HOOK request filter\")\n\t// \t\t// r.Header.Add(\"Authorization\", \"Bearer 1234-dynamic-value\")\n\t// \t\tnext.ServeHTTP(w, r)\n\t// \t})\n\t// }\n\n\t// Verify the Provider with local Pact Files\n\terr := verifier.VerifyProvider(t, VerifyRequest{\n\t\tProviderBaseURL: \"http://localhost:9000\",\n\t\tBrokerURL: \"http://localhost:9292\",\n\t\tProvider: \"GreetingAPI\",\n\t\tProviderVersion: \"1.0.0\",\n\t\tPublishVerificationResults: true,\n\t\t// PactFiles: []string{\n\t\t// \tfilepath.ToSlash(fmt.Sprintf(\"%s/GreetingAPIConsumer-GreetingAPI.json\", pactDir)),\n\t\t// },\n\t\t// RequestFilter: f,\n\t\t// BeforeEach: func() error {\n\t\t// \tlog.Println(\"[DEBUG] HOOK before each\")\n\t\t// \treturn nil\n\t\t// },\n\t\t// AfterEach: func() error {\n\t\t// \tlog.Println(\"[DEBUG] HOOK after each\")\n\t\t// \treturn nil\n\t\t// },\n\t\t// StateHandlers: StateHandlers{\n\t\t// \t\"User foo exists\": func(setup bool, s ProviderStateV3) (ProviderStateV3Response, error) {\n\n\t\t// \t\tif setup {\n\t\t// \t\t\tlog.Println(\"[DEBUG] HOOK calling user foo exists state handler\", s)\n\t\t// \t\t} else {\n\t\t// \t\t\tlog.Println(\"[DEBUG] HOOK teardown the 'User foo exists' state\")\n\t\t// \t\t}\n\n\t\t// \t\t// ... do something, such as create \"foo\" in the database\n\n\t\t// \t\t// Optionally (if there are generators in the pact) return provider state values to be used in the verification\n\t\t// \t\treturn ProviderStateV3Response{\"uuid\": \"1234\"}, nil\n\t\t// \t},\n\t\t// },\n\t})\n\n\tassert.NoError(t, err)\n}", "func TestNewClient_CustomHttpClient(t *testing.T) {\n\tt.Parallel()\n\n\tclient := NewClient(nil, http.DefaultClient, ProviderPreev)\n\n\tif client == nil {\n\t\tt.Fatal(\"failed to load client\")\n\t}\n\n\t// Test providers\n\tif client.Providers[0] != ProviderPreev {\n\t\tt.Fatalf(\"expected the first provider to be %d, not %d\", ProviderPreev, client.Providers[0])\n\t}\n}", "func MockedProvider(t *testing.T, c *config.Config, callback string) (*config.Config, goth.Provider) {\n\tconst (\n\t\ttestClientKey = \"provider-test-client-key\"\n\t\ttestSecret = \"provider-test-secret\"\n\t\ttestCallback = \"http://auth.exmaple.com/test/callback\"\n\t)\n\tmp := newMockProvider(t, callback)\n\tp := provider.Name(mp.Name())\n\tprovider.AddExternal(p)\n\tt.Cleanup(func() {\n\t\tdelete(provider.External, p)\n\t})\n\tif callback == \"\" {\n\t\tcallback = testCallback\n\t}\n\tc.Authorization.Providers[p] = config.Provider{\n\t\tClientKey: testClientKey,\n\t\tSecret: testSecret,\n\t\tCallbackURL: callback,\n\t}\n\treturn c, mp\n}", "func TestInterdomainFloatingNetworkServiceRegistry(t *testing.T) {\n\tt.Cleanup(func() { goleak.VerifyNone(t) })\n\n\tctx, cancel := context.WithTimeout(context.Background(), time.Second*10)\n\tdefer cancel()\n\n\tdnsServer := sandbox.NewFakeResolver()\n\n\tdomain1 := sandbox.NewBuilder(ctx, t).\n\t\tSetNodesCount(0).\n\t\tSetDNSResolver(dnsServer).\n\t\tBuild()\n\n\tdomain2 := sandbox.NewBuilder(ctx, t).\n\t\tSetNodesCount(0).\n\t\tSetDNSResolver(dnsServer).\n\t\tBuild()\n\n\tdomain3 := sandbox.NewBuilder(ctx, t).\n\t\tSetNodesCount(0).\n\t\tSetRegistryProxySupplier(nil).\n\t\tSetNSMgrProxySupplier(nil).\n\t\tSetDNSResolver(dnsServer).\n\t\tSetDNSDomainName(\"floating.domain\").\n\t\tBuild()\n\n\tregistryClient := registryclient.NewNetworkServiceRegistryClient(ctx,\n\t\tregistryclient.WithDialOptions(grpc.WithTransportCredentials(insecure.NewCredentials())),\n\t\tregistryclient.WithClientURL(domain2.Registry.URL))\n\n\t_, err := registryClient.Register(\n\t\tctx,\n\t\t&registryapi.NetworkService{\n\t\t\tName: \"ns-1@\" + domain3.Name,\n\t\t},\n\t)\n\trequire.Nil(t, err)\n\n\tcc, err := grpc.DialContext(ctx, grpcutils.URLToTarget(domain1.Registry.URL), grpc.WithBlock(), grpc.WithTransportCredentials(insecure.NewCredentials()))\n\trequire.Nil(t, err)\n\tdefer func() {\n\t\t_ = cc.Close()\n\t}()\n\n\tclient := registryapi.NewNetworkServiceRegistryClient(cc)\n\n\tstream, err := client.Find(ctx, &registryapi.NetworkServiceQuery{\n\t\tNetworkService: &registryapi.NetworkService{\n\t\t\tName: \"ns-1@\" + domain3.Name,\n\t\t},\n\t})\n\n\trequire.Nil(t, err)\n\n\tlist := registryapi.ReadNetworkServiceList(stream)\n\n\trequire.Len(t, list, 1)\n\trequire.Equal(t, \"ns-1@\"+domain3.Name, list[0].Name)\n}", "func (sc *ShamClient) discover() error {\n\tsc.logger.Debugf(\"discovering endpoints for service %s\", sc.serviceName)\n\tresponse, err := sc.httpClient.Get(sc.serviceRegistry.URL + \"/sgulreg/services/\" + sc.serviceName)\n\tif err != nil {\n\t\tsc.logger.Errorf(\"Error making service discovery HTTP request: %s\", err)\n\t\tsc.fallbackDiscovery()\n\t\treturn ErrFailedDiscoveryRequest\n\t}\n\tsc.logger.Debugf(\"discovery response content-length: %s\", response.Header.Get(\"Content-length\"))\n\n\tbody, err := ioutil.ReadAll(response.Body)\n\tif err != nil {\n\t\tsc.logger.Errorf(\"Error reading service discovery HTTP response body: %s\", err)\n\t\tsc.fallbackDiscovery()\n\t\treturn ErrFailedDiscoveryResponseBody\n\t}\n\tdefer response.Body.Close()\n\n\tvar serviceInfo registry.ServiceInfoResponse\n\tjson.Unmarshal([]byte(body), &serviceInfo)\n\n\tif len(serviceInfo.Instances) > 0 {\n\t\tvar endpoints []string\n\t\tfor _, instance := range serviceInfo.Instances {\n\t\t\tsc.logger.Debugf(\"discovered service %s endpoint serviceID: %s\", sc.serviceName, instance.InstanceID)\n\t\t\tendpoint := fmt.Sprintf(\"%s://%s%s\", instance.Schema, instance.Host, sc.apiPath)\n\t\t\tendpoints = append(endpoints, endpoint)\n\t\t}\n\n\t\t// sc.localRegistry = endpoints\n\t\tsc.setLocalRegistry(endpoints)\n\t\tsc.logger.Infof(\"discovered service %s endpoints: %+v\", sc.serviceName, sc.localRegistry)\n\t}\n\n\tif len(sc.localRegistry) == 0 {\n\t\t// sc.localRegistry = sc.serviceRegistry.Fallback\n\t\tsc.setLocalRegistry(sc.serviceRegistry.Fallback)\n\t\tsc.logger.Infof(\"using Fallback registry for service %s: %+v\", sc.serviceName, sc.localRegistry)\n\t}\n\n\treturn nil\n}", "func (m *MockLocalConfigProvider) GetName() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetName\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func (m *MockResolver) Lookup(service, key string) (HostInfo, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Lookup\", service, key)\n\tret0, _ := ret[0].(HostInfo)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func newProviderImpl(name string) (Provider, error) {\n\tif name == LOCAL {\n\t\treturn &LocalProvider{}, nil\n\t}\n\n\tif name == AWS {\n\t\treturn &AwsProvider{}, nil\n\t}\n\n\treturn nil, errors.New(fmt.Sprintf(\"Provider '%s' doesn't exist\", name))\n}", "func testInMemoryDataStore() IDataStore {\n return NewInMemoryDataStore();\n}", "func TestInterdomainNetworkServiceRegistry(t *testing.T) {\n\tt.Cleanup(func() { goleak.VerifyNone(t) })\n\n\tctx, cancel := context.WithTimeout(context.Background(), time.Second*10)\n\tdefer cancel()\n\n\tdnsServer := sandbox.NewFakeResolver()\n\n\tdomain1 := sandbox.NewBuilder(ctx, t).\n\t\tSetNodesCount(0).\n\t\tSetDNSResolver(dnsServer).\n\t\tBuild()\n\n\tdomain2 := sandbox.NewBuilder(ctx, t).\n\t\tSetNodesCount(0).\n\t\tSetDNSResolver(dnsServer).\n\t\tSetDNSDomainName(\"cluster.remote\").\n\t\tBuild()\n\n\tclient1 := registryclient.NewNetworkServiceRegistryClient(ctx,\n\t\tregistryclient.WithDialOptions(grpc.WithTransportCredentials(insecure.NewCredentials())),\n\t\tregistryclient.WithClientURL(domain1.Registry.URL))\n\n\tclient2 := registryclient.NewNetworkServiceRegistryClient(ctx,\n\t\tregistryclient.WithDialOptions(grpc.WithTransportCredentials(insecure.NewCredentials())),\n\t\tregistryclient.WithClientURL(domain2.Registry.URL))\n\n\t_, err := client2.Register(context.Background(), &registryapi.NetworkService{Name: \"ns-1\"})\n\trequire.NoError(t, err)\n\n\tstream, err := client1.Find(ctx, &registryapi.NetworkServiceQuery{\n\t\tNetworkService: &registryapi.NetworkService{\n\t\t\tName: \"ns-1@\" + domain2.Name,\n\t\t},\n\t})\n\n\trequire.Nil(t, err)\n\n\tlist := registryapi.ReadNetworkServiceList(stream)\n\n\trequire.Len(t, list, 1)\n\trequire.Equal(t, \"ns-1@\"+domain2.Name, list[0].Name)\n}", "func (m *MockAPI) HostMonitoring() {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"HostMonitoring\")\n}", "func (p *PodmanTestIntegration) StartRemoteService() {\n}", "func Test_Init(t *testing.T) {\n\tclient, err := Load(\"\", true)\n\tassert.Nil(t, err)\n\tmockClient = client\n}", "func TestInterdomainFloatingNetworkServiceRegistry(t *testing.T) {\n\ttool := newInterdomainTestingTool(t)\n\tdefer tool.verifyNoneLeaks()\n\tdefer tool.cleanup()\n\tconst localRegistryDomain = \"domain1.local.registry\"\n\tconst proxyRegistryDomain = \"domain1.proxy.registry\"\n\tconst remoteRegistryDomain = \"domain3.local.registry\"\n\tconst remoteProxyRegistryDomain = \"domain3.proxy.registry\"\n\tconst floatingRegistryDomain = \"domain2.floating.registry\"\n\n\tfMem := memory.NewNetworkServiceRegistryServer()\n\tctx, cancel := context.WithCancel(context.Background())\n\tdefer cancel()\n\n\tproxyRegistryURL1 := tool.startNetworkServiceRegistryServerAsync(proxyRegistryDomain, proxyNSRegistryServer(ctx, localRegistryDomain, tool))\n\ttool.startNetworkServiceRegistryServerAsync(localRegistryDomain, localNSRegistryServer(ctx, proxyRegistryURL1))\n\n\tproxyRegistryURL2 := tool.startNetworkServiceRegistryServerAsync(remoteProxyRegistryDomain, proxyNSRegistryServer(ctx, remoteRegistryDomain, tool))\n\ttool.startNetworkServiceRegistryServerAsync(remoteRegistryDomain, localNSRegistryServer(ctx, proxyRegistryURL2))\n\n\ttool.startNetworkServiceRegistryServerAsync(floatingRegistryDomain, fMem)\n\n\tdomain2Client := registry.NewNetworkServiceRegistryClient(tool.dialDomain(remoteRegistryDomain))\n\t_, err := domain2Client.Register(context.Background(), &registry.NetworkService{\n\t\tName: \"ns-1@\" + floatingRegistryDomain,\n\t})\n\trequire.Nil(t, err)\n\n\tfStream, err := adapters.NetworkServiceServerToClient(fMem).Find(context.Background(), &registry.NetworkServiceQuery{NetworkService: &registry.NetworkService{}})\n\trequire.Nil(t, err)\n\trequire.Len(t, registry.ReadNetworkServiceList(fStream), 1)\n\n\tdomain1Client := registry.NewNetworkServiceRegistryClient(tool.dialDomain(localRegistryDomain))\n\n\tstream, err := domain1Client.Find(context.Background(), &registry.NetworkServiceQuery{\n\t\tNetworkService: &registry.NetworkService{\n\t\t\tName: \"ns-1@\" + floatingRegistryDomain,\n\t\t},\n\t})\n\n\trequire.Nil(t, err)\n\n\tlist := registry.ReadNetworkServiceList(stream)\n\n\trequire.Len(t, list, 1)\n\trequire.Equal(t, \"ns-1@\"+remoteRegistryDomain, list[0].Name)\n}", "func IgrenoreTestP2PServiceRunAddPeer(t *testing.T) {\n\tmockActor := new(MockActorService)\n\tdummyBlock := types.Block{Hash: dummyBlockHash, Header: &types.BlockHeader{BlockNo: dummyBlockHeight}}\n\tmockActor.On(\"CallRequest\", mock.Anything, mock.Anything).Return(message.GetBlockRsp{Block: &dummyBlock}, nil)\n\t//mockMF := new(MockMoFactory)\n\ttarget := &networkTransport{conf: config.NewServerContext(\"\", \"\").GetDefaultConfig().(*config.Config).P2P,\n\t\tlogger:log.NewLogger(\"test.p2p\") }\n\n\ttarget.Host = &mockHost{peerstore.NewPeerstore(pstoremem.NewKeyBook(), pstoremem.NewAddrBook(), pstoremem.NewPeerMetadata())}\n\ttarget.selfMeta.ID = peer.ID(\"gwegw\")\n\n\tsampleAddr1 := PeerMeta{ID: \"ddd\", IPAddress: \"192.168.0.1\", Port: 33888, Outbound: true}\n\tsampleAddr2 := PeerMeta{ID: \"fff\", IPAddress: \"192.168.0.2\", Port: 33888, Outbound: true}\n\ttarget.GetOrCreateStream(sampleAddr1, aergoP2PSub)\n\ttarget.GetOrCreateStream(sampleAddr1, aergoP2PSub)\n\ttime.Sleep(time.Second)\n\tif len(target.Peerstore().Peers()) != 1 {\n\t\tt.Errorf(\"Peer count : Expected %d, Actually %d\", 1, len(target.Peerstore().Peers()))\n\t}\n\ttarget.GetOrCreateStream(sampleAddr2, aergoP2PSub)\n\ttime.Sleep(time.Second * 1)\n\tif len(target.Peerstore().Peers()) != 2 {\n\t\tt.Errorf(\"Peer count : Expected %d, Actually %d\", 2, len(target.Peerstore().Peers()))\n\t}\n}", "func TestLocal(t *testing.T) {\n\tConvey(\"While using Local Shell\", t, func() {\n\n\t\tl := NewLocal()\n\n\t\tConvey(\"The generic Executor test should pass\", func() {\n\t\t\ttestExecutor(t, l)\n\t\t})\n\t})\n\n\tConvey(\"Local Executor with decorations\", t, func() {\n\t\tConvey(\"Should run properly when no decorations are used\", func() {\n\t\t\tl := NewLocalIsolated()\n\t\t\t_, err := l.Execute(\"echo NewLocalIsolated\")\n\t\t\tSo(err, ShouldBeNil)\n\t\t})\n\n\t\tConvey(\"Should run properly when no single decoration is used\", func() {\n\t\t\ttaskSet := isolation.Taskset{CPUList: isolation.NewIntSet(1, 2)}\n\t\t\tl := NewLocalIsolated(taskSet)\n\t\t\t_, err := l.Execute(\"echo NewLocalIsolated\")\n\t\t\tSo(err, ShouldBeNil)\n\t\t})\n\n\t\tConvey(\"Should run properly when multiple decorations are used\", func() {\n\t\t\ttaskSet := isolation.Taskset{CPUList: isolation.NewIntSet(1, 2)}\n\t\t\tl := NewLocalIsolated(taskSet, taskSet)\n\t\t\t_, err := l.Execute(\"echo NewLocalIsolated\")\n\t\t\tSo(err, ShouldBeNil)\n\t\t})\n\t})\n\n\tConvey(\"While using Local Shell using cgroups\", t, func() {\n\t\tuser, err := user.Current()\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Cannot get current user\")\n\t\t}\n\n\t\tif user.Name != \"root\" {\n\t\t\tt.Skipf(\"Need to be privileged user to run cgroups tests\")\n\t\t}\n\n\t\tcmd := exec.Command(\"cgexec\")\n\t\terr = cmd.Run()\n\t\tif err != nil {\n\t\t\tt.Skipf(\"%s\", err)\n\t\t}\n\n\t\tConvey(\"Creating a single cgroup with cpu set for core 0 numa node 0\", func() {\n\t\t\tcpuset, err := cgroup.NewCPUSet(\"/A\", isolation.NewIntSet(0), isolation.NewIntSet(0), false, false)\n\t\t\tSo(err, ShouldBeNil)\n\t\t\tcpuset.Create()\n\t\t\tdefer cpuset.Clean()\n\n\t\t\tl := NewLocalIsolated(cpuset)\n\t\t\ttask, err := l.Execute(\"/bin/echo foobar\")\n\t\t\tSo(err, ShouldBeNil)\n\t\t\tdefer task.EraseOutput()\n\n\t\t\t// Wait until command has terminated.\n\t\t\ttask.Wait(0)\n\n\t\t\t// Ensure task is not running any longer.\n\t\t\ttaskState := task.Status()\n\t\t\tSo(taskState, ShouldEqual, TERMINATED)\n\n\t\t\t// Verify that the exit code represents successful run (exit code 0).\n\t\t\texitcode, err := task.ExitCode()\n\t\t\tSo(err, ShouldBeNil)\n\t\t\tSo(exitcode, ShouldEqual, 0)\n\t\t})\n\n\t\tConvey(\"Creating a two cgroups (cpu shares and memory) for one command\", func() {\n\t\t\tshares := isolation.NewCPUShares(\"/A\", 1024)\n\t\t\tshares.Create()\n\t\t\tdefer shares.Clean()\n\n\t\t\tmemory := isolation.NewMemorySize(\"/A\", 64*1024*1024)\n\t\t\tmemory.Create()\n\t\t\tdefer memory.Clean()\n\n\t\t\tl := NewLocalIsolated(isolation.Decorators{shares, memory})\n\t\t\ttask, err := l.Execute(\"/bin/echo foobar\")\n\t\t\tSo(err, ShouldBeNil)\n\t\t\tdefer task.EraseOutput()\n\n\t\t\t// Wait until command has terminated.\n\t\t\ttask.Wait(0)\n\n\t\t\t// Ensure task is not running any longer.\n\t\t\ttaskState := task.Status()\n\t\t\tSo(taskState, ShouldEqual, TERMINATED)\n\n\t\t\t// Verify that the exit code represents successful run (exit code 0).\n\t\t\texitcode, err := task.ExitCode()\n\t\t\tSo(err, ShouldBeNil)\n\t\t\tSo(exitcode, ShouldEqual, 0)\n\t\t})\n\n\t\tConvey(\"Creating nested cgroups with cpu shares\", func() {\n\t\t\tsharesA := isolation.NewCPUShares(\"/A\", 1024)\n\t\t\tsharesA.Create()\n\t\t\tdefer sharesA.Clean()\n\n\t\t\tsharesB := isolation.NewCPUShares(\"/A/B\", 1024)\n\t\t\tsharesB.Create()\n\t\t\tdefer sharesB.Clean()\n\n\t\t\tsharesC := isolation.NewCPUShares(\"/A/C\", 1024)\n\t\t\tsharesC.Create()\n\t\t\tdefer sharesC.Clean()\n\n\t\t\t// First command.\n\t\t\tl1 := NewLocalIsolated(sharesB)\n\t\t\ttask1, err := l1.Execute(\"/bin/echo foobar\")\n\t\t\tSo(err, ShouldBeNil)\n\t\t\tdefer task1.EraseOutput()\n\n\t\t\t// Wait until command has terminated.\n\t\t\ttask1.Wait(0)\n\n\t\t\t// Ensure task is not running any longer.\n\t\t\ttaskState1 := task1.Status()\n\t\t\tSo(taskState1, ShouldEqual, TERMINATED)\n\n\t\t\t// Verify that the exit code represents successful run (exit code 0).\n\t\t\texitcode1, err := task1.ExitCode()\n\t\t\tSo(err, ShouldBeNil)\n\t\t\tSo(exitcode1, ShouldEqual, 0)\n\n\t\t\t// Second command.\n\t\t\tl2 := NewLocalIsolated(sharesC)\n\t\t\ttask2, err := l2.Execute(\"/bin/echo foobar\")\n\t\t\tSo(err, ShouldBeNil)\n\t\t\tdefer task2.EraseOutput()\n\n\t\t\t// Wait until command has terminated.\n\t\t\ttask2.Wait(0)\n\n\t\t\t// Ensure task is not running any longer.\n\t\t\ttaskState2 := task2.Status()\n\t\t\tSo(taskState2, ShouldEqual, TERMINATED)\n\n\t\t\t// Verify that the exit code represents successful run (exit code 0).\n\t\t\texitcode2, err := task2.ExitCode()\n\t\t\tSo(err, ShouldBeNil)\n\t\t\tSo(exitcode2, ShouldEqual, 0)\n\t\t})\n\t})\n}", "func Test(t *testing.T) {\n\tsuite.Run(t, &DiscoverySuite{})\n}", "func TestFromContext(t *testing.T) {\n\t// Create a mocked peers cache connected to a mock directory\n\tcache, mgds, err := makePeersCache()\n\trequire.NoError(t, err, \"could not create mocked peers cache\")\n\tdefer mgds.Shutdown()\n\n\t// Make assertions about what is being looked up in the GDS\n\tmgds.OnLookup = func(_ context.Context, in *gds.LookupRequest) (out *gds.LookupReply, err error) {\n\t\t// Assert that the expected common name is being looked up\n\t\trequire.Equal(t, \"server.trisa.dev\", in.CommonName, \"unexpected common name in lookup request\")\n\t\trequire.Empty(t, in.Id, \"unexpected id in lookup request\")\n\t\trequire.Empty(t, in.RegisteredDirectory, \"unexpected registered directory in lookup request\")\n\n\t\treturn &gds.LookupReply{\n\t\t\tId: \"0960c00e-68a7-4606-9d0f-ff8537186d34\",\n\t\t\tRegisteredDirectory: \"localhost\",\n\t\t\tCommonName: \"server.trisa.dev\",\n\t\t\tEndpoint: \"server.trisa.dev:4000\",\n\t\t\tName: \"Testing VASP\",\n\t\t\tCountry: \"US\",\n\t\t\tVerifiedOn: \"2022-05-10T22:29:55Z\",\n\t\t}, nil\n\t}\n\n\t// Create an mTLS connection to test the context over bufconn\n\tcerts, pool, err := loadCertificates(\"testdata/server.pem\")\n\trequire.NoError(t, err, \"could not load server certificate fixtures\")\n\n\tremote, err := apimock.NewAuth(nil, certs, pool)\n\trequire.NoError(t, err, \"could not create remote universal mock\")\n\tdefer remote.Shutdown()\n\n\t// Lookup the peer from the directory service and connect it to the remote\n\tpeer, err := cache.Lookup(\"server.trisa.dev\")\n\trequire.NoError(t, err, \"could not lookup peer from directory service\")\n\n\topts := make([]grpc.DialOption, 0, 2)\n\topts = append(opts, grpc.WithContextDialer(remote.Channel().Dialer))\n\n\tclientCerts, clientPool, err := loadCertificates(\"testdata/client.pem\")\n\trequire.NoError(t, err, \"could not load client certificate fixture\")\n\tcreds, err := mtls.ClientCreds(peer.Info().Endpoint, clientCerts, clientPool)\n\trequire.NoError(t, err, \"could not create mtls client credentials\")\n\topts = append(opts, creds)\n\n\terr = peer.Connect(opts...)\n\trequire.NoError(t, err, \"could not connect to remote peer with mtls credentials\")\n\n\t// Setup to get the context from the remote dialer\n\tremote.OnTransfer = func(ctx context.Context, _ *api.SecureEnvelope) (*api.SecureEnvelope, error) {\n\t\t// Ok, after all that work above we finally have an actual gRPC context with mTLS info\n\t\tpeer, err := cache.FromContext(ctx)\n\t\trequire.NoError(t, err, \"could not lookup peer from context\")\n\n\t\tinfo := peer.Info()\n\t\trequire.Equal(t, \"client.trisa.dev\", info.CommonName, \"unknown common name\")\n\n\t\t// Don't return anything\n\t\treturn &api.SecureEnvelope{}, nil\n\t}\n\n\t// Make the request with the client to finish the tests\n\t_, err = peer.Transfer(&api.SecureEnvelope{})\n\trequire.NoError(t, err, \"could not make transfer to initiate from context tests\")\n\n\t// TODO: Test with different certificates to make sure the auth info parsing in FromContext is correct\n}", "func NewFakeProvider(t *testing.T) *FakeProvider {\n\tbuilder := chain.NewBuilder(t, address.Address{})\n\treturn &FakeProvider{\n\t\tBuilder: builder,\n\t\tt: t,\n\t\tactors: make(map[address.Address]*types.Actor)}\n}", "func TestInterdomainNetworkServiceRegistry(t *testing.T) {\n\ttool := newInterdomainTestingTool(t)\n\tdefer tool.verifyNoneLeaks()\n\tdefer tool.cleanup()\n\n\tconst localRegistryDomain = \"domain1.local.registry\"\n\tconst proxyRegistryDomain = \"domain1.proxy.registry\"\n\tconst remoteRegistryDomain = \"domain2.local.registry\"\n\n\tctx, cancel := context.WithCancel(context.Background())\n\tdefer cancel()\n\n\tproxyRegistryURL := tool.startNetworkServiceRegistryServerAsync(proxyRegistryDomain, proxyNSRegistryServer(ctx, localRegistryDomain, tool))\n\ttool.startNetworkServiceRegistryServerAsync(localRegistryDomain, localNSRegistryServer(ctx, proxyRegistryURL))\n\n\tremoteMem := memory.NewNetworkServiceRegistryServer()\n\t_, err := remoteMem.Register(context.Background(), &registry.NetworkService{Name: \"ns-1\"})\n\trequire.Nil(t, err)\n\n\ttool.startNetworkServiceRegistryServerAsync(remoteRegistryDomain, remoteMem)\n\n\tclient := registry.NewNetworkServiceRegistryClient(tool.dialDomain(localRegistryDomain))\n\n\tstream, err := client.Find(context.Background(), &registry.NetworkServiceQuery{\n\t\tNetworkService: &registry.NetworkService{\n\t\t\tName: \"ns-1@\" + remoteRegistryDomain,\n\t\t},\n\t})\n\n\trequire.Nil(t, err)\n\n\tlist := registry.ReadNetworkServiceList(stream)\n\n\trequire.Len(t, list, 1)\n\trequire.Equal(t, \"ns-1@\"+remoteRegistryDomain, list[0].Name)\n}", "func (m *MockRepoClient) LocalPath() (string, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"LocalPath\")\n\tret0, _ := ret[0].(string)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func NewMockDiscoveryService(err error, peers ...fab.Peer) *MockStaticDiscoveryService {\n\treturn &MockStaticDiscoveryService{Error: err, Peers: peers}\n}", "func (sc *ShamClient) setLocalRegistry(endpoints []string) {\n\tsc.lrMutex.Lock()\n\tdefer sc.lrMutex.Unlock()\n\n\tsc.localRegistry = endpoints\n}", "func (m *MockProvider) OnEndpointsSynced() {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"OnEndpointsSynced\")\n}", "func Init(ctx *context.T, name string, auth security.Authorizer, localTag string, discoveryTTL time.Duration) (*context.T, func(), error) {\n\tprotocol, _ := flow.RegisteredProtocol(\"vine\")\n\tv := protocol.(*vine)\n\tctx, cancel := context.WithCancel(ctx)\n\t_, server, err := v23.WithNewServer(ctx, name, VineServer(v), auth)\n\tif err != nil {\n\t\tcancel()\n\t\treturn nil, func() {}, err\n\t}\n\tserverShutdown := func() {\n\t\tcancel()\n\t\t<-server.Closed()\n\t}\n\t// Nodes are not discoverable until the test controller sets nodes as discoverable.\n\tplugin, err := vineplugin.NewWithTTL(ctx, discoveryServerName(localTag), v.discPeers, discoveryTTL)\n\tif err != nil {\n\t\tserverShutdown()\n\t\treturn nil, func() {}, err\n\t}\n\tdf, err := discovery.NewFactory(ctx, plugin)\n\tif err != nil {\n\t\tserverShutdown()\n\t\treturn nil, func() {}, err\n\t}\n\tfactory.InjectFactory(df)\n\tlspec := v23.GetListenSpec(ctx).Copy()\n\tfor i, addr := range lspec.Addrs {\n\t\tlspec.Addrs[i].Protocol = \"vine\"\n\t\tlspec.Addrs[i].Address = createListeningAddress(addr.Protocol, addr.Address)\n\t}\n\tctx = v23.WithListenSpec(ctx, lspec)\n\tctx = WithLocalTag(ctx, localTag)\n\tshutdown := func() {\n\t\tdf.Shutdown()\n\t\tserverShutdown()\n\t}\n\treturn ctx, shutdown, nil\n}", "func TestEndpoints_LocalAlreadyRunning(t *testing.T) {\n\tendpoints1, config1, cleanup1 := newEndpoints(t)\n\tdefer cleanup1()\n\n\trequire.NoError(t, endpoints1.Up(config1))\n\n\tendpoints2, config2, cleanup2 := newEndpoints(t)\n\tconfig2.Dir = config1.Dir\n\tconfig2.UnixSocket = config1.UnixSocket\n\tdefer cleanup2()\n\n\terr := endpoints2.Up(config2)\n\tassert.EqualError(t, err, \"local endpoint: LXD is already running\")\n}", "func setupToDoListServiceTest(t *testing.T) func() {\n\tctrl := gomock.NewController(t)\n\tmockToDoListRepository = ports.NewMockToDoListRepository(ctrl)\n\tdefaultToDoListService = NewToDoListService(mockToDoListRepository)\n\treturn func() {\n\t\tdefaultToDoListService = nil\n\t\tdefer ctrl.Finish()\n\t}\n}", "func (m *MockDirStore) Lookup(arg0, arg1, arg2 string) (buildpack.Descriptor, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Lookup\", arg0, arg1, arg2)\n\tret0, _ := ret[0].(buildpack.Descriptor)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (_m *Interface) Discovery() discovery.DiscoveryInterface {\n\tret := _m.Called()\n\n\tvar r0 discovery.DiscoveryInterface\n\tif rf, ok := ret.Get(0).(func() discovery.DiscoveryInterface); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(discovery.DiscoveryInterface)\n\t\t}\n\t}\n\n\treturn r0\n}", "func (m *MockProviders) InfraProvider() fab.InfraProvider {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"InfraProvider\")\n\tret0, _ := ret[0].(fab.InfraProvider)\n\treturn ret0\n}", "func (s *TestBase) Setup() {\n\tvar err error\n\tshardID := 10\n\tclusterName := s.ClusterMetadata.GetCurrentClusterName()\n\n\ts.DefaultTestCluster.SetupTestDatabase()\n\tif s.VisibilityTestCluster != s.DefaultTestCluster {\n\t\ts.VisibilityTestCluster.SetupTestDatabase()\n\t}\n\n\tcfg := s.DefaultTestCluster.Config()\n\tfactory := client.NewFactory(&cfg, clusterName, nil, s.logger)\n\n\ts.TaskMgr, err = factory.NewTaskManager()\n\ts.fatalOnError(\"NewTaskManager\", err)\n\n\ts.MetadataManager, err = factory.NewMetadataManager()\n\ts.fatalOnError(\"NewMetadataManager\", err)\n\n\ts.HistoryV2Mgr, err = factory.NewHistoryManager()\n\ts.fatalOnError(\"NewHistoryManager\", err)\n\n\ts.ShardMgr, err = factory.NewShardManager()\n\ts.fatalOnError(\"NewShardManager\", err)\n\n\ts.ExecutionMgrFactory = factory\n\ts.ExecutionManager, err = factory.NewExecutionManager(shardID)\n\ts.fatalOnError(\"NewExecutionManager\", err)\n\n\tvisibilityFactory := factory\n\tif s.VisibilityTestCluster != s.DefaultTestCluster {\n\t\tvCfg := s.VisibilityTestCluster.Config()\n\t\tvisibilityFactory = client.NewFactory(&vCfg, clusterName, nil, s.logger)\n\t}\n\t// SQL currently doesn't have support for visibility manager\n\ts.VisibilityMgr, err = visibilityFactory.NewVisibilityManager()\n\tif err != nil {\n\t\ts.fatalOnError(\"NewVisibilityManager\", err)\n\t}\n\n\ts.ReadLevel = 0\n\ts.ReplicationReadLevel = 0\n\ts.ShardInfo = &p.ShardInfo{\n\t\tShardID: shardID,\n\t\tRangeID: 0,\n\t\tTransferAckLevel: 0,\n\t\tReplicationAckLevel: 0,\n\t\tTimerAckLevel: time.Time{},\n\t\tClusterTimerAckLevel: map[string]time.Time{clusterName: time.Time{}},\n\t\tClusterTransferAckLevel: map[string]int64{clusterName: 0},\n\t}\n\n\ts.TaskIDGenerator = &TestTransferTaskIDGenerator{}\n\terr = s.ShardMgr.CreateShard(&p.CreateShardRequest{ShardInfo: s.ShardInfo})\n\ts.fatalOnError(\"CreateShard\", err)\n\n\tqueue, err := factory.NewDomainReplicationQueue()\n\ts.fatalOnError(\"Create DomainReplicationQueue\", err)\n\ts.DomainReplicationQueue = queue\n}", "func (mr *MockProvidersMockRecorder) LocalDiscoveryProvider() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"LocalDiscoveryProvider\", reflect.TypeOf((*MockProviders)(nil).LocalDiscoveryProvider))\n}", "func Discovery(*DiscoveryRequest, *DiscoveryResponse) {}", "func (m *MockProvider) Provide(arg0 string) blobclient.Client {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Provide\", arg0)\n\tret0, _ := ret[0].(blobclient.Client)\n\treturn ret0\n}", "func TestGetCloudProvider(t *testing.T) {\n\tfakeCredFile := \"fake-cred-file.json\"\n\tfakeKubeConfig := \"fake-kube-config\"\n\temptyKubeConfig := \"empty-kube-config\"\n\tfakeContent := `\napiVersion: v1\nclusters:\n- cluster:\n server: https://localhost:8080\n name: foo-cluster\ncontexts:\n- context:\n cluster: foo-cluster\n user: foo-user\n namespace: bar\n name: foo-context\ncurrent-context: foo-context\nkind: Config\nusers:\n- name: foo-user\n user:\n exec:\n apiVersion: client.authentication.k8s.io/v1alpha1\n args:\n - arg-1\n - arg-2\n command: foo-command\n`\n\n\terr := createTestFile(emptyKubeConfig)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tdefer func() {\n\t\tif err := os.Remove(emptyKubeConfig); err != nil {\n\t\t\tt.Error(err)\n\t\t}\n\t}()\n\n\ttests := []struct {\n\t\tdesc string\n\t\tcreateFakeCredFile bool\n\t\tcreateFakeKubeConfig bool\n\t\tkubeconfig string\n\t\tnodeID string\n\t\tuserAgent string\n\t\tallowEmptyCloudConfig bool\n\t\texpectedErr error\n\t}{\n\t\t{\n\t\t\tdesc: \"out of cluster, no kubeconfig, no credential file\",\n\t\t\tkubeconfig: \"\",\n\t\t\tnodeID: \"\",\n\t\t\tallowEmptyCloudConfig: true,\n\t\t\texpectedErr: nil,\n\t\t},\n\t\t{\n\t\t\tdesc: \"[failure][disallowEmptyCloudConfig] out of cluster, no kubeconfig, no credential file\",\n\t\t\tkubeconfig: \"\",\n\t\t\tnodeID: \"\",\n\t\t\tallowEmptyCloudConfig: false,\n\t\t\texpectedErr: nil,\n\t\t},\n\t\t{\n\t\t\tdesc: \"[failure] out of cluster & in cluster, specify a non-exist kubeconfig, no credential file\",\n\t\t\tkubeconfig: \"/tmp/non-exist.json\",\n\t\t\tnodeID: \"\",\n\t\t\tallowEmptyCloudConfig: true,\n\t\t\texpectedErr: nil,\n\t\t},\n\t\t{\n\t\t\tdesc: \"[failure] out of cluster & in cluster, specify a empty kubeconfig, no credential file\",\n\t\t\tkubeconfig: emptyKubeConfig,\n\t\t\tnodeID: \"\",\n\t\t\tallowEmptyCloudConfig: true,\n\t\t\texpectedErr: fmt.Errorf(\"failed to get KubeClient: invalid configuration: no configuration has been provided, try setting KUBERNETES_MASTER environment variable\"),\n\t\t},\n\t\t{\n\t\t\tdesc: \"[failure] out of cluster & in cluster, specify a fake kubeconfig, no credential file\",\n\t\t\tcreateFakeKubeConfig: true,\n\t\t\tkubeconfig: fakeKubeConfig,\n\t\t\tnodeID: \"\",\n\t\t\tallowEmptyCloudConfig: true,\n\t\t\texpectedErr: nil,\n\t\t},\n\t\t{\n\t\t\tdesc: \"[success] out of cluster & in cluster, no kubeconfig, a fake credential file\",\n\t\t\tcreateFakeCredFile: true,\n\t\t\tkubeconfig: \"\",\n\t\t\tnodeID: \"\",\n\t\t\tuserAgent: \"useragent\",\n\t\t\tallowEmptyCloudConfig: true,\n\t\t\texpectedErr: nil,\n\t\t},\n\t}\n\n\tfor _, test := range tests {\n\t\tif test.createFakeKubeConfig {\n\t\t\tif err := createTestFile(fakeKubeConfig); err != nil {\n\t\t\t\tt.Error(err)\n\t\t\t}\n\t\t\tdefer func() {\n\t\t\t\tif err := os.Remove(fakeKubeConfig); err != nil {\n\t\t\t\t\tt.Error(err)\n\t\t\t\t}\n\t\t\t}()\n\n\t\t\tif err := os.WriteFile(fakeKubeConfig, []byte(fakeContent), 0666); err != nil {\n\t\t\t\tt.Error(err)\n\t\t\t}\n\t\t}\n\t\tif test.createFakeCredFile {\n\t\t\tif err := createTestFile(fakeCredFile); err != nil {\n\t\t\t\tt.Error(err)\n\t\t\t}\n\t\t\tdefer func() {\n\t\t\t\tif err := os.Remove(fakeCredFile); err != nil {\n\t\t\t\t\tt.Error(err)\n\t\t\t\t}\n\t\t\t}()\n\n\t\t\toriginalCredFile, ok := os.LookupEnv(DefaultAzureCredentialFileEnv)\n\t\t\tif ok {\n\t\t\t\tdefer os.Setenv(DefaultAzureCredentialFileEnv, originalCredFile)\n\t\t\t} else {\n\t\t\t\tdefer os.Unsetenv(DefaultAzureCredentialFileEnv)\n\t\t\t}\n\t\t\tos.Setenv(DefaultAzureCredentialFileEnv, fakeCredFile)\n\t\t}\n\t\tcloud, err := getCloudProvider(test.kubeconfig, test.nodeID, \"\", \"\", test.userAgent, test.allowEmptyCloudConfig, 25.0, 50)\n\t\tif !reflect.DeepEqual(err, test.expectedErr) && test.expectedErr != nil && !strings.Contains(err.Error(), test.expectedErr.Error()) {\n\t\t\tt.Errorf(\"desc: %s,\\n input: %q, GetCloudProvider err: %v, expectedErr: %v\", test.desc, test.kubeconfig, err, test.expectedErr)\n\t\t}\n\t\tif cloud == nil {\n\t\t\tt.Errorf(\"return value of getCloudProvider should not be nil even there is error\")\n\t\t} else {\n\t\t\tassert.Equal(t, cloud.Environment.StorageEndpointSuffix, storage.DefaultBaseURL)\n\t\t\tassert.Equal(t, cloud.UserAgent, test.userAgent)\n\t\t}\n\t}\n}", "func hackClusterConfigForLocalTestingInKIND(\n\tremoteCluster *api.Cluster,\n\tremoteContextName, clusterDomainOverride string,\n) error {\n\tserverUrl, err := url.Parse(remoteCluster.Server)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif strings.HasPrefix(remoteContextName, \"kind-\") &&\n\t\t(serverUrl.Hostname() == \"127.0.0.1\" || serverUrl.Hostname() == \"localhost\") &&\n\t\tclusterDomainOverride != \"\" {\n\n\t\tremoteCluster.Server = fmt.Sprintf(\"https://%s:%s\", clusterDomainOverride, serverUrl.Port())\n\t\tremoteCluster.InsecureSkipTLSVerify = true\n\t\tremoteCluster.CertificateAuthority = \"\"\n\t\tremoteCluster.CertificateAuthorityData = []byte(\"\")\n\t}\n\n\treturn nil\n}", "func (m *MockProvider) OnServiceSynced() {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"OnServiceSynced\")\n}", "func (m *MockBKDataApiConfigInformer) Lister() v10.BKDataApiConfigLister {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Lister\")\n\tret0, _ := ret[0].(v10.BKDataApiConfigLister)\n\treturn ret0\n}", "func (m *MockLocalConfigProvider) Exists() bool {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Exists\")\n\tret0, _ := ret[0].(bool)\n\treturn ret0\n}", "func Local(clArgs []string, stdin io.Reader, stdout, stderr io.Writer, reg *testing.Registry, d Delegate) int {\n\tcfg := NewStaticConfig(reg, localTestTimeout, d)\n\treturn run(context.Background(), clArgs, stdin, stdout, stderr, cfg)\n}", "func StartMockups() {\n\tenabledMocks = true\n}", "func (p *TestProvider) Provide(addr string) Client {\n\tc, ok := p.clients[addr]\n\tif !ok {\n\t\tlog.Panicf(\"addr %s not found\", addr)\n\t}\n\treturn c\n}", "func (_m *ComputeAPI) LookupClusters(project string) ([]*container.Cluster, error) {\n\tret := _m.Called(project)\n\n\tvar r0 []*container.Cluster\n\tif rf, ok := ret.Get(0).(func(string) []*container.Cluster); ok {\n\t\tr0 = rf(project)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).([]*container.Cluster)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(string) error); ok {\n\t\tr1 = rf(project)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func TestLookup(t *testing.T) {\n\t// Create a mocked peers cache connected to a mock directory\n\tcache, mgds, err := makePeersCache()\n\trequire.NoError(t, err, \"could not create mocked peers cache\")\n\tdefer mgds.Shutdown()\n\n\t// Handle the case where the GDS returns an error\n\tmgds.UseError(gdsmock.LookupRPC, codes.NotFound, \"could not find peer with that common name\")\n\tpeer, err := cache.Lookup(\"unknown\")\n\trequire.EqualError(t, err, \"rpc error: code = NotFound desc = could not find peer with that common name\")\n\trequire.Nil(t, peer, \"peer should be nil when an error is returned\")\n\n\t// Handle the case where the GDS returns an error in the lookup reply\n\tmgds.OnLookup = func(context.Context, *gds.LookupRequest) (*gds.LookupReply, error) {\n\t\treturn &gds.LookupReply{\n\t\t\tError: &gds.Error{\n\t\t\t\tCode: 99,\n\t\t\t\tMessage: \"the GDS really shouldn't be returning these errors\",\n\t\t\t},\n\t\t}, nil\n\t}\n\n\tpeer, err = cache.Lookup(\"unknown\")\n\trequire.EqualError(t, err, \"[99] the GDS really shouldn't be returning these errors\")\n\trequire.Nil(t, peer, \"peer should be nil when an error is returned\")\n\n\t// Lookup should not error if GDS returns a nil identity and nil signing certificate\n\trequire.NoError(t, mgds.UseFixture(gdsmock.LookupRPC, \"testdata/leonardo.trisa.dev.pb.json\"))\n\tpeer, err = cache.Lookup(\"leonardo.trisa.dev\")\n\trequire.NoError(t, err, \"could not lookup peer from directory service\")\n\trequire.Nil(t, peer.SigningKey(), \"signing key should be nil when no certificate is returned\")\n\n\t// Configure a reply fixture for the other lookup test cases\n\treply := &gds.LookupReply{}\n\trequire.NoError(t, loadGRPCFixture(\"testdata/leonardo.trisa.dev.pb.json\", reply))\n\tmgds.OnLookup = func(context.Context, *gds.LookupRequest) (*gds.LookupReply, error) {\n\t\treturn reply, nil\n\t}\n\n\t// Generate keys to distinguish between identity and signing certificates\n\torigCert, origKey, err := generateCertificate()\n\trequire.NoError(t, err, \"could not generate certificate\")\n\tidentityCert, _, err := generateCertificate()\n\trequire.NoError(t, err, \"could not generate certificate\")\n\tsigningCert, signingKey, err := generateCertificate()\n\trequire.NoError(t, err, \"could not generate certificate\")\n\n\t// Lookup should store the identity key if the identity certificate is available on the lookup reply\n\treply.CommonName = \"identity\"\n\treply.IdentityCertificate = origCert\n\tpeer, err = cache.Lookup(\"identity\")\n\trequire.NoError(t, err, \"could not lookup peer from directory service\")\n\trequire.Equal(t, origKey, peer.SigningKey(), \"identity key should be stored\")\n\n\t// Lookup should not overwrite an existing key on the peer\n\treply.IdentityCertificate = identityCert\n\tpeer, err = cache.Lookup(\"identity\")\n\trequire.NoError(t, err, \"could not lookup peer from directory service\")\n\trequire.Equal(t, origKey, peer.SigningKey(), \"identity key should not be overwritten\")\n\n\t// Lookup should store the signing key if the signing certificate is available on the lookup reply\n\treply.CommonName = \"signing\"\n\treply.IdentityCertificate = nil\n\treply.SigningCertificate = signingCert\n\tpeer, err = cache.Lookup(\"signing\")\n\trequire.NoError(t, err, \"could not lookup peer from directory service\")\n\trequire.Equal(t, signingKey, peer.SigningKey(), \"signing key should be stored\")\n\n\t// Lookup should prefer the signing certificate over the identity certificate if both are available on the lookup reply\n\treply.CommonName = \"both\"\n\treply.IdentityCertificate = identityCert\n\treply.SigningCertificate = signingCert\n\tpeer, err = cache.Lookup(\"both\")\n\trequire.NoError(t, err, \"could not lookup peer from directory service\")\n\trequire.Equal(t, signingKey, peer.SigningKey(), \"signing key should be stored\")\n\n\t// Handle the case where the GDS returns valid responses\n\tmgds.Reset()\n\tmgds.OnLookup = func(_ context.Context, in *gds.LookupRequest) (out *gds.LookupReply, err error) {\n\t\tout = &gds.LookupReply{}\n\t\tswitch in.CommonName {\n\t\tcase \"leonardo.trisa.dev\":\n\t\t\tif err = loadGRPCFixture(\"testdata/leonardo.trisa.dev.pb.json\", out); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\tcase \"donatello.example.com\":\n\t\t\tif err = loadGRPCFixture(\"testdata/donatello.example.com.pb.json\", out); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\tdefault:\n\t\t\treturn nil, status.Error(codes.NotFound, \"unknown TRISA counterparty\")\n\t\t}\n\t\treturn out, nil\n\t}\n\n\t// Test concurrent Lookup calls\n\tt.Run(\"lookup\", func(t *testing.T) {\n\t\ttests := []struct {\n\t\t\tname string\n\t\t\tpeer string\n\t\t}{\n\t\t\t{\"lookup-leonardo\", \"leonardo.trisa.dev\"},\n\t\t\t{\"lookup-donatello\", \"donatello.example.com\"},\n\t\t}\n\t\tfor _, tt := range tests {\n\t\t\ttt := tt\n\t\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\t\tt.Parallel()\n\t\t\t\tp, err := cache.Lookup(tt.peer)\n\t\t\t\trequire.NoError(t, err)\n\t\t\t\trequire.NotNil(t, p)\n\t\t\t})\n\t\t}\n\t})\n\n\trequire.Equal(t, 0, mgds.Calls[gdsmock.SearchRPC])\n\trequire.Equal(t, 2, mgds.Calls[gdsmock.LookupRPC])\n\trequire.Equal(t, 0, mgds.Calls[gdsmock.StatusRPC])\n\n\t// Cache should contain the two peers\n\tleonardo, err := cache.Get(\"leonardo.trisa.dev\")\n\trequire.NoError(t, err)\n\trequire.Equal(t, \"19d84515-007a-48cc-9efd-b153a263e77c\", leonardo.Info().ID)\n\trequire.Equal(t, \"testdirectory.org\", leonardo.Info().RegisteredDirectory)\n\trequire.Equal(t, \"leonardo.trisa.dev\", leonardo.Info().CommonName)\n\trequire.Equal(t, \"leonardo.trisa.dev:8000\", leonardo.Info().Endpoint)\n\n\tdonatello, err := cache.Get(\"donatello.example.com\")\n\trequire.NoError(t, err)\n\trequire.Equal(t, \"b19c9ebd-82f5-4bda-91ef-226e3ecee4b8\", donatello.Info().ID)\n\trequire.Equal(t, \"testdirectory.org\", donatello.Info().RegisteredDirectory)\n\trequire.Equal(t, \"donatello.example.com\", donatello.Info().CommonName)\n\trequire.Equal(t, \"donatello.example.com:443\", donatello.Info().Endpoint)\n}", "func TestSetupMock(t *testing.T) {\n\tt.SkipNow()\n\tstudent, mocks, err := MockCluster(true, nil, t)\n\tif err != nil {\n\t\tt.Error(\"Couldn't set up mock cluster\", err)\n\t}\n\n\tt.Log(\"Created student node:\", student)\n\tt.Log(\"Created mock nodes:\", mocks)\n\n\ttime.Sleep(DefaultConfig().ElectionTimeout * 2)\n\tt.Log(\"Student node is:\", student.State)\n\ttime.Sleep(DefaultConfig().ElectionTimeout * 2)\n\tt.Log(\"Student node is:\", student.State)\n}", "func (self *discovery) callDiscoveryService(action string, successState bool) error {\n\tlog.Infof(\"[Server] Attempting to %s with the discovery service...\", action)\n\n\tazName, _ := util.GetAwsAZName()\n\tregSize := reg.size()\n\tmachineClass := os.Getenv(\"H2O_MACHINE_CLASS\")\n\n\tendpoints := make([]*register.MultiRequest_Endpoint, regSize)\n\ti := 0\n\tfor _, endpoint := range reg.iterate() {\n\t\tendpoints[i] = &register.MultiRequest_Endpoint{\n\t\t\tName: proto.String(endpoint.Name),\n\t\t\tMean: proto.Int32(endpoint.Mean),\n\t\t\tUpper95: proto.Int32(endpoint.Upper95),\n\t\t\tSubscribe: proto.String(endpoint.Subscribe),\n\t\t}\n\n\t\ti++\n\t}\n\n\tservice := &dscShared.Service{\n\t\tName: proto.String(Name),\n\t\tDescription: proto.String(Description),\n\t\tVersion: proto.Uint64(Version),\n\t\tSource: proto.String(Source),\n\t\tOwnerEmail: proto.String(OwnerEmail),\n\t\tOwnerMobile: proto.String(OwnerMobile),\n\t\tOwnerTeam: proto.String(OwnerTeam),\n\t}\n\n\trequest, err := ScopedRequest(\n\t\t\"com.HailoOSS.kernel.discovery\",\n\t\taction,\n\t\t&register.MultiRequest{\n\t\t\tInstanceId: proto.String(InstanceID),\n\t\t\tHostname: proto.String(self.hostname),\n\t\t\tMachineClass: proto.String(machineClass),\n\t\t\tAzName: proto.String(azName),\n\t\t\tService: service,\n\t\t\tEndpoints: endpoints,\n\t\t},\n\t)\n\n\tif err != nil {\n\t\tlog.Warnf(\"[Server] Failed to build request when %sing services\", action)\n\t\treturn err\n\t}\n\n\t// explicitly define timeout, since we're happy to wait\n\tclientOptions := client.Options{\"retries\": 0, \"timeout\": 5 * time.Second}\n\n\trsp := &register.Response{}\n\tif err := client.Req(request, rsp, clientOptions); err != nil {\n\t\tlog.Warnf(\"[Server] Failed to %s services: %v\", action, err)\n\t\treturn err\n\t}\n\n\t// ok -- all done!\n\tself.connected = successState\n\tlog.Infof(\"[Server] Successfully %sed with the hive mind!\", action)\n\n\treturn nil\n}", "func NewMockInterfaceProvider(managedInterfacesRegexp string, autoRefresh bool) (nt.InterfaceProvider,\n\tchan time.Time, error) {\n\tch := make(chan time.Time)\n\tip, err := nt.NewChanInterfaceProvider(ch, &MockInterfaceLister{}, managedInterfacesRegexp,\n\t\tautoRefresh)\n\treturn ip, ch, err\n}", "func (bil *baseInstanceList) newMockCloud() cloud.Cloud {\n\tc := cloud.NewMockGCE(nil)\n\n\t// insert hooks to lazy create a instance when needed\n\tc.MockInstances.GetHook = bil.newGAGetHook()\n\tc.MockBetaInstances.GetHook = bil.newBetaGetHook()\n\n\treturn c\n}", "func unmanagedProviderFactory(provider addrs.Provider, reattach *plugin.ReattachConfig) providers.Factory {\n\treturn func() (providers.Interface, error) {\n\t\tconfig := &plugin.ClientConfig{\n\t\t\tHandshakeConfig: tfplugin.Handshake,\n\t\t\tLogger: logging.NewProviderLogger(\"unmanaged.\"),\n\t\t\tAllowedProtocols: []plugin.Protocol{plugin.ProtocolGRPC},\n\t\t\tManaged: false,\n\t\t\tReattach: reattach,\n\t\t\tSyncStdout: logging.PluginOutputMonitor(fmt.Sprintf(\"%s:stdout\", provider)),\n\t\t\tSyncStderr: logging.PluginOutputMonitor(fmt.Sprintf(\"%s:stderr\", provider)),\n\t\t}\n\n\t\tif reattach.ProtocolVersion == 0 {\n\t\t\t// As of the 0.15 release, sdk.v2 doesn't include the protocol\n\t\t\t// version in the ReattachConfig (only recently added to\n\t\t\t// go-plugin), so client.NegotiatedVersion() always returns 0. We\n\t\t\t// assume that an unmanaged provider reporting protocol version 0 is\n\t\t\t// actually using proto v5 for backwards compatibility.\n\t\t\tif defaultPlugins, ok := tfplugin.VersionedPlugins[5]; ok {\n\t\t\t\tconfig.Plugins = defaultPlugins\n\t\t\t} else {\n\t\t\t\treturn nil, errors.New(\"no supported plugins for protocol 0\")\n\t\t\t}\n\t\t} else if plugins, ok := tfplugin.VersionedPlugins[reattach.ProtocolVersion]; !ok {\n\t\t\treturn nil, fmt.Errorf(\"no supported plugins for protocol %d\", reattach.ProtocolVersion)\n\t\t} else {\n\t\t\tconfig.Plugins = plugins\n\t\t}\n\n\t\tclient := plugin.NewClient(config)\n\t\trpcClient, err := client.Client()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\traw, err := rpcClient.Dispense(tfplugin.ProviderPluginName)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// store the client so that the plugin can kill the child process\n\t\tprotoVer := client.NegotiatedVersion()\n\t\tswitch protoVer {\n\t\tcase 0, 5:\n\t\t\t// As of the 0.15 release, sdk.v2 doesn't include the protocol\n\t\t\t// version in the ReattachConfig (only recently added to\n\t\t\t// go-plugin), so client.NegotiatedVersion() always returns 0. We\n\t\t\t// assume that an unmanaged provider reporting protocol version 0 is\n\t\t\t// actually using proto v5 for backwards compatibility.\n\t\t\tp := raw.(*tfplugin.GRPCProvider)\n\t\t\tp.PluginClient = client\n\t\t\treturn p, nil\n\t\tcase 6:\n\t\t\tp := raw.(*tfplugin6.GRPCProvider)\n\t\t\tp.PluginClient = client\n\t\t\treturn p, nil\n\t\tdefault:\n\t\t\treturn nil, fmt.Errorf(\"unsupported protocol version %d\", protoVer)\n\t\t}\n\t}\n}", "func (m *MockRemotes) Lookup(arg0 string) (*git.Remote, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Lookup\", arg0)\n\tret0, _ := ret[0].(*git.Remote)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (c *Clientset) Discovery() discovery.DiscoveryInterface {\n\treturn c.FakeDiscovery\n}", "func (ds *localDiscoveryService) Initialize(ctx contextAPI.Local) error {\r\n\tds.mspID = ctx.Identifier().MSPID\r\n\treturn nil\r\n}", "func NewlocalShimClient(c *config.ClusterControllerConfig) ShimServiceClient {\n\tk8sClient, err := k8sclient.NewK8sClient(k8sclient.K8sOption{KubeConfig: c.KubeConfig})\n\tif err != nil {\n\t\tklog.Errorf(\"failed to create k8s client: %v\", err)\n\t\treturn nil\n\t}\n\n\tlocal := &localShimClient{\n\t\thandlers: make(map[string]handler.Handler),\n\t}\n\n\tlocal.handlers[otev1.ClusterControllerDestAPI] = handler.NewK8sHandler(k8sClient)\n\tlocal.handlers[otev1.ClusterControllerDestHelm] = handler.NewHTTPProxyHandler(c.HelmTillerAddr)\n\treturn local\n}", "func ProviderTest(initial Initial, observer invoker.Observer, settings Settings) (Configurator, func(), error) {\n\tc, e := NewMockConfigurator(initial, observer, settings)\n\treturn c, func() {}, e\n}", "func newDiscoveryTool(\n\tregions []string,\n\tproject string,\n\tlg telegraf.Logger,\n\tcredential auth.Credential,\n\trateLimit int,\n\tdiscoveryInterval time.Duration,\n) (*discoveryTool, error) {\n\tvar (\n\t\tdscReq = map[string]discoveryRequest{}\n\t\tcli = map[string]aliyunSdkClient{}\n\t\tresponseRootKey string\n\t\tresponseObjectIDKey string\n\t\terr error\n\t\tnoDiscoverySupportErr = fmt.Errorf(\"no discovery support for project %q\", project)\n\t)\n\n\tif len(regions) == 0 {\n\t\tregions = aliyunRegionList\n\t\tlg.Infof(\"'regions' is not provided! Discovery data will be queried across %d regions:\\n%s\",\n\t\t\tlen(aliyunRegionList), strings.Join(aliyunRegionList, \",\"))\n\t}\n\n\tif rateLimit == 0 { //Can be a rounding case\n\t\trateLimit = 1\n\t}\n\n\tfor _, region := range regions {\n\t\tswitch project {\n\t\tcase \"acs_ecs_dashboard\":\n\t\t\tdscReq[region] = ecs.CreateDescribeInstancesRequest()\n\t\t\tresponseRootKey = \"Instances\"\n\t\t\tresponseObjectIDKey = \"InstanceId\"\n\t\tcase \"acs_rds_dashboard\":\n\t\t\tdscReq[region] = rds.CreateDescribeDBInstancesRequest()\n\t\t\tresponseRootKey = \"Items\"\n\t\t\tresponseObjectIDKey = \"DBInstanceId\"\n\t\tcase \"acs_slb_dashboard\":\n\t\t\tdscReq[region] = slb.CreateDescribeLoadBalancersRequest()\n\t\t\tresponseRootKey = \"LoadBalancers\"\n\t\t\tresponseObjectIDKey = \"LoadBalancerId\"\n\t\tcase \"acs_memcache\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_ocs\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_oss\":\n\t\t\t// oss is really complicated and its' own format\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_vpc_eip\":\n\t\t\tdscReq[region] = vpc.CreateDescribeEipAddressesRequest()\n\t\t\tresponseRootKey = \"EipAddresses\"\n\t\t\tresponseObjectIDKey = \"AllocationId\"\n\t\tcase \"acs_kvstore\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_mns_new\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_cdn\":\n\t\t\t//API replies are in its own format.\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_polardb\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_gdb\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_ads\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_mongodb\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_express_connect\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_fc\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_nat_gateway\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_sls_dashboard\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_containerservice_dashboard\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_vpn\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_bandwidth_package\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_cen\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_ens\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_opensearch\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_scdn\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_drds\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_iot\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_directmail\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_elasticsearch\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_ess_dashboard\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_streamcompute\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_global_acceleration\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_hitsdb\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_kafka\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_openad\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_pcdn\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_dcdn\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_petadata\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_videolive\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_hybriddb\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_adb\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_mps\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_maxcompute_prepay\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_hdfs\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_ddh\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_hbr\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_hdr\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_cds\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tdefault:\n\t\t\treturn nil, fmt.Errorf(\"project %q is not recognized by discovery\", project)\n\t\t}\n\n\t\tcli[region], err = sdk.NewClientWithOptions(region, sdk.NewConfig(), credential)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tif len(dscReq) == 0 || len(cli) == 0 {\n\t\treturn nil, fmt.Errorf(\"can't build discovery request for project: %q, regions: %v\", project, regions)\n\t}\n\n\treturn &discoveryTool{\n\t\treq: dscReq,\n\t\tcli: cli,\n\t\trespRootKey: responseRootKey,\n\t\trespObjectIDKey: responseObjectIDKey,\n\t\trateLimit: rateLimit,\n\t\tinterval: discoveryInterval,\n\t\treqDefaultPageSize: 20,\n\t\tdataChan: make(chan map[string]interface{}, 1),\n\t\tlg: lg,\n\t}, nil\n}", "func TestInternalInit(t *testing.T) {\n\tvar err error\n\n\t// delete the default path\n\tdbPath := filepath.Join(fs.CacheDir, \"cache-backend\", *RemoteName+\".db\")\n\tboltDb, err = cache.GetPersistent(dbPath, &cache.Features{PurgeDb: true})\n\trequire.NoError(t, err)\n\tfstest.Initialise()\n\n\tif len(*WrapRemote) == 0 {\n\t\t*WrapRemote = \"localInternal:/var/tmp/rclone-cache\"\n\t\tfs.ConfigFileSet(\"localInternal\", \"type\", \"local\")\n\t\tfs.ConfigFileSet(\"localInternal\", \"nounc\", \"true\")\n\t}\n\n\tremoteExists := false\n\tfor _, s := range fs.ConfigFileSections() {\n\t\tif s == *RemoteName {\n\t\t\tremoteExists = true\n\t\t}\n\t}\n\n\tif !remoteExists {\n\t\tfs.ConfigFileSet(*RemoteName, \"type\", \"cache\")\n\t\tfs.ConfigFileSet(*RemoteName, \"remote\", *WrapRemote)\n\t\tfs.ConfigFileSet(*RemoteName, \"chunk_size\", \"1024\")\n\t\tfs.ConfigFileSet(*RemoteName, \"chunk_total_size\", \"2048\")\n\t\tfs.ConfigFileSet(*RemoteName, \"info_age\", infoAge.String())\n\t}\n\n\t_ = flag.Set(\"cache-chunk-no-memory\", \"true\")\n\t_ = flag.Set(\"cache-workers\", strconv.Itoa(workers))\n\t_ = flag.Set(\"cache-chunk-clean-interval\", chunkClean.String())\n\n\t// Instantiate root\n\trootFs, err = fs.NewFs(*RemoteName + \":\")\n\trequire.NoError(t, err)\n\t_ = rootFs.Features().Purge()\n\trequire.NoError(t, err)\n\terr = rootFs.Mkdir(\"\")\n\trequire.NoError(t, err)\n\n\t// flush cache\n\t_, err = getCacheFs(rootFs)\n\trequire.NoError(t, err)\n}", "func Mock(codec codec.Codec) (*Client, io.Closer, error) {\n\tdir, err := ioutil.TempDir(\"\", \"etcd\")\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tcfg := embed.NewConfig()\n\tcfg.Logger = \"zap\"\n\tcfg.Dir = dir\n\tlpurl, _ := url.Parse(\"http://localhost:0\")\n\tlcurl, _ := url.Parse(\"http://localhost:0\")\n\tcfg.LPUrls = []url.URL{*lpurl}\n\tcfg.LCUrls = []url.URL{*lcurl}\n\n\tetcd, err := embed.StartEtcd(cfg)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tselect {\n\tcase <-etcd.Server.ReadyNotify():\n\tcase <-time.After(etcdStartTimeout):\n\t\tetcd.Server.Stop() // trigger a shutdown\n\t\treturn nil, nil, fmt.Errorf(\"server took too long to start\")\n\t}\n\n\tcloser := CloserFunc(func() error {\n\t\tetcd.Server.Stop()\n\t\treturn nil\n\t})\n\n\tvar config Config\n\tflagext.DefaultValues(&config)\n\n\tclient := &Client{\n\t\tcfg: config,\n\t\tcodec: codec,\n\t\tcli: v3client.New(etcd.Server),\n\t}\n\n\treturn client, closer, nil\n}", "func (m *MockUpstreamIntf) LocalHeight() uint64 {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"LocalHeight\")\n\tret0, _ := ret[0].(uint64)\n\treturn ret0\n}", "func (m *MockInterface) Init(kubeconfigPath, kubeconfigContext string) error {\n\treturn nil\n}", "func WithLocalDiscoveryProvider(discoveryProvider fab.LocalDiscoveryProvider) SDKContextParams {\n\treturn func(ctx *Provider) {\n\t\tctx.localDiscoveryProvider = discoveryProvider\n\t}\n}", "func (m *MockClusterScoper) Location() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Location\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}" ]
[ "0.7341058", "0.632302", "0.5986372", "0.58804214", "0.5836367", "0.56410253", "0.5597734", "0.5465775", "0.5429311", "0.54236996", "0.5394687", "0.53897685", "0.5385342", "0.53083503", "0.5291153", "0.5270716", "0.5252473", "0.52352184", "0.5203148", "0.5182315", "0.51554424", "0.51373076", "0.51317257", "0.5131219", "0.51069343", "0.5104862", "0.5101072", "0.50829625", "0.50779665", "0.50580496", "0.50442785", "0.5015747", "0.5007717", "0.50073826", "0.49975476", "0.49859568", "0.4977625", "0.49743494", "0.49542406", "0.49527407", "0.49426416", "0.4939108", "0.49213752", "0.49193934", "0.49170017", "0.4905363", "0.4891342", "0.48856932", "0.48853382", "0.4885069", "0.48847178", "0.48819792", "0.48745868", "0.48625183", "0.4855074", "0.48422745", "0.4837798", "0.48357165", "0.48329988", "0.4817016", "0.48164788", "0.4812812", "0.48124698", "0.48033565", "0.48010418", "0.47864047", "0.4778217", "0.47769454", "0.47767922", "0.47681028", "0.47661555", "0.4762952", "0.47612557", "0.47560406", "0.47491106", "0.47456867", "0.474457", "0.4738789", "0.47361666", "0.4736134", "0.47360688", "0.47348568", "0.4726774", "0.47182944", "0.4711988", "0.47100633", "0.47040755", "0.47027513", "0.47025004", "0.4702348", "0.46925232", "0.468725", "0.46867567", "0.46827984", "0.46812293", "0.46764582", "0.46750093", "0.4665986", "0.4664836", "0.46601477" ]
0.7134569
1
LocalDiscoveryProvider indicates an expected call of LocalDiscoveryProvider
func (mr *MockProvidersMockRecorder) LocalDiscoveryProvider() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "LocalDiscoveryProvider", reflect.TypeOf((*MockProviders)(nil).LocalDiscoveryProvider)) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (mr *MockClientMockRecorder) LocalDiscoveryProvider() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"LocalDiscoveryProvider\", reflect.TypeOf((*MockClient)(nil).LocalDiscoveryProvider))\n}", "func (c *Provider) LocalDiscoveryProvider() fab.LocalDiscoveryProvider {\n\treturn c.localDiscoveryProvider\n}", "func (m *MockClient) LocalDiscoveryProvider() fab.LocalDiscoveryProvider {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"LocalDiscoveryProvider\")\n\tret0, _ := ret[0].(fab.LocalDiscoveryProvider)\n\treturn ret0\n}", "func (m *MockProviders) LocalDiscoveryProvider() fab.LocalDiscoveryProvider {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"LocalDiscoveryProvider\")\n\tret0, _ := ret[0].(fab.LocalDiscoveryProvider)\n\treturn ret0\n}", "func (c *Local) LocalDiscoveryService() fab.DiscoveryService {\n\treturn c.localDiscovery\n}", "func (_e *MockPlcDriver_Expecter) SupportsDiscovery() *MockPlcDriver_SupportsDiscovery_Call {\n\treturn &MockPlcDriver_SupportsDiscovery_Call{Call: _e.mock.On(\"SupportsDiscovery\")}\n}", "func (sc *ShamClient) fallbackDiscovery() {\n\tif len(sc.localRegistry) == 0 {\n\t\tsc.setLocalRegistry(sc.serviceRegistry.Fallback)\n\t\tsc.logger.Infof(\"using Fallback registry for service %s: %+v\", sc.serviceName, sc.localRegistry)\n\t} else {\n\t\tsc.logger.Infof(\"continue using local registry for service %s: %+v\", sc.serviceName, sc.localRegistry)\n\t}\n}", "func (m *Module) gatherProviderLocalNames() {\n\tproviders := make(map[addrs.Provider]string)\n\tfor k, v := range m.ProviderRequirements.RequiredProviders {\n\t\tproviders[v.Type] = k\n\t}\n\tm.ProviderLocalNames = providers\n}", "func (l *Factory) CreateLocalDiscoveryProvider(config fabApi.EndpointConfig) (fabApi.LocalDiscoveryProvider, error) {\n\tlogger.Debug(\"create local Provider Impl\")\n\treturn &impl{config, l.LocalPeer, l.LocalPeerTLSCertPem}, nil\n}", "func WithLocalDiscoveryProvider(discoveryProvider fab.LocalDiscoveryProvider) SDKContextParams {\n\treturn func(ctx *Provider) {\n\t\tctx.localDiscoveryProvider = discoveryProvider\n\t}\n}", "func (s *gossipServiceDiscovery) LocalDiscovery(ctx context.Context) (*localPeersDTO, error) {\n\treq := discClient.\n\t\tNewRequest().AddLocalPeersQuery()\n\n\tres, err := s.client.Send(ctx, req, s.getAuthInfo())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpeers, err := res.ForLocal().Peers()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdc := newLocalPeersDTO()\n\n\treturn s.parseDiscoverLocalPeers(dc, peers), nil\n}", "func (m *MockMemberList) LocalNode() discovery.Member {\n\tret := m.ctrl.Call(m, \"LocalNode\")\n\tret0, _ := ret[0].(discovery.Member)\n\treturn ret0\n}", "func MissingProviderSuggestion(ctx context.Context, addr addrs.Provider, source Source, reqs Requirements) addrs.Provider {\n\tif !addr.IsDefault() {\n\t\treturn addr\n\t}\n\n\t// Before possibly looking up legacy naming, see if the user has another provider\n\t// named in their requirements that is of the same type, and offer that\n\t// as a suggestion\n\tfor req := range reqs {\n\t\tif req != addr && req.Type == addr.Type {\n\t\t\treturn req\n\t\t}\n\t}\n\n\t// Our strategy here, for a default provider, is to use the default\n\t// registry's special API for looking up \"legacy\" providers and try looking\n\t// for a legacy provider whose type name matches the type of the given\n\t// provider. This should then find a suitable answer for any provider\n\t// that was originally auto-installable in v0.12 and earlier but moved\n\t// into a non-default namespace as part of introducing the hierarchical\n\t// provider namespace.\n\t//\n\t// To achieve that, we need to find the direct registry client in\n\t// particular from the given source, because that is the only Source\n\t// implementation that can actually handle a legacy provider lookup.\n\tregSource := findLegacyProviderLookupSource(addr.Hostname, source)\n\tif regSource == nil {\n\t\t// If there's no direct registry source in the installation config\n\t\t// then we can't provide a renaming suggestion.\n\t\treturn addr\n\t}\n\n\tdefaultNS, redirectNS, err := regSource.lookupLegacyProviderNamespace(ctx, addr.Hostname, addr.Type)\n\tif err != nil {\n\t\treturn addr\n\t}\n\n\tswitch {\n\tcase redirectNS != \"\":\n\t\treturn addrs.Provider{\n\t\t\tHostname: addr.Hostname,\n\t\t\tNamespace: redirectNS,\n\t\t\tType: addr.Type,\n\t\t}\n\tdefault:\n\t\treturn addrs.Provider{\n\t\t\tHostname: addr.Hostname,\n\t\t\tNamespace: defaultNS,\n\t\t\tType: addr.Type,\n\t\t}\n\t}\n}", "func NewLocalProvider(t []string) Provider {\n\treturn newLocalProviderWithClock(t, clock.New())\n}", "func (c *TestConnection) LocalAddr() net.Addr {\n return nil\n}", "func Discovery(*DiscoveryRequest, *DiscoveryResponse) {}", "func TestLogConfigInLocal(t *testing.T) {\n\t// Check if\n}", "func NewLocal(clientProvider context.ClientProvider) (*Local, error) {\n\tclient, err := clientProvider()\n\tif err != nil {\n\t\treturn nil, errors.WithMessage(err, \"failed to get client context to create local context\")\n\t}\n\n\tdiscoveryService, err := client.LocalDiscoveryProvider().CreateLocalDiscoveryService(client.Identifier().MSPID)\n\tif err != nil {\n\t\treturn nil, errors.WithMessage(err, \"failed to create local discovery service\")\n\t}\n\n\tlocal := &Local{\n\t\tClient: client,\n\t\tlocalDiscovery: discoveryService,\n\t}\n\n\tif ci, ok := discoveryService.(localServiceInit); ok {\n\t\tif err := ci.Initialize(local); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn local, nil\n}", "func (mr *MockInterfaceMockRecorder) Discovery() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Discovery\", reflect.TypeOf((*MockInterface)(nil).Discovery))\n}", "func (mph *MockPeerHandler) LocalAddr() string {\n\treturn \"\"\n}", "func (_m *MockPlcDriver) SupportsDiscovery() bool {\n\tret := _m.Called()\n\n\tvar r0 bool\n\tif rf, ok := ret.Get(0).(func() bool); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tr0 = ret.Get(0).(bool)\n\t}\n\n\treturn r0\n}", "func setupDiscovery(ctx context.Context, h host.Host) error {\n\t// setup mDNS discovery to find local peers\n\tdisc, err := discovery.NewMdnsService(ctx, h, DiscoveryInterval, DiscoveryServiceTag)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tn := discoveryNotifee{h: h}\n\tdisc.RegisterNotifee(&n)\n\treturn nil\n}", "func hackClusterConfigForLocalTestingInKIND(\n\tremoteCluster *api.Cluster,\n\tremoteContextName, clusterDomainOverride string,\n) error {\n\tserverUrl, err := url.Parse(remoteCluster.Server)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif strings.HasPrefix(remoteContextName, \"kind-\") &&\n\t\t(serverUrl.Hostname() == \"127.0.0.1\" || serverUrl.Hostname() == \"localhost\") &&\n\t\tclusterDomainOverride != \"\" {\n\n\t\tremoteCluster.Server = fmt.Sprintf(\"https://%s:%s\", clusterDomainOverride, serverUrl.Port())\n\t\tremoteCluster.InsecureSkipTLSVerify = true\n\t\tremoteCluster.CertificateAuthority = \"\"\n\t\tremoteCluster.CertificateAuthorityData = []byte(\"\")\n\t}\n\n\treturn nil\n}", "func TestLocalDomain_NetworkServiceRegistry(t *testing.T) {\n\tt.Cleanup(func() { goleak.VerifyNone(t) })\n\n\tctx, cancel := context.WithTimeout(context.Background(), time.Second)\n\tdefer cancel()\n\n\tdnsServer := sandbox.NewFakeResolver()\n\n\tdomain1 := sandbox.NewBuilder(ctx, t).\n\t\tSetNodesCount(0).\n\t\tSetDNSDomainName(\"cluster.local\").\n\t\tSetDNSResolver(dnsServer).\n\t\tBuild()\n\n\tclient1 := registryclient.NewNetworkServiceRegistryClient(ctx,\n\t\tregistryclient.WithDialOptions(grpc.WithTransportCredentials(insecure.NewCredentials())),\n\t\tregistryclient.WithClientURL(domain1.Registry.URL))\n\n\texpected, err := client1.Register(context.Background(), &registryapi.NetworkService{\n\t\tName: \"ns-1@\" + domain1.Name,\n\t})\n\n\trequire.Nil(t, err)\n\trequire.True(t, strings.Contains(expected.GetName(), \"@\"+domain1.Name))\n\n\tclient2 := registryclient.NewNetworkServiceRegistryClient(ctx,\n\t\tregistryclient.WithDialOptions(grpc.WithTransportCredentials(insecure.NewCredentials())),\n\t\tregistryclient.WithClientURL(domain1.Registry.URL))\n\n\tstream, err := client2.Find(context.Background(), &registryapi.NetworkServiceQuery{\n\t\tNetworkService: &registryapi.NetworkService{\n\t\t\tName: expected.Name,\n\t\t},\n\t})\n\n\trequire.Nil(t, err)\n\n\tlist := registryapi.ReadNetworkServiceList(stream)\n\n\trequire.Len(t, list, 1)\n\trequire.Equal(t, \"ns-1@cluster.local\", list[0].Name)\n}", "func (o *LocalDatabaseProvider) GetBlockLocalDnsRequestsOk() (*bool, bool) {\n\tif o == nil || o.BlockLocalDnsRequests == nil {\n\t\treturn nil, false\n\t}\n\treturn o.BlockLocalDnsRequests, true\n}", "func (o *LocalDatabaseProvider) HasBlockLocalDnsRequests() bool {\n\tif o != nil && o.BlockLocalDnsRequests != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (ds *localDiscoveryService) Initialize(ctx contextAPI.Local) error {\r\n\tds.mspID = ctx.Identifier().MSPID\r\n\treturn nil\r\n}", "func newLocalProviderWithClock(t []string, clock clock.Clock) Provider {\n\tp := &localProvider{\n\t\ttags: t,\n\t\texpectedTags: t,\n\t}\n\n\tif config.IsExpectedTagsSet(coreConfig.Datadog) {\n\t\tp.expectedTags = append(p.tags, hostMetadataUtils.GetHostTags(context.TODO(), false, coreConfig.Datadog).System...)\n\n\t\t// expected tags deadline is based on the agent start time, which may have been earlier\n\t\t// than the current time.\n\t\texpectedTagsDeadline := coreConfig.StartTime.Add(coreConfig.Datadog.GetDuration(\"logs_config.expected_tags_duration\"))\n\n\t\t// reset submitExpectedTags after deadline elapsed\n\t\tclock.AfterFunc(expectedTagsDeadline.Sub(clock.Now()), func() {\n\t\t\tp.Lock()\n\t\t\tdefer p.Unlock()\n\t\t\tp.expectedTags = nil\n\t\t})\n\t}\n\n\treturn p\n}", "func TestDiscoveryFeatureGate(t *testing.T) {\n\tnewIntegrationTest(\"minimal.example.com\", \"public-jwks-apiserver\").\n\t\twithDefaultServiceAccountRoles24().\n\t\twithServiceAccountRole(\"aws-node-termination-handler.kube-system\", true).\n\t\twithDefaultAddons24().\n\t\twithOIDCDiscovery().\n\t\trunTestTerraformAWS(t)\n}", "func requiresNativeServiceDiscovery(group string, services []*Service, basic, checks *set.Set[string]) {\n\tfor _, tgService := range services {\n\t\tif tgService.Provider == ServiceProviderNomad {\n\t\t\tbasic.Insert(group)\n\t\t\tif len(tgService.Checks) > 0 {\n\t\t\t\tchecks.Insert(group)\n\t\t\t}\n\t\t}\n\t}\n}", "func IndirectlyTested() string {\n\treturn \"This function is tested via a function reference rather than a direct call\"\n}", "func (m *MockEarlyConnection) LocalAddr() net.Addr {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"LocalAddr\")\n\tret0, _ := ret[0].(net.Addr)\n\treturn ret0\n}", "func NewNewDiscoveryOK() *NewDiscoveryOK {\n\treturn &NewDiscoveryOK{}\n}", "func (dp *MockStaticDiscoveryProvider) CreateLocalDiscoveryService(mspID string) (fab.DiscoveryService, error) {\n\treturn &MockStaticDiscoveryService{Error: dp.Error, Peers: dp.Peers}, nil\n}", "func TestDefaultProviderIsWarnOnceProvider(t *testing.T) {\n\t// create logger that writes to buffer using the default logger provider\n\tbuf := &bytes.Buffer{}\n\tlogger := svc1log.New(buf, wlog.DebugLevel) // uses default provider\n\n\t// verify that output provides warning that no logger provider was specified\n\tlogger.Info(\"Test output 1\")\n\tconst wantOutput = `[WARNING] Logging operation that uses the default logger provider was performed without specifying a logger provider implementation. To see logger output, set the global logger provider implementation using wlog.SetDefaultLoggerProvider or by importing an implementation. This warning can be disabled by setting the global logger provider to be the noop logger provider using wlog.SetDefaultLoggerProvider(wlog.NewNoopLoggerProvider()).` + \"\\n\"\n\tgot := buf.String()\n\tassert.Equal(t, wantOutput, got)\n\n\t// verify that warning is only written on first call to logger\n\tlogger.Info(\"Test output 2\")\n\tbuf.Reset()\n\tgot = buf.String()\n\tassert.Equal(t, \"\", got)\n}", "func shouldUseLocalWithFallback(ic *operatorv1.IngressController, service *corev1.Service) (bool, error) {\n\t// By default, use local-with-fallback when using the \"Local\" external\n\t// traffic policy.\n\tif service.Spec.ExternalTrafficPolicy != corev1.ServiceExternalTrafficPolicyTypeLocal {\n\t\treturn false, nil\n\t}\n\n\t// Allow the user to override local-with-fallback.\n\tif len(ic.Spec.UnsupportedConfigOverrides.Raw) > 0 {\n\t\tvar unsupportedConfigOverrides struct {\n\t\t\tLocalWithFallback string `json:\"localWithFallback\"`\n\t\t}\n\t\tif err := json.Unmarshal(ic.Spec.UnsupportedConfigOverrides.Raw, &unsupportedConfigOverrides); err != nil {\n\t\t\treturn false, fmt.Errorf(\"ingresscontroller %q has invalid spec.unsupportedConfigOverrides: %w\", ic.Name, err)\n\t\t}\n\t\toverride := unsupportedConfigOverrides.LocalWithFallback\n\t\tif len(override) != 0 {\n\t\t\tif val, err := strconv.ParseBool(override); err != nil {\n\t\t\t\treturn false, fmt.Errorf(\"ingresscontroller %q has invalid spec.unsupportedConfigOverrides.localWithFallback: %w\", ic.Name, err)\n\t\t\t} else {\n\t\t\t\treturn val, nil\n\t\t\t}\n\t\t}\n\t}\n\n\treturn true, nil\n}", "func (l *impl) CreateLocalDiscoveryService(mspID string) (fabApi.DiscoveryService, error) {\n\treturn &localDiscoveryService{l.clientConfig, l.localPeer, l.localPeerTLSCertPem}, nil\n}", "func testMdns(t *testing.T) {\n\tservice := \"_liqo._tcp\"\n\tdomain := \"local.\"\n\n\tgo clientCluster.discoveryCtrl.Register()\n\n\ttime.Sleep(1 * time.Second)\n\n\ttxts := []*discovery.TxtData{}\n\tclientCluster.discoveryCtrl.Resolve(service, domain, 3, &txts)\n\n\ttime.Sleep(1 * time.Second)\n\n\t// TODO: find better way to test mDNS, local IP is not always detected\n\tassert.Assert(t, len(txts) >= 0, \"If this line is reached test would be successful, no foreign packet can reach our testing environment at the moment\")\n}", "func (r *NamespaceMapReconciler) checkLocalClusterID() error {\n\tif r.LocalClusterID == \"\" {\n\t\tclusterID, err := liqoutils.GetClusterID(r.Client)\n\t\tif err != nil || clusterID == \"\" {\n\t\t\treturn err\n\t\t}\n\t\tr.LocalClusterID = clusterID\n\t}\n\treturn nil\n}", "func (mr *MockServiceMockRecorder) Discovery() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Discovery\", reflect.TypeOf((*MockService)(nil).Discovery))\n}", "func (_m *Session) LocalAddr() net.Addr {\n\tret := _m.Called()\n\n\tvar r0 net.Addr\n\tif rf, ok := ret.Get(0).(func() net.Addr); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(net.Addr)\n\t\t}\n\t}\n\n\treturn r0\n}", "func (mr *MockMemberListMockRecorder) LocalNode() *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"LocalNode\", reflect.TypeOf((*MockMemberList)(nil).LocalNode))\n}", "func (m *MockPacketHandler) LocalAddr() net.Addr {\n\tret := m.ctrl.Call(m, \"LocalAddr\")\n\tret0, _ := ret[0].(net.Addr)\n\treturn ret0\n}", "func newLocalService(config fab.EndpointConfig, mspID string, opts ...coptions.Opt) *LocalService {\n\tlogger.Debug(\"Creating new local discovery service\")\n\n\ts := &LocalService{mspID: mspID}\n\ts.service = newService(config, s.queryPeers, opts...)\n\treturn s\n}", "func (mr *MockEarlyConnectionMockRecorder) LocalAddr() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"LocalAddr\", reflect.TypeOf((*MockEarlyConnection)(nil).LocalAddr))\n}", "func (m *Module) ProviderForLocalConfig(pc addrs.LocalProviderConfig) addrs.Provider {\n\treturn m.ImpliedProviderForUnqualifiedType(pc.LocalName)\n}", "func TestEndpoints_LocalAlreadyRunning(t *testing.T) {\n\tendpoints1, config1, cleanup1 := newEndpoints(t)\n\tdefer cleanup1()\n\n\trequire.NoError(t, endpoints1.Up(config1))\n\n\tendpoints2, config2, cleanup2 := newEndpoints(t)\n\tconfig2.Dir = config1.Dir\n\tconfig2.UnixSocket = config1.UnixSocket\n\tdefer cleanup2()\n\n\terr := endpoints2.Up(config2)\n\tassert.EqualError(t, err, \"local endpoint: LXD is already running\")\n}", "func NonLocalReplicasFallback() func(policy *tokenAwareHostPolicy) {\n\treturn func(t *tokenAwareHostPolicy) {\n\t\tt.nonLocalReplicasFallback = true\n\t}\n}", "func (i *localInitializer) Initialize(plugin admission.Interface) {\n\tif wants, ok := plugin.(WantsDefaultNodeSelector); ok {\n\t\twants.SetDefaultNodeSelector(i.defaultNodeSelector)\n\t}\n}", "func gatherDiscovery(dataType string, info Info) bool {\n\tif info.ServiceDiscovery == nil {\n\t\tinfo.Status.Warning(\"The Submariner service discovery components are not installed\")\n\t\treturn true\n\t}\n\n\tswitch dataType {\n\tcase Logs:\n\t\tgatherServiceDiscoveryPodLogs(&info)\n\t\tgatherCoreDNSPodLogs(&info)\n\tcase Resources:\n\t\tgatherServiceExports(&info, corev1.NamespaceAll)\n\t\tgatherServiceImports(&info, corev1.NamespaceAll)\n\t\tgatherEndpointSlices(&info, corev1.NamespaceAll)\n\t\tgatherConfigMapLighthouseDNS(&info, info.ServiceDiscovery.Namespace)\n\t\tgatherConfigMapCoreDNS(&info)\n\t\tgatherLabeledServices(&info, internalSvcLabel)\n\tdefault:\n\t\treturn false\n\t}\n\n\treturn true\n}", "func startDiscovery() (err error) {\n\tlogger := log.New()\n\n\tif debug {\n\t\tlogger.Level = log.DebugLevel\n\t}\n\tgolifx.SetLogger(logger)\n\n\tif err := initClient(); err != nil {\n\t\ttick := time.Tick(2 * time.Second)\n\t\tdone := make(chan bool)\n\t\tselect {\n\t\tcase <-done:\n\t\tcase <-tick:\n\t\t\terr = initClient()\n\t\t\tif err == nil {\n\t\t\t\tdone <- true\n\t\t\t}\n\t\t}\n\t}\n\n\tclient.SetDiscoveryInterval(30 * time.Second)\n\n\tif timeout > 0 {\n\t\tclient.SetTimeout(time.Duration(timeout))\n\t}\n\n\tlog.Info(`Initiated LIFX client`)\n\n\treturn nil\n}", "func (me TxsdRegistryHandleSimpleContentExtensionRegistry) IsLocal() bool {\n\treturn me.String() == \"local\"\n}", "func (s *Drive) Local() bool { return s.config.OAuth.ClientID == \"\" }", "func discoverer() {\n\t// use \"peerdiscovery\" package to actively discover\n\t// new peers on the network\n\t// every time there's a new peer, \"store\" it in \"peers\"\n\t// and \"add\" the user on the UI (i.e use ui.AddUser)\n\t// if there's an error, log.Fatal ;)\n}", "func TestPeopleTracking(t *testing.T) {\n\tsomeone := trackSomeone()\n\tassert.NotNil(t, someone.location)\n}", "func unmanagedProviderFactory(provider addrs.Provider, reattach *plugin.ReattachConfig) providers.Factory {\n\treturn func() (providers.Interface, error) {\n\t\tconfig := &plugin.ClientConfig{\n\t\t\tHandshakeConfig: tfplugin.Handshake,\n\t\t\tLogger: logging.NewProviderLogger(\"unmanaged.\"),\n\t\t\tAllowedProtocols: []plugin.Protocol{plugin.ProtocolGRPC},\n\t\t\tManaged: false,\n\t\t\tReattach: reattach,\n\t\t\tSyncStdout: logging.PluginOutputMonitor(fmt.Sprintf(\"%s:stdout\", provider)),\n\t\t\tSyncStderr: logging.PluginOutputMonitor(fmt.Sprintf(\"%s:stderr\", provider)),\n\t\t}\n\n\t\tif reattach.ProtocolVersion == 0 {\n\t\t\t// As of the 0.15 release, sdk.v2 doesn't include the protocol\n\t\t\t// version in the ReattachConfig (only recently added to\n\t\t\t// go-plugin), so client.NegotiatedVersion() always returns 0. We\n\t\t\t// assume that an unmanaged provider reporting protocol version 0 is\n\t\t\t// actually using proto v5 for backwards compatibility.\n\t\t\tif defaultPlugins, ok := tfplugin.VersionedPlugins[5]; ok {\n\t\t\t\tconfig.Plugins = defaultPlugins\n\t\t\t} else {\n\t\t\t\treturn nil, errors.New(\"no supported plugins for protocol 0\")\n\t\t\t}\n\t\t} else if plugins, ok := tfplugin.VersionedPlugins[reattach.ProtocolVersion]; !ok {\n\t\t\treturn nil, fmt.Errorf(\"no supported plugins for protocol %d\", reattach.ProtocolVersion)\n\t\t} else {\n\t\t\tconfig.Plugins = plugins\n\t\t}\n\n\t\tclient := plugin.NewClient(config)\n\t\trpcClient, err := client.Client()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\traw, err := rpcClient.Dispense(tfplugin.ProviderPluginName)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// store the client so that the plugin can kill the child process\n\t\tprotoVer := client.NegotiatedVersion()\n\t\tswitch protoVer {\n\t\tcase 0, 5:\n\t\t\t// As of the 0.15 release, sdk.v2 doesn't include the protocol\n\t\t\t// version in the ReattachConfig (only recently added to\n\t\t\t// go-plugin), so client.NegotiatedVersion() always returns 0. We\n\t\t\t// assume that an unmanaged provider reporting protocol version 0 is\n\t\t\t// actually using proto v5 for backwards compatibility.\n\t\t\tp := raw.(*tfplugin.GRPCProvider)\n\t\t\tp.PluginClient = client\n\t\t\treturn p, nil\n\t\tcase 6:\n\t\t\tp := raw.(*tfplugin6.GRPCProvider)\n\t\t\tp.PluginClient = client\n\t\t\treturn p, nil\n\t\tdefault:\n\t\t\treturn nil, fmt.Errorf(\"unsupported protocol version %d\", protoVer)\n\t\t}\n\t}\n}", "func TestEndpoints_LocalUnknownUnixGroup(t *testing.T) {\n\tendpoints, config, cleanup := newEndpoints(t)\n\tdefer cleanup()\n\n\tconfig.LocalUnixSocketGroup = \"xquibaz\"\n\terr := endpoints.Up(config)\n\n\tassert.EqualError(\n\t\tt, err, \"local endpoint: cannot get group ID of 'xquibaz': group: unknown group xquibaz\")\n}", "func (m *MockInformation) LocalLocation() *universe.View {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"LocalLocation\")\n\tret0, _ := ret[0].(*universe.View)\n\treturn ret0\n}", "func NewMockDiscoveryProvider(err error, peers []fab.Peer) (*MockStaticDiscoveryProvider, error) {\n\treturn &MockStaticDiscoveryProvider{Error: err, Peers: peers}, nil\n}", "func TestGatherOnSetLocalDescription(t *testing.T) {\n\tlim := test.TimeOut(time.Second * 30)\n\tdefer lim.Stop()\n\n\treport := test.CheckRoutines(t)\n\tdefer report()\n\n\tpcOfferGathered := make(chan SessionDescription)\n\tpcAnswerGathered := make(chan SessionDescription)\n\n\ts := SettingEngine{}\n\tapi := NewAPI(WithSettingEngine(s))\n\n\tpcOffer, err := api.NewPeerConnection(Configuration{})\n\tif err != nil {\n\t\tt.Error(err.Error())\n\t}\n\n\t// We need to create a data channel in order to trigger ICE\n\tif _, err = pcOffer.CreateDataChannel(\"initial_data_channel\", nil); err != nil {\n\t\tt.Error(err.Error())\n\t}\n\n\tpcOffer.OnICECandidate(func(i *ICECandidate) {\n\t\tif i == nil {\n\t\t\tclose(pcOfferGathered)\n\t\t}\n\t})\n\n\toffer, err := pcOffer.CreateOffer(nil)\n\tif err != nil {\n\t\tt.Error(err.Error())\n\t} else if err = pcOffer.SetLocalDescription(offer); err != nil {\n\t\tt.Error(err.Error())\n\t}\n\n\t<-pcOfferGathered\n\n\tpcAnswer, err := api.NewPeerConnection(Configuration{})\n\tif err != nil {\n\t\tt.Error(err.Error())\n\t}\n\n\tpcAnswer.OnICECandidate(func(i *ICECandidate) {\n\t\tif i == nil {\n\t\t\tclose(pcAnswerGathered)\n\t\t}\n\t})\n\n\tif err = pcAnswer.SetRemoteDescription(offer); err != nil {\n\t\tt.Error(err.Error())\n\t}\n\n\tselect {\n\tcase <-pcAnswerGathered:\n\t\tt.Fatal(\"pcAnswer started gathering with no SetLocalDescription\")\n\t// Gathering is async, not sure of a better way to catch this currently\n\tcase <-time.After(3 * time.Second):\n\t}\n\n\tanswer, err := pcAnswer.CreateAnswer(nil)\n\tif err != nil {\n\t\tt.Error(err.Error())\n\t} else if err = pcAnswer.SetLocalDescription(answer); err != nil {\n\t\tt.Error(err.Error())\n\t}\n\t<-pcAnswerGathered\n\tclosePairNow(t, pcOffer, pcAnswer)\n}", "func (rs *EpNodeAccelRisers) discoverLocalPhase2() error {\n\tvar savedError error\n\tfor i, r := range rs.OIDs {\n\t\tr.discoverLocalPhase2()\n\t\tif r.LastStatus == RedfishSubtypeNoSupport {\n\t\t\terrlog.Printf(\"Key %s: RF NodeAccelRiser type not supported: %s\",\n\t\t\t\ti, r.RedfishSubtype)\n\t\t} else if r.LastStatus != DiscoverOK {\n\t\t\terr := fmt.Errorf(\"Key %s: %s\", i, r.LastStatus)\n\t\t\terrlog.Printf(\"NodeAccelRisers discoverLocalPhase2: saw error: %s\", err)\n\t\t\tsavedError = err\n\t\t}\n\t}\n\treturn savedError\n}", "func (mr *MockClientMockRecorder) InfraProvider() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"InfraProvider\", reflect.TypeOf((*MockClient)(nil).InfraProvider))\n}", "func (mr *MockPacketHandlerMockRecorder) LocalAddr() *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"LocalAddr\", reflect.TypeOf((*MockPacketHandler)(nil).LocalAddr))\n}", "func (ts *Tester) Provider() string {\n\treturn \"eks\"\n}", "func TestExternalNameService(t *testing.T) {\n\trh, c, done := setup(t, enableExternalNameService(t))\n\tdefer done()\n\n\ts1 := fixture.NewService(\"kuard\").\n\t\tWithSpec(v1.ServiceSpec{\n\t\t\tPorts: []v1.ServicePort{{\n\t\t\t\tPort: 80,\n\t\t\t\tTargetPort: intstr.FromInt(8080),\n\t\t\t}},\n\t\t\tExternalName: \"foo.io\",\n\t\t\tType: v1.ServiceTypeExternalName,\n\t\t})\n\n\ti1 := &networking_v1.Ingress{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: \"kuard\",\n\t\t\tNamespace: s1.Namespace,\n\t\t},\n\t\tSpec: networking_v1.IngressSpec{\n\t\t\tDefaultBackend: featuretests.IngressBackend(s1),\n\t\t},\n\t}\n\trh.OnAdd(s1)\n\trh.OnAdd(i1)\n\n\tc.Request(routeType).Equals(&envoy_discovery_v3.DiscoveryResponse{\n\t\tResources: resources(t,\n\t\t\tenvoy_v3.RouteConfiguration(\"ingress_http\",\n\t\t\t\tenvoy_v3.VirtualHost(\"*\",\n\t\t\t\t\t&envoy_route_v3.Route{\n\t\t\t\t\t\tMatch: routePrefix(\"/\"),\n\t\t\t\t\t\tAction: routeCluster(\"default/kuard/80/da39a3ee5e\"),\n\t\t\t\t\t},\n\t\t\t\t),\n\t\t\t),\n\t\t),\n\t\tTypeUrl: routeType,\n\t})\n\n\tc.Request(clusterType).Equals(&envoy_discovery_v3.DiscoveryResponse{\n\t\tResources: resources(t,\n\t\t\texternalNameCluster(\"default/kuard/80/da39a3ee5e\", \"default/kuard\", \"default_kuard_80\", \"foo.io\", 80),\n\t\t),\n\t\tTypeUrl: clusterType,\n\t})\n\n\trh.OnDelete(i1)\n\n\trh.OnAdd(fixture.NewProxy(\"kuard\").\n\t\tWithFQDN(\"kuard.projectcontour.io\").\n\t\tWithSpec(contour_api_v1.HTTPProxySpec{\n\t\t\tRoutes: []contour_api_v1.Route{{\n\t\t\t\tServices: []contour_api_v1.Service{{\n\t\t\t\t\tName: s1.Name,\n\t\t\t\t\tPort: 80,\n\t\t\t\t}},\n\t\t\t}},\n\t\t}),\n\t)\n\n\tc.Request(routeType).Equals(&envoy_discovery_v3.DiscoveryResponse{\n\t\tResources: resources(t,\n\t\t\tenvoy_v3.RouteConfiguration(\"ingress_http\",\n\t\t\t\tenvoy_v3.VirtualHost(\"kuard.projectcontour.io\",\n\t\t\t\t\t&envoy_route_v3.Route{\n\t\t\t\t\t\tMatch: routePrefix(\"/\"),\n\t\t\t\t\t\tAction: routeCluster(\"default/kuard/80/a28d1ec01b\"),\n\t\t\t\t\t},\n\t\t\t\t),\n\t\t\t),\n\t\t),\n\t\tTypeUrl: routeType,\n\t})\n\n\tc.Request(clusterType).Equals(&envoy_discovery_v3.DiscoveryResponse{\n\t\tResources: resources(t,\n\t\t\texternalNameCluster(\"default/kuard/80/a28d1ec01b\", \"default/kuard\", \"default_kuard_80\", \"foo.io\", 80),\n\t\t),\n\t\tTypeUrl: clusterType,\n\t})\n\n\t// After we set the Host header, the cluster should remain\n\t// the same, but the Route should do update the Host header.\n\trh.OnDelete(fixture.NewProxy(\"kuard\").WithSpec(contour_api_v1.HTTPProxySpec{}))\n\trh.OnAdd(fixture.NewProxy(\"kuard\").\n\t\tWithFQDN(\"kuard.projectcontour.io\").\n\t\tWithSpec(contour_api_v1.HTTPProxySpec{\n\t\t\tRoutes: []contour_api_v1.Route{{\n\t\t\t\tServices: []contour_api_v1.Service{{\n\t\t\t\t\tName: s1.Name,\n\t\t\t\t\tPort: 80,\n\t\t\t\t}},\n\t\t\t\tRequestHeadersPolicy: &contour_api_v1.HeadersPolicy{\n\t\t\t\t\tSet: []contour_api_v1.HeaderValue{{\n\t\t\t\t\t\tName: \"Host\",\n\t\t\t\t\t\tValue: \"external.address\",\n\t\t\t\t\t}},\n\t\t\t\t},\n\t\t\t}},\n\t\t}),\n\t)\n\n\tc.Request(routeType).Equals(&envoy_discovery_v3.DiscoveryResponse{\n\t\tTypeUrl: routeType,\n\t\tResources: resources(t,\n\t\t\tenvoy_v3.RouteConfiguration(\"ingress_http\",\n\t\t\t\tenvoy_v3.VirtualHost(\"kuard.projectcontour.io\",\n\t\t\t\t\t&envoy_route_v3.Route{\n\t\t\t\t\t\tMatch: routePrefix(\"/\"),\n\t\t\t\t\t\tAction: routeHostRewrite(\"default/kuard/80/95e871afaf\", \"external.address\"),\n\t\t\t\t\t},\n\t\t\t\t),\n\t\t\t),\n\t\t),\n\t})\n\n\tc.Request(clusterType).Equals(&envoy_discovery_v3.DiscoveryResponse{\n\t\tTypeUrl: clusterType,\n\t\tResources: resources(t,\n\t\t\texternalNameCluster(\"default/kuard/80/95e871afaf\", \"default/kuard\", \"default_kuard_80\", \"foo.io\", 80),\n\t\t),\n\t})\n\n\t// Now try the same configuration, but enable HTTP/2. We\n\t// should still find that the same configuration applies, but\n\t// TLS is enabled and the SNI server name is overwritten from\n\t// the Host header.\n\trh.OnDelete(fixture.NewProxy(\"kuard\").WithSpec(contour_api_v1.HTTPProxySpec{}))\n\trh.OnAdd(fixture.NewProxy(\"kuard\").\n\t\tWithFQDN(\"kuard.projectcontour.io\").\n\t\tWithSpec(contour_api_v1.HTTPProxySpec{\n\t\t\tRoutes: []contour_api_v1.Route{{\n\t\t\t\tServices: []contour_api_v1.Service{{\n\t\t\t\t\tProtocol: ref.To(\"h2\"),\n\t\t\t\t\tName: s1.Name,\n\t\t\t\t\tPort: 80,\n\t\t\t\t}},\n\t\t\t\tRequestHeadersPolicy: &contour_api_v1.HeadersPolicy{\n\t\t\t\t\tSet: []contour_api_v1.HeaderValue{{\n\t\t\t\t\t\tName: \"Host\",\n\t\t\t\t\t\tValue: \"external.address\",\n\t\t\t\t\t}},\n\t\t\t\t},\n\t\t\t}},\n\t\t}),\n\t)\n\n\tc.Request(routeType).Equals(&envoy_discovery_v3.DiscoveryResponse{\n\t\tTypeUrl: routeType,\n\t\tResources: resources(t,\n\t\t\tenvoy_v3.RouteConfiguration(\"ingress_http\",\n\t\t\t\tenvoy_v3.VirtualHost(\"kuard.projectcontour.io\",\n\t\t\t\t\t&envoy_route_v3.Route{\n\t\t\t\t\t\tMatch: routePrefix(\"/\"),\n\t\t\t\t\t\tAction: routeHostRewrite(\"default/kuard/80/cdbf075ad8\", \"external.address\"),\n\t\t\t\t\t},\n\t\t\t\t),\n\t\t\t),\n\t\t),\n\t})\n\n\tc.Request(clusterType).Equals(&envoy_discovery_v3.DiscoveryResponse{\n\t\tTypeUrl: clusterType,\n\t\tResources: resources(t,\n\t\t\tDefaultCluster(\n\t\t\t\texternalNameCluster(\"default/kuard/80/cdbf075ad8\", \"default/kuard\", \"default_kuard_80\", \"foo.io\", 80),\n\t\t\t\t&envoy_cluster_v3.Cluster{\n\t\t\t\t\tTypedExtensionProtocolOptions: map[string]*anypb.Any{\n\t\t\t\t\t\t\"envoy.extensions.upstreams.http.v3.HttpProtocolOptions\": protobuf.MustMarshalAny(\n\t\t\t\t\t\t\t&envoy_extensions_upstream_http_v3.HttpProtocolOptions{\n\t\t\t\t\t\t\t\tUpstreamProtocolOptions: &envoy_extensions_upstream_http_v3.HttpProtocolOptions_ExplicitHttpConfig_{\n\t\t\t\t\t\t\t\t\tExplicitHttpConfig: &envoy_extensions_upstream_http_v3.HttpProtocolOptions_ExplicitHttpConfig{\n\t\t\t\t\t\t\t\t\t\tProtocolConfig: &envoy_extensions_upstream_http_v3.HttpProtocolOptions_ExplicitHttpConfig_Http2ProtocolOptions{},\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t&envoy_cluster_v3.Cluster{\n\t\t\t\t\tTransportSocket: envoy_v3.UpstreamTLSTransportSocket(\n\t\t\t\t\t\tenvoy_v3.UpstreamTLSContext(nil, \"external.address\", nil, \"h2\"),\n\t\t\t\t\t),\n\t\t\t\t},\n\t\t\t),\n\t\t),\n\t})\n\n\t// Now try the same configuration, but enable TLS (which\n\t// means HTTP/1.1 over TLS) rather than HTTP/2. We should get\n\t// TLS enabled with the overridden SNI name. but no HTTP/2\n\t// protocol config.\n\trh.OnDelete(fixture.NewProxy(\"kuard\").WithSpec(contour_api_v1.HTTPProxySpec{}))\n\trh.OnAdd(fixture.NewProxy(\"kuard\").\n\t\tWithFQDN(\"kuard.projectcontour.io\").\n\t\tWithSpec(contour_api_v1.HTTPProxySpec{\n\t\t\tRoutes: []contour_api_v1.Route{{\n\t\t\t\tServices: []contour_api_v1.Service{{\n\t\t\t\t\tProtocol: ref.To(\"tls\"),\n\t\t\t\t\tName: s1.Name,\n\t\t\t\t\tPort: 80,\n\t\t\t\t}},\n\t\t\t\tRequestHeadersPolicy: &contour_api_v1.HeadersPolicy{\n\t\t\t\t\tSet: []contour_api_v1.HeaderValue{{\n\t\t\t\t\t\tName: \"Host\",\n\t\t\t\t\t\tValue: \"external.address\",\n\t\t\t\t\t}},\n\t\t\t\t},\n\t\t\t}},\n\t\t}),\n\t)\n\n\tc.Request(routeType).Equals(&envoy_discovery_v3.DiscoveryResponse{\n\t\tTypeUrl: routeType,\n\t\tResources: resources(t,\n\t\t\tenvoy_v3.RouteConfiguration(\"ingress_http\",\n\t\t\t\tenvoy_v3.VirtualHost(\"kuard.projectcontour.io\",\n\t\t\t\t\t&envoy_route_v3.Route{\n\t\t\t\t\t\tMatch: routePrefix(\"/\"),\n\t\t\t\t\t\tAction: routeHostRewrite(\"default/kuard/80/f9439c1de8\", \"external.address\"),\n\t\t\t\t\t},\n\t\t\t\t),\n\t\t\t),\n\t\t),\n\t})\n\n\tc.Request(clusterType).Equals(&envoy_discovery_v3.DiscoveryResponse{\n\t\tTypeUrl: clusterType,\n\t\tResources: resources(t,\n\t\t\tDefaultCluster(\n\t\t\t\texternalNameCluster(\"default/kuard/80/f9439c1de8\", \"default/kuard\", \"default_kuard_80\", \"foo.io\", 80),\n\t\t\t\t&envoy_cluster_v3.Cluster{\n\t\t\t\t\tTransportSocket: envoy_v3.UpstreamTLSTransportSocket(\n\t\t\t\t\t\tenvoy_v3.UpstreamTLSContext(nil, \"external.address\", nil),\n\t\t\t\t\t),\n\t\t\t\t},\n\t\t\t),\n\t\t),\n\t})\n\n\tsec1 := &v1.Secret{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: \"secret\",\n\t\t\tNamespace: \"default\",\n\t\t},\n\t\tType: \"kubernetes.io/tls\",\n\t\tData: featuretests.Secretdata(featuretests.CERTIFICATE, featuretests.RSA_PRIVATE_KEY),\n\t}\n\n\t// Create TCPProxy with upstream protocol 'tls' to an externalName type service\n\t// and verify that the SNI on the upstream request matches the externalName value.\n\trh.OnDelete(fixture.NewProxy(\"kuard\").WithSpec(contour_api_v1.HTTPProxySpec{}))\n\trh.OnAdd(sec1)\n\trh.OnAdd(fixture.NewProxy(\"kuard\").\n\t\tWithFQDN(\"kuard.projectcontour.io\").\n\t\tWithCertificate(sec1.Name).\n\t\tWithSpec(contour_api_v1.HTTPProxySpec{\n\t\t\tTCPProxy: &contour_api_v1.TCPProxy{\n\t\t\t\tServices: []contour_api_v1.Service{{\n\t\t\t\t\tProtocol: ref.To(\"tls\"),\n\t\t\t\t\tName: s1.Name,\n\t\t\t\t\tPort: 80,\n\t\t\t\t}},\n\t\t\t},\n\t\t}),\n\t)\n\n\tc.Request(clusterType).Equals(&envoy_discovery_v3.DiscoveryResponse{\n\t\tTypeUrl: clusterType,\n\t\tResources: resources(t,\n\t\t\tDefaultCluster(\n\t\t\t\texternalNameCluster(\"default/kuard/80/7d449598f5\", \"default/kuard\", \"default_kuard_80\", \"foo.io\", 80),\n\t\t\t\t&envoy_cluster_v3.Cluster{\n\t\t\t\t\tTransportSocket: envoy_v3.UpstreamTLSTransportSocket(\n\t\t\t\t\t\tenvoy_v3.UpstreamTLSContext(nil, \"foo.io\", nil),\n\t\t\t\t\t),\n\t\t\t\t},\n\t\t\t),\n\t\t),\n\t})\n}", "func become_discoverable(args []string) {\n\tsongs := get_local_song_info(args[2])\n\tmsg_content := \"\"\n\tfor _, s := range songs {\n\t\tmsg_content += s\n\t}\n\tmsg := prepare_msg(INIT, 0, []byte(msg_content))\n\ttracker := send(*msg, TRACKER_IP+args[1])\n\tdefer tracker.Close()\n}", "func (o *SmscSession) GetLocalAddrOk() (*string, bool) {\n\tif o == nil || o.LocalAddr == nil {\n\t\treturn nil, false\n\t}\n\treturn o.LocalAddr, true\n}", "func (r *EpNodeAccelRiser) discoverLocalPhase2() {\n\t// Should never happen\n\tif r.epRF == nil {\n\t\terrlog.Printf(\"Error: RedfishEP == nil for odataID: %s\\n\",\n\t\t\tr.OdataID)\n\t\tr.LastStatus = EndpointInvalid\n\t\treturn\n\t}\n\tif r.LastStatus != VerifyingData {\n\t\treturn\n\t}\n\n\tr.Ordinal = r.epRF.getNodeAccelRiserOrdinal(r)\n\tr.Type = r.epRF.getNodeAccelRiserHMSType(r)\n\tr.ID = r.epRF.getNodeAccelRiserHMSID(r, r.Type, r.Ordinal)\n\tif r.NodeAccelRiserRF.Status.State != \"Absent\" {\n\t\tr.Status = \"Populated\"\n\t\tr.State = base.StatePopulated.String()\n\t\tr.Flag = base.FlagOK.String()\n\t\tgeneratedFRUID, err := GetNodeAccelRiserFRUID(r)\n\t\tif err != nil {\n\t\t\terrlog.Printf(\"FRUID Error: %s\\n\", err.Error())\n\t\t\terrlog.Printf(\"Using untrackable FRUID: %s\\n\", generatedFRUID)\n\t\t}\n\t\tr.FRUID = generatedFRUID\n\t} else {\n\t\tr.Status = \"Empty\"\n\t\tr.State = base.StateEmpty.String()\n\t\t//the state of the component is known (empty), it is not locked, does not have an alert or warning, so therefore Flag defaults to OK.\n\t\tr.Flag = base.FlagOK.String()\n\t}\n\t// Check if we have something valid to insert into the data store\n\tif (base.GetHMSType(r.ID) == base.NodeAccelRiser) && (r.Type == base.NodeAccelRiser.String()) {\n\t\terrlog.Printf(\"NodeAccelRiser discoverLocalPhase2: VALID xname ID ('%s') and Type ('%s') for: %s\\n\",\n\t\t\tr.ID, r.Type, r.NodeAccelRiserURL)\n\t} else {\n\t\terrlog.Printf(\"Error: Bad xname ID ('%s') or Type ('%s') for: %s\\n\",\n\t\t\tr.ID, r.Type, r.NodeAccelRiserURL)\n\t\tr.LastStatus = VerificationFailed\n\t\treturn\n\t}\n\tif rfVerbose > 0 {\n\t\tjout, _ := json.MarshalIndent(r, \"\", \" \")\n\t\terrlog.Printf(\"%s\\n\", jout)\n\t\terrlog.Printf(\"NodeAccelRiser ID: %s\\n\", r.ID)\n\t\terrlog.Printf(\"NodeAccelRiser FRUID: %s\\n\", r.FRUID)\n\t}\n\tr.LastStatus = DiscoverOK\n}", "func TestUnreachableMarks(t *testing.T) {\n\tseeds := []string {\"127.0.0.1:6000\",}\n\tmanager1 := CreatePeerManager(6000, 6001, nil, FullMode)\n\tmanager2 := CreatePeerManager(7000, 7001, seeds, FullMode)\n\tmanager3 := CreatePeerManager(8000, 8001, seeds, FullMode)\n\n\t// Change update period to lengthen the time between marking a peer unreachable \n\t// and the next status update\n\tmanager1.StatusUpdatePeriod=500*time.Millisecond\n\tmanager2.StatusUpdatePeriod=500*time.Millisecond\n\tmanager3.StatusUpdatePeriod=500*time.Millisecond\n\n\tmarkPeer := func(t *testing.T) {\n\t\tmanager1.MarkPeerUnreachable(\"127.0.0.1:8001\")\n\t\tmanager1.MarkPeerUnreachable(\"127.0.0.1:8001\")\n\t\tmanager1.MarkPeerUnreachable(\"127.0.0.1:8001\")\n\t\tavailable := GetPeerManagerAvailablePeers(manager1)\n\t\texpected := []string {\"127.0.0.1:6001\", \"127.0.0.1:7001\"}\n\t\tif !MapOnlyContains(available, expected) {\n\t\t\tt.Errorf(\"Peer 127.0.0.1:8001 wasn't marked unreachable %v\\n\", available)\n\t\t}\n\t}\n\n\t// After some time has passed all the peers should be available again\n\tallPeers := []string {\"127.0.0.1:6001\", \"127.0.0.1:7001\", \"127.0.0.1:8001\"}\n\tPeerManagerPropagationHelper(t, manager1, manager2, manager3,\n\t\tallPeers, allPeers, allPeers, markPeer, 3200*time.Millisecond, 8*time.Second)\n}", "func IsClusterLocal(domain string) bool {\n\treturn strings.HasSuffix(domain, pkgnet.GetClusterDomainName())\n}", "func loadProvider(providerConfig *provider.Config) (provider.Provider, error) {\n\tp, ok := providerCollection[providerConfig.Label]\n\tif !ok {\n\t\treturn nil, errors.NotFoundf(\"provider called `%s`\", providerConfig.Label)\n\t}\n\n\tvar err error\n\tp, err = p.Initialize(providerConfig)\n\tif err != nil {\n\t\tannotation := fmt.Sprintf(\"loading provider %s\", providerConfig.Label)\n\t\treturn nil, errors.Annotate(err, annotation)\n\t}\n\n\treturn p, nil\n}", "func (c *ChannelConn) LocalAddr() net.Addr {\n\treturn nil\n}", "func TestEntryInitiallyUnknown(t *testing.T) {\n\tc := DefaultNUDConfigurations()\n\te, nudDisp, linkRes, clock := entryTestSetup(c)\n\n\te.mu.Lock()\n\tif e.mu.neigh.State != Unknown {\n\t\tt.Errorf(\"got e.mu.neigh.State = %q, want = %q\", e.mu.neigh.State, Unknown)\n\t}\n\te.mu.Unlock()\n\n\tclock.Advance(c.RetransmitTimer)\n\n\t// No probes should have been sent.\n\tlinkRes.mu.Lock()\n\tdiff := cmp.Diff([]entryTestProbeInfo(nil), linkRes.mu.probes)\n\tlinkRes.mu.Unlock()\n\tif diff != \"\" {\n\t\tt.Fatalf(\"link address resolver probes mismatch (-want, +got):\\n%s\", diff)\n\t}\n\n\t// No events should have been dispatched.\n\tnudDisp.mu.Lock()\n\tif diff := cmp.Diff([]testEntryEventInfo(nil), nudDisp.mu.events); diff != \"\" {\n\t\tt.Errorf(\"nud dispatcher events mismatch (-want, +got):\\n%s\", diff)\n\t}\n\tnudDisp.mu.Unlock()\n}", "func genLocalAddr() string {\n\treturn fmt.Sprintf(\"localhost:%d\", test.GetFreePort())\n}", "func (m *Monitor) AddLocalCluster(versionObj *unstructured.Unstructured) bool {\n\tvar clusterVersionGvr = schema.GroupVersionResource{\n\t\tGroup: \"config.openshift.io\",\n\t\tVersion: \"v1\",\n\t\tResource: \"clusterversions\",\n\t}\n\tvar dynamicClient dynamic.Interface\n\tvar err error\n\tglog.V(2).Info(\"Adding Local Cluster ID.\")\n\tif versionObj == nil {\n\t\tdynamicClient = config.GetDynamicClient()\n\t\tversionObj, err = dynamicClient.Resource(clusterVersionGvr).Get(context.TODO(), \"version\", metav1.GetOptions{})\n\t}\n\tif err != nil {\n\t\tglog.V(2).Infof(\"Failed to get clusterversions : %v\", err)\n\t\treturn false\n\t}\n\tclusterID, _, err := unstructured.NestedString(versionObj.Object, \"spec\", \"clusterID\")\n\tif err != nil {\n\t\tglog.V(2).Infof(\"Failed to get OCP clusterID from version: %v\", err)\n\t\treturn false\n\t}\n\t// If the cluster ID is not empty add to list and return true\n\tif clusterID != \"\" {\n\t\tlock.Lock()\n\t\tm.ManagedClusterInfo = append(m.ManagedClusterInfo, types.ManagedClusterInfo{\n\t\t\tClusterID: clusterID,\n\t\t\tNamespace: localClusterName,\n\t\t})\n\t\tlock.Unlock()\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (a AppContext) DiscoveryToken() string {\n\treturn DiscoveryToken\n}", "func fakeDiscovery() discovery.DiscoveryInterface {\n\tfake := &fakediscovery.FakeDiscovery{Fake: &coretesting.Fake{}}\n\tapps := []metav1.APIResource{\n\t\t{Name: \"deployments\", Namespaced: true, Kind: \"Deployment\"},\n\t\t{Name: \"controllerrevisions\", Namespaced: true, Kind: \"ControllerRevision\"},\n\t\t{Name: \"daemonsets\", Namespaced: true, Kind: \"DaemonSet\"},\n\t\t{Name: \"replicasets\", Namespaced: true, Kind: \"ReplicaSet\"},\n\t\t{Name: \"statefulsets\", Namespaced: true, Kind: \"StatefulSet\"},\n\t}\n\tfake.Resources = []*metav1.APIResourceList{\n\t\t{\n\t\t\tGroupVersion: corev1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"bindings\", Namespaced: true, Kind: \"Binding\"},\n\t\t\t\t{Name: \"componentstatuses\", Kind: \"ComponentStatus\"},\n\t\t\t\t{Name: \"configmaps\", Namespaced: true, Kind: \"ConfigMap\"},\n\t\t\t\t{Name: \"endpoints\", Namespaced: true, Kind: \"Endpoints\"},\n\t\t\t\t{Name: \"events\", Namespaced: true, Kind: \"Event\"},\n\t\t\t\t{Name: \"limitranges\", Namespaced: true, Kind: \"LimitRange\"},\n\t\t\t\t{Name: \"namespaces\", Kind: \"Namespace\"},\n\t\t\t\t{Name: \"nodes\", Kind: \"Node\"},\n\t\t\t\t{Name: \"persistentvolumeclaims\", Namespaced: true, Kind: \"PersistentVolumeClaim\"},\n\t\t\t\t{Name: \"persistentvolumes\", Kind: \"PersistentVolume\"},\n\t\t\t\t{Name: \"pods\", Namespaced: true, Kind: \"Pod\"},\n\t\t\t\t{Name: \"podtemplates\", Namespaced: true, Kind: \"PodTemplate\"},\n\t\t\t\t{Name: \"replicationcontrollers\", Namespaced: true, Kind: \"ReplicationController\"},\n\t\t\t\t{Name: \"resourcequotas\", Namespaced: true, Kind: \"ResourceQuota\"},\n\t\t\t\t{Name: \"secrets\", Namespaced: true, Kind: \"Secret\"},\n\t\t\t\t{Name: \"serviceaccounts\", Namespaced: true, Kind: \"ServiceAccount\"},\n\t\t\t\t{Name: \"services\", Namespaced: true, Kind: \"Service\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: rbacv1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"clusterroles\", Kind: \"ClusterRole\"},\n\t\t\t\t{Name: \"clusterrolebindings\", Kind: \"ClusterRoleBinding\"},\n\t\t\t\t{Name: \"clusterroles\", Kind: \"ClusterRole\"},\n\t\t\t\t{Name: \"rolebindings\", Namespaced: true, Kind: \"RoleBinding\"},\n\t\t\t\t{Name: \"roles\", Namespaced: true, Kind: \"Role\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: appsv1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: apps,\n\t\t},\n\t\t{\n\t\t\tGroupVersion: appsv1beta1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: apps,\n\t\t},\n\t\t{\n\t\t\tGroupVersion: appsv1beta2.SchemeGroupVersion.String(),\n\t\t\tAPIResources: apps,\n\t\t},\n\t\t{\n\t\t\tGroupVersion: apiextensionsv1beta1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"customresourcedefinitions\", Kind: \"CustomResourceDefinition\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: apiextensionsv1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"customresourcedefinitions\", Kind: \"CustomResourceDefinition\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: storagev1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"storageclasses\", Kind: \"StorageClass\"},\n\t\t\t\t{Name: \"volumeattachments\", Kind: \"VolumeAttachment\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: storagev1beta1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"storageclasses\", Kind: \"StorageClass\"},\n\t\t\t\t{Name: \"volumeattachments\", Kind: \"VolumeAttachment\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: extensionsv1beta1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"ingresses\", Namespaced: true, Kind: \"Ingress\"},\n\t\t\t\t{Name: \"networkpolicies\", Namespaced: true, Kind: \"NetworkPolicy\"},\n\t\t\t\t{Name: \"podsecuritypolicies\", Kind: \"PodSecurityPolicy\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: networkingv1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"networkpolicies\", Namespaced: true, Kind: \"NetworkPolicy\"},\n\t\t\t\t{Name: \"ingresses\", Namespaced: true, Kind: \"Ingress\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: authenticationv1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"tokenreviews\", Kind: \"TokenReview\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: autoscalingv1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"horizontalpodautoscalers\", Kind: \"HorizontalPodAutoscaler\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: autoscalingv2beta1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"horizontalpodautoscalers\", Kind: \"HorizontalPodAutoscaler\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: autoscalingv2beta2.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"horizontalpodautoscalers\", Kind: \"HorizontalPodAutoscaler\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: policyv1beta1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"poddisruptionbudgets\", Namespaced: true, Kind: \"PodDisruptionBudget\"},\n\t\t\t\t{Name: \"podsecuritypolicies\", Kind: \"PodSecurityPolicy\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: rbacsyncv1alpha.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"clusterrbacsyncconfigs\", Kind: \"ClusterRBACSyncConfig\"},\n\t\t\t\t{Name: \"rbacsyncconfigs\", Namespaced: true, Kind: \"RBACSyncConfig\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: batchv1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"jobs\", Namespaced: true, Kind: \"Job\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: batchv1b1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"cronjobs\", Namespaced: true, Kind: \"CronJob\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: arkv1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"backups\", Namespaced: true, Kind: \"Backup\"},\n\t\t\t\t{Name: \"backupstoragelocations\", Namespaced: true, Kind: \"BackupStorageLocation\"},\n\t\t\t\t{Name: \"configs\", Namespaced: true, Kind: \"Config\"},\n\t\t\t\t{Name: \"deletebackuprequests\", Namespaced: true, Kind: \"DeleteBackupRequest\"},\n\t\t\t\t{Name: \"downloadrequests\", Namespaced: true, Kind: \"DownloadRequest\"},\n\t\t\t\t{Name: \"podvolumebackups\", Namespaced: true, Kind: \"PodVolumeBackup\"},\n\t\t\t\t{Name: \"podvolumerestores\", Namespaced: true, Kind: \"PodVolumeRestore\"},\n\t\t\t\t{Name: \"resticrepositories\", Namespaced: true, Kind: \"ResticRepository\"},\n\t\t\t\t{Name: \"restores\", Namespaced: true, Kind: \"Restore\"},\n\t\t\t\t{Name: \"schedules\", Namespaced: true, Kind: \"Schedule\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: istio.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"sidecar\", Namespaced: true, Kind: \"Sidecar\"},\n\t\t\t\t{Name: \"virtualservice\", Namespaced: true, Kind: \"VirtualService\"},\n\t\t\t\t{Name: \"destinationrule\", Namespaced: true, Kind: \"DestinationRule\"},\n\t\t\t\t{Name: \"gateway\", Namespaced: true, Kind: \"Gateway\"},\n\t\t\t\t{Name: \"serviceentry\", Kind: \"ServiceEntry\"},\n\t\t\t\t{Name: \"envoyfilter\", Namespaced: true, Kind: \"EnvoyFilter\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: istiov1b1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"sidecar\", Namespaced: true, Kind: \"Sidecar\"},\n\t\t\t\t{Name: \"virtualservice\", Namespaced: true, Kind: \"VirtualService\"},\n\t\t\t\t{Name: \"destinationrule\", Namespaced: true, Kind: \"DestinationRule\"},\n\t\t\t\t{Name: \"gateway\", Namespaced: true, Kind: \"Gateway\"},\n\t\t\t\t{Name: \"serviceentry\", Kind: \"ServiceEntry\"},\n\t\t\t\t{Name: \"envoyfilter\", Namespaced: true, Kind: \"EnvoyFilter\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: istiosecurityv1beta1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"authorizationpolicy\", Namespaced: true, Kind: \"AuthorizationPolicy\"},\n\t\t\t\t{Name: \"peerauthentication\", Namespaced: true, Kind: \"PeerAuthentication\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: csr.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"certificatesigningrequests\", Kind: \"CertificateSigningRequest\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: csrv1b1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"certificatesigningrequests\", Kind: \"CertificateSigningRequest\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: admissionregistrationv1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"validatingwebhookconfigurations\", Kind: \"ValidatingWebhookConfiguration\"},\n\t\t\t\t{Name: \"mutatingwebhookconfigurations\", Kind: \"MutatingWebhookConfiguration\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: admissionregistrationv1b1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"validatingwebhookconfigurations\", Kind: \"ValidatingWebhookConfiguration\"},\n\t\t\t\t{Name: \"mutatingwebhookconfigurations\", Kind: \"MutatingWebhookConfiguration\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: schedulingv1beta1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"priorityclass\", Kind: \"PriorityClass\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: schedulingv1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"priorityclass\", Kind: \"PriorityClass\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: apiregistrationv1b1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"apiservice\", Kind: \"APIService\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: apiregistrationv1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"apiservice\", Kind: \"APIService\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: vpav1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"verticalpodautoscalers\", Kind: \"VerticalPodAutoscaler\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: vpav1beta2.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"verticalpodautoscalers\", Kind: \"VerticalPodAutoscaler\"},\n\t\t\t},\n\t\t},\n\t}\n\treturn fake\n}", "func Provider() tfbridge.ProviderInfo {\n\t// Instantiate the Terraform provider\n\tp := shimv2.NewProvider(xyz.Provider())\n\n\t// Create a Pulumi provider mapping\n\tprov := tfbridge.ProviderInfo{\n\t\tP: p,\n\t\tName: \"xyz\",\n\t\t// DisplayName is a way to be able to change the casing of the provider\n\t\t// name when being displayed on the Pulumi registry\n\t\tDisplayName: \"\",\n\t\t// The default publisher for all packages is Pulumi.\n\t\t// Change this to your personal name (or a company name) that you\n\t\t// would like to be shown in the Pulumi Registry if this package is published\n\t\t// there.\n\t\tPublisher: \"Pulumi\",\n\t\t// LogoURL is optional but useful to help identify your package in the Pulumi Registry\n\t\t// if this package is published there.\n\t\t//\n\t\t// You may host a logo on a domain you control or add an SVG logo for your package\n\t\t// in your repository and use the raw content URL for that file as your logo URL.\n\t\tLogoURL: \"\",\n\t\t// PluginDownloadURL is an optional URL used to download the Provider\n\t\t// for use in Pulumi programs\n\t\t// e.g https://github.com/org/pulumi-provider-name/releases/\n\t\tPluginDownloadURL: \"\",\n\t\tDescription: \"A Pulumi package for creating and managing xyz cloud resources.\",\n\t\t// category/cloud tag helps with categorizing the package in the Pulumi Registry.\n\t\t// For all available categories, see `Keywords` in\n\t\t// https://www.pulumi.com/docs/guides/pulumi-packages/schema/#package.\n\t\tKeywords: []string{\"pulumi\", \"xyz\", \"category/cloud\"},\n\t\tLicense: \"Apache-2.0\",\n\t\tHomepage: \"https://www.pulumi.com\",\n\t\tRepository: \"https://github.com/pulumi/pulumi-xyz\",\n\t\t// The GitHub Org for the provider - defaults to `terraform-providers`. Note that this\n\t\t// should match the TF provider module's require directive, not any replace directives.\n\t\tGitHubOrg: \"\",\n\t\tConfig: map[string]*tfbridge.SchemaInfo{\n\t\t\t// Add any required configuration here, or remove the example below if\n\t\t\t// no additional points are required.\n\t\t\t// \"region\": {\n\t\t\t// \tType: tfbridge.MakeType(\"region\", \"Region\"),\n\t\t\t// \tDefault: &tfbridge.DefaultInfo{\n\t\t\t// \t\tEnvVars: []string{\"AWS_REGION\", \"AWS_DEFAULT_REGION\"},\n\t\t\t// \t},\n\t\t\t// },\n\t\t},\n\t\tPreConfigureCallback: preConfigureCallback,\n\t\tResources: map[string]*tfbridge.ResourceInfo{\n\t\t\t// Map each resource in the Terraform provider to a Pulumi type. Two examples\n\t\t\t// are below - the single line form is the common case. The multi-line form is\n\t\t\t// needed only if you wish to override types or other default options.\n\t\t\t//\n\t\t\t// \"aws_iam_role\": {Tok: tfbridge.MakeResource(mainPkg, mainMod, \"IamRole\")}\n\t\t\t//\n\t\t\t// \"aws_acm_certificate\": {\n\t\t\t// \tTok: tfbridge.MakeResource(mainPkg, mainMod, \"Certificate\"),\n\t\t\t// \tFields: map[string]*tfbridge.SchemaInfo{\n\t\t\t// \t\t\"tags\": {Type: tfbridge.MakeType(mainPkg, \"Tags\")},\n\t\t\t// \t},\n\t\t\t// },\n\t\t},\n\t\tDataSources: map[string]*tfbridge.DataSourceInfo{\n\t\t\t// Map each resource in the Terraform provider to a Pulumi function. An example\n\t\t\t// is below.\n\t\t\t// \"aws_ami\": {Tok: tfbridge.MakeDataSource(mainPkg, mainMod, \"getAmi\")},\n\t\t},\n\t\tJavaScript: &tfbridge.JavaScriptInfo{\n\t\t\t// List any npm dependencies and their versions\n\t\t\tDependencies: map[string]string{\n\t\t\t\t\"@pulumi/pulumi\": \"^3.0.0\",\n\t\t\t},\n\t\t\tDevDependencies: map[string]string{\n\t\t\t\t\"@types/node\": \"^10.0.0\", // so we can access strongly typed node definitions.\n\t\t\t\t\"@types/mime\": \"^2.0.0\",\n\t\t\t},\n\t\t\t// See the documentation for tfbridge.OverlayInfo for how to lay out this\n\t\t\t// section, or refer to the AWS provider. Delete this section if there are\n\t\t\t// no overlay files.\n\t\t\t//Overlay: &tfbridge.OverlayInfo{},\n\t\t},\n\t\tPython: &tfbridge.PythonInfo{\n\t\t\t// List any Python dependencies and their version ranges\n\t\t\tRequires: map[string]string{\n\t\t\t\t\"pulumi\": \">=3.0.0,<4.0.0\",\n\t\t\t},\n\t\t},\n\t\tGolang: &tfbridge.GolangInfo{\n\t\t\tImportBasePath: filepath.Join(\n\t\t\t\tfmt.Sprintf(\"github.com/pulumi/pulumi-%[1]s/sdk/\", mainPkg),\n\t\t\t\ttfbridge.GetModuleMajorVersion(version.Version),\n\t\t\t\t\"go\",\n\t\t\t\tmainPkg,\n\t\t\t),\n\t\t\tGenerateResourceContainerTypes: true,\n\t\t},\n\t\tCSharp: &tfbridge.CSharpInfo{\n\t\t\tPackageReferences: map[string]string{\n\t\t\t\t\"Pulumi\": \"3.*\",\n\t\t\t},\n\t\t},\n\t}\n\n\t// These are new API's that you may opt to use to automatically compute resource tokens,\n\t// and apply auto aliasing for full backwards compatibility.\n\t// For more information, please reference: https://pkg.go.dev/github.com/pulumi/pulumi-terraform-bridge/v3/pkg/tfbridge#ProviderInfo.ComputeTokens\n\tprov.MustComputeTokens(tokens.SingleModule(\"xyz_\", mainMod,\n\t\ttokens.MakeStandard(mainPkg)))\n\tprov.MustApplyAutoAliasing()\n\tprov.SetAutonaming(255, \"-\")\n\n\treturn prov\n}", "func (m *Module) LocalNameForProvider(p addrs.Provider) string {\n\tif existing, exists := m.ProviderLocalNames[p]; exists {\n\t\treturn existing\n\t} else {\n\t\t// If there isn't a map entry, fall back to the default:\n\t\t// Type = LocalName\n\t\treturn p.Type\n\t}\n}", "func NewLocalDatabaseProvider(name string, type_ string) *LocalDatabaseProvider {\n\tthis := LocalDatabaseProvider{}\n\tthis.Name = name\n\tthis.Type = type_\n\tvar deviceLimitPerUser int32 = 100\n\tthis.DeviceLimitPerUser = &deviceLimitPerUser\n\tvar adminProvider bool = false\n\tthis.AdminProvider = &adminProvider\n\tvar inactivityTimeoutMinutes int32 = 0\n\tthis.InactivityTimeoutMinutes = &inactivityTimeoutMinutes\n\tvar networkInactivityTimeoutEnabled bool = false\n\tthis.NetworkInactivityTimeoutEnabled = &networkInactivityTimeoutEnabled\n\tvar blockLocalDnsRequests bool = false\n\tthis.BlockLocalDnsRequests = &blockLocalDnsRequests\n\tvar userLockoutThreshold int32 = 5\n\tthis.UserLockoutThreshold = &userLockoutThreshold\n\tvar userLockoutDurationMinutes int32 = 1\n\tthis.UserLockoutDurationMinutes = &userLockoutDurationMinutes\n\tvar minPasswordLength int32 = 0\n\tthis.MinPasswordLength = &minPasswordLength\n\treturn &this\n}", "func (sc *ShamClient) discover() error {\n\tsc.logger.Debugf(\"discovering endpoints for service %s\", sc.serviceName)\n\tresponse, err := sc.httpClient.Get(sc.serviceRegistry.URL + \"/sgulreg/services/\" + sc.serviceName)\n\tif err != nil {\n\t\tsc.logger.Errorf(\"Error making service discovery HTTP request: %s\", err)\n\t\tsc.fallbackDiscovery()\n\t\treturn ErrFailedDiscoveryRequest\n\t}\n\tsc.logger.Debugf(\"discovery response content-length: %s\", response.Header.Get(\"Content-length\"))\n\n\tbody, err := ioutil.ReadAll(response.Body)\n\tif err != nil {\n\t\tsc.logger.Errorf(\"Error reading service discovery HTTP response body: %s\", err)\n\t\tsc.fallbackDiscovery()\n\t\treturn ErrFailedDiscoveryResponseBody\n\t}\n\tdefer response.Body.Close()\n\n\tvar serviceInfo registry.ServiceInfoResponse\n\tjson.Unmarshal([]byte(body), &serviceInfo)\n\n\tif len(serviceInfo.Instances) > 0 {\n\t\tvar endpoints []string\n\t\tfor _, instance := range serviceInfo.Instances {\n\t\t\tsc.logger.Debugf(\"discovered service %s endpoint serviceID: %s\", sc.serviceName, instance.InstanceID)\n\t\t\tendpoint := fmt.Sprintf(\"%s://%s%s\", instance.Schema, instance.Host, sc.apiPath)\n\t\t\tendpoints = append(endpoints, endpoint)\n\t\t}\n\n\t\t// sc.localRegistry = endpoints\n\t\tsc.setLocalRegistry(endpoints)\n\t\tsc.logger.Infof(\"discovered service %s endpoints: %+v\", sc.serviceName, sc.localRegistry)\n\t}\n\n\tif len(sc.localRegistry) == 0 {\n\t\t// sc.localRegistry = sc.serviceRegistry.Fallback\n\t\tsc.setLocalRegistry(sc.serviceRegistry.Fallback)\n\t\tsc.logger.Infof(\"using Fallback registry for service %s: %+v\", sc.serviceName, sc.localRegistry)\n\t}\n\n\treturn nil\n}", "func (a *Adapter) makeProviderOrDie() provider.CustomMetricsProvider {\n\tconfig, err := a.ClientConfig()\n\tif err != nil {\n\t\tklog.Fatalf(\"unable to construct dynamic client: %v\", err)\n\t}\n\n\tclient, err := a.DynamicClient()\n\tif err != nil {\n\t\tklog.Fatalf(\"unable to construct dynamic client: %v\", err)\n\t}\n\n\tmapper, err := a.RESTMapper()\n\tif err != nil {\n\t\tklog.Fatalf(\"unable to construct discovery REST mapper: %v\", err)\n\t}\n\n\treturn customprovider.New(client, config, mapper)\n}", "func TestMinimal_NoneDNS(t *testing.T) {\n\tt.Setenv(\"KOPS_RUN_TOO_NEW_VERSION\", \"1\")\n\n\tnewIntegrationTest(\"minimal.example.com\", \"minimal-dns-none\").\n\t\twithAddons(\n\t\t\tawsEBSCSIAddon,\n\t\t\tawsCCMAddon,\n\t\t).\n\t\trunTestTerraformAWS(t)\n}", "func (m *Meta) providerLocalCacheDir() *providercache.Dir {\n\tm.fixupMissingWorkingDir()\n\tdir := m.WorkingDir.ProviderLocalCacheDir()\n\treturn providercache.NewDir(dir)\n}", "func (o *LocalDatabaseProvider) GetAdminProviderOk() (*bool, bool) {\n\tif o == nil || o.AdminProvider == nil {\n\t\treturn nil, false\n\t}\n\treturn o.AdminProvider, true\n}", "func Test_Provider(t *testing.T) {\n\t// SetLogLevel(\"TRACE\")\n\t// CheckVersion()\n\n\t// Start provider API in the background\n\tgo InitProvider()\n\t// err := InitProvider()\n\t// if err != nil {\n\t// \tlog.Fatalf(\"Error initializing Provider %+v\", err)\n\t// }\n\n\tverifier := HTTPVerifier{}\n\t// Authorization middleware\n\t// This is your chance to modify the request before it hits your provider\n\t// NOTE: this should be used very carefully, as it has the potential to\n\t// _change_ the contract\n\t// f := func(next http.Handler) http.Handler {\n\t// \treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t// \t\tlog.Println(\"[DEBUG] HOOK request filter\")\n\t// \t\t// r.Header.Add(\"Authorization\", \"Bearer 1234-dynamic-value\")\n\t// \t\tnext.ServeHTTP(w, r)\n\t// \t})\n\t// }\n\n\t// Verify the Provider with local Pact Files\n\terr := verifier.VerifyProvider(t, VerifyRequest{\n\t\tProviderBaseURL: \"http://localhost:9000\",\n\t\tBrokerURL: \"http://localhost:9292\",\n\t\tProvider: \"GreetingAPI\",\n\t\tProviderVersion: \"1.0.0\",\n\t\tPublishVerificationResults: true,\n\t\t// PactFiles: []string{\n\t\t// \tfilepath.ToSlash(fmt.Sprintf(\"%s/GreetingAPIConsumer-GreetingAPI.json\", pactDir)),\n\t\t// },\n\t\t// RequestFilter: f,\n\t\t// BeforeEach: func() error {\n\t\t// \tlog.Println(\"[DEBUG] HOOK before each\")\n\t\t// \treturn nil\n\t\t// },\n\t\t// AfterEach: func() error {\n\t\t// \tlog.Println(\"[DEBUG] HOOK after each\")\n\t\t// \treturn nil\n\t\t// },\n\t\t// StateHandlers: StateHandlers{\n\t\t// \t\"User foo exists\": func(setup bool, s ProviderStateV3) (ProviderStateV3Response, error) {\n\n\t\t// \t\tif setup {\n\t\t// \t\t\tlog.Println(\"[DEBUG] HOOK calling user foo exists state handler\", s)\n\t\t// \t\t} else {\n\t\t// \t\t\tlog.Println(\"[DEBUG] HOOK teardown the 'User foo exists' state\")\n\t\t// \t\t}\n\n\t\t// \t\t// ... do something, such as create \"foo\" in the database\n\n\t\t// \t\t// Optionally (if there are generators in the pact) return provider state values to be used in the verification\n\t\t// \t\treturn ProviderStateV3Response{\"uuid\": \"1234\"}, nil\n\t\t// \t},\n\t\t// },\n\t})\n\n\tassert.NoError(t, err)\n}", "func TestPreparerInterface(t *testing.T) {\n\tt.Parallel()\n\n\tassert.Implements(t, (*resource.Resource)(nil), new(user.Preparer))\n}", "func LivenessProbe(w http.ResponseWriter, r *http.Request) {\n\tglog.V(2).Info(\"livenessProbe - Checking local cluster id.\")\n\tmonitor := monitor.NewClusterMonitor()\n\n\t//Get local-cluster id , if -1 is returned then service will\n\t// not be able to get to cloud.redhat.com\n\tif monitor.GetLocalCluster() == \"-1\" {\n\t\t// Respond with error.\n\t\tglog.Warning(\"Cannot get local-cluster id.\")\n\t\thttp.Error(w, \"Cannot get local-cluster id.\", 503)\n\t\treturn\n\t}\n\t// Respond with success\n\tfmt.Fprint(w, \"OK\")\n}", "func shouldDiscoverHost(name string) bool {\n\tparts := strings.Split(name, \".\")\n\tif len(parts) == 1 {\n\t\tif parts[0] == \"localhost\" {\n\t\t\treturn false\n\t\t}\n\t\treturn true\n\t}\n\treturn parts[len(parts)-1] == domain\n}", "func Local(clArgs []string, stdin io.Reader, stdout, stderr io.Writer, reg *testing.Registry, d Delegate) int {\n\tcfg := NewStaticConfig(reg, localTestTimeout, d)\n\treturn run(context.Background(), clArgs, stdin, stdout, stderr, cfg)\n}", "func (i instances) discoverNodeByProviderID(ctx context.Context, providerID string) (*vmopv1alpha1.VirtualMachine, error) {\n\treturn discoverNodeByProviderID(ctx, providerID, i.namespace, i.vmClient)\n}", "func (mr *MockInformationMockRecorder) LocalLocation() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"LocalLocation\", reflect.TypeOf((*MockInformation)(nil).LocalLocation))\n}", "func DiscoveryRegister() (cancel context.CancelFunc) {\n\tconf := &naming.Config{\n\t\tNodes: config.Nodes, // NOTE: 配置种子节点(1个或多个),client内部可根据/discovery/nodes节点获取全部node(方便后面增减节点)\n\t\tZone: config.Zone,\n\t\tEnv: config.Env,\n\t}\n\tdis := naming.New(conf)\n\tins := &naming.Instance{\n\t\tZone: config.Zone,\n\t\tEnv: config.Env,\n\t\tAppID: config.AppID,\n\t\t// Hostname:\"\", // NOTE: hostname 不需要,会优先使用discovery new时Config配置的值,如没有则从os.Hostname方法获取!!!\n\t\tAddrs: config.Addrs,\n\t\tLastTs: time.Now().Unix(),\n\t\tMetadata: config.Metadata,\n\t}\n\tcancel, _ = dis.Register(ins)\n\tfmt.Println(\"register\")\n\t// Unordered output4\n\treturn\n}", "func (_m *AuthServer) mustEmbedUnimplementedAuthServer() {\n\t_m.Called()\n}", "func (a AppContext) DiscoveryAddress() string {\n\treturn DiscoveryURL\n}", "func (s *Drive) Local() bool {\n\treturn s.client.Local()\n}", "func loadLocalOrCmConfigIfValid() {\n\n\tswitch len(devStartOps.LocalSyncDir) {\n\tcase 0:\n\t\tp, err := nocalhostSvc.GetProfile()\n\t\tmust(err)\n\n\t\tif p.Associate == \"\" {\n\t\t\tmust(errors.New(\"'local-sync(-s)' should specify while svc is not associate with local dir\"))\n\t\t}\n\t\tdevStartOps.LocalSyncDir = append(devStartOps.LocalSyncDir, p.Associate)\n\n\t\t_ = nocalhostApp.ReloadSvcCfg(deployment, base.SvcTypeOf(serviceType), false, false)\n\tcase 1:\n\t\tmust(nocalhostSvc.Associate(devStartOps.LocalSyncDir[0]))\n\n\t\t_ = nocalhostApp.ReloadSvcCfg(deployment, base.SvcTypeOf(serviceType), false, false)\n\tdefault:\n\t\tlog.Fatal(errors.New(\"Can not define multi 'local-sync(-s)'\"))\n\t}\n}", "func (udp *UdpServer) handleDiscovery(dev *iotDev) ([]byte, error) {\n var err error\n var ips []net.IP\n\n ips, err = udp.getItfIps(udp.itf)\n if err != nil {\n return nil, err\n }\n\n if len(ips) == 0 {\n msg := fmt.Sprintf(\"wifiItf %f has no IP addresses.\\n\", udp.itf.Name)\n return nil, errors.New(msg)\n }\n\n return dev.sendCmd(udp.cfg.UdpPort, newServerCmd(ips[0], udp.cfg.TcpPort))\n}", "func TestExternalIP(t *testing.T) {\n\t_, err := ExternalIP()\n\tif err != nil {\n\t\tt.Errorf(\"ExternalIP failed : %w\", err)\n\t}\n}", "func (u *UnknownProvider) GetProviderString() string {\n\treturn \"unknown\"\n}" ]
[ "0.71185005", "0.70378065", "0.6612463", "0.6476195", "0.55475986", "0.5541227", "0.5527965", "0.55172056", "0.5478023", "0.5338072", "0.5255968", "0.5243303", "0.51792115", "0.5099424", "0.5093659", "0.5090468", "0.5076508", "0.5007823", "0.500113", "0.49984255", "0.4971726", "0.4944357", "0.49337965", "0.492813", "0.49224925", "0.48673758", "0.485305", "0.48300058", "0.48239806", "0.48129028", "0.48089984", "0.4800091", "0.4779157", "0.4778343", "0.47731546", "0.47638914", "0.47626168", "0.47612745", "0.47440523", "0.47322175", "0.47283977", "0.47162804", "0.46721917", "0.4665258", "0.46606436", "0.46556205", "0.4648585", "0.46371606", "0.46318448", "0.46286982", "0.45888573", "0.45676714", "0.45665953", "0.4548693", "0.454098", "0.45370302", "0.45337668", "0.45246407", "0.45037746", "0.4498726", "0.44901973", "0.448815", "0.4486914", "0.44834536", "0.4473178", "0.44715792", "0.44586912", "0.44546407", "0.44540605", "0.4452811", "0.44354653", "0.44329637", "0.44272283", "0.44268042", "0.44204426", "0.44195455", "0.44186428", "0.44165012", "0.4414285", "0.44042328", "0.44034308", "0.4401184", "0.4400007", "0.43990198", "0.43988526", "0.4397026", "0.43966848", "0.43963063", "0.43805528", "0.43801683", "0.43751276", "0.43708676", "0.43699977", "0.4367944", "0.4365555", "0.43542573", "0.43448427", "0.43442205", "0.43417695", "0.4340182" ]
0.7020587
2
SigningManager mocks base method
func (m *MockProviders) SigningManager() core.SigningManager { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "SigningManager") ret0, _ := ret[0].(core.SigningManager) return ret0 }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (m *MockClient) SigningManager() core.SigningManager {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"SigningManager\")\n\tret0, _ := ret[0].(core.SigningManager)\n\treturn ret0\n}", "func (pc *MockProviderContext) SigningManager() fab.SigningManager {\n\treturn pc.signingManager\n}", "func NewMockSigner(kis []KeyInfo) MockSigner {\n\tvar ms MockSigner\n\tms.AddrKeyInfo = make(map[address.Address]KeyInfo)\n\tfor _, k := range kis {\n\t\t// extract public key\n\t\tpub := k.PublicKey()\n\t\tnewAddr, err := address.NewSecp256k1Address(pub)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tms.Addresses = append(ms.Addresses, newAddr)\n\t\tms.AddrKeyInfo[newAddr] = k\n\t\tms.PubKeys = append(ms.PubKeys, pub)\n\t}\n\treturn ms\n}", "func (m *CryptographyServiceMock) Sign(p []byte) (r *insolar.Signature, r1 error) {\n\tcounter := atomic.AddUint64(&m.SignPreCounter, 1)\n\tdefer atomic.AddUint64(&m.SignCounter, 1)\n\n\tif len(m.SignMock.expectationSeries) > 0 {\n\t\tif counter > uint64(len(m.SignMock.expectationSeries)) {\n\t\t\tm.t.Fatalf(\"Unexpected call to CryptographyServiceMock.Sign. %v\", p)\n\t\t\treturn\n\t\t}\n\n\t\tinput := m.SignMock.expectationSeries[counter-1].input\n\t\ttestify_assert.Equal(m.t, *input, CryptographyServiceMockSignInput{p}, \"CryptographyService.Sign got unexpected parameters\")\n\n\t\tresult := m.SignMock.expectationSeries[counter-1].result\n\t\tif result == nil {\n\t\t\tm.t.Fatal(\"No results are set for the CryptographyServiceMock.Sign\")\n\t\t\treturn\n\t\t}\n\n\t\tr = result.r\n\t\tr1 = result.r1\n\n\t\treturn\n\t}\n\n\tif m.SignMock.mainExpectation != nil {\n\n\t\tinput := m.SignMock.mainExpectation.input\n\t\tif input != nil {\n\t\t\ttestify_assert.Equal(m.t, *input, CryptographyServiceMockSignInput{p}, \"CryptographyService.Sign got unexpected parameters\")\n\t\t}\n\n\t\tresult := m.SignMock.mainExpectation.result\n\t\tif result == nil {\n\t\t\tm.t.Fatal(\"No results are set for the CryptographyServiceMock.Sign\")\n\t\t}\n\n\t\tr = result.r\n\t\tr1 = result.r1\n\n\t\treturn\n\t}\n\n\tif m.SignFunc == nil {\n\t\tm.t.Fatalf(\"Unexpected call to CryptographyServiceMock.Sign. %v\", p)\n\t\treturn\n\t}\n\n\treturn m.SignFunc(p)\n}", "func (m *DeviceHealthAttestationState) SetTestSigning(value *string)() {\n err := m.GetBackingStore().Set(\"testSigning\", value)\n if err != nil {\n panic(err)\n }\n}", "func TestVerifySignedMessage(t *testing.T) {\n\tfor _, tc := range []struct {\n\t\tdesc string\n\t\tsettings *crypt.PkiSettings\n\t\tsetup func(mdb *mocks.MockDepsBundle, setupDone *bool) error\n\t\tmessageToSign string\n\t\tbase64Signature string\n\t\tPEMPublicKey string\n\t\texpectedError *testtools.ErrorSpec\n\t\texpectedValidity bool\n\t}{\n\t\t{\n\t\t\tdesc: \"invalid base64 signature\",\n\t\t\tsettings: &crypt.PkiSettings{\n\t\t\t\tAlgorithm: x509.ECDSA,\n\t\t\t\tPrivateKeyPath: \".prog/ecdsa_priv.key\",\n\t\t\t\tPublicKeyPath: \".prog/ecdsa.pub\",\n\t\t\t},\n\t\t\tsetup: func(mdb *mocks.MockDepsBundle, setupDone *bool) error {\n\t\t\t\treturn nil\n\t\t\t},\n\t\t\tmessageToSign: \"some other message\",\n\t\t\tbase64Signature: \"@#$^&*()_\",\n\t\t\tPEMPublicKey: \"\",\n\t\t\texpectedError: &testtools.ErrorSpec{\n\t\t\t\tType: \"base64.CorruptInputError\",\n\t\t\t\tMessage: \"illegal base64 data at input byte 0\",\n\t\t\t},\n\t\t\texpectedValidity: false,\n\t\t},\n\t\t{\n\t\t\tdesc: \"empty PEM key\",\n\t\t\tsettings: &crypt.PkiSettings{\n\t\t\t\tAlgorithm: x509.ECDSA,\n\t\t\t\tPrivateKeyPath: \".prog/ecdsa_priv.key\",\n\t\t\t\tPublicKeyPath: \".prog/ecdsa.pub\",\n\t\t\t},\n\t\t\tsetup: func(mdb *mocks.MockDepsBundle, setupDone *bool) error {\n\t\t\t\treturn nil\n\t\t\t},\n\t\t\tmessageToSign: \"some other message\",\n\t\t\tbase64Signature: \"abcdefgh\",\n\t\t\tPEMPublicKey: \"\",\n\t\t\texpectedError: &testtools.ErrorSpec{\n\t\t\t\tType: \"*errors.errorString\",\n\t\t\t\tMessage: \"No PEM data was found\",\n\t\t\t},\n\t\t\texpectedValidity: false,\n\t\t},\n\t\t{\n\t\t\tdesc: \"bad key data\",\n\t\t\tsettings: &crypt.PkiSettings{\n\t\t\t\tAlgorithm: x509.ECDSA,\n\t\t\t\tPrivateKeyPath: \".prog/ecdsa_priv.key\",\n\t\t\t\tPublicKeyPath: \".prog/ecdsa.pub\",\n\t\t\t},\n\t\t\tsetup: func(mdb *mocks.MockDepsBundle, setupDone *bool) error {\n\t\t\t\treturn nil\n\t\t\t},\n\t\t\tmessageToSign: \"some other message\",\n\t\t\tbase64Signature: \"abcdefgh\",\n\t\t\tPEMPublicKey: \"-----BEGIN INVALID DATA-----\\n\" +\n\t\t\t\t\"MTIzNDU2Nzg5MGFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6\\n\" +\n\t\t\t\t\"-----END INVALID DATA-----\\n\",\n\t\t\texpectedError: &testtools.ErrorSpec{\n\t\t\t\tType: \"asn1.StructuralError\",\n\t\t\t\tMessage: \"asn1: structure \" +\n\t\t\t\t\t\"error: tags don't match (16 vs {class:0 \" +\n\t\t\t\t\t\"tag:17 \" +\n\t\t\t\t\t\"length:50 \" +\n\t\t\t\t\t\"isCompound:true}) {optional:false \" +\n\t\t\t\t\t\"explicit:false \" +\n\t\t\t\t\t\"application:false \" +\n\t\t\t\t\t\"defaultValue:<nil> \" +\n\t\t\t\t\t\"tag:<nil> \" +\n\t\t\t\t\t\"stringType:0 \" +\n\t\t\t\t\t\"timeType:0 \" +\n\t\t\t\t\t\"set:false \" +\n\t\t\t\t\t\"omitEmpty:false} publicKeyInfo @2\",\n\t\t\t},\n\t\t\texpectedValidity: false,\n\t\t},\n\t\t{\n\t\t\tdesc: \"invalid signature\",\n\t\t\tsettings: &crypt.PkiSettings{\n\t\t\t\tAlgorithm: x509.ECDSA,\n\t\t\t\tPrivateKeyPath: \".prog/ecdsa_priv.key\",\n\t\t\t\tPublicKeyPath: \".prog/ecdsa.pub\",\n\t\t\t},\n\t\t\tsetup: func(mdb *mocks.MockDepsBundle, setupDone *bool) error {\n\t\t\t\treturn nil\n\t\t\t},\n\t\t\tmessageToSign: \"some other message\",\n\t\t\tbase64Signature: \"abcdefgh\",\n\t\t\tPEMPublicKey: \"-----BEGIN ECDSA PUBLIC KEY-----\\n\" +\n\t\t\t\t\"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE7WzVjtn9Gk+WHr5xbv8XMvooqU25\\n\" +\n\t\t\t\t\"BhgNjZ/vHZLBdVtCOjk4KxjS1UBfQm0c3TRxWBl3hj2AmnJbCrnGofMHBQ==\\n\" +\n\t\t\t\t\"-----END ECDSA PUBLIC KEY-----\\n\",\n\t\t\texpectedError: &testtools.ErrorSpec{\n\t\t\t\tType: \"asn1.SyntaxError\",\n\t\t\t\tMessage: \"asn1: syntax error: truncated tag or length\",\n\t\t\t},\n\t\t\texpectedValidity: false,\n\t\t},\n\t\t{\n\t\t\tdesc: \"ecdsa key for rsa mode\",\n\t\t\tsettings: &crypt.PkiSettings{\n\t\t\t\tAlgorithm: x509.RSA,\n\t\t\t\tPrivateKeyPath: \".prog/ecdsa_priv.key\",\n\t\t\t\tPublicKeyPath: \".prog/ecdsa.pub\",\n\t\t\t},\n\t\t\tsetup: func(mdb *mocks.MockDepsBundle, setupDone *bool) error {\n\t\t\t\treturn nil\n\t\t\t},\n\t\t\tmessageToSign: \"some other message\",\n\t\t\tbase64Signature: \"N3SuIdWI7XlXDteTmcOZUd2OBacyUWY+/+A8SC4QUBz9rXnldBqXha6YyGwnTuizxuy6quQ2QDFdtW16dj7EQk3lozfngskyhc2r86q3AUbdFDvrQVphMQhzsgBhHVoMjCL/YRfvtzCTWhBxegjVMLraLDCBb8IZTIqcMYafYyeJTvAnjBuntlZ+14TDuTt14Uqz85T04CXxBEqlIXMMKpTc01ST4Jsxz5HLO+At1htXp5eHOUFtQSilm3G7iO8ynhgPcXHDWfMAWu6VySUoHWCG70pJaCq6ehF7223t0UFOCqAyDyyQyP9yeUHj8F75SPSxfJm8iKXGx2LND/qLYw==\",\n\t\t\tPEMPublicKey: \"-----BEGIN RSA PUBLIC KEY-----\\n\" +\n\t\t\t\t\"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE7WzVjtn9Gk+WHr5xbv8XMvooqU25\\n\" +\n\t\t\t\t\"BhgNjZ/vHZLBdVtCOjk4KxjS1UBfQm0c3TRxWBl3hj2AmnJbCrnGofMHBQ==\\n\" +\n\t\t\t\t\"-----END RSA PUBLIC KEY-----\\n\",\n\t\t\texpectedError: &testtools.ErrorSpec{\n\t\t\t\tType: \"*errors.errorString\",\n\t\t\t\tMessage: \"Expecting a *rsa.PublicKey, but encountered a *ecdsa.PublicKey instead\",\n\t\t\t},\n\t\t\texpectedValidity: false,\n\t\t},\n\t\t{\n\t\t\tdesc: \"rsa key for ecdsa mode\",\n\t\t\tsettings: &crypt.PkiSettings{\n\t\t\t\tAlgorithm: x509.ECDSA,\n\t\t\t\tPrivateKeyPath: \".prog/ecdsa_priv.key\",\n\t\t\t\tPublicKeyPath: \".prog/ecdsa.pub\",\n\t\t\t},\n\t\t\tsetup: func(mdb *mocks.MockDepsBundle, setupDone *bool) error {\n\t\t\t\treturn nil\n\t\t\t},\n\t\t\tmessageToSign: \"some other message\",\n\t\t\tbase64Signature: \"MEYCIQDPM0fc/PFauoZzpltH3RpWtlaqRnL0gFk5WFiLMrFqrwIhAIDvlBozU6Ky2UC9xOSq3YZ5iFuO356t9RnHOElaaXFJ\",\n\t\t\tPEMPublicKey: \"-----BEGIN RSA PUBLIC KEY-----\\n\" +\n\t\t\t\t\"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAzCTTFKQBHfTN8jW6q8PT\\n\" +\n\t\t\t\t\"HNZKWnRPxSt9kpgWmyqFaZnEUipgoKGAxSIsVrl2PJSm5OlgkVzx+MY+LWM64VKM\\n\" +\n\t\t\t\t\"bRpUUGJR3zdMNhwZQX0hjOpLpVJvUwD78utVs8vijrU7sH48usFiaZQYjy4m4hQh\\n\" +\n\t\t\t\t\"63/x4h3KVz7YqUnlRMzYJFT43+AwYzYuEpzWRxtW7IObJPtjtmYVoqva98fF6aj5\\n\" +\n\t\t\t\t\"uHAsvaAgZGBalHXmCiPzKiGU/halzXSPvyJ2Cqz2aUqMHgwi/2Ip4z/mrfX+mUTa\\n\" +\n\t\t\t\t\"S+LyBy7GgqJ5vbkGArMagJIc0eARF60r6Uf483xh17oniABdLJy4qlLf6PcEU+ut\\n\" +\n\t\t\t\t\"EwIDAQAB\\n\" +\n\t\t\t\t\"-----END RSA PUBLIC KEY-----\\n\",\n\t\t\texpectedError: &testtools.ErrorSpec{\n\t\t\t\tType: \"*errors.errorString\",\n\t\t\t\tMessage: \"Expecting a *ecdsa.PublicKey, but encountered a *rsa.PublicKey instead\",\n\t\t\t},\n\t\t\texpectedValidity: false,\n\t\t},\n\t} {\n\t\tt.Run(fmt.Sprintf(\"Subtest: %s\", tc.desc), func(tt *testing.T) {\n\t\t\tmockDepsBundle := mocks.NewDefaultMockDeps(\"\", []string{\"progname\"}, \"/home/user\", nil)\n\t\t\treturnedNormally := false\n\t\t\tvar tooling *crypt.CryptoTooling\n\t\t\tvar actualErr error\n\t\t\tvar actualValidity bool\n\t\t\terr := mockDepsBundle.InvokeCallInMockedEnv(func() error {\n\t\t\t\tsetupComplete := false\n\t\t\t\tinnerErr := tc.setup(mockDepsBundle, &setupComplete)\n\t\t\t\tif innerErr != nil {\n\t\t\t\t\treturn innerErr\n\t\t\t\t}\n\t\t\t\tvar toolingErr error\n\t\t\t\ttooling, toolingErr = crypt.GetCryptoTooling(mockDepsBundle.Deps, tc.settings)\n\t\t\t\tif toolingErr != nil {\n\t\t\t\t\treturn toolingErr\n\t\t\t\t}\n\t\t\t\tsetupComplete = true\n\t\t\t\tactualValidity, actualErr = tooling.VerifySignedMessage(tc.messageToSign, tc.base64Signature, tc.PEMPublicKey)\n\t\t\t\treturnedNormally = true\n\t\t\t\treturn nil\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\ttt.Errorf(\"Unexpected error calling mockDepsBundle.InvokeCallInMockedEnv(): %s\", err.Error())\n\t\t\t}\n\t\t\tif exitStatus := mockDepsBundle.GetExitStatus(); (exitStatus != 0) || !returnedNormally {\n\t\t\t\ttt.Error(\"EncodeAndSaveKey() should not have paniced or called os.Exit.\")\n\t\t\t}\n\t\t\tif (mockDepsBundle.OutBuf.String() != \"\") || (mockDepsBundle.ErrBuf.String() != \"\") {\n\t\t\t\ttt.Errorf(\"EncodeAndSaveKey() should not have output any data. Saw stdout:\\n%s\\nstderr:\\n%s\", mockDepsBundle.OutBuf.String(), mockDepsBundle.ErrBuf.String())\n\t\t\t}\n\t\t\tif err := tc.expectedError.EnsureMatches(actualErr); err != nil {\n\t\t\t\ttt.Error(err.Error())\n\t\t\t}\n\t\t\tif tc.expectedError == nil {\n\t\t\t\tif actualValidity != tc.expectedValidity {\n\t\t\t\t\ttt.Errorf(\"Signature is %#v when %#v expected\", actualValidity, tc.expectedValidity)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif tc.expectedValidity {\n\t\t\t\t\ttt.Error(\"TEST CASE INVALID. Should not expect \\\"valid\\\".\")\n\t\t\t\t}\n\t\t\t\tif actualValidity {\n\t\t\t\t\ttt.Error(\"Error was expected. Should not report \\\"valid\\\".\")\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n}", "func mockedGranter(kubeutil *kube.Kube, app *v1.RadixRegistration, namespace string, serviceAccount *corev1.ServiceAccount) error {\n\treturn nil\n}", "func TestCryptoSignerInterfaceBehavior(t *testing.T) {\n\tcs := NewCryptoService(trustmanager.NewKeyMemoryStore(passphraseRetriever))\n\tinterfaces.EmptyCryptoServiceInterfaceBehaviorTests(t, cs)\n\tinterfaces.CreateGetKeyCryptoServiceInterfaceBehaviorTests(t, cs, data.ECDSAKey)\n\n\tcs = NewCryptoService(trustmanager.NewKeyMemoryStore(passphraseRetriever))\n\tinterfaces.CreateListKeyCryptoServiceInterfaceBehaviorTests(t, cs, data.ECDSAKey)\n\n\tcs = NewCryptoService(trustmanager.NewKeyMemoryStore(passphraseRetriever))\n\tinterfaces.AddGetKeyCryptoServiceInterfaceBehaviorTests(t, cs, data.ECDSAKey)\n\n\tcs = NewCryptoService(trustmanager.NewKeyMemoryStore(passphraseRetriever))\n\tinterfaces.AddListKeyCryptoServiceInterfaceBehaviorTests(t, cs, data.ECDSAKey)\n}", "func (c *Provider) SigningManager() core.SigningManager {\n\treturn c.signingManager\n}", "func (mmSignWith *mDigestHolderMockSignWith) Set(f func(signer DigestSigner) (s1 SignedDigestHolder)) *DigestHolderMock {\n\tif mmSignWith.defaultExpectation != nil {\n\t\tmmSignWith.mock.t.Fatalf(\"Default expectation is already set for the DigestHolder.SignWith method\")\n\t}\n\n\tif len(mmSignWith.expectations) > 0 {\n\t\tmmSignWith.mock.t.Fatalf(\"Some expectations are already set for the DigestHolder.SignWith method\")\n\t}\n\n\tmmSignWith.mock.funcSignWith = f\n\treturn mmSignWith.mock\n}", "func (m *MockMachine) SignerKey() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"SignerKey\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func (mmSignWith *mDigestHolderMockSignWith) When(signer DigestSigner) *DigestHolderMockSignWithExpectation {\n\tif mmSignWith.mock.funcSignWith != nil {\n\t\tmmSignWith.mock.t.Fatalf(\"DigestHolderMock.SignWith mock is already set by Set\")\n\t}\n\n\texpectation := &DigestHolderMockSignWithExpectation{\n\t\tmock: mmSignWith.mock,\n\t\tparams: &DigestHolderMockSignWithParams{signer},\n\t}\n\tmmSignWith.expectations = append(mmSignWith.expectations, expectation)\n\treturn expectation\n}", "func (m *MockClient) Sign(arg0 []byte) ([]byte, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Sign\", arg0)\n\tret0, _ := ret[0].([]byte)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *mCryptographyServiceMockSign) Set(f func(p []byte) (r *insolar.Signature, r1 error)) *CryptographyServiceMock {\n\tm.mainExpectation = nil\n\tm.expectationSeries = nil\n\n\tm.mock.SignFunc = f\n\treturn m.mock\n}", "func TestSenderRequest_Sign(t *testing.T) {\r\n\r\n\t// Create key\r\n\tkey, err := bitcoin.CreatePrivateKeyString()\r\n\tassert.NoError(t, err)\r\n\tassert.NotNil(t, key)\r\n\r\n\t// Create the request / message\r\n\tsenderRequest := &SenderRequest{\r\n\t\tDt: time.Now().UTC().Format(time.RFC3339),\r\n\t\tSenderHandle: testAlias + \"@\" + testDomain,\r\n\t\tSenderName: testName,\r\n\t\tPurpose: testMessage,\r\n\t}\r\n\r\n\tvar signature string\r\n\r\n\tt.Run(\"invalid key - empty\", func(t *testing.T) {\r\n\t\tsignature, err = senderRequest.Sign(\"\")\r\n\t\tassert.Error(t, err)\r\n\t\tassert.Equal(t, len(signature), 0)\r\n\t})\r\n\r\n\tt.Run(\"invalid key - 0\", func(t *testing.T) {\r\n\t\tsignature, err = senderRequest.Sign(\"0\")\r\n\t\tassert.Error(t, err)\r\n\t\tassert.Equal(t, len(signature), 0)\r\n\t})\r\n\r\n\tt.Run(\"invalid dt\", func(t *testing.T) {\r\n\t\tsenderRequest.Dt = \"\"\r\n\t\tsignature, err = senderRequest.Sign(key)\r\n\t\tassert.Error(t, err)\r\n\t\tassert.Equal(t, len(signature), 0)\r\n\t})\r\n\r\n\tt.Run(\"invalid sender handle\", func(t *testing.T) {\r\n\t\tsenderRequest.Dt = time.Now().UTC().Format(time.RFC3339)\r\n\t\tsenderRequest.SenderHandle = \"\"\r\n\t\tsignature, err = senderRequest.Sign(key)\r\n\t\tassert.Error(t, err)\r\n\t\tassert.Equal(t, len(signature), 0)\r\n\t})\r\n\r\n\tt.Run(\"valid signature\", func(t *testing.T) {\r\n\t\tsenderRequest.SenderHandle = testAlias + \"@\" + testDomain\r\n\t\tsignature, err = senderRequest.Sign(key)\r\n\t\tassert.NoError(t, err)\r\n\t\tassert.NotEqual(t, len(signature), 0)\r\n\r\n\t\t// Get address for verification\r\n\t\tvar address string\r\n\t\taddress, err = bitcoin.GetAddressFromPrivateKeyString(key, false)\r\n\t\tassert.NoError(t, err)\r\n\r\n\t\t// Verify the signature\r\n\t\terr = senderRequest.Verify(address, signature)\r\n\t\tassert.NoError(t, err)\r\n\t})\r\n}", "func (mm *MessageMaker) Signer() *MockSigner {\n\treturn mm.signer\n}", "func (mm *MessageMaker) Signer() *MockSigner {\n\treturn mm.signer\n}", "func (a *ActiveDevice) setSigningKey(g *GlobalContext, uv keybase1.UserVersion, deviceID keybase1.DeviceID,\n\tsigKey GenericKey, deviceName string) error {\n\ta.Lock()\n\tdefer a.Unlock()\n\n\tif err := a.internalUpdateUserVersionDeviceID(uv, deviceID); err != nil {\n\t\treturn err\n\t}\n\n\ta.signingKey = sigKey\n\tif len(deviceName) > 0 {\n\t\ta.deviceName = deviceName\n\t}\n\ta.nistFactory = NewNISTFactory(g, uv.Uid, deviceID, sigKey)\n\treturn nil\n}", "func (m *mSignatureKeyHolderMockGetSignMethod) Set(f func() (r SignMethod)) *SignatureKeyHolderMock {\n\tm.mainExpectation = nil\n\tm.expectationSeries = nil\n\n\tm.mock.GetSignMethodFunc = f\n\treturn m.mock\n}", "func (m *CryptographyServiceMock) Verify(p crypto.PublicKey, p1 insolar.Signature, p2 []byte) (r bool) {\n\tcounter := atomic.AddUint64(&m.VerifyPreCounter, 1)\n\tdefer atomic.AddUint64(&m.VerifyCounter, 1)\n\n\tif len(m.VerifyMock.expectationSeries) > 0 {\n\t\tif counter > uint64(len(m.VerifyMock.expectationSeries)) {\n\t\t\tm.t.Fatalf(\"Unexpected call to CryptographyServiceMock.Verify. %v %v %v\", p, p1, p2)\n\t\t\treturn\n\t\t}\n\n\t\tinput := m.VerifyMock.expectationSeries[counter-1].input\n\t\ttestify_assert.Equal(m.t, *input, CryptographyServiceMockVerifyInput{p, p1, p2}, \"CryptographyService.Verify got unexpected parameters\")\n\n\t\tresult := m.VerifyMock.expectationSeries[counter-1].result\n\t\tif result == nil {\n\t\t\tm.t.Fatal(\"No results are set for the CryptographyServiceMock.Verify\")\n\t\t\treturn\n\t\t}\n\n\t\tr = result.r\n\n\t\treturn\n\t}\n\n\tif m.VerifyMock.mainExpectation != nil {\n\n\t\tinput := m.VerifyMock.mainExpectation.input\n\t\tif input != nil {\n\t\t\ttestify_assert.Equal(m.t, *input, CryptographyServiceMockVerifyInput{p, p1, p2}, \"CryptographyService.Verify got unexpected parameters\")\n\t\t}\n\n\t\tresult := m.VerifyMock.mainExpectation.result\n\t\tif result == nil {\n\t\t\tm.t.Fatal(\"No results are set for the CryptographyServiceMock.Verify\")\n\t\t}\n\n\t\tr = result.r\n\n\t\treturn\n\t}\n\n\tif m.VerifyFunc == nil {\n\t\tm.t.Fatalf(\"Unexpected call to CryptographyServiceMock.Verify. %v %v %v\", p, p1, p2)\n\t\treturn\n\t}\n\n\treturn m.VerifyFunc(p, p1, p2)\n}", "func setupSignature(t *testing.T) (stop func(), clients []*exec.Cmd, contractPath, contractFilePath string) {\n\t// Cleanup\n\teraseDatabase()\n\n\t// Start the platform\n\tworkingDir, err := ioutil.TempDir(\"\", \"dfss_\")\n\tassert.Equal(t, nil, err)\n\t_, _, _, stop, ca, err := startPlatform(workingDir)\n\tassert.Equal(t, nil, err)\n\n\ttime.Sleep(2 * time.Second)\n\n\t// Register clients\n\tclient1, err := createClient(workingDir, ca, 9091)\n\tassert.Equal(t, nil, err)\n\terr = registerAndAuth(client1, \"client1@example.com\", \"password\", \"\", true, true)\n\tassert.Equal(t, nil, err)\n\tclient2, err := createClient(workingDir, ca, 9092)\n\tassert.Equal(t, nil, err)\n\terr = registerAndAuth(client2, \"client2@example.com\", \"password\", \"\", true, true)\n\tassert.Equal(t, nil, err)\n\tclient3, err := createClient(workingDir, ca, 9093)\n\tassert.Equal(t, nil, err)\n\terr = registerAndAuth(client3, \"client3@example.com\", \"password\", \"\", true, true)\n\tassert.Equal(t, nil, err)\n\n\t// Create contract\n\tclient1 = newClient(client1)\n\tsetLastArg(client1, \"new\", true)\n\tcontractFilePath = filepath.Join(\"testdata\", \"contract.txt\")\n\tclient1.Stdin = strings.NewReader(\n\t\t\"password\\n\" +\n\t\t\tcontractFilePath + \"\\n\" +\n\t\t\t\"\\n\" +\n\t\t\t\"client1@example.com\\n\" +\n\t\t\t\"client2@example.com\\n\" +\n\t\t\t\"client3@example.com\\n\" +\n\t\t\t\"\\n\",\n\t)\n\terr = checkStderr(t, client1, \"\")\n\tassert.Equal(t, nil, err)\n\n\t// Get contract file\n\tcontractEntity := getContract(\"contract.txt\", 0)\n\tcontractData, err := contract.GetJSON(contractEntity)\n\tassert.Equal(t, nil, err)\n\tcontractPath = filepath.Join(workingDir, \"c.dfss\")\n\terr = ioutil.WriteFile(contractPath, contractData, os.ModePerm)\n\tassert.Equal(t, nil, err)\n\n\t// Test with wrong file, should abort\n\twrongFileClient := newClient(client1)\n\tsetLastArg(wrongFileClient, \"sign\", true)\n\tsetLastArg(wrongFileClient, contractPath, false)\n\twrongFileClient.Stdin = strings.NewReader(\"wrongfile.txt\\npassword\\nyes\\n\")\n\t_, err = wrongFileClient.Output()\n\tassert.NotNil(t, err)\n\n\tclients = make([]*exec.Cmd, 3)\n\tclients[0] = newClient(client1)\n\tclients[1] = newClient(client2)\n\tclients[2] = newClient(client3)\n\treturn\n}", "func TestKeyExchangeSigning(t *testing.T) {\n\tA := \"peerA\"\n\tB := \"peerB\"\n\n\t// generate A's key\n\tkeyA, err := rsa.GenerateKey(rand.Reader, 512)\n\tif err != nil {\n\t\tt.Errorf(\"Could not create private key: %v\", err)\n\t}\n\n\t// generate B's key\n\tkeyB, err := rsa.GenerateKey(rand.Reader, 512)\n\tif err != nil {\n\t\tt.Errorf(\"Could not create private key: %v\", err)\n\t}\n\n\trecordForB := KeyRecord{\n\t\tOwner: B,\n\t\tKeyPub: keyB.PublicKey,\n\t}\n\n\t// A signs B's key\n\tkeyBBytes, err := SerializeKey(recordForB.KeyPub)\n\n\tif err != nil {\n\t\tt.Errorf(\"Could not serialize the key: %v\", err)\n\t}\n\n\tmsg := create(keyBBytes, recordForB.Owner, *keyA, A)\n\n\t// check that the signature is correct\n\terr = Verify(msg, keyA.PublicKey)\n\n\tif err != nil {\n\t\tt.Errorf(\"Signature of message is wrong: %v\", err)\n\t}\n\n\ttrustedRecordForB := TrustedKeyRecord{\n\t\tKeyRecord: recordForB,\n\t\tConfidence: 1.0,\n\t}\n\n\tmsg = trustedRecordForB.ConstructMessage(*keyA, A)\n\n\terr = Verify(msg, keyA.PublicKey)\n\n\tif err != nil {\n\t\tt.Errorf(\"Signature of message is wrong: %v\", err)\n\t}\n}", "func NewSignedMessageForTestGetter(ms MockSigner) func() *SignedMessage {\n\ti := 0\n\treturn func() *SignedMessage {\n\t\ts := fmt.Sprintf(\"smsg%d\", i)\n\t\ti++\n\t\tnewAddr, err := address.NewActorAddress([]byte(s + \"-to\"))\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tmsg := NewMessage(\n\t\t\tms.Addresses[0], // from needs to be an address from the signer\n\t\t\tnewAddr,\n\t\t\t0,\n\t\t\tZeroAttoFIL,\n\t\t\ts,\n\t\t\t[]byte(\"params\"))\n\t\tsmsg, err := NewSignedMessage(*msg, &ms, NewGasPrice(0), NewGasUnits(0))\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\treturn smsg\n\t}\n}", "func (m *mSignatureKeyHolderMockGetSignatureKeyMethod) Set(f func() (r SignatureMethod)) *SignatureKeyHolderMock {\n\tm.mainExpectation = nil\n\tm.expectationSeries = nil\n\n\tm.mock.GetSignatureKeyMethodFunc = f\n\treturn m.mock\n}", "func (c CryptoServiceTester) TestSignWithKey(t *testing.T) {\n\tcryptoService := c.cryptoServiceFactory()\n\tcontent := []byte(\"this is a secret\")\n\n\ttufKey, err := cryptoService.Create(c.role, c.gun, c.keyAlgo)\n\trequire.NoError(t, err, c.errorMsg(\"error creating key\"))\n\n\t// Test Sign\n\tprivKey, role, err := cryptoService.GetPrivateKey(tufKey.ID())\n\trequire.NoError(t, err, c.errorMsg(\"failed to get private key\"))\n\trequire.Equal(t, c.role, role)\n\n\tsignature, err := privKey.Sign(rand.Reader, content, nil)\n\trequire.NoError(t, err, c.errorMsg(\"signing failed\"))\n\n\tverifier, ok := signed.Verifiers[algoToSigType[c.keyAlgo]]\n\trequire.True(t, ok, c.errorMsg(\"Unknown verifier for algorithm\"))\n\n\terr = verifier.Verify(tufKey, signature, content)\n\trequire.NoError(t, err,\n\t\tc.errorMsg(\"verification failed for %s key type\", c.keyAlgo))\n}", "func (mmSignWith *mDigestHolderMockSignWith) Return(s1 SignedDigestHolder) *DigestHolderMock {\n\tif mmSignWith.mock.funcSignWith != nil {\n\t\tmmSignWith.mock.t.Fatalf(\"DigestHolderMock.SignWith mock is already set by Set\")\n\t}\n\n\tif mmSignWith.defaultExpectation == nil {\n\t\tmmSignWith.defaultExpectation = &DigestHolderMockSignWithExpectation{mock: mmSignWith.mock}\n\t}\n\tmmSignWith.defaultExpectation.results = &DigestHolderMockSignWithResults{s1}\n\treturn mmSignWith.mock\n}", "func (m *MockTransactionApi) SignWithPrivkey(tx *types.Transaction, outpoint *types.OutPoint, privkey *types.Privkey, sighashType types.SigHashType, utxoList *[]types.UtxoData) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"SignWithPrivkey\", tx, outpoint, privkey, sighashType, utxoList)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func mockChildPackages() {\n\n\t// Fake an AWS credentials file so that the mfile package will nehave as if it is happy\n\tsetFakeCredentials()\n\n\t// Fake out the creds package into using an apparently credentials response from AWS\n\tcreds.SetGetSessionTokenFunc(func(awsService *sts.STS, input *sts.GetSessionTokenInput) (*sts.GetSessionTokenOutput, error) {\n\t\treturn getSessionTokenOutput, nil\n\t})\n\n}", "func (c CryptoServiceTester) TestCreateAndGetWhenMultipleKeystores(t *testing.T) {\n\tcryptoService := c.cryptoServiceFactory()\n\tcryptoService.keyStores = append(cryptoService.keyStores,\n\t\ttrustmanager.NewKeyMemoryStore(passphraseRetriever))\n\n\t// Test Create\n\ttufKey, err := cryptoService.Create(c.role, c.gun, c.keyAlgo)\n\trequire.NoError(t, err, c.errorMsg(\"error creating key\"))\n\n\t// Only the first keystore should have the key\n\tkeyPath := tufKey.ID()\n\t_, _, err = cryptoService.keyStores[0].GetKey(keyPath)\n\trequire.NoError(t, err, c.errorMsg(\n\t\t\"First keystore does not have the key %s\", keyPath))\n\t_, _, err = cryptoService.keyStores[1].GetKey(keyPath)\n\trequire.Error(t, err, c.errorMsg(\n\t\t\"Second keystore has the key %s\", keyPath))\n\n\t// GetKey works across multiple keystores\n\tretrievedKey := cryptoService.GetKey(tufKey.ID())\n\trequire.NotNil(t, retrievedKey,\n\t\tc.errorMsg(\"Could not find key ID %s\", tufKey.ID()))\n}", "func (m *DeviceHealthAttestationState) GetTestSigning()(*string) {\n val, err := m.GetBackingStore().Get(\"testSigning\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func TestSend(t *testing.T) {\n\thelper := sleet_t.NewTestHelper(t)\n\turl := \"https://cert.api.firstdata.com/gateway/v2/payments\"\n\n\tvar gotHeader http.Header\n\tvar authRequestRaw, authResponseRaw, authErrorRaw []byte\n\n\tauthRequestRaw = helper.ReadFile(\"test_data/authRequest.json\")\n\tauthResponseRaw = helper.ReadFile(\"test_data/authResponse.json\")\n\tauthErrorRaw = helper.ReadFile(\"test_data/400Response.json\")\n\n\tvar request *Request = new(Request)\n\thelper.Unmarshal(authRequestRaw, request)\n\n\tt.Run(\"With Successful Response\", func(t *testing.T) {\n\t\thttpmock.Activate()\n\t\tdefer httpmock.DeactivateAndReset()\n\n\t\thttpmock.RegisterResponder(\"POST\", url, func(req *http.Request) (*http.Response, error) {\n\t\t\tgotHeader = req.Header\n\t\t\tresp := httpmock.NewBytesResponse(http.StatusOK, authResponseRaw)\n\t\t\treturn resp, nil\n\t\t})\n\n\t\tfirstDataClient := NewClient(common.Sandbox, Credentials{defaultApiKey, defaultApiSecret})\n\n\t\tvar want *Response = new(Response)\n\t\thelper.Unmarshal(authResponseRaw, want)\n\n\t\tgot, _, err := firstDataClient.sendRequest(context.TODO(), defaultReqId, url, *request)\n\n\t\tt.Run(\"Response Struct\", func(t *testing.T) {\n\t\t\tif err != nil {\n\t\t\t\tt.Fatalf(\"Error thrown after sending request %q\", err)\n\t\t\t}\n\n\t\t\tif !cmp.Equal(*got, *want, sleet_t.CompareUnexported) {\n\t\t\t\tt.Error(\"Response body does not match expected\")\n\t\t\t\tt.Error(cmp.Diff(*want, *got, sleet_t.CompareUnexported))\n\t\t\t}\n\t\t})\n\n\t\tt.Run(\"Request Headers\", func(t *testing.T) {\n\t\t\ttimestamp := strconv.FormatInt(time.Now().Unix(), 10)\n\n\t\t\tsignature := makeSignature(\n\t\t\t\ttimestamp,\n\t\t\t\tfirstDataClient.credentials.ApiKey,\n\t\t\t\tfirstDataClient.credentials.ApiSecret,\n\t\t\t\tdefaultReqId,\n\t\t\t\tstrings.TrimSpace(string(authRequestRaw)),\n\t\t\t)\n\n\t\t\theader_cases := []struct {\n\t\t\t\tlabel string\n\t\t\t\twant string\n\t\t\t\tgot string\n\t\t\t}{\n\t\t\t\t{\"defaultApiKey\", defaultApiKey, gotHeader.Get(\"Api-Key\")},\n\t\t\t\t{\"RequestID\", defaultReqId, gotHeader.Get(\"Client-Request-Id\")},\n\t\t\t\t{\"Signature\", signature, gotHeader.Get(\"Message-Signature\")},\n\t\t\t\t{\"Timestamp\", timestamp, gotHeader.Get(\"Timestamp\")},\n\t\t\t}\n\n\t\t\tfor _, c := range header_cases {\n\t\t\t\tt.Run(c.label, func(t *testing.T) {\n\t\t\t\t\tif c.got != c.want {\n\t\t\t\t\t\tt.Errorf(\"Got %q, want %q\", c.got, c.want)\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t}\n\t\t})\n\t})\n\n\tt.Run(\"With Error Response\", func(t *testing.T) {\n\t\thttpmock.Activate()\n\t\tdefer httpmock.DeactivateAndReset()\n\n\t\thttpmock.RegisterResponder(\"POST\", url, func(req *http.Request) (*http.Response, error) {\n\t\t\tgotHeader = req.Header\n\t\t\tresp := httpmock.NewBytesResponse(http.StatusForbidden, authErrorRaw)\n\t\t\treturn resp, nil\n\t\t})\n\n\t\tfirstDataClient := NewClient(common.Sandbox, Credentials{defaultApiKey, defaultApiSecret})\n\n\t\tvar want *Response = new(Response)\n\t\thelper.Unmarshal(authErrorRaw, want)\n\n\t\tgot, _, err := firstDataClient.sendRequest(context.TODO(), defaultReqId, url, *request)\n\n\t\tt.Run(\"Response Struct\", func(t *testing.T) {\n\t\t\tif err != nil {\n\t\t\t\tt.Fatalf(\"Error thrown after sending request %q\", err)\n\t\t\t}\n\n\t\t\tif !cmp.Equal(*got, *want, sleet_t.CompareUnexported) {\n\t\t\t\tt.Error(\"Response body does not match expected\")\n\t\t\t\tt.Error(cmp.Diff(*want, *got, sleet_t.CompareUnexported))\n\t\t\t}\n\t\t})\n\t})\n}", "func Sign(ctx context.Context, txf Factory, name string, txBuilder client.TxBuilder, overwriteSig bool) error {\n\tif txf.keybase == nil {\n\t\treturn errors.New(\"keybase must be set prior to signing a transaction\")\n\t}\n\n\tvar err error\n\tsignMode := txf.signMode\n\tif signMode == signing.SignMode_SIGN_MODE_UNSPECIFIED {\n\t\t// use the SignModeHandler's default mode if unspecified\n\t\tsignMode, err = authsigning.APISignModeToInternal(txf.txConfig.SignModeHandler().DefaultMode())\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tk, err := txf.keybase.Key(name)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tpubKey, err := k.GetPubKey()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsignerData := authsigning.SignerData{\n\t\tChainID: txf.chainID,\n\t\tAccountNumber: txf.accountNumber,\n\t\tSequence: txf.sequence,\n\t\tPubKey: pubKey,\n\t\tAddress: sdk.AccAddress(pubKey.Address()).String(),\n\t}\n\n\t// For SIGN_MODE_DIRECT, calling SetSignatures calls setSignerInfos on\n\t// TxBuilder under the hood, and SignerInfos is needed to generated the\n\t// sign bytes. This is the reason for setting SetSignatures here, with a\n\t// nil signature.\n\t//\n\t// Note: this line is not needed for SIGN_MODE_LEGACY_AMINO, but putting it\n\t// also doesn't affect its generated sign bytes, so for code's simplicity\n\t// sake, we put it here.\n\tsigData := signing.SingleSignatureData{\n\t\tSignMode: signMode,\n\t\tSignature: nil,\n\t}\n\tsig := signing.SignatureV2{\n\t\tPubKey: pubKey,\n\t\tData: &sigData,\n\t\tSequence: txf.Sequence(),\n\t}\n\n\tvar prevSignatures []signing.SignatureV2\n\tif !overwriteSig {\n\t\tprevSignatures, err = txBuilder.GetTx().GetSignaturesV2()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\t// Overwrite or append signer infos.\n\tvar sigs []signing.SignatureV2\n\tif overwriteSig {\n\t\tsigs = []signing.SignatureV2{sig}\n\t} else {\n\t\tsigs = append(sigs, prevSignatures...)\n\t\tsigs = append(sigs, sig)\n\t}\n\tif err := txBuilder.SetSignatures(sigs...); err != nil {\n\t\treturn err\n\t}\n\n\tif err := checkMultipleSigners(txBuilder.GetTx()); err != nil {\n\t\treturn err\n\t}\n\n\tbytesToSign, err := authsigning.GetSignBytesAdapter(\n\t\tctx, txf.txConfig.SignModeHandler(),\n\t\tsignMode, signerData, txBuilder.GetTx())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Sign those bytes\n\tsigBytes, _, err := txf.keybase.Sign(name, bytesToSign, signMode)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Construct the SignatureV2 struct\n\tsigData = signing.SingleSignatureData{\n\t\tSignMode: signMode,\n\t\tSignature: sigBytes,\n\t}\n\tsig = signing.SignatureV2{\n\t\tPubKey: pubKey,\n\t\tData: &sigData,\n\t\tSequence: txf.Sequence(),\n\t}\n\n\tif overwriteSig {\n\t\terr = txBuilder.SetSignatures(sig)\n\t} else {\n\t\tprevSignatures = append(prevSignatures, sig)\n\t\terr = txBuilder.SetSignatures(prevSignatures...)\n\t}\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to set signatures on payload: %w\", err)\n\t}\n\n\t// Run optional preprocessing if specified. By default, this is unset\n\t// and will return nil.\n\treturn txf.PreprocessTx(name, txBuilder)\n}", "func (m *SignatureKeyHolderMock) CheckMocksCalled() {\n\tm.Finish()\n}", "func (c CryptoServiceTester) TestSignNoMatchingKeys(t *testing.T) {\n\tcryptoService := c.cryptoServiceFactory()\n\n\tprivKey, err := utils.GenerateECDSAKey(rand.Reader)\n\trequire.NoError(t, err, c.errorMsg(\"error creating key\"))\n\n\t// Test Sign\n\t_, _, err = cryptoService.GetPrivateKey(privKey.ID())\n\trequire.Error(t, err, c.errorMsg(\"Should not have found private key\"))\n}", "func NewKeyManager(t mockConstructorTestingTNewKeyManager) *KeyManager {\n\tmock := &KeyManager{}\n\tmock.Mock.Test(t)\n\n\tt.Cleanup(func() { mock.AssertExpectations(t) })\n\n\treturn mock\n}", "func (m *mCryptographyServiceMockSign) Return(r *insolar.Signature, r1 error) *CryptographyServiceMock {\n\tm.mock.SignFunc = nil\n\tm.expectationSeries = nil\n\n\tif m.mainExpectation == nil {\n\t\tm.mainExpectation = &CryptographyServiceMockSignExpectation{}\n\t}\n\tm.mainExpectation.result = &CryptographyServiceMockSignResult{r, r1}\n\treturn m.mock\n}", "func (m *mSignatureKeyHolderMockGetSignatureKeyType) Set(f func() (r SignatureKeyType)) *SignatureKeyHolderMock {\n\tm.mainExpectation = nil\n\tm.expectationSeries = nil\n\n\tm.mock.GetSignatureKeyTypeFunc = f\n\treturn m.mock\n}", "func Test_VerifySigFromTass(t *testing.T) {\n\trequire := require.New(t)\n\n\t//c := &sm2.Driver{}\n\n\txBytes := common.FromHex(\"0000000000000000000000000000000000000000000000000000000000000000FD4241057FEC6CBEEC501F7E1763751B8F6DFCFB910FB634FBB76A16639EF172\")\n\tyBytes := common.FromHex(\"00000000000000000000000000000000000000000000000000000000000000001C6DA89F9C1A5EE9B6108E5A2A5FE336962630A34DBA1AF428451E1CE63BB3CF\")\n\tx := new(big.Int).SetBytes(xBytes)\n\ty := new(big.Int).SetBytes(yBytes)\n\n\tpublicKey := &gmsm_sm2.PublicKey{\n\t\tX: x,\n\t\tY: y,\n\t}\n\tvar pubSM2 sm2.PubKeySM2\n\tcopy(pubSM2[:], gmsm_sm2.Compress(publicKey))\n\n\trBytes := common.FromHex(\"00000000000000000000000000000000000000000000000000000000000000003AA29337E7149047FB8AE83F30AA00125E23173C88F284ADDED2E5B59ACAA5B9\")\n\tsBytes := common.FromHex(\"0000000000000000000000000000000000000000000000000000000000000000E2E9338109D74269578216039FD4D1C764E7F6F142CBB2E3035E7E49D375D330\")\n\tr := new(big.Int).SetBytes(rBytes)\n\ts := new(big.Int).SetBytes(sBytes)\n\n\tsignature := sm2.SignatureSM2(sm2.Serialize(r, s))\n\n\tmsg := []byte(\"112233445566112233445566112233445566112233445566\")\n\tok := pubSM2.VerifyBytes(msg, signature)\n\trequire.Equal(true, ok)\n}", "func (m *mSignatureKeyHolderMockGetSignatureKeyType) Return(r SignatureKeyType) *SignatureKeyHolderMock {\n\tm.mock.GetSignatureKeyTypeFunc = nil\n\tm.expectationSeries = nil\n\n\tif m.mainExpectation == nil {\n\t\tm.mainExpectation = &SignatureKeyHolderMockGetSignatureKeyTypeExpectation{}\n\t}\n\tm.mainExpectation.result = &SignatureKeyHolderMockGetSignatureKeyTypeResult{r}\n\treturn m.mock\n}", "func TestPrettyPrintRootAndSigningKeys(t *testing.T) {\n\tret := passphrase.ConstantRetriever(\"pass\")\n\tkeyStores := []trustmanager.KeyStore{\n\t\ttrustmanager.NewKeyMemoryStore(ret),\n\t\t&otherMemoryStore{GenericKeyStore: *trustmanager.NewKeyMemoryStore(ret)},\n\t}\n\n\tlongNameShortened := \"...\" + strings.Repeat(\"z\", 37)\n\n\tkeys := make([]data.PrivateKey, 4)\n\tfor i := 0; i < 4; i++ {\n\t\tkey, err := utils.GenerateED25519Key(rand.Reader)\n\t\trequire.NoError(t, err)\n\t\tkeys[i] = key\n\t}\n\n\troot := data.CanonicalRootRole\n\n\t// add keys to the key stores\n\trequire.NoError(t, keyStores[0].AddKey(trustmanager.KeyInfo{Role: root, Gun: \"\"}, keys[0]))\n\trequire.NoError(t, keyStores[1].AddKey(trustmanager.KeyInfo{Role: root, Gun: \"\"}, keys[0]))\n\trequire.NoError(t, keyStores[0].AddKey(trustmanager.KeyInfo{Role: data.CanonicalTargetsRole, Gun: data.GUN(strings.Repeat(\"/a\", 30))}, keys[1]))\n\trequire.NoError(t, keyStores[1].AddKey(trustmanager.KeyInfo{Role: data.CanonicalSnapshotRole, Gun: \"short/gun\"}, keys[1]))\n\trequire.NoError(t, keyStores[0].AddKey(trustmanager.KeyInfo{Role: \"targets/a\", Gun: \"\"}, keys[3]))\n\trequire.NoError(t, keyStores[0].AddKey(trustmanager.KeyInfo{Role: \"invalidRole\", Gun: \"\"}, keys[2]))\n\n\texpected := [][]string{\n\t\t// root always comes first\n\t\t{root.String(), keys[0].ID(), keyStores[0].Name()},\n\t\t{root.String(), keys[0].ID(), longNameShortened},\n\t\t// these have no gun, so they come first\n\t\t{\"invalidRole\", keys[2].ID(), keyStores[0].Name()},\n\t\t{\"targets/a\", keys[3].ID(), keyStores[0].Name()},\n\t\t// these have guns, and are sorted then by guns\n\t\t{data.CanonicalTargetsRole.String(), \"...\" + strings.Repeat(\"/a\", 11), keys[1].ID(), keyStores[0].Name()},\n\t\t{data.CanonicalSnapshotRole.String(), \"short/gun\", keys[1].ID(), longNameShortened},\n\t}\n\n\tvar b bytes.Buffer\n\tprettyPrintKeys(keyStores, &b)\n\ttext, err := ioutil.ReadAll(&b)\n\trequire.NoError(t, err)\n\n\tlines := strings.Split(strings.TrimSpace(string(text)), \"\\n\")\n\trequire.Len(t, lines, len(expected)+2)\n\n\t// starts with headers\n\trequire.True(t, reflect.DeepEqual(strings.Fields(lines[0]),\n\t\t[]string{\"ROLE\", \"GUN\", \"KEY\", \"ID\", \"LOCATION\"}))\n\trequire.Equal(t, \"----\", lines[1][:4])\n\n\tfor i, line := range lines[2:] {\n\t\t// we are purposely not putting spaces in test data so easier to split\n\t\tsplitted := strings.Fields(line)\n\t\tfor j, v := range splitted {\n\t\t\trequire.Equal(t, expected[i][j], strings.TrimSpace(v))\n\t\t}\n\t}\n}", "func signatureHelper(t *testing.T, failure bool) {\n\t// Setup\n\tstop, clients, contractPath, contractFilePath := setupSignature(t)\n\tdefer stop()\n\n\tstopBefore, expectedProofFile1, expectedProofFile2 := \"1\", 0, 0\n\tif !failure {\n\t\tstopBefore, expectedProofFile1, expectedProofFile2 = \"2\", 2, 1\n\t}\n\n\t// Configure client3 to be faulty\n\tsetLastArg(clients[2], \"--stopbefore\", true)\n\tsetLastArg(clients[2], stopBefore, false)\n\tsetLastArg(clients[2], \"sign\", false)\n\n\t// Sign!\n\tcloseChannel := make(chan []byte, 3)\n\tfor i := 0; i < 3; i++ {\n\t\tsetLastArg(clients[i], \"sign\", true)\n\t\tsetLastArg(clients[i], contractPath, false)\n\t\tgo func(c *exec.Cmd, i int) {\n\t\t\tc.Stdin = strings.NewReader(contractFilePath + \"\\npassword\\nyes\\n\")\n\t\t\tc.Stderr = bufio.NewWriter(os.Stdout)\n\t\t\toutput, _ := c.Output()\n\t\t\tcloseChannel <- output\n\t\t}(clients[i], i)\n\t}\n\n\tfor i := 0; i < 3; i++ {\n\t\t// TODO check stderr?\n\t\t<-closeChannel\n\t}\n\n\tcheckProofFile(t, expectedProofFile1)\n\tfilename := checkRecoverFile(t, \"client3@example.com\")\n\tcallRecover(newClient(clients[2]), filename)\n\t_ = os.Remove(filename)\n\tcheckProofFile(t, expectedProofFile2)\n\n\ttime.Sleep(time.Second)\n\treturn\n}", "func (m *mSignatureKeyHolderMockGetSignatureKeyMethod) Return(r SignatureMethod) *SignatureKeyHolderMock {\n\tm.mock.GetSignatureKeyMethodFunc = nil\n\tm.expectationSeries = nil\n\n\tif m.mainExpectation == nil {\n\t\tm.mainExpectation = &SignatureKeyHolderMockGetSignatureKeyMethodExpectation{}\n\t}\n\tm.mainExpectation.result = &SignatureKeyHolderMockGetSignatureKeyMethodResult{r}\n\treturn m.mock\n}", "func (f *Factory) Sign(name string, txBuilder sdk.TxBuilder) error {\n\tsignMode := f.signMode\n\tif signMode == signing.SignMode_SIGN_MODE_UNSPECIFIED {\n\t\t// use the SignModeHandler's default mode if unspecified\n\t\tsignMode = f.txConfig.SignModeHandler().DefaultMode()\n\t}\n\tsignerData := sdk.SignerData{\n\t\tChainID: f.chainID,\n\t\tAccountNumber: f.accountNumber,\n\t\tSequence: f.sequence,\n\t}\n\n\tpubkey, _, err := f.keyManager.Find(name, f.password)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// For SIGN_MODE_DIRECT, calling SetSignatures calls setSignerInfos on\n\t// Factory under the hood, and SignerInfos is needed to generated the\n\t// sign bytes. This is the reason for setting SetSignatures here, with a\n\t// nil signature.\n\t//\n\t// Note: this line is not needed for SIGN_MODE_LEGACY_AMINO, but putting it\n\t// also doesn't affect its generated sign bytes, so for code's simplicity\n\t// sake, we put it here.\n\tsigData := signing.SingleSignatureData{\n\t\tSignMode: signMode,\n\t\tSignature: nil,\n\t}\n\tsig := signing.SignatureV2{\n\t\tPubKey: pubkey,\n\t\tData: &sigData,\n\t\tSequence: f.Sequence(),\n\t}\n\tif err := txBuilder.SetSignatures(sig); err != nil {\n\t\treturn err\n\t}\n\n\t// Generate the bytes to be signed.\n\tsignBytes, err := f.signModeHandler.GetSignBytes(signMode, signerData, txBuilder.GetTx())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Sign those bytes\n\tsigBytes, _, err := f.keyManager.Sign(name, f.password, signBytes)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Construct the SignatureV2 struct\n\tsigData = signing.SingleSignatureData{\n\t\tSignMode: signMode,\n\t\tSignature: sigBytes,\n\t}\n\tsig = signing.SignatureV2{\n\t\tPubKey: pubkey,\n\t\tData: &sigData,\n\t\tSequence: f.Sequence(),\n\t}\n\n\t// And here the tx is populated with the signature\n\treturn txBuilder.SetSignatures(sig)\n}", "func TestService_Handle_Inviter(t *testing.T) {\n\tmockStore := &mockstorage.MockStore{Store: make(map[string]mockstorage.DBEntry)}\n\tstoreProv := mockstorage.NewCustomMockStoreProvider(mockStore)\n\tk := newKMS(t, storeProv)\n\tprov := &protocol.MockProvider{\n\t\tStoreProvider: storeProv,\n\t\tServiceMap: map[string]interface{}{\n\t\t\tmediator.Coordination: &mockroute.MockMediatorSvc{},\n\t\t},\n\t\tCustomKMS: k,\n\t\tKeyTypeValue: kms.ED25519Type,\n\t\tKeyAgreementTypeValue: kms.X25519ECDHKWType,\n\t}\n\n\tctx := &context{\n\t\toutboundDispatcher: prov.OutboundDispatcher(),\n\t\tcrypto: &tinkcrypto.Crypto{},\n\t\tkms: k,\n\t\tkeyType: kms.ED25519Type,\n\t\tkeyAgreementType: kms.X25519ECDHKWType,\n\t}\n\n\tverPubKey, encPubKey := newSigningAndEncryptionDIDKeys(t, ctx)\n\n\tctx.vdRegistry = &mockvdr.MockVDRegistry{CreateValue: createDIDDocWithKey(verPubKey, encPubKey)}\n\n\tconnRec, err := connection.NewRecorder(prov)\n\trequire.NoError(t, err)\n\trequire.NotNil(t, connRec)\n\n\tctx.connectionRecorder = connRec\n\n\tdoc, err := ctx.vdRegistry.Create(testMethod, nil)\n\trequire.NoError(t, err)\n\n\ts, err := New(prov)\n\trequire.NoError(t, err)\n\n\tactionCh := make(chan service.DIDCommAction, 10)\n\terr = s.RegisterActionEvent(actionCh)\n\trequire.NoError(t, err)\n\n\tstatusCh := make(chan service.StateMsg, 10)\n\terr = s.RegisterMsgEvent(statusCh)\n\trequire.NoError(t, err)\n\n\tcompletedFlag := make(chan struct{})\n\trespondedFlag := make(chan struct{})\n\n\tgo msgEventListener(t, statusCh, respondedFlag, completedFlag)\n\n\tgo func() { service.AutoExecuteActionEvent(actionCh) }()\n\n\tinvitation := &Invitation{\n\t\tType: InvitationMsgType,\n\t\tID: randomString(),\n\t\tLabel: \"Bob\",\n\t\tRecipientKeys: []string{verPubKey},\n\t\tServiceEndpoint: \"http://alice.agent.example.com:8081\",\n\t}\n\n\terr = ctx.connectionRecorder.SaveInvitation(invitation.ID, invitation)\n\trequire.NoError(t, err)\n\n\tthid := randomString()\n\n\t// Invitation was previously sent by Alice to Bob.\n\t// Bob now sends a did-exchange Invitation\n\tpayloadBytes, err := json.Marshal(\n\t\t&Request{\n\t\t\tType: RequestMsgType,\n\t\t\tID: thid,\n\t\t\tLabel: \"Bob\",\n\t\t\tThread: &decorator.Thread{\n\t\t\t\tPID: invitation.ID,\n\t\t\t},\n\t\t\tDID: doc.DIDDocument.ID,\n\t\t\tDocAttach: unsignedDocAttach(t, doc.DIDDocument),\n\t\t})\n\trequire.NoError(t, err)\n\tmsg, err := service.ParseDIDCommMsgMap(payloadBytes)\n\trequire.NoError(t, err)\n\t_, err = s.HandleInbound(msg, service.NewDIDCommContext(doc.DIDDocument.ID, \"\", nil))\n\trequire.NoError(t, err)\n\n\tselect {\n\tcase <-respondedFlag:\n\tcase <-time.After(2 * time.Second):\n\t\trequire.Fail(t, \"didn't receive post event responded\")\n\t}\n\t// Alice automatically sends exchange Response to Bob\n\t// Bob replies with an ACK\n\tpayloadBytes, err = json.Marshal(\n\t\t&model.Ack{\n\t\t\tType: AckMsgType,\n\t\t\tID: randomString(),\n\t\t\tStatus: \"OK\",\n\t\t\tThread: &decorator.Thread{ID: thid},\n\t\t})\n\trequire.NoError(t, err)\n\n\tdidMsg, err := service.ParseDIDCommMsgMap(payloadBytes)\n\trequire.NoError(t, err)\n\n\t_, err = s.HandleInbound(didMsg, service.NewDIDCommContext(doc.DIDDocument.ID, \"\", nil))\n\trequire.NoError(t, err)\n\n\tselect {\n\tcase <-completedFlag:\n\tcase <-time.After(2 * time.Second):\n\t\trequire.Fail(t, \"didn't receive post event complete\")\n\t}\n\n\tvalidateState(t, s, thid, findNamespace(AckMsgType), (&completed{}).Name())\n}", "func TestNewIdentityManager(t *testing.T) {\n\tt.Run(\"success\", func(t *testing.T) {\n\t\tepCfg := &mocks.EndpointConfig{}\n\t\tepCfg.NetworkConfigReturns(&fab.NetworkConfig{\n\t\t\tOrganizations: map[string]fab.OrganizationConfig{\"org1msp\": {}},\n\t\t})\n\n\t\tm, err := newIdentityManager(\"org1MSP\", &mocks.CryptoSuite{}, epCfg, \"./msp\")\n\t\trequire.NoError(t, err)\n\t\trequire.NotNil(t, m)\n\t})\n\n\tt.Run(\"No endpoint config -> error\", func(t *testing.T) {\n\t\tm, err := newIdentityManager(\"org1MSP\", &mocks.CryptoSuite{}, nil, \"./msp\")\n\t\trequire.EqualError(t, err, \"endpoint config is required\")\n\t\trequire.Nil(t, m)\n\t})\n\n\tt.Run(\"No org name -> error\", func(t *testing.T) {\n\t\tm, err := newIdentityManager(\"\", nil, &mocks.EndpointConfig{}, \"./msp\")\n\t\trequire.EqualError(t, err, \"orgName is required\")\n\t\trequire.Nil(t, m)\n\t})\n\n\tt.Run(\"No crypto suite -> error\", func(t *testing.T) {\n\t\tm, err := newIdentityManager(\"org1MSP\", nil, &mocks.EndpointConfig{}, \"./msp\")\n\t\trequire.EqualError(t, err, \"cryptoProvider is required\")\n\t\trequire.Nil(t, m)\n\t})\n\n\tt.Run(\"Org not found -> error\", func(t *testing.T) {\n\t\tepCfg := &mocks.EndpointConfig{}\n\t\tepCfg.NetworkConfigReturns(&fab.NetworkConfig{})\n\n\t\tm, err := newIdentityManager(\"org1MSP\", &mocks.CryptoSuite{}, epCfg, \"./msp\")\n\t\trequire.EqualError(t, err, \"org config retrieval failed\")\n\t\trequire.Nil(t, m)\n\t})\n\n\tt.Run(\"MSP config path not provided -> error\", func(t *testing.T) {\n\t\tepCfg := &mocks.EndpointConfig{}\n\t\tepCfg.NetworkConfigReturns(&fab.NetworkConfig{\n\t\t\tOrganizations: map[string]fab.OrganizationConfig{\"org1msp\": {}},\n\t\t})\n\n\t\tm, err := newIdentityManager(\"org1MSP\", &mocks.CryptoSuite{}, epCfg, \"\")\n\t\trequire.EqualError(t, err, \"either mspConfigPath or an embedded list of users is required\")\n\t\trequire.Nil(t, m)\n\t})\n}", "func NewSignatureKeyHolderMock(t minimock.Tester) *SignatureKeyHolderMock {\n\tm := &SignatureKeyHolderMock{t: t}\n\n\tif controller, ok := t.(minimock.MockController); ok {\n\t\tcontroller.RegisterMocker(m)\n\t}\n\n\tm.AsByteStringMock = mSignatureKeyHolderMockAsByteString{mock: m}\n\tm.AsBytesMock = mSignatureKeyHolderMockAsBytes{mock: m}\n\tm.EqualsMock = mSignatureKeyHolderMockEquals{mock: m}\n\tm.FixedByteSizeMock = mSignatureKeyHolderMockFixedByteSize{mock: m}\n\tm.FoldToUint64Mock = mSignatureKeyHolderMockFoldToUint64{mock: m}\n\tm.GetSignMethodMock = mSignatureKeyHolderMockGetSignMethod{mock: m}\n\tm.GetSignatureKeyMethodMock = mSignatureKeyHolderMockGetSignatureKeyMethod{mock: m}\n\tm.GetSignatureKeyTypeMock = mSignatureKeyHolderMockGetSignatureKeyType{mock: m}\n\tm.ReadMock = mSignatureKeyHolderMockRead{mock: m}\n\tm.WriteToMock = mSignatureKeyHolderMockWriteTo{mock: m}\n\n\treturn m\n}", "func (m *MockSigner) Sign(arg0 *ecdsa.PrivateKey, arg1 proto0.Message) (*proto.Signature, error) {\n\tret := m.ctrl.Call(m, \"Sign\", arg0, arg1)\n\tret0, _ := ret[0].(*proto.Signature)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (mmSignWith *mDigestHolderMockSignWith) Expect(signer DigestSigner) *mDigestHolderMockSignWith {\n\tif mmSignWith.mock.funcSignWith != nil {\n\t\tmmSignWith.mock.t.Fatalf(\"DigestHolderMock.SignWith mock is already set by Set\")\n\t}\n\n\tif mmSignWith.defaultExpectation == nil {\n\t\tmmSignWith.defaultExpectation = &DigestHolderMockSignWithExpectation{}\n\t}\n\n\tmmSignWith.defaultExpectation.params = &DigestHolderMockSignWithParams{signer}\n\tfor _, e := range mmSignWith.expectations {\n\t\tif minimock.Equal(e.params, mmSignWith.defaultExpectation.params) {\n\t\t\tmmSignWith.mock.t.Fatalf(\"Expectation set by When has same params: %#v\", *mmSignWith.defaultExpectation.params)\n\t\t}\n\t}\n\n\treturn mmSignWith\n}", "func TestDelegatorProxyValidatorShares7Steps(t *testing.T) {\n\n}", "func (m *mSignatureKeyHolderMockGetSignMethod) Return(r SignMethod) *SignatureKeyHolderMock {\n\tm.mock.GetSignMethodFunc = nil\n\tm.expectationSeries = nil\n\n\tif m.mainExpectation == nil {\n\t\tm.mainExpectation = &SignatureKeyHolderMockGetSignMethodExpectation{}\n\t}\n\tm.mainExpectation.result = &SignatureKeyHolderMockGetSignMethodResult{r}\n\treturn m.mock\n}", "func NewCryptographyServiceMock(t minimock.Tester) *CryptographyServiceMock {\n\tm := &CryptographyServiceMock{t: t}\n\n\tif controller, ok := t.(minimock.MockController); ok {\n\t\tcontroller.RegisterMocker(m)\n\t}\n\n\tm.GetPublicKeyMock = mCryptographyServiceMockGetPublicKey{mock: m}\n\tm.SignMock = mCryptographyServiceMockSign{mock: m}\n\tm.VerifyMock = mCryptographyServiceMockVerify{mock: m}\n\n\treturn m\n}", "func (m *mActiveNodeMockGetSignatureVerifier) Set(f func() (r cryptkit.SignatureVerifier)) *ActiveNodeMock {\n\tm.mainExpectation = nil\n\tm.expectationSeries = nil\n\n\tm.mock.GetSignatureVerifierFunc = f\n\treturn m.mock\n}", "func (mmGetPacketSignature *mPacketParserMockGetPacketSignature) Set(f func() (s1 cryptkit.SignedDigest)) *PacketParserMock {\n\tif mmGetPacketSignature.defaultExpectation != nil {\n\t\tmmGetPacketSignature.mock.t.Fatalf(\"Default expectation is already set for the PacketParser.GetPacketSignature method\")\n\t}\n\n\tif len(mmGetPacketSignature.expectations) > 0 {\n\t\tmmGetPacketSignature.mock.t.Fatalf(\"Some expectations are already set for the PacketParser.GetPacketSignature method\")\n\t}\n\n\tmmGetPacketSignature.mock.funcGetPacketSignature = f\n\treturn mmGetPacketSignature.mock\n}", "func NewMockSigner(ctrl *gomock.Controller) *MockSigner {\n\tmock := &MockSigner{ctrl: ctrl}\n\tmock.recorder = &MockSignerMockRecorder{mock}\n\treturn mock\n}", "func (m *MockSignerDecrypter) Sign(arg0 io.Reader, arg1 []byte, arg2 crypto.SignerOpts) ([]byte, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Sign\", arg0, arg1, arg2)\n\tret0, _ := ret[0].([]byte)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func newKeyServerWithMocking(user upspin.UserName, ref string, data []byte) (*server, *storagetest.ExpectDownloadCapturePut) {\n\tmockGCP := &storagetest.ExpectDownloadCapturePut{\n\t\tRef: []string{ref},\n\t\tData: [][]byte{data},\n\t\tPutContents: make([][]byte, 0, 1),\n\t\tPutRef: make([]string, 0, 1),\n\t}\n\ts := &server{\n\t\tstorage: mockGCP,\n\t\tuser: user,\n\t\tlookupTXT: mockLookupTXT,\n\t\tlogger: &noopLogger{},\n\t\tcache: cache.NewLRU(10),\n\t\tnegCache: cache.NewLRU(10),\n\t}\n\treturn s, mockGCP\n}", "func NewSignedMessageForTestGetter(ms MockSigner) func(uint64) *types.SignedMessage {\n\ti := 0\n\treturn func(nonce uint64) *types.SignedMessage {\n\t\ts := fmt.Sprintf(\"smsg%d\", i)\n\t\ti++\n\t\tnewAddr, err := address.NewSecp256k1Address([]byte(s + \"-to\"))\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tmsg := NewMeteredMessage(\n\t\t\tms.Addresses[0], // from needs to be an address from the signer\n\t\t\tnewAddr,\n\t\t\tnonce,\n\t\t\ttypes.ZeroFIL,\n\t\t\t0,\n\t\t\t[]byte(\"params\"),\n\t\t\ttypes.ZeroFIL,\n\t\t\ttypes.ZeroFIL,\n\t\t\t0,\n\t\t)\n\t\tsmsg, err := NewSignedMessage(context.TODO(), *msg, &ms)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\treturn smsg\n\t}\n}", "func NewMockSignersAndKeyInfo(numSigners int) (MockSigner, []KeyInfo) {\n\tki := MustGenerateKeyInfo(numSigners, 42)\n\tsigner := NewMockSigner(ki)\n\treturn signer, ki\n}", "func (mmGetPacketSignature *mPacketParserMockGetPacketSignature) Return(s1 cryptkit.SignedDigest) *PacketParserMock {\n\tif mmGetPacketSignature.mock.funcGetPacketSignature != nil {\n\t\tmmGetPacketSignature.mock.t.Fatalf(\"PacketParserMock.GetPacketSignature mock is already set by Set\")\n\t}\n\n\tif mmGetPacketSignature.defaultExpectation == nil {\n\t\tmmGetPacketSignature.defaultExpectation = &PacketParserMockGetPacketSignatureExpectation{mock: mmGetPacketSignature.mock}\n\t}\n\tmmGetPacketSignature.defaultExpectation.results = &PacketParserMockGetPacketSignatureResults{s1}\n\treturn mmGetPacketSignature.mock\n}", "func (m *SignatureKeyHolderMock) Equals(p SignatureKeyHolder) (r bool) {\n\tcounter := atomic.AddUint64(&m.EqualsPreCounter, 1)\n\tdefer atomic.AddUint64(&m.EqualsCounter, 1)\n\n\tif len(m.EqualsMock.expectationSeries) > 0 {\n\t\tif counter > uint64(len(m.EqualsMock.expectationSeries)) {\n\t\t\tm.t.Fatalf(\"Unexpected call to SignatureKeyHolderMock.Equals. %v\", p)\n\t\t\treturn\n\t\t}\n\n\t\tinput := m.EqualsMock.expectationSeries[counter-1].input\n\t\ttestify_assert.Equal(m.t, *input, SignatureKeyHolderMockEqualsInput{p}, \"SignatureKeyHolder.Equals got unexpected parameters\")\n\n\t\tresult := m.EqualsMock.expectationSeries[counter-1].result\n\t\tif result == nil {\n\t\t\tm.t.Fatal(\"No results are set for the SignatureKeyHolderMock.Equals\")\n\t\t\treturn\n\t\t}\n\n\t\tr = result.r\n\n\t\treturn\n\t}\n\n\tif m.EqualsMock.mainExpectation != nil {\n\n\t\tinput := m.EqualsMock.mainExpectation.input\n\t\tif input != nil {\n\t\t\ttestify_assert.Equal(m.t, *input, SignatureKeyHolderMockEqualsInput{p}, \"SignatureKeyHolder.Equals got unexpected parameters\")\n\t\t}\n\n\t\tresult := m.EqualsMock.mainExpectation.result\n\t\tif result == nil {\n\t\t\tm.t.Fatal(\"No results are set for the SignatureKeyHolderMock.Equals\")\n\t\t}\n\n\t\tr = result.r\n\n\t\treturn\n\t}\n\n\tif m.EqualsFunc == nil {\n\t\tm.t.Fatalf(\"Unexpected call to SignatureKeyHolderMock.Equals. %v\", p)\n\t\treturn\n\t}\n\n\treturn m.EqualsFunc(p)\n}", "func NewSysProbeUtil(t interface {\n\tmock.TestingT\n\tCleanup(func())\n}) *SysProbeUtil {\n\tmock := &SysProbeUtil{}\n\tmock.Mock.Test(t)\n\n\tt.Cleanup(func() { mock.AssertExpectations(t) })\n\n\treturn mock\n}", "func (m *mCryptographyServiceMockVerify) Set(f func(p crypto.PublicKey, p1 insolar.Signature, p2 []byte) (r bool)) *CryptographyServiceMock {\n\tm.mainExpectation = nil\n\tm.expectationSeries = nil\n\n\tm.mock.VerifyFunc = f\n\treturn m.mock\n}", "func (m *mSignatureKeyHolderMockEquals) Set(f func(p SignatureKeyHolder) (r bool)) *SignatureKeyHolderMock {\n\tm.mainExpectation = nil\n\tm.expectationSeries = nil\n\n\tm.mock.EqualsFunc = f\n\treturn m.mock\n}", "func TestTokenSignature(t *testing.T) {\n\tdb.InitDB()\n\tvar router *gin.Engine = routes.SetupRouter()\n\n\tvar user models.UserCreate = utils.CreateUser(\"Tom\", \"qwerty1234\", t, router)\n\tuser.Token = utils.ConnectUser(\"Tom\", \"qwerty1234\", t, router)\n\n\tsplittedToken := strings.Split(user.Token, \".\")\n\tif len(splittedToken) != 3 {\n\t\tlog.Fatal(\"Bad token.\")\n\t\tt.Fail()\n\t}\n\n\theader := splittedToken[0]\n\tpayload := splittedToken[1]\n\tsignature := splittedToken[2]\n\tsignature = signature + \"modif\"\n\tmodifiedToken := header + \".\" + payload + \".\" + signature\n\n\tvar url string = \"/v1/user/\" + strconv.Itoa(user.ID)\n\tvar bearer = \"Bearer \" + modifiedToken\n\trecord := httptest.NewRecorder()\n\trequest, _ := http.NewRequest(\"GET\", url, nil)\n\trequest.Header.Add(\"Content-Type\", \"application/json\")\n\trequest.Header.Add(\"Authorization\", bearer)\n\n\trouter.ServeHTTP(record, request)\n\n\tvar message Message\n\terr := json.Unmarshal([]byte(record.Body.String()), &message)\n\tif err != nil {\n\t\tlog.Fatal(\"Bad output: \", err.Error())\n\t\tt.Fail()\n\t}\n\n\tassert.Equal(t, record.Code, 403)\n\tassert.Equal(t, message.Message, \"Bad signature\")\n\n\tuser.Token = utils.ConnectUser(\"Tom\", \"qwerty1234\", t, router)\n\tutils.CleanUser(user.ID, user.Token, t, router)\n\tdb.CloseDB()\n}", "func newMockKvCapabilityVerifier(t mockConstructorTestingTnewMockKvCapabilityVerifier) *mockKvCapabilityVerifier {\n\tmock := &mockKvCapabilityVerifier{}\n\tmock.Mock.Test(t)\n\n\tt.Cleanup(func() { mock.AssertExpectations(t) })\n\n\treturn mock\n}", "func NewTranslationKeyStore(t mockConstructorTestingTNewTranslationKeyStore) *TranslationKeyStore {\n\tmock := &TranslationKeyStore{}\n\tmock.Mock.Test(t)\n\n\tt.Cleanup(func() { mock.AssertExpectations(t) })\n\n\treturn mock\n}", "func (_m *Keychain) Sign(_a0 []byte) ([]byte, error) {\n\tret := _m.Called(_a0)\n\n\tvar r0 []byte\n\tif rf, ok := ret.Get(0).(func([]byte) []byte); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).([]byte)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func([]byte) error); ok {\n\t\tr1 = rf(_a0)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (m *mSignatureKeyHolderMockGetSignMethod) Expect() *mSignatureKeyHolderMockGetSignMethod {\n\tm.mock.GetSignMethodFunc = nil\n\tm.expectationSeries = nil\n\n\tif m.mainExpectation == nil {\n\t\tm.mainExpectation = &SignatureKeyHolderMockGetSignMethodExpectation{}\n\t}\n\n\treturn m\n}", "func NewMockKeystore(auth *communications.Headers, logger log.Logger) definitions.Keystore {\n\ts := new(inmemKeystore)\n\ts.headers = auth\n\treturn s\n}", "func (m *mActiveNodeMockGetSignatureVerifier) Return(r cryptkit.SignatureVerifier) *ActiveNodeMock {\n\tm.mock.GetSignatureVerifierFunc = nil\n\tm.expectationSeries = nil\n\n\tif m.mainExpectation == nil {\n\t\tm.mainExpectation = &ActiveNodeMockGetSignatureVerifierExpectation{}\n\t}\n\tm.mainExpectation.result = &ActiveNodeMockGetSignatureVerifierResult{r}\n\treturn m.mock\n}", "func (_m *mockSigningKeyGetter) flushCachedSigningKeys(issuer string) error {\n\tret := _m.Called(issuer)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(string) error); ok {\n\t\tr0 = rf(issuer)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (mr *MockClientMockRecorder) SigningManager() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"SigningManager\", reflect.TypeOf((*MockClient)(nil).SigningManager))\n}", "func (m *MockFullNode) WalletSign(arg0 context.Context, arg1 address.Address, arg2 []byte, arg3 types0.MsgMeta) (*crypto.Signature, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"WalletSign\", arg0, arg1, arg2, arg3)\n\tret0, _ := ret[0].(*crypto.Signature)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (s *ServiceSuite) TestMacaroonPaperFig6FailsWithBindingOnTamperedSignature(c *gc.C) {\n\tlocator := bakery.NewThirdPartyStore()\n\tas := newBakery(\"as-loc\", locator)\n\tts := newBakery(\"ts-loc\", locator)\n\tfs := newBakery(\"fs-loc\", locator)\n\n\t// ts creates a macaroon.\n\ttsMacaroon, err := ts.Oven.NewMacaroon(testContext, bakery.LatestVersion, ages, nil, bakery.LoginOp)\n\tc.Assert(err, gc.IsNil)\n\n\t// ts somehow sends the macaroon to fs which adds a third party caveat to be discharged by as.\n\terr = fs.Oven.AddCaveat(testContext, tsMacaroon, checkers.Caveat{Location: \"as-loc\", Condition: \"user==bob\"})\n\tc.Assert(err, gc.IsNil)\n\n\t// client asks for a discharge macaroon for each third party caveat\n\td, err := bakery.DischargeAll(testContext, tsMacaroon, func(ctx context.Context, cav macaroon.Caveat, payload []byte) (*bakery.Macaroon, error) {\n\t\tc.Assert(cav.Location, gc.Equals, \"as-loc\")\n\t\treturn discharge(ctx, as.Oven, thirdPartyStrcmpChecker(\"user==bob\"), cav, payload)\n\t})\n\tc.Assert(err, gc.IsNil)\n\n\t// client has all the discharge macaroons. For each discharge macaroon bind it to our tsMacaroon\n\t// and add it to our request.\n\tfor _, dm := range d[1:] {\n\t\tdm.Bind([]byte(\"tampered-signature\")) // Bind against an incorrect signature.\n\t}\n\n\t// client makes request to ts.\n\t_, err = ts.Checker.Auth(d).Allow(testContext, bakery.LoginOp)\n\t// TODO fix this error message.\n\tc.Assert(err, gc.ErrorMatches, \"verification failed: signature mismatch after caveat verification\")\n}", "func (m *SignatureKeyHolderMock) MinimockFinish() {\n\n\tif !m.AsByteStringFinished() {\n\t\tm.t.Fatal(\"Expected call to SignatureKeyHolderMock.AsByteString\")\n\t}\n\n\tif !m.AsBytesFinished() {\n\t\tm.t.Fatal(\"Expected call to SignatureKeyHolderMock.AsBytes\")\n\t}\n\n\tif !m.EqualsFinished() {\n\t\tm.t.Fatal(\"Expected call to SignatureKeyHolderMock.Equals\")\n\t}\n\n\tif !m.FixedByteSizeFinished() {\n\t\tm.t.Fatal(\"Expected call to SignatureKeyHolderMock.FixedByteSize\")\n\t}\n\n\tif !m.FoldToUint64Finished() {\n\t\tm.t.Fatal(\"Expected call to SignatureKeyHolderMock.FoldToUint64\")\n\t}\n\n\tif !m.GetSignMethodFinished() {\n\t\tm.t.Fatal(\"Expected call to SignatureKeyHolderMock.GetSignMethod\")\n\t}\n\n\tif !m.GetSignatureKeyMethodFinished() {\n\t\tm.t.Fatal(\"Expected call to SignatureKeyHolderMock.GetSignatureKeyMethod\")\n\t}\n\n\tif !m.GetSignatureKeyTypeFinished() {\n\t\tm.t.Fatal(\"Expected call to SignatureKeyHolderMock.GetSignatureKeyType\")\n\t}\n\n\tif !m.ReadFinished() {\n\t\tm.t.Fatal(\"Expected call to SignatureKeyHolderMock.Read\")\n\t}\n\n\tif !m.WriteToFinished() {\n\t\tm.t.Fatal(\"Expected call to SignatureKeyHolderMock.WriteTo\")\n\t}\n\n}", "func TestAuthenticatedRequest(t *testing.T) {\n\tvar e error\n\tprivateKey, e = readPrivateKey()\n\tif e != nil {\n\t\tpanic(e)\n\t}\n\tConvey(\"Simple authenticated requests\", t, func() {\n\t\tConvey(\"Authenticated GET to / path should return a 200 response\", func() {\n\t\t\tw := makeAuthenticatedRequest(\"GET\", \"/\", jwt.MapClaims{\"foo\": \"bar\"}, nil)\n\t\t\tSo(w.Code, ShouldEqual, http.StatusOK)\n\t\t})\n\t\tConvey(\"Authenticated GET to /protected path should return a 200 response if expected algorithm is not specified\", func() {\n\t\t\tvar expectedAlgorithm jwt.SigningMethod = nil\n\t\t\tw := makeAuthenticatedRequest(\"GET\", \"/protected\", jwt.MapClaims{\"foo\": \"bar\"}, expectedAlgorithm)\n\t\t\tSo(w.Code, ShouldEqual, http.StatusOK)\n\t\t\tresponseBytes, err := ioutil.ReadAll(w.Body)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\tresponseString := string(responseBytes)\n\t\t\t// check that the encoded data in the jwt was properly returned as json\n\t\t\tSo(responseString, ShouldEqual, `{\"text\":\"bar\"}`)\n\t\t})\n\t\tConvey(\"Authenticated GET to /protected path should return a 200 response if expected algorithm is correct\", func() {\n\t\t\texpectedAlgorithm := jwt.SigningMethodHS256\n\t\t\tw := makeAuthenticatedRequest(\"GET\", \"/protected\", jwt.MapClaims{\"foo\": \"bar\"}, expectedAlgorithm)\n\t\t\tSo(w.Code, ShouldEqual, http.StatusOK)\n\t\t\tresponseBytes, err := ioutil.ReadAll(w.Body)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\tresponseString := string(responseBytes)\n\t\t\t// check that the encoded data in the jwt was properly returned as json\n\t\t\tSo(responseString, ShouldEqual, `{\"text\":\"bar\"}`)\n\t\t})\n\t\tConvey(\"Authenticated GET to /protected path should return a 401 response if algorithm is not expected one\", func() {\n\t\t\texpectedAlgorithm := jwt.SigningMethodRS256\n\t\t\tw := makeAuthenticatedRequest(\"GET\", \"/protected\", jwt.MapClaims{\"foo\": \"bar\"}, expectedAlgorithm)\n\t\t\tSo(w.Code, ShouldEqual, http.StatusUnauthorized)\n\t\t\tresponseBytes, err := ioutil.ReadAll(w.Body)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\tresponseString := string(responseBytes)\n\t\t\t// check that the encoded data in the jwt was properly returned as json\n\t\t\tSo(strings.TrimSpace(responseString), ShouldEqual, \"Expected RS256 signing method but token specified HS256\")\n\t\t})\n\t})\n}", "func (e *DigestHolderMockSignWithExpectation) Then(s1 SignedDigestHolder) *DigestHolderMock {\n\te.results = &DigestHolderMockSignWithResults{s1}\n\treturn e.mock\n}", "func (_m *mockSigningKeyGetter) getSigningKey(r *http.Request, issuer string, kid string) ([]byte, error) {\n\tret := _m.Called(r, issuer, kid)\n\n\tvar r0 []byte\n\tif rf, ok := ret.Get(0).(func(*http.Request, string, string) []byte); ok {\n\t\tr0 = rf(r, issuer, kid)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).([]byte)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(*http.Request, string, string) error); ok {\n\t\tr1 = rf(r, issuer, kid)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func TestWorkloadAgentGenerateSecretFromFile(t *testing.T) {\n\tfakeCACli, err := mock.NewMockCAClient(0, time.Hour)\n\tif err != nil {\n\t\tt.Fatalf(\"Error creating Mock CA client: %v\", err)\n\t}\n\topt := Options{\n\t\tRotationInterval: 200 * time.Millisecond,\n\t\tEvictionDuration: 0,\n\t}\n\n\tfetcher := &secretfetcher.SecretFetcher{\n\t\tUseCaClient: true,\n\t\tCaClient: fakeCACli,\n\t}\n\n\tvar wgAddedWatch sync.WaitGroup\n\tvar notifyEvent sync.WaitGroup\n\n\taddedWatchProbe := func(_ string, _ bool) { wgAddedWatch.Done() }\n\n\tvar closed bool\n\tnotifyCallback := func(_ ConnKey, _ *model.SecretItem) error {\n\t\tif !closed {\n\t\t\tnotifyEvent.Done()\n\t\t}\n\t\treturn nil\n\t}\n\n\t// Supply a fake watcher so that we can watch file events.\n\tvar fakeWatcher *filewatcher.FakeWatcher\n\tnewFileWatcher, fakeWatcher = filewatcher.NewFakeWatcher(addedWatchProbe)\n\n\tsc := NewSecretCache(fetcher, notifyCallback, opt)\n\tdefer func() {\n\t\tclosed = true\n\t\tsc.Close()\n\t\tnewFileWatcher = filewatcher.NewWatcher\n\t}()\n\n\trootCertPath := \"./testdata/root-cert.pem\"\n\tkeyPath := \"./testdata/key.pem\"\n\tcertChainPath := \"./testdata/cert-chain.pem\"\n\tsc.existingRootCertFile = rootCertPath\n\tsc.existingKeyFile = keyPath\n\tsc.existingCertChainFile = certChainPath\n\tcertchain, err := ioutil.ReadFile(certChainPath)\n\tif err != nil {\n\t\tt.Fatalf(\"Error reading the cert chain file: %v\", err)\n\t}\n\tprivateKey, err := ioutil.ReadFile(keyPath)\n\tif err != nil {\n\t\tt.Fatalf(\"Error reading the private key file: %v\", err)\n\t}\n\trootCert, err := ioutil.ReadFile(rootCertPath)\n\tif err != nil {\n\t\tt.Fatalf(\"Error reading the root cert file: %v\", err)\n\t}\n\n\tconID := \"proxy1-id\"\n\tctx := context.Background()\n\n\twgAddedWatch.Add(1) // Watch should be added for cert file.\n\tnotifyEvent.Add(1) // Nofify should be called once.\n\n\tgotSecret, err := sc.GenerateSecret(ctx, conID, WorkloadKeyCertResourceName, \"jwtToken1\")\n\n\twgAddedWatch.Wait()\n\tnotifyEvent.Wait()\n\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to get secrets: %v\", err)\n\t}\n\tcheckBool(t, \"SecretExist\", sc.SecretExist(conID, WorkloadKeyCertResourceName, \"jwtToken1\", gotSecret.Version), true)\n\texpectedSecret := &model.SecretItem{\n\t\tResourceName: WorkloadKeyCertResourceName,\n\t\tCertificateChain: certchain,\n\t\tPrivateKey: privateKey,\n\t}\n\tif err := verifySecret(gotSecret, expectedSecret); err != nil {\n\t\tt.Errorf(\"Secret verification failed: %v\", err)\n\t}\n\n\twgAddedWatch.Add(1) // Watch should be added for root file.\n\tnotifyEvent.Add(1) // Notify should be called once.\n\n\tgotSecretRoot, err := sc.GenerateSecret(ctx, conID, RootCertReqResourceName, \"jwtToken1\")\n\n\twgAddedWatch.Wait()\n\tnotifyEvent.Wait()\n\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to get secrets: %v\", err)\n\t}\n\tcheckBool(t, \"SecretExist\", sc.SecretExist(conID, RootCertReqResourceName, \"jwtToken1\", gotSecretRoot.Version), true)\n\tif got, want := atomic.LoadUint64(&sc.rootCertChangedCount), uint64(0); got != want {\n\t\tt.Errorf(\"rootCertChangedCount: got: %v, want: %v\", got, want)\n\t}\n\n\trootExpiration, err := nodeagentutil.ParseCertAndGetExpiryTimestamp(rootCert)\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to get the expiration time from the existing root file\")\n\t}\n\texpectedSecret = &model.SecretItem{\n\t\tResourceName: RootCertReqResourceName,\n\t\tRootCert: rootCert,\n\t\tExpireTime: rootExpiration,\n\t}\n\tif err := verifyRootCASecret(gotSecretRoot, expectedSecret); err != nil {\n\t\tt.Errorf(\"Secret verification failed: %v\", err)\n\t}\n\n\tkey := ConnKey{\n\t\tConnectionID: conID,\n\t\tResourceName: WorkloadKeyCertResourceName,\n\t}\n\tcachedSecret, found := sc.secrets.Load(key)\n\tif !found {\n\t\tt.Errorf(\"Failed to find secret for proxy %q from secret store: %v\", conID, err)\n\t}\n\tif !reflect.DeepEqual(*gotSecret, cachedSecret) {\n\t\tt.Errorf(\"Secret key: got %+v, want %+v\", *gotSecret, cachedSecret)\n\t}\n\n\t// Inject a file write event and validate that Notify is called.\n\tnotifyEvent.Add(1)\n\tfakeWatcher.InjectEvent(certChainPath, fsnotify.Event{\n\t\tName: certChainPath,\n\t\tOp: fsnotify.Write,\n\t})\n\tnotifyEvent.Wait()\n}", "func (m *MockManager) SerializeContentSHA(arg0 string) error {\n\tret := m.ctrl.Call(m, \"SerializeContentSHA\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func TestSenderRequest_Verify(t *testing.T) {\r\n\r\n\t// Create key\r\n\tkey, err := bitcoin.CreatePrivateKeyString()\r\n\tassert.NoError(t, err)\r\n\tassert.NotNil(t, key)\r\n\r\n\t// Create the request / message\r\n\tsenderRequest := &SenderRequest{\r\n\t\tDt: time.Now().UTC().Format(time.RFC3339),\r\n\t\tSenderHandle: testAlias + \"@\" + testDomain,\r\n\t\tSenderName: testName,\r\n\t\tPurpose: testMessage,\r\n\t}\r\n\r\n\t// Sign\r\n\tvar signature string\r\n\tsignature, err = senderRequest.Sign(key)\r\n\tassert.NoError(t, err)\r\n\tassert.NotEqual(t, 0, len(signature))\r\n\r\n\t// Get address from private key\r\n\tvar address string\r\n\taddress, err = bitcoin.GetAddressFromPrivateKeyString(key, false)\r\n\tassert.NoError(t, err)\r\n\tassert.NotNil(t, address)\r\n\r\n\tt.Run(\"valid verification\", func(t *testing.T) {\r\n\t\terr = senderRequest.Verify(address, signature)\r\n\t\tassert.NoError(t, err)\r\n\t})\r\n\r\n\tt.Run(\"invalid - empty address\", func(t *testing.T) {\r\n\t\terr = senderRequest.Verify(\"\", signature)\r\n\t\tassert.Error(t, err)\r\n\t})\r\n\r\n\tt.Run(\"invalid - empty signature\", func(t *testing.T) {\r\n\t\terr = senderRequest.Verify(address, \"\")\r\n\t\tassert.Error(t, err)\r\n\t})\r\n\r\n\tt.Run(\"invalid - wrong signature - hex short\", func(t *testing.T) {\r\n\t\terr = senderRequest.Verify(address, \"0\")\r\n\t\tassert.Error(t, err)\r\n\t})\r\n\r\n\tt.Run(\"invalid - wrong signature\", func(t *testing.T) {\r\n\t\terr = senderRequest.Verify(address, \"73646661736466736466617364667364666173646673646661736466\")\r\n\t\tassert.Error(t, err)\r\n\t})\r\n}", "func (s) TestDistributor(t *testing.T) {\n\tdist := NewDistributor()\n\n\t// Read cert/key files from testdata.\n\tkm, err := loadKeyMaterials()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\t// wantKM1 has both local and root certs.\n\twantKM1 := *km\n\t// wantKM2 has only local certs. Roots are nil-ed out.\n\twantKM2 := *km\n\twantKM2.Roots = nil\n\n\t// Create a goroutines which work in lockstep with the rest of the test.\n\t// This goroutine reads the key material from the distributor while the rest\n\t// of the test sets it.\n\tvar wg sync.WaitGroup\n\twg.Add(1)\n\terrCh := make(chan error)\n\tproceedCh := make(chan struct{})\n\tgo func() {\n\t\tdefer wg.Done()\n\n\t\t// The first call to KeyMaterial() should timeout because no key\n\t\t// material has been set on the distributor as yet.\n\t\tctx, cancel := context.WithTimeout(context.Background(), defaultTestTimeout/2)\n\t\tdefer cancel()\n\t\tif _, err := dist.KeyMaterial(ctx); err != context.DeadlineExceeded {\n\t\t\terrCh <- err\n\t\t\treturn\n\t\t}\n\t\tproceedCh <- struct{}{}\n\n\t\t// This call to KeyMaterial() should return the key material with both\n\t\t// the local certs and the root certs.\n\t\tctx, cancel = context.WithTimeout(context.Background(), defaultTestTimeout)\n\t\tdefer cancel()\n\t\tgotKM, err := dist.KeyMaterial(ctx)\n\t\tif err != nil {\n\t\t\terrCh <- err\n\t\t\treturn\n\t\t}\n\t\tif !reflect.DeepEqual(gotKM, &wantKM1) {\n\t\t\terrCh <- fmt.Errorf(\"provider.KeyMaterial() = %+v, want %+v\", gotKM, wantKM1)\n\t\t}\n\t\tproceedCh <- struct{}{}\n\n\t\t// This call to KeyMaterial() should eventually return key material with\n\t\t// only the local certs.\n\t\tctx, cancel = context.WithTimeout(context.Background(), defaultTestTimeout)\n\t\tdefer cancel()\n\t\tfor {\n\t\t\tgotKM, err := dist.KeyMaterial(ctx)\n\t\t\tif err != nil {\n\t\t\t\terrCh <- err\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif reflect.DeepEqual(gotKM, &wantKM2) {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tproceedCh <- struct{}{}\n\n\t\t// This call to KeyMaterial() should return nil key material and a\n\t\t// non-nil error.\n\t\tctx, cancel = context.WithTimeout(context.Background(), defaultTestTimeout)\n\t\tdefer cancel()\n\t\tfor {\n\t\t\tgotKM, err := dist.KeyMaterial(ctx)\n\t\t\tif gotKM == nil && err == errProviderTestInternal {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\t// If we have gotten any error other than\n\t\t\t\t// errProviderTestInternal, we should bail out.\n\t\t\t\terrCh <- err\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tproceedCh <- struct{}{}\n\n\t\t// This call to KeyMaterial() should eventually return errProviderClosed\n\t\t// error.\n\t\tctx, cancel = context.WithTimeout(context.Background(), defaultTestTimeout)\n\t\tdefer cancel()\n\t\tfor {\n\t\t\tif _, err := dist.KeyMaterial(ctx); err == errProviderClosed {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\ttime.Sleep(100 * time.Millisecond)\n\t\t}\n\t}()\n\n\twaitAndDo(t, proceedCh, errCh, func() {\n\t\tdist.Set(&wantKM1, nil)\n\t})\n\n\twaitAndDo(t, proceedCh, errCh, func() {\n\t\tdist.Set(&wantKM2, nil)\n\t})\n\n\twaitAndDo(t, proceedCh, errCh, func() {\n\t\tdist.Set(&wantKM2, errProviderTestInternal)\n\t})\n\n\twaitAndDo(t, proceedCh, errCh, func() {\n\t\tdist.Stop()\n\t})\n\n}", "func (m *SignatureKeyHolderMock) MinimockWait(timeout time.Duration) {\n\ttimeoutCh := time.After(timeout)\n\tfor {\n\t\tok := true\n\t\tok = ok && m.AsByteStringFinished()\n\t\tok = ok && m.AsBytesFinished()\n\t\tok = ok && m.EqualsFinished()\n\t\tok = ok && m.FixedByteSizeFinished()\n\t\tok = ok && m.FoldToUint64Finished()\n\t\tok = ok && m.GetSignMethodFinished()\n\t\tok = ok && m.GetSignatureKeyMethodFinished()\n\t\tok = ok && m.GetSignatureKeyTypeFinished()\n\t\tok = ok && m.ReadFinished()\n\t\tok = ok && m.WriteToFinished()\n\n\t\tif ok {\n\t\t\treturn\n\t\t}\n\n\t\tselect {\n\t\tcase <-timeoutCh:\n\n\t\t\tif !m.AsByteStringFinished() {\n\t\t\t\tm.t.Error(\"Expected call to SignatureKeyHolderMock.AsByteString\")\n\t\t\t}\n\n\t\t\tif !m.AsBytesFinished() {\n\t\t\t\tm.t.Error(\"Expected call to SignatureKeyHolderMock.AsBytes\")\n\t\t\t}\n\n\t\t\tif !m.EqualsFinished() {\n\t\t\t\tm.t.Error(\"Expected call to SignatureKeyHolderMock.Equals\")\n\t\t\t}\n\n\t\t\tif !m.FixedByteSizeFinished() {\n\t\t\t\tm.t.Error(\"Expected call to SignatureKeyHolderMock.FixedByteSize\")\n\t\t\t}\n\n\t\t\tif !m.FoldToUint64Finished() {\n\t\t\t\tm.t.Error(\"Expected call to SignatureKeyHolderMock.FoldToUint64\")\n\t\t\t}\n\n\t\t\tif !m.GetSignMethodFinished() {\n\t\t\t\tm.t.Error(\"Expected call to SignatureKeyHolderMock.GetSignMethod\")\n\t\t\t}\n\n\t\t\tif !m.GetSignatureKeyMethodFinished() {\n\t\t\t\tm.t.Error(\"Expected call to SignatureKeyHolderMock.GetSignatureKeyMethod\")\n\t\t\t}\n\n\t\t\tif !m.GetSignatureKeyTypeFinished() {\n\t\t\t\tm.t.Error(\"Expected call to SignatureKeyHolderMock.GetSignatureKeyType\")\n\t\t\t}\n\n\t\t\tif !m.ReadFinished() {\n\t\t\t\tm.t.Error(\"Expected call to SignatureKeyHolderMock.Read\")\n\t\t\t}\n\n\t\t\tif !m.WriteToFinished() {\n\t\t\t\tm.t.Error(\"Expected call to SignatureKeyHolderMock.WriteTo\")\n\t\t\t}\n\n\t\t\tm.t.Fatalf(\"Some mocks were not called on time: %s\", timeout)\n\t\t\treturn\n\t\tdefault:\n\t\t\ttime.Sleep(time.Millisecond)\n\t\t}\n\t}\n}", "func setupGovKeeper(t *testing.T, expectations ...func(sdk.Context, mocks)) (\n\t*keeper.Keeper,\n\tmocks,\n\tmoduletestutil.TestEncodingConfig,\n\tsdk.Context,\n) {\n\tt.Helper()\n\tkey := storetypes.NewKVStoreKey(types.StoreKey)\n\tstoreService := runtime.NewKVStoreService(key)\n\ttestCtx := testutil.DefaultContextWithDB(t, key, storetypes.NewTransientStoreKey(\"transient_test\"))\n\tctx := testCtx.Ctx.WithBlockHeader(cmtproto.Header{Time: cmttime.Now()})\n\tencCfg := moduletestutil.MakeTestEncodingConfig()\n\tv1.RegisterInterfaces(encCfg.InterfaceRegistry)\n\tv1beta1.RegisterInterfaces(encCfg.InterfaceRegistry)\n\tbanktypes.RegisterInterfaces(encCfg.InterfaceRegistry)\n\n\t// Create MsgServiceRouter, but don't populate it before creating the gov\n\t// keeper.\n\tmsr := baseapp.NewMsgServiceRouter()\n\n\t// gomock initializations\n\tctrl := gomock.NewController(t)\n\tm := mocks{\n\t\tacctKeeper: govtestutil.NewMockAccountKeeper(ctrl),\n\t\tbankKeeper: govtestutil.NewMockBankKeeper(ctrl),\n\t\tstakingKeeper: govtestutil.NewMockStakingKeeper(ctrl),\n\t\tdistributionKeeper: govtestutil.NewMockDistributionKeeper(ctrl),\n\t}\n\tif len(expectations) == 0 {\n\t\tmockDefaultExpectations(ctx, m)\n\t} else {\n\t\tfor _, exp := range expectations {\n\t\t\texp(ctx, m)\n\t\t}\n\t}\n\n\t// Gov keeper initializations\n\n\tgovKeeper := keeper.NewKeeper(encCfg.Codec, storeService, m.acctKeeper, m.bankKeeper, m.stakingKeeper, m.distributionKeeper, msr, types.DefaultConfig(), govAcct.String())\n\trequire.NoError(t, govKeeper.ProposalID.Set(ctx, 1))\n\tgovRouter := v1beta1.NewRouter() // Also register legacy gov handlers to test them too.\n\tgovRouter.AddRoute(types.RouterKey, v1beta1.ProposalHandler)\n\tgovKeeper.SetLegacyRouter(govRouter)\n\terr := govKeeper.Params.Set(ctx, v1.DefaultParams())\n\trequire.NoError(t, err)\n\terr = govKeeper.Constitution.Set(ctx, \"constitution\")\n\trequire.NoError(t, err)\n\n\t// Register all handlers for the MegServiceRouter.\n\tmsr.SetInterfaceRegistry(encCfg.InterfaceRegistry)\n\tv1.RegisterMsgServer(msr, keeper.NewMsgServerImpl(govKeeper))\n\tbanktypes.RegisterMsgServer(msr, nil) // Nil is fine here as long as we never execute the proposal's Msgs.\n\n\treturn govKeeper, m, encCfg, ctx\n}", "func (m *mCryptographyServiceMockVerify) Expect(p crypto.PublicKey, p1 insolar.Signature, p2 []byte) *mCryptographyServiceMockVerify {\n\tm.mock.VerifyFunc = nil\n\tm.expectationSeries = nil\n\n\tif m.mainExpectation == nil {\n\t\tm.mainExpectation = &CryptographyServiceMockVerifyExpectation{}\n\t}\n\tm.mainExpectation.input = &CryptographyServiceMockVerifyInput{p, p1, p2}\n\treturn m\n}", "func TestMissingSigningKey(t *testing.T) {\n\tf, _ := createNewSwizzler(t)\n\n\t// delete the snapshot, timestamp, and root keys\n\tnoKeys := []data.RoleName{\n\t\tdata.CanonicalSnapshotRole, data.CanonicalTimestampRole, data.CanonicalRootRole}\n\tfor _, role := range noKeys {\n\t\tk := f.CryptoService.ListKeys(role)\n\t\trequire.Len(t, k, 1)\n\t\trequire.NoError(t, f.CryptoService.RemoveKey(k[0]))\n\t}\n\n\t// these are all the functions that require re-signing\n\trequire.IsType(t, ErrNoKeyForRole{}, f.OffsetMetadataVersion(data.CanonicalSnapshotRole, 1))\n\trequire.IsType(t, ErrNoKeyForRole{}, f.ExpireMetadata(data.CanonicalSnapshotRole))\n\trequire.IsType(t, ErrNoKeyForRole{}, f.SetThreshold(data.CanonicalSnapshotRole, 2))\n\trequire.IsType(t, ErrNoKeyForRole{}, f.UpdateSnapshotHashes())\n\trequire.IsType(t, ErrNoKeyForRole{}, f.UpdateTimestampHash())\n}", "func (mr *MockProvidersMockRecorder) SigningManager() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"SigningManager\", reflect.TypeOf((*MockProviders)(nil).SigningManager))\n}", "func TestRootFromSignedCopiesSignatures(t *testing.T) {\n\tsigned, err := validRootTemplate().ToSigned()\n\trequire.NoError(t, err)\n\n\tsignedRoot, err := RootFromSigned(signed)\n\trequire.NoError(t, err)\n\n\tsigned.Signatures[0] = Signature{KeyID: \"key3\", Method: \"method3\", Signature: []byte(\"world\")}\n\n\trequire.Equal(t, \"key3\", signed.Signatures[0].KeyID)\n\trequire.Equal(t, \"key1\", signedRoot.Signatures[0].KeyID)\n}", "func (mt *mockTokenBuilder) SetKeyService(keyService string) {\n\t//TODO some mocking\n}", "func GenTestsForVerify(f *os.File) {\n\titems := []*verifyItem{\n\t\t{Keys: 1, Message: \"\"},\n\t\t{Keys: 1, Message: \"idena go\"},\n\t\t{Keys: 1, Message: \"long message: 9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999\"},\n\t\t{Keys: 2, Message: \"2 keys 1\"},\n\t\t{Keys: 2, Message: \"2 keys 2\"},\n\t\t{Keys: 3, Message: \"3 keys\"},\n\t\t{Keys: 4, Message: \"4 keys\"},\n\t\t{Keys: 10, Message: \"10 keys\"},\n\t\t{Keys: 100, Message: \"100 keys\"},\n\t\t{Keys: 356, Message: \"356 keys\"},\n\t\t{Keys: 800, Message: \"800 keys\"},\n\t\t{Keys: 1024, Message: \"1024 keys\"},\n\t\t{Keys: 2048, Message: \"2048 keys\"},\n\t\t{Keys: 4000, Message: \"4000 keys\"},\n\t\t{Keys: 6000, Message: \"4000 keys\"},\n\t\t{Keys: 9000, Message: \"9000 keys\"},\n\t\t{Keys: 10000, Message: \"10000 keys\"},\n\t}\n\tpriKeys := make([]*bls.PriKey, 0)\n\tpubKeys1 := make([]*bls.PubKey1, 0)\n\tpubKeys2 := make([]*bls.PubKey2, 0)\n\tfor i, item := range items {\n\t\tfmt.Printf(\"generating %v: keys=%v, message=%v\\n\", i+1, item.Keys, item.Message)\n\t\t// prepare keys\n\t\tfor i := len(priKeys); i < item.Keys; i++ {\n\t\t\tk, _ := bls.NewPriKey(nil)\n\t\t\tpriKeys = append(priKeys, k)\n\t\t\tpubKeys1, pubKeys2 = append(pubKeys1, k.GetPub1()), append(pubKeys2, k.GetPub2())\n\t\t}\n\t\tsigs := make([]*bls.Signature, item.Keys)\n\t\tfor i := 0; i < item.Keys; i++ {\n\t\t\tsigs[i] = priKeys[i].Sign([]byte(item.Message))\n\t\t}\n\t\tasig := bls.AggregateSignatures(sigs)\n\t\titem.Signature = asig.ToHex()\n\t\tapk1 := bls.AggregatePubKeys1(pubKeys1[:item.Keys])\n\t\titem.Apk1 = apk1.ToHex()\n\t\tapk2 := bls.AggregatePubKeys2(pubKeys2[:item.Keys])\n\t\titem.Apk2 = apk2.ToHex()\n\t}\n\ts, _ := json.MarshalIndent(items, \"\", \" \")\n\t_, _ = f.Write(s)\n\tfmt.Printf(\"\\n> Data has written to %v\\n\", f.Name())\n}", "func (m *MockisCryptoAsymApiReqSetupPrivateKeyEx_Key) isCryptoAsymApiReqSetupPrivateKeyEx_Key() {\n\tm.ctrl.Call(m, \"isCryptoAsymApiReqSetupPrivateKeyEx_Key\")\n}", "func (m *mSignatureKeyHolderMockGetSignatureKeyMethod) Expect() *mSignatureKeyHolderMockGetSignatureKeyMethod {\n\tm.mock.GetSignatureKeyMethodFunc = nil\n\tm.expectationSeries = nil\n\n\tif m.mainExpectation == nil {\n\t\tm.mainExpectation = &SignatureKeyHolderMockGetSignatureKeyMethodExpectation{}\n\t}\n\n\treturn m\n}", "func TestSlashValidatorAtCurrentHeightWithSlashingProtection(t *testing.T) {\n\t// use disr types module name to withdraw the reward without errors and\n\tmoduleDelegatorName := distrtypes.ModuleName\n\n\tapp, ctx, _, _ := bootstrapSlashTest(t, 10)\n\tapp.StakingKeeper.SetSlashingProtestedModules(func() map[string]struct{} {\n\t\treturn map[string]struct{}{\n\t\t\tmoduleDelegatorName: {},\n\t\t}\n\t})\n\tapp.StakingKeeper.SetHooks(types.NewMultiStakingHooks(app.DistrKeeper.Hooks()))\n\n\tvalBondTokens := app.StakingKeeper.TokensFromConsensusPower(ctx, 10)\n\tvalReward := app.StakingKeeper.TokensFromConsensusPower(ctx, 1).ToDec()\n\tdelBondTokens := app.StakingKeeper.TokensFromConsensusPower(ctx, 2)\n\tdelProtectedBondTokens := app.StakingKeeper.TokensFromConsensusPower(ctx, 4)\n\tdelProtectedExpectedReward := app.StakingKeeper.TokensFromConsensusPower(ctx, 875).QuoRaw(1000) // 0.875\n\ttotalDelegation := valBondTokens.Add(delBondTokens).Add(delProtectedBondTokens)\n\n\tfraction := sdk.NewDecWithPrec(5, 1)\n\n\t// generate delegator account\n\tdelAddr := simapp.AddTestAddrs(app, ctx, 1, delBondTokens)[0]\n\t// generate protected delegator account\n\terr := app.BankKeeper.SendCoinsFromAccountToModule(ctx, simapp.AddTestAddrs(app, ctx, 1, delProtectedBondTokens)[0],\n\t\tmoduleDelegatorName, sdk.NewCoins(sdk.NewCoin(app.StakingKeeper.BondDenom(ctx), delProtectedBondTokens)))\n\trequire.NoError(t, err)\n\tdelProtectedAddr := app.AccountKeeper.GetModuleAddress(moduleDelegatorName)\n\n\t// get already created validator\n\tvaConsAddr := sdk.ConsAddress(PKs[0].Address())\n\t// delegate from normal account\n\tval, found := app.StakingKeeper.GetValidatorByConsAddr(ctx, vaConsAddr)\n\trequire.True(t, found)\n\t// call this function here to init the validator in the distribution module\n\tapp.StakingKeeper.AfterValidatorCreated(ctx, val.GetOperator())\n\n\t// delegate from normal account\n\tdelShares := delegate(t, app, ctx, vaConsAddr, delAddr, delBondTokens)\n\t// delegate from protected account\n\tdelegate(t, app, ctx, vaConsAddr, delProtectedAddr, delProtectedBondTokens)\n\n\t// capture the current bond state\n\tbondedPool := app.StakingKeeper.GetBondedPool(ctx)\n\toldBondedPoolBalances := app.BankKeeper.GetAllBalances(ctx, bondedPool.GetAddress())\n\t// end block\n\tapplyValidatorSetUpdates(t, ctx, app.StakingKeeper, 1)\n\n\t// mint coins for the distr module\n\trequire.NoError(t, app.BankKeeper.MintCoins(ctx, minttypes.ModuleName, sdk.NewCoins(sdk.NewCoin(app.StakingKeeper.BondDenom(ctx), valReward.TruncateInt()))))\n\trequire.NoError(t, app.BankKeeper.SendCoinsFromModuleToModule(ctx, minttypes.ModuleName, distrtypes.ModuleName, sdk.NewCoins(sdk.NewCoin(app.StakingKeeper.BondDenom(ctx), valReward.TruncateInt()))))\n\t// add reward to the validator to withdraw by the protected module\n\tapp.DistrKeeper.AllocateTokensToValidator(ctx, val, sdk.NewDecCoins(sdk.NewDecCoinFromDec(app.StakingKeeper.BondDenom(ctx), valReward)))\n\n\t// get current power\n\tpower := app.StakingKeeper.GetLastValidatorPower(ctx, val.GetOperator())\n\trequire.Equal(t, app.StakingKeeper.TokensToConsensusPower(ctx, totalDelegation), power)\n\n\t// increase the block number to be able to get the reward\n\tctx = app.BaseApp.NewContext(false, tmproto.Header{Height: app.LastBlockHeight() + 1})\n\t// now slash based on the current power\n\tapp.StakingKeeper.Slash(ctx, vaConsAddr, ctx.BlockHeight(), power, fraction)\n\t// end block\n\tapplyValidatorSetUpdates(t, ctx, app.StakingKeeper, 1)\n\n\t// read updated test\n\tval, found = app.StakingKeeper.GetValidator(ctx, val.GetOperator())\n\tassert.True(t, found)\n\t// power decreased, the protected delegation was remove from the calculation\n\t// since the module is protected from the slashing\n\texpectedPower := app.StakingKeeper.TokensToConsensusPower(ctx,\n\t\ttotalDelegation.Sub(delProtectedBondTokens).\n\t\t\tToDec().Mul(fraction).TruncateInt())\n\tpower = val.GetConsensusPower(app.StakingKeeper.PowerReduction(ctx))\n\trequire.Equal(t, expectedPower, power)\n\n\t// pool bonded shares decreased\n\tnewBondedPoolBalances := app.BankKeeper.GetAllBalances(ctx, bondedPool.GetAddress())\n\tdiffTokens := oldBondedPoolBalances.Sub(newBondedPoolBalances).AmountOf(app.StakingKeeper.BondDenom(ctx))\n\trequire.Equal(t, totalDelegation.Sub(delProtectedBondTokens).ToDec().Mul(fraction).TruncateInt().\n\t\t// add undelegated tokens\n\t\tAdd(delProtectedBondTokens).String(), diffTokens.String())\n\n\t// check the delegation slashing\n\tunbondDelegationAmount, err := app.StakingKeeper.Unbond(ctx, delAddr, val.GetOperator(), delShares)\n\tassert.NoError(t, err)\n\t// the amount 50% less because of the slashing\n\tassert.Equal(t, delBondTokens.ToDec().Mul(fraction).TruncateInt(), unbondDelegationAmount)\n\n\t// check that protected module has no delegation now\n\t_, found = app.StakingKeeper.GetDelegation(ctx, delProtectedAddr, val.GetOperator())\n\tassert.False(t, found)\n\n\tdelProtectedBalance := app.BankKeeper.GetAllBalances(ctx, delProtectedAddr)\n\tassert.Equal(t, sdk.NewCoins(sdk.NewCoin(app.StakingKeeper.BondDenom(ctx), delProtectedBondTokens.Add(delProtectedExpectedReward))), delProtectedBalance)\n}", "func TestHandleNewValidator(t *testing.T) {\n\tapp := simapp.Setup(false)\n\tctx := app.BaseApp.NewContext(false, tmproto.Header{})\n\n\taddrDels := simapp.AddTestAddrsIncremental(app, ctx, 1, sdk.TokensFromConsensusPower(200, sdk.DefaultPowerReduction))\n\tvalAddrs := simapp.ConvertAddrsToValAddrs(addrDels)\n\tpks := simapp.CreateTestPubKeys(1)\n\taddr, val := valAddrs[0], pks[0]\n\ttstaking := teststaking.NewHelper(t, ctx, app.CustomStakingKeeper, app.CustomGovKeeper)\n\tctx = ctx.WithBlockHeight(1)\n\n\t// Validator created\n\ttstaking.CreateValidator(addr, val, true)\n\n\tstaking.EndBlocker(ctx, app.CustomStakingKeeper)\n\n\t// Now a validator, for two blocks\n\tapp.CustomSlashingKeeper.HandleValidatorSignature(ctx, val.Address(), 100, true)\n\tctx = ctx.WithBlockHeight(2)\n\tapp.CustomSlashingKeeper.HandleValidatorSignature(ctx, val.Address(), 100, false)\n\n\tinfo, found := app.CustomSlashingKeeper.GetValidatorSigningInfo(ctx, sdk.ConsAddress(val.Address()))\n\trequire.True(t, found)\n\trequire.Equal(t, int64(1), info.StartHeight)\n\trequire.Equal(t, int64(1), info.MischanceConfidence)\n\trequire.Equal(t, int64(0), info.Mischance)\n\trequire.Equal(t, int64(1), info.MissedBlocksCounter)\n\trequire.Equal(t, int64(1), info.ProducedBlocksCounter)\n\trequire.Equal(t, time.Unix(0, 0).UTC(), info.InactiveUntil)\n\n\t// validator should be active still, should not have been inactivated\n\tvalidator, _ := app.CustomStakingKeeper.GetValidatorByConsAddr(ctx, sdk.GetConsAddress(val))\n\trequire.Equal(t, stakingtypes.Active, validator.GetStatus())\n}", "func (m *DigestHolderMock) MinimockSignWithInspect() {\n\tfor _, e := range m.SignWithMock.expectations {\n\t\tif mm_atomic.LoadUint64(&e.Counter) < 1 {\n\t\t\tm.t.Errorf(\"Expected call to DigestHolderMock.SignWith with params: %#v\", *e.params)\n\t\t}\n\t}\n\n\t// if default expectation was set then invocations count should be greater than zero\n\tif m.SignWithMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterSignWithCounter) < 1 {\n\t\tif m.SignWithMock.defaultExpectation.params == nil {\n\t\t\tm.t.Error(\"Expected call to DigestHolderMock.SignWith\")\n\t\t} else {\n\t\t\tm.t.Errorf(\"Expected call to DigestHolderMock.SignWith with params: %#v\", *m.SignWithMock.defaultExpectation.params)\n\t\t}\n\t}\n\t// if func was set then invocations count should be greater than zero\n\tif m.funcSignWith != nil && mm_atomic.LoadUint64(&m.afterSignWithCounter) < 1 {\n\t\tm.t.Error(\"Expected call to DigestHolderMock.SignWith\")\n\t}\n}", "func MockSealProof(proofType abi.RegisteredSealProof, minerAddr address.Address) ([]byte, error) {\n\tplen, err := proofType.ProofSize()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tproof := make([]byte, plen)\n\ti := copy(proof, mockSealProofPrefix)\n\tbinary.BigEndian.PutUint64(proof[i:], uint64(proofType))\n\ti += 8\n\ti += copy(proof[i:], minerAddr.Bytes())\n\treturn proof, nil\n}", "func (m *MockKeystore) EXPECT() *MockKeystoreMockRecorder {\n\treturn m.recorder\n}", "func (m *MockKeystore) EXPECT() *MockKeystoreMockRecorder {\n\treturn m.recorder\n}", "func TestSyncCredentials(t *testing.T) {\n\tkey, err := goRSA.GenerateKey(rand.Reader, 2048)\n\tassert.NoError(t, err)\n\n\texpSigner, err := ssh.NewSignerFromKey(key)\n\tassert.NoError(t, err)\n\n\texpHost := \"8.8.8.8\"\n\tmockFs := afero.NewMemMapFs()\n\n\tgetSftpFs = func(host string, signer ssh.Signer) (sftpFs, error) {\n\t\tassert.Equal(t, expSigner, signer)\n\t\tassert.Equal(t, expHost, host)\n\t\treturn mockSFTPFs{mockFs}, nil\n\t}\n\n\tca, err := rsa.NewCertificateAuthority()\n\tassert.NoError(t, err)\n\n\tcredentialedMachines := map[string]struct{}{}\n\tsyncCredentialsOnce(expSigner, ca,\n\t\t[]db.Machine{{PublicIP: expHost, PrivateIP: \"9.9.9.9\"}},\n\t\tcredentialedMachines)\n\tassert.Len(t, credentialedMachines, 1)\n\n\taferoFs := afero.Afero{Fs: mockFs}\n\tcertBytes, err := aferoFs.ReadFile(filepath.Join(tlsIO.MinionTLSDir, \"quilt.crt\"))\n\tassert.NoError(t, err)\n\tassert.NotEmpty(t, certBytes)\n\n\tkeyBytes, err := aferoFs.ReadFile(filepath.Join(tlsIO.MinionTLSDir, \"quilt.key\"))\n\tassert.NoError(t, err)\n\tassert.NotEmpty(t, keyBytes)\n\n\tcaBytes, err := aferoFs.ReadFile(filepath.Join(tlsIO.MinionTLSDir,\n\t\t\"certificate_authority.crt\"))\n\tassert.NoError(t, err)\n\tassert.NotEmpty(t, caBytes)\n}", "func (m *CryptographyServiceMock) CheckMocksCalled() {\n\tm.Finish()\n}" ]
[ "0.6744976", "0.6281368", "0.61853397", "0.61265033", "0.6016525", "0.592078", "0.5888198", "0.5882686", "0.5746892", "0.5725966", "0.56851", "0.56679803", "0.5576283", "0.55425304", "0.54525506", "0.5445765", "0.5445765", "0.5444539", "0.5439745", "0.54370964", "0.5416044", "0.5414758", "0.54021543", "0.53748715", "0.5361519", "0.5332156", "0.53113747", "0.5296614", "0.5296607", "0.52906865", "0.528123", "0.52753794", "0.5260811", "0.52595", "0.52483714", "0.52471966", "0.5243438", "0.5238439", "0.5238411", "0.5235445", "0.5224488", "0.52185446", "0.5201778", "0.5193008", "0.51921415", "0.5190983", "0.51889974", "0.51864594", "0.51774186", "0.5175045", "0.5138169", "0.51270604", "0.51108676", "0.5109353", "0.5101822", "0.5072238", "0.5055519", "0.50538194", "0.5028797", "0.50222147", "0.5013571", "0.5010214", "0.50079125", "0.50047827", "0.5001866", "0.50007087", "0.49935657", "0.498166", "0.49810144", "0.49773052", "0.49662858", "0.49645585", "0.49630088", "0.49540702", "0.49445885", "0.4942568", "0.4937983", "0.49365988", "0.4935299", "0.49265346", "0.49224478", "0.49170843", "0.4905023", "0.49048933", "0.4900649", "0.4899051", "0.48983788", "0.48980942", "0.4886465", "0.48814878", "0.488088", "0.48799878", "0.4876407", "0.48762742", "0.48745525", "0.48732942", "0.48638487", "0.48638487", "0.48583442", "0.48579228" ]
0.6785916
0
SigningManager indicates an expected call of SigningManager
func (mr *MockProvidersMockRecorder) SigningManager() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SigningManager", reflect.TypeOf((*MockProviders)(nil).SigningManager)) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (mr *MockClientMockRecorder) SigningManager() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"SigningManager\", reflect.TypeOf((*MockClient)(nil).SigningManager))\n}", "func (pc *MockProviderContext) SigningManager() fab.SigningManager {\n\treturn pc.signingManager\n}", "func (m *MetricsProvider) SignerSign(value time.Duration) {\n}", "func (c *Provider) SigningManager() core.SigningManager {\n\treturn c.signingManager\n}", "func TestSignContractFailure(t *testing.T) {\n\tsignatureHelper(t, true)\n}", "func (m *DigestHolderMock) MinimockSignWithDone() bool {\n\tfor _, e := range m.SignWithMock.expectations {\n\t\tif mm_atomic.LoadUint64(&e.Counter) < 1 {\n\t\t\treturn false\n\t\t}\n\t}\n\n\t// if default expectation was set then invocations count should be greater than zero\n\tif m.SignWithMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterSignWithCounter) < 1 {\n\t\treturn false\n\t}\n\t// if func was set then invocations count should be greater than zero\n\tif m.funcSignWith != nil && mm_atomic.LoadUint64(&m.afterSignWithCounter) < 1 {\n\t\treturn false\n\t}\n\treturn true\n}", "func TestSignContractSuccess(t *testing.T) {\n\tsignatureHelper(t, false)\n}", "func TestVerifySignedMessage(t *testing.T) {\n\tfor _, tc := range []struct {\n\t\tdesc string\n\t\tsettings *crypt.PkiSettings\n\t\tsetup func(mdb *mocks.MockDepsBundle, setupDone *bool) error\n\t\tmessageToSign string\n\t\tbase64Signature string\n\t\tPEMPublicKey string\n\t\texpectedError *testtools.ErrorSpec\n\t\texpectedValidity bool\n\t}{\n\t\t{\n\t\t\tdesc: \"invalid base64 signature\",\n\t\t\tsettings: &crypt.PkiSettings{\n\t\t\t\tAlgorithm: x509.ECDSA,\n\t\t\t\tPrivateKeyPath: \".prog/ecdsa_priv.key\",\n\t\t\t\tPublicKeyPath: \".prog/ecdsa.pub\",\n\t\t\t},\n\t\t\tsetup: func(mdb *mocks.MockDepsBundle, setupDone *bool) error {\n\t\t\t\treturn nil\n\t\t\t},\n\t\t\tmessageToSign: \"some other message\",\n\t\t\tbase64Signature: \"@#$^&*()_\",\n\t\t\tPEMPublicKey: \"\",\n\t\t\texpectedError: &testtools.ErrorSpec{\n\t\t\t\tType: \"base64.CorruptInputError\",\n\t\t\t\tMessage: \"illegal base64 data at input byte 0\",\n\t\t\t},\n\t\t\texpectedValidity: false,\n\t\t},\n\t\t{\n\t\t\tdesc: \"empty PEM key\",\n\t\t\tsettings: &crypt.PkiSettings{\n\t\t\t\tAlgorithm: x509.ECDSA,\n\t\t\t\tPrivateKeyPath: \".prog/ecdsa_priv.key\",\n\t\t\t\tPublicKeyPath: \".prog/ecdsa.pub\",\n\t\t\t},\n\t\t\tsetup: func(mdb *mocks.MockDepsBundle, setupDone *bool) error {\n\t\t\t\treturn nil\n\t\t\t},\n\t\t\tmessageToSign: \"some other message\",\n\t\t\tbase64Signature: \"abcdefgh\",\n\t\t\tPEMPublicKey: \"\",\n\t\t\texpectedError: &testtools.ErrorSpec{\n\t\t\t\tType: \"*errors.errorString\",\n\t\t\t\tMessage: \"No PEM data was found\",\n\t\t\t},\n\t\t\texpectedValidity: false,\n\t\t},\n\t\t{\n\t\t\tdesc: \"bad key data\",\n\t\t\tsettings: &crypt.PkiSettings{\n\t\t\t\tAlgorithm: x509.ECDSA,\n\t\t\t\tPrivateKeyPath: \".prog/ecdsa_priv.key\",\n\t\t\t\tPublicKeyPath: \".prog/ecdsa.pub\",\n\t\t\t},\n\t\t\tsetup: func(mdb *mocks.MockDepsBundle, setupDone *bool) error {\n\t\t\t\treturn nil\n\t\t\t},\n\t\t\tmessageToSign: \"some other message\",\n\t\t\tbase64Signature: \"abcdefgh\",\n\t\t\tPEMPublicKey: \"-----BEGIN INVALID DATA-----\\n\" +\n\t\t\t\t\"MTIzNDU2Nzg5MGFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6\\n\" +\n\t\t\t\t\"-----END INVALID DATA-----\\n\",\n\t\t\texpectedError: &testtools.ErrorSpec{\n\t\t\t\tType: \"asn1.StructuralError\",\n\t\t\t\tMessage: \"asn1: structure \" +\n\t\t\t\t\t\"error: tags don't match (16 vs {class:0 \" +\n\t\t\t\t\t\"tag:17 \" +\n\t\t\t\t\t\"length:50 \" +\n\t\t\t\t\t\"isCompound:true}) {optional:false \" +\n\t\t\t\t\t\"explicit:false \" +\n\t\t\t\t\t\"application:false \" +\n\t\t\t\t\t\"defaultValue:<nil> \" +\n\t\t\t\t\t\"tag:<nil> \" +\n\t\t\t\t\t\"stringType:0 \" +\n\t\t\t\t\t\"timeType:0 \" +\n\t\t\t\t\t\"set:false \" +\n\t\t\t\t\t\"omitEmpty:false} publicKeyInfo @2\",\n\t\t\t},\n\t\t\texpectedValidity: false,\n\t\t},\n\t\t{\n\t\t\tdesc: \"invalid signature\",\n\t\t\tsettings: &crypt.PkiSettings{\n\t\t\t\tAlgorithm: x509.ECDSA,\n\t\t\t\tPrivateKeyPath: \".prog/ecdsa_priv.key\",\n\t\t\t\tPublicKeyPath: \".prog/ecdsa.pub\",\n\t\t\t},\n\t\t\tsetup: func(mdb *mocks.MockDepsBundle, setupDone *bool) error {\n\t\t\t\treturn nil\n\t\t\t},\n\t\t\tmessageToSign: \"some other message\",\n\t\t\tbase64Signature: \"abcdefgh\",\n\t\t\tPEMPublicKey: \"-----BEGIN ECDSA PUBLIC KEY-----\\n\" +\n\t\t\t\t\"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE7WzVjtn9Gk+WHr5xbv8XMvooqU25\\n\" +\n\t\t\t\t\"BhgNjZ/vHZLBdVtCOjk4KxjS1UBfQm0c3TRxWBl3hj2AmnJbCrnGofMHBQ==\\n\" +\n\t\t\t\t\"-----END ECDSA PUBLIC KEY-----\\n\",\n\t\t\texpectedError: &testtools.ErrorSpec{\n\t\t\t\tType: \"asn1.SyntaxError\",\n\t\t\t\tMessage: \"asn1: syntax error: truncated tag or length\",\n\t\t\t},\n\t\t\texpectedValidity: false,\n\t\t},\n\t\t{\n\t\t\tdesc: \"ecdsa key for rsa mode\",\n\t\t\tsettings: &crypt.PkiSettings{\n\t\t\t\tAlgorithm: x509.RSA,\n\t\t\t\tPrivateKeyPath: \".prog/ecdsa_priv.key\",\n\t\t\t\tPublicKeyPath: \".prog/ecdsa.pub\",\n\t\t\t},\n\t\t\tsetup: func(mdb *mocks.MockDepsBundle, setupDone *bool) error {\n\t\t\t\treturn nil\n\t\t\t},\n\t\t\tmessageToSign: \"some other message\",\n\t\t\tbase64Signature: \"N3SuIdWI7XlXDteTmcOZUd2OBacyUWY+/+A8SC4QUBz9rXnldBqXha6YyGwnTuizxuy6quQ2QDFdtW16dj7EQk3lozfngskyhc2r86q3AUbdFDvrQVphMQhzsgBhHVoMjCL/YRfvtzCTWhBxegjVMLraLDCBb8IZTIqcMYafYyeJTvAnjBuntlZ+14TDuTt14Uqz85T04CXxBEqlIXMMKpTc01ST4Jsxz5HLO+At1htXp5eHOUFtQSilm3G7iO8ynhgPcXHDWfMAWu6VySUoHWCG70pJaCq6ehF7223t0UFOCqAyDyyQyP9yeUHj8F75SPSxfJm8iKXGx2LND/qLYw==\",\n\t\t\tPEMPublicKey: \"-----BEGIN RSA PUBLIC KEY-----\\n\" +\n\t\t\t\t\"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE7WzVjtn9Gk+WHr5xbv8XMvooqU25\\n\" +\n\t\t\t\t\"BhgNjZ/vHZLBdVtCOjk4KxjS1UBfQm0c3TRxWBl3hj2AmnJbCrnGofMHBQ==\\n\" +\n\t\t\t\t\"-----END RSA PUBLIC KEY-----\\n\",\n\t\t\texpectedError: &testtools.ErrorSpec{\n\t\t\t\tType: \"*errors.errorString\",\n\t\t\t\tMessage: \"Expecting a *rsa.PublicKey, but encountered a *ecdsa.PublicKey instead\",\n\t\t\t},\n\t\t\texpectedValidity: false,\n\t\t},\n\t\t{\n\t\t\tdesc: \"rsa key for ecdsa mode\",\n\t\t\tsettings: &crypt.PkiSettings{\n\t\t\t\tAlgorithm: x509.ECDSA,\n\t\t\t\tPrivateKeyPath: \".prog/ecdsa_priv.key\",\n\t\t\t\tPublicKeyPath: \".prog/ecdsa.pub\",\n\t\t\t},\n\t\t\tsetup: func(mdb *mocks.MockDepsBundle, setupDone *bool) error {\n\t\t\t\treturn nil\n\t\t\t},\n\t\t\tmessageToSign: \"some other message\",\n\t\t\tbase64Signature: \"MEYCIQDPM0fc/PFauoZzpltH3RpWtlaqRnL0gFk5WFiLMrFqrwIhAIDvlBozU6Ky2UC9xOSq3YZ5iFuO356t9RnHOElaaXFJ\",\n\t\t\tPEMPublicKey: \"-----BEGIN RSA PUBLIC KEY-----\\n\" +\n\t\t\t\t\"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAzCTTFKQBHfTN8jW6q8PT\\n\" +\n\t\t\t\t\"HNZKWnRPxSt9kpgWmyqFaZnEUipgoKGAxSIsVrl2PJSm5OlgkVzx+MY+LWM64VKM\\n\" +\n\t\t\t\t\"bRpUUGJR3zdMNhwZQX0hjOpLpVJvUwD78utVs8vijrU7sH48usFiaZQYjy4m4hQh\\n\" +\n\t\t\t\t\"63/x4h3KVz7YqUnlRMzYJFT43+AwYzYuEpzWRxtW7IObJPtjtmYVoqva98fF6aj5\\n\" +\n\t\t\t\t\"uHAsvaAgZGBalHXmCiPzKiGU/halzXSPvyJ2Cqz2aUqMHgwi/2Ip4z/mrfX+mUTa\\n\" +\n\t\t\t\t\"S+LyBy7GgqJ5vbkGArMagJIc0eARF60r6Uf483xh17oniABdLJy4qlLf6PcEU+ut\\n\" +\n\t\t\t\t\"EwIDAQAB\\n\" +\n\t\t\t\t\"-----END RSA PUBLIC KEY-----\\n\",\n\t\t\texpectedError: &testtools.ErrorSpec{\n\t\t\t\tType: \"*errors.errorString\",\n\t\t\t\tMessage: \"Expecting a *ecdsa.PublicKey, but encountered a *rsa.PublicKey instead\",\n\t\t\t},\n\t\t\texpectedValidity: false,\n\t\t},\n\t} {\n\t\tt.Run(fmt.Sprintf(\"Subtest: %s\", tc.desc), func(tt *testing.T) {\n\t\t\tmockDepsBundle := mocks.NewDefaultMockDeps(\"\", []string{\"progname\"}, \"/home/user\", nil)\n\t\t\treturnedNormally := false\n\t\t\tvar tooling *crypt.CryptoTooling\n\t\t\tvar actualErr error\n\t\t\tvar actualValidity bool\n\t\t\terr := mockDepsBundle.InvokeCallInMockedEnv(func() error {\n\t\t\t\tsetupComplete := false\n\t\t\t\tinnerErr := tc.setup(mockDepsBundle, &setupComplete)\n\t\t\t\tif innerErr != nil {\n\t\t\t\t\treturn innerErr\n\t\t\t\t}\n\t\t\t\tvar toolingErr error\n\t\t\t\ttooling, toolingErr = crypt.GetCryptoTooling(mockDepsBundle.Deps, tc.settings)\n\t\t\t\tif toolingErr != nil {\n\t\t\t\t\treturn toolingErr\n\t\t\t\t}\n\t\t\t\tsetupComplete = true\n\t\t\t\tactualValidity, actualErr = tooling.VerifySignedMessage(tc.messageToSign, tc.base64Signature, tc.PEMPublicKey)\n\t\t\t\treturnedNormally = true\n\t\t\t\treturn nil\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\ttt.Errorf(\"Unexpected error calling mockDepsBundle.InvokeCallInMockedEnv(): %s\", err.Error())\n\t\t\t}\n\t\t\tif exitStatus := mockDepsBundle.GetExitStatus(); (exitStatus != 0) || !returnedNormally {\n\t\t\t\ttt.Error(\"EncodeAndSaveKey() should not have paniced or called os.Exit.\")\n\t\t\t}\n\t\t\tif (mockDepsBundle.OutBuf.String() != \"\") || (mockDepsBundle.ErrBuf.String() != \"\") {\n\t\t\t\ttt.Errorf(\"EncodeAndSaveKey() should not have output any data. Saw stdout:\\n%s\\nstderr:\\n%s\", mockDepsBundle.OutBuf.String(), mockDepsBundle.ErrBuf.String())\n\t\t\t}\n\t\t\tif err := tc.expectedError.EnsureMatches(actualErr); err != nil {\n\t\t\t\ttt.Error(err.Error())\n\t\t\t}\n\t\t\tif tc.expectedError == nil {\n\t\t\t\tif actualValidity != tc.expectedValidity {\n\t\t\t\t\ttt.Errorf(\"Signature is %#v when %#v expected\", actualValidity, tc.expectedValidity)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif tc.expectedValidity {\n\t\t\t\t\ttt.Error(\"TEST CASE INVALID. Should not expect \\\"valid\\\".\")\n\t\t\t\t}\n\t\t\t\tif actualValidity {\n\t\t\t\t\ttt.Error(\"Error was expected. Should not report \\\"valid\\\".\")\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n}", "func (validator *validatorImpl) Sign(msg []byte) ([]byte, error) {\n\treturn validator.signWithEnrollmentKey(msg)\n}", "func (mr *MockMachineMockRecorder) SignerKey() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"SignerKey\", reflect.TypeOf((*MockMachine)(nil).SignerKey))\n}", "func TestSenderRequest_Sign(t *testing.T) {\r\n\r\n\t// Create key\r\n\tkey, err := bitcoin.CreatePrivateKeyString()\r\n\tassert.NoError(t, err)\r\n\tassert.NotNil(t, key)\r\n\r\n\t// Create the request / message\r\n\tsenderRequest := &SenderRequest{\r\n\t\tDt: time.Now().UTC().Format(time.RFC3339),\r\n\t\tSenderHandle: testAlias + \"@\" + testDomain,\r\n\t\tSenderName: testName,\r\n\t\tPurpose: testMessage,\r\n\t}\r\n\r\n\tvar signature string\r\n\r\n\tt.Run(\"invalid key - empty\", func(t *testing.T) {\r\n\t\tsignature, err = senderRequest.Sign(\"\")\r\n\t\tassert.Error(t, err)\r\n\t\tassert.Equal(t, len(signature), 0)\r\n\t})\r\n\r\n\tt.Run(\"invalid key - 0\", func(t *testing.T) {\r\n\t\tsignature, err = senderRequest.Sign(\"0\")\r\n\t\tassert.Error(t, err)\r\n\t\tassert.Equal(t, len(signature), 0)\r\n\t})\r\n\r\n\tt.Run(\"invalid dt\", func(t *testing.T) {\r\n\t\tsenderRequest.Dt = \"\"\r\n\t\tsignature, err = senderRequest.Sign(key)\r\n\t\tassert.Error(t, err)\r\n\t\tassert.Equal(t, len(signature), 0)\r\n\t})\r\n\r\n\tt.Run(\"invalid sender handle\", func(t *testing.T) {\r\n\t\tsenderRequest.Dt = time.Now().UTC().Format(time.RFC3339)\r\n\t\tsenderRequest.SenderHandle = \"\"\r\n\t\tsignature, err = senderRequest.Sign(key)\r\n\t\tassert.Error(t, err)\r\n\t\tassert.Equal(t, len(signature), 0)\r\n\t})\r\n\r\n\tt.Run(\"valid signature\", func(t *testing.T) {\r\n\t\tsenderRequest.SenderHandle = testAlias + \"@\" + testDomain\r\n\t\tsignature, err = senderRequest.Sign(key)\r\n\t\tassert.NoError(t, err)\r\n\t\tassert.NotEqual(t, len(signature), 0)\r\n\r\n\t\t// Get address for verification\r\n\t\tvar address string\r\n\t\taddress, err = bitcoin.GetAddressFromPrivateKeyString(key, false)\r\n\t\tassert.NoError(t, err)\r\n\r\n\t\t// Verify the signature\r\n\t\terr = senderRequest.Verify(address, signature)\r\n\t\tassert.NoError(t, err)\r\n\t})\r\n}", "func (m *MockProviders) SigningManager() core.SigningManager {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"SigningManager\")\n\tret0, _ := ret[0].(core.SigningManager)\n\treturn ret0\n}", "func (m *MockClient) SigningManager() core.SigningManager {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"SigningManager\")\n\tret0, _ := ret[0].(core.SigningManager)\n\treturn ret0\n}", "func (uv *UtxoVM) verifySignatures(tx *pb.Transaction, digestHash []byte) (bool, map[string]bool, error) {\n\t// XuperSign is not empty, use XuperSign verify\n\tif tx.GetXuperSign() != nil {\n\t\treturn uv.verifyXuperSign(tx, digestHash)\n\t}\n\n\t// Not XuperSign(multisig/rignsign etc.), use old signature process\n\tverifiedAddr := make(map[string]bool)\n\tif len(tx.InitiatorSigns) < 1 || len(tx.AuthRequire) != len(tx.AuthRequireSigns) {\n\t\treturn false, nil, errors.New(\"invalid signature param\")\n\t}\n\n\t// verify initiator\n\takType := acl.IsAccount(tx.Initiator)\n\tif akType == 0 {\n\t\t// check initiator address signature\n\t\tok, err := pm.IdentifyAK(tx.Initiator, tx.InitiatorSigns[0], digestHash)\n\t\tif err != nil || !ok {\n\t\t\tuv.xlog.Warn(\"verifySignatures failed\", \"address\", tx.Initiator, \"error\", err)\n\t\t\treturn false, nil, err\n\t\t}\n\t\tverifiedAddr[tx.Initiator] = true\n\t} else if akType == 1 {\n\t\tinitiatorAddr := make([]string, 0)\n\t\t// check initiator account signatures\n\t\tfor _, sign := range tx.InitiatorSigns {\n\t\t\tak, err := uv.cryptoClient.GetEcdsaPublicKeyFromJSON([]byte(sign.PublicKey))\n\t\t\tif err != nil {\n\t\t\t\tuv.xlog.Warn(\"verifySignatures failed\", \"address\", tx.Initiator, \"error\", err)\n\t\t\t\treturn false, nil, err\n\t\t\t}\n\t\t\taddr, err := uv.cryptoClient.GetAddressFromPublicKey(ak)\n\t\t\tif err != nil {\n\t\t\t\tuv.xlog.Warn(\"verifySignatures failed\", \"address\", tx.Initiator, \"error\", err)\n\t\t\t\treturn false, nil, err\n\t\t\t}\n\t\t\tok, err := pm.IdentifyAK(addr, sign, digestHash)\n\t\t\tif !ok {\n\t\t\t\tuv.xlog.Warn(\"verifySignatures failed\", \"address\", tx.Initiator, \"error\", err)\n\t\t\t\treturn ok, nil, err\n\t\t\t}\n\t\t\tverifiedAddr[addr] = true\n\t\t\tinitiatorAddr = append(initiatorAddr, tx.Initiator+\"/\"+addr)\n\t\t}\n\t\tok, err := pm.IdentifyAccount(tx.Initiator, initiatorAddr, uv.aclMgr)\n\t\tif !ok {\n\t\t\tuv.xlog.Warn(\"verifySignatures initiator permission check failed\",\n\t\t\t\t\"account\", tx.Initiator, \"error\", err)\n\t\t\treturn false, nil, err\n\t\t}\n\t} else {\n\t\tuv.xlog.Warn(\"verifySignatures failed, invalid address\", \"address\", tx.Initiator)\n\t\treturn false, nil, ErrInvalidSignature\n\t}\n\n\t// verify authRequire\n\tfor idx, authReq := range tx.AuthRequire {\n\t\tsplitRes := strings.Split(authReq, \"/\")\n\t\taddr := splitRes[len(splitRes)-1]\n\t\tsignInfo := tx.AuthRequireSigns[idx]\n\t\tif _, has := verifiedAddr[addr]; has {\n\t\t\tcontinue\n\t\t}\n\t\tok, err := pm.IdentifyAK(addr, signInfo, digestHash)\n\t\tif err != nil || !ok {\n\t\t\tuv.xlog.Warn(\"verifySignatures failed\", \"address\", addr, \"error\", err)\n\t\t\treturn false, nil, err\n\t\t}\n\t\tverifiedAddr[addr] = true\n\t}\n\treturn true, verifiedAddr, nil\n}", "func TestMissingSigningKey(t *testing.T) {\n\tf, _ := createNewSwizzler(t)\n\n\t// delete the snapshot, timestamp, and root keys\n\tnoKeys := []data.RoleName{\n\t\tdata.CanonicalSnapshotRole, data.CanonicalTimestampRole, data.CanonicalRootRole}\n\tfor _, role := range noKeys {\n\t\tk := f.CryptoService.ListKeys(role)\n\t\trequire.Len(t, k, 1)\n\t\trequire.NoError(t, f.CryptoService.RemoveKey(k[0]))\n\t}\n\n\t// these are all the functions that require re-signing\n\trequire.IsType(t, ErrNoKeyForRole{}, f.OffsetMetadataVersion(data.CanonicalSnapshotRole, 1))\n\trequire.IsType(t, ErrNoKeyForRole{}, f.ExpireMetadata(data.CanonicalSnapshotRole))\n\trequire.IsType(t, ErrNoKeyForRole{}, f.SetThreshold(data.CanonicalSnapshotRole, 2))\n\trequire.IsType(t, ErrNoKeyForRole{}, f.UpdateSnapshotHashes())\n\trequire.IsType(t, ErrNoKeyForRole{}, f.UpdateTimestampHash())\n}", "func (mr *MockClientMockRecorder) Sign(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Sign\", reflect.TypeOf((*MockClient)(nil).Sign), arg0)\n}", "func (m *imageProcessor) checkSignature(e *kevent.Kevent) {\n\tchecksum := e.Kparams.MustGetUint32(kparams.ImageCheckSum)\n\tsign, ok := m.signatures[checksum]\n\tif !ok {\n\t\tfilename := e.GetParamAsString(kparams.FileName)\n\t\tsign = signature.Check(filename)\n\t\tif sign == nil {\n\t\t\treturn\n\t\t}\n\t\tif sign.IsSigned() {\n\t\t\tsign.Verify()\n\t\t}\n\t\tm.signatures[checksum] = sign\n\t}\n\tif sign != nil {\n\t\t_ = e.Kparams.SetValue(kparams.ImageSignatureType, sign.Type)\n\t\t_ = e.Kparams.SetValue(kparams.ImageSignatureLevel, sign.Level)\n\t}\n}", "func (m *DeviceHealthAttestationState) SetTestSigning(value *string)() {\n err := m.GetBackingStore().Set(\"testSigning\", value)\n if err != nil {\n panic(err)\n }\n}", "func Sign(ctx context.Context, txf Factory, name string, txBuilder client.TxBuilder, overwriteSig bool) error {\n\tif txf.keybase == nil {\n\t\treturn errors.New(\"keybase must be set prior to signing a transaction\")\n\t}\n\n\tvar err error\n\tsignMode := txf.signMode\n\tif signMode == signing.SignMode_SIGN_MODE_UNSPECIFIED {\n\t\t// use the SignModeHandler's default mode if unspecified\n\t\tsignMode, err = authsigning.APISignModeToInternal(txf.txConfig.SignModeHandler().DefaultMode())\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tk, err := txf.keybase.Key(name)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tpubKey, err := k.GetPubKey()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsignerData := authsigning.SignerData{\n\t\tChainID: txf.chainID,\n\t\tAccountNumber: txf.accountNumber,\n\t\tSequence: txf.sequence,\n\t\tPubKey: pubKey,\n\t\tAddress: sdk.AccAddress(pubKey.Address()).String(),\n\t}\n\n\t// For SIGN_MODE_DIRECT, calling SetSignatures calls setSignerInfos on\n\t// TxBuilder under the hood, and SignerInfos is needed to generated the\n\t// sign bytes. This is the reason for setting SetSignatures here, with a\n\t// nil signature.\n\t//\n\t// Note: this line is not needed for SIGN_MODE_LEGACY_AMINO, but putting it\n\t// also doesn't affect its generated sign bytes, so for code's simplicity\n\t// sake, we put it here.\n\tsigData := signing.SingleSignatureData{\n\t\tSignMode: signMode,\n\t\tSignature: nil,\n\t}\n\tsig := signing.SignatureV2{\n\t\tPubKey: pubKey,\n\t\tData: &sigData,\n\t\tSequence: txf.Sequence(),\n\t}\n\n\tvar prevSignatures []signing.SignatureV2\n\tif !overwriteSig {\n\t\tprevSignatures, err = txBuilder.GetTx().GetSignaturesV2()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\t// Overwrite or append signer infos.\n\tvar sigs []signing.SignatureV2\n\tif overwriteSig {\n\t\tsigs = []signing.SignatureV2{sig}\n\t} else {\n\t\tsigs = append(sigs, prevSignatures...)\n\t\tsigs = append(sigs, sig)\n\t}\n\tif err := txBuilder.SetSignatures(sigs...); err != nil {\n\t\treturn err\n\t}\n\n\tif err := checkMultipleSigners(txBuilder.GetTx()); err != nil {\n\t\treturn err\n\t}\n\n\tbytesToSign, err := authsigning.GetSignBytesAdapter(\n\t\tctx, txf.txConfig.SignModeHandler(),\n\t\tsignMode, signerData, txBuilder.GetTx())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Sign those bytes\n\tsigBytes, _, err := txf.keybase.Sign(name, bytesToSign, signMode)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Construct the SignatureV2 struct\n\tsigData = signing.SingleSignatureData{\n\t\tSignMode: signMode,\n\t\tSignature: sigBytes,\n\t}\n\tsig = signing.SignatureV2{\n\t\tPubKey: pubKey,\n\t\tData: &sigData,\n\t\tSequence: txf.Sequence(),\n\t}\n\n\tif overwriteSig {\n\t\terr = txBuilder.SetSignatures(sig)\n\t} else {\n\t\tprevSignatures = append(prevSignatures, sig)\n\t\terr = txBuilder.SetSignatures(prevSignatures...)\n\t}\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to set signatures on payload: %w\", err)\n\t}\n\n\t// Run optional preprocessing if specified. By default, this is unset\n\t// and will return nil.\n\treturn txf.PreprocessTx(name, txBuilder)\n}", "func (m *CryptographyServiceMock) Sign(p []byte) (r *insolar.Signature, r1 error) {\n\tcounter := atomic.AddUint64(&m.SignPreCounter, 1)\n\tdefer atomic.AddUint64(&m.SignCounter, 1)\n\n\tif len(m.SignMock.expectationSeries) > 0 {\n\t\tif counter > uint64(len(m.SignMock.expectationSeries)) {\n\t\t\tm.t.Fatalf(\"Unexpected call to CryptographyServiceMock.Sign. %v\", p)\n\t\t\treturn\n\t\t}\n\n\t\tinput := m.SignMock.expectationSeries[counter-1].input\n\t\ttestify_assert.Equal(m.t, *input, CryptographyServiceMockSignInput{p}, \"CryptographyService.Sign got unexpected parameters\")\n\n\t\tresult := m.SignMock.expectationSeries[counter-1].result\n\t\tif result == nil {\n\t\t\tm.t.Fatal(\"No results are set for the CryptographyServiceMock.Sign\")\n\t\t\treturn\n\t\t}\n\n\t\tr = result.r\n\t\tr1 = result.r1\n\n\t\treturn\n\t}\n\n\tif m.SignMock.mainExpectation != nil {\n\n\t\tinput := m.SignMock.mainExpectation.input\n\t\tif input != nil {\n\t\t\ttestify_assert.Equal(m.t, *input, CryptographyServiceMockSignInput{p}, \"CryptographyService.Sign got unexpected parameters\")\n\t\t}\n\n\t\tresult := m.SignMock.mainExpectation.result\n\t\tif result == nil {\n\t\t\tm.t.Fatal(\"No results are set for the CryptographyServiceMock.Sign\")\n\t\t}\n\n\t\tr = result.r\n\t\tr1 = result.r1\n\n\t\treturn\n\t}\n\n\tif m.SignFunc == nil {\n\t\tm.t.Fatalf(\"Unexpected call to CryptographyServiceMock.Sign. %v\", p)\n\t\treturn\n\t}\n\n\treturn m.SignFunc(p)\n}", "func (mr *MockTransactionApiMockRecorder) VerifySign(tx, outpoint, amount, txinUtxoList interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"VerifySign\", reflect.TypeOf((*MockTransactionApi)(nil).VerifySign), tx, outpoint, amount, txinUtxoList)\n}", "func (s *ServiceSuite) TestMacaroonPaperFig6FailsWithBindingOnTamperedSignature(c *gc.C) {\n\tlocator := bakery.NewThirdPartyStore()\n\tas := newBakery(\"as-loc\", locator)\n\tts := newBakery(\"ts-loc\", locator)\n\tfs := newBakery(\"fs-loc\", locator)\n\n\t// ts creates a macaroon.\n\ttsMacaroon, err := ts.Oven.NewMacaroon(testContext, bakery.LatestVersion, ages, nil, bakery.LoginOp)\n\tc.Assert(err, gc.IsNil)\n\n\t// ts somehow sends the macaroon to fs which adds a third party caveat to be discharged by as.\n\terr = fs.Oven.AddCaveat(testContext, tsMacaroon, checkers.Caveat{Location: \"as-loc\", Condition: \"user==bob\"})\n\tc.Assert(err, gc.IsNil)\n\n\t// client asks for a discharge macaroon for each third party caveat\n\td, err := bakery.DischargeAll(testContext, tsMacaroon, func(ctx context.Context, cav macaroon.Caveat, payload []byte) (*bakery.Macaroon, error) {\n\t\tc.Assert(cav.Location, gc.Equals, \"as-loc\")\n\t\treturn discharge(ctx, as.Oven, thirdPartyStrcmpChecker(\"user==bob\"), cav, payload)\n\t})\n\tc.Assert(err, gc.IsNil)\n\n\t// client has all the discharge macaroons. For each discharge macaroon bind it to our tsMacaroon\n\t// and add it to our request.\n\tfor _, dm := range d[1:] {\n\t\tdm.Bind([]byte(\"tampered-signature\")) // Bind against an incorrect signature.\n\t}\n\n\t// client makes request to ts.\n\t_, err = ts.Checker.Auth(d).Allow(testContext, bakery.LoginOp)\n\t// TODO fix this error message.\n\tc.Assert(err, gc.ErrorMatches, \"verification failed: signature mismatch after caveat verification\")\n}", "func (t *SuiteSuite) VerifyMethodsWrongSignatureSkipped1(x int) {\n\tt.Fatalf(\"This should never run.\")\n}", "func (mr *MockSignerMockRecorder) Sign(arg0, arg1 interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Sign\", reflect.TypeOf((*MockSigner)(nil).Sign), arg0, arg1)\n}", "func (m *DigestHolderMock) MinimockSignWithInspect() {\n\tfor _, e := range m.SignWithMock.expectations {\n\t\tif mm_atomic.LoadUint64(&e.Counter) < 1 {\n\t\t\tm.t.Errorf(\"Expected call to DigestHolderMock.SignWith with params: %#v\", *e.params)\n\t\t}\n\t}\n\n\t// if default expectation was set then invocations count should be greater than zero\n\tif m.SignWithMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterSignWithCounter) < 1 {\n\t\tif m.SignWithMock.defaultExpectation.params == nil {\n\t\t\tm.t.Error(\"Expected call to DigestHolderMock.SignWith\")\n\t\t} else {\n\t\t\tm.t.Errorf(\"Expected call to DigestHolderMock.SignWith with params: %#v\", *m.SignWithMock.defaultExpectation.params)\n\t\t}\n\t}\n\t// if func was set then invocations count should be greater than zero\n\tif m.funcSignWith != nil && mm_atomic.LoadUint64(&m.afterSignWithCounter) < 1 {\n\t\tm.t.Error(\"Expected call to DigestHolderMock.SignWith\")\n\t}\n}", "func TestSign(w http.ResponseWriter, r *http.Request) {\n\tconf := ConfLoad()\n\n\t// Returns a Public / Private Key Pair\n\t// Read JSON config from app.yaml\n\tif v := os.Getenv(\"PRIV_KEY\"); v != \"\" {\n\t\terr := json.Unmarshal([]byte(v), &conf)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"%#v\", conf)\n\t\t\tpanic(err)\n\t\t}\n\t}\n\n\t// Get the public key\n\tvar pubkey ecdsa.PublicKey\n\tpubkey = conf.PublicKey\n\n\t// Try signing a message\n\tmessage := []byte(\"99999999\")\n\tsig1, sig2, err := ecdsa.Sign(rand.Reader, &conf.PrivateKey, message)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// Try verifying the signature\n\tresult := ecdsa.Verify(&pubkey, message, sig1, sig2)\n\tif result != true {\n\t\tpanic(\"Unable to verify signature\")\n\t}\n\n\tfmt.Fprintf(w, \"message: %#v\\n\\nsig1: %#v\\nsig2: %#v\", string(message[:]), sig1, sig2)\n\n}", "func (m *CryptographyServiceMock) SignFinished() bool {\n\t// if expectation series were set then invocations count should be equal to expectations count\n\tif len(m.SignMock.expectationSeries) > 0 {\n\t\treturn atomic.LoadUint64(&m.SignCounter) == uint64(len(m.SignMock.expectationSeries))\n\t}\n\n\t// if main expectation was set then invocations count should be greater than zero\n\tif m.SignMock.mainExpectation != nil {\n\t\treturn atomic.LoadUint64(&m.SignCounter) > 0\n\t}\n\n\t// if func was set then invocations count should be greater than zero\n\tif m.SignFunc != nil {\n\t\treturn atomic.LoadUint64(&m.SignCounter) > 0\n\t}\n\n\treturn true\n}", "func verifySignatures(sectionSender sectionWithSigSender) bool {\n\tsection := sectionSender.Section\n\tkeysNeeded := make(map[rainslib.SignatureMetaData]bool)\n\tsection.NeededKeys(keysNeeded)\n\tpublicKeys, missingKeys, ok := publicKeysPresent(section.GetSubjectZone(), section.GetContext(), keysNeeded)\n\tif ok {\n\t\tlog.Info(\"All public keys are present.\", \"msgSectionWithSig\", section)\n\t\taddZoneAndContextToContainedSections(section)\n\t\treturn validSignature(section, publicKeys)\n\t}\n\thandleMissingKeys(sectionSender, missingKeys)\n\treturn false\n}", "func (fs fakeService) Signature(ctx *context.T, call rpc.ServerCall) ([]signature.Interface, error) {\n\tctx.Infof(\"Fake Service Signature???\")\n\treturn nil, nil\n}", "func (m EncMessage) Sign(k []byte) error {\n\treturn errors.New(\"Sign method must be overridden\")\n}", "func (_RandomBeacon *RandomBeaconTransactor) ReportUnauthorizedSigning(opts *bind.TransactOpts, signedMsgSender []byte, groupId uint64, groupMembers []uint32) (*types.Transaction, error) {\n\treturn _RandomBeacon.contract.Transact(opts, \"reportUnauthorizedSigning\", signedMsgSender, groupId, groupMembers)\n}", "func TestSignature(t *testing.T) {\n\tt.Parallel()\n\n\ttree := writeTree(t, `\n-- go.mod --\nmodule example.com\ngo 1.18\n\n-- a.go --\npackage a\nimport \"fmt\"\nfunc f() {\n\tfmt.Println(123)\n}\n`)\n\t// no arguments\n\t{\n\t\tres := gopls(t, tree, \"signature\")\n\t\tres.checkExit(false)\n\t\tres.checkStderr(\"expects 1 argument\")\n\t}\n\t// at 123 inside fmt.Println() call\n\t{\n\t\tres := gopls(t, tree, \"signature\", \"a.go:4:15\")\n\t\tres.checkExit(true)\n\t\tres.checkStdout(\"Println\\\\(a ...\")\n\t\tres.checkStdout(\"Println formats using the default formats...\")\n\t}\n}", "func (mmSignWith *mDigestHolderMockSignWith) When(signer DigestSigner) *DigestHolderMockSignWithExpectation {\n\tif mmSignWith.mock.funcSignWith != nil {\n\t\tmmSignWith.mock.t.Fatalf(\"DigestHolderMock.SignWith mock is already set by Set\")\n\t}\n\n\texpectation := &DigestHolderMockSignWithExpectation{\n\t\tmock: mmSignWith.mock,\n\t\tparams: &DigestHolderMockSignWithParams{signer},\n\t}\n\tmmSignWith.expectations = append(mmSignWith.expectations, expectation)\n\treturn expectation\n}", "func signatureHelper(t *testing.T, failure bool) {\n\t// Setup\n\tstop, clients, contractPath, contractFilePath := setupSignature(t)\n\tdefer stop()\n\n\tstopBefore, expectedProofFile1, expectedProofFile2 := \"1\", 0, 0\n\tif !failure {\n\t\tstopBefore, expectedProofFile1, expectedProofFile2 = \"2\", 2, 1\n\t}\n\n\t// Configure client3 to be faulty\n\tsetLastArg(clients[2], \"--stopbefore\", true)\n\tsetLastArg(clients[2], stopBefore, false)\n\tsetLastArg(clients[2], \"sign\", false)\n\n\t// Sign!\n\tcloseChannel := make(chan []byte, 3)\n\tfor i := 0; i < 3; i++ {\n\t\tsetLastArg(clients[i], \"sign\", true)\n\t\tsetLastArg(clients[i], contractPath, false)\n\t\tgo func(c *exec.Cmd, i int) {\n\t\t\tc.Stdin = strings.NewReader(contractFilePath + \"\\npassword\\nyes\\n\")\n\t\t\tc.Stderr = bufio.NewWriter(os.Stdout)\n\t\t\toutput, _ := c.Output()\n\t\t\tcloseChannel <- output\n\t\t}(clients[i], i)\n\t}\n\n\tfor i := 0; i < 3; i++ {\n\t\t// TODO check stderr?\n\t\t<-closeChannel\n\t}\n\n\tcheckProofFile(t, expectedProofFile1)\n\tfilename := checkRecoverFile(t, \"client3@example.com\")\n\tcallRecover(newClient(clients[2]), filename)\n\t_ = os.Remove(filename)\n\tcheckProofFile(t, expectedProofFile2)\n\n\ttime.Sleep(time.Second)\n\treturn\n}", "func (s *BaseLittleDuckListener) EnterFactor_sign(ctx *Factor_signContext) {}", "func TestValidateRootRotationMissingNewSig(t *testing.T) {\n\ttestValidateRootRotationMissingNewSig(t, data.ECDSAKey, data.ECDSAx509Key)\n\tif !testing.Short() {\n\t\ttestValidateRootRotationMissingNewSig(t, data.RSAKey, data.RSAx509Key)\n\t}\n}", "func (k *KeyRing) verifySignature(signer string, signee *Key, signature *Signature) error {\n\tmessage := append(signee.Public, byte(signature.Trust))\n\tif !k.cryptoEngine.Verify(k.keys[signer].Public, message, signature.Data) {\n\t\treturn ErrInvalidSignature\n\t}\n\treturn nil\n}", "func (a *Ali) Verify(publicKey, sign []byte, req *NotifyReq) error {\n\tp, _ := pem.Decode(publicKey)\n\tif p == nil {\n\t\tpanic(\"Public key broken!\")\n\t}\n\tpub, err := x509.ParsePKIXPublicKey(p.Bytes)\n\tif err != nil {\n\t\treturn err\n\t}\n\th := crypto.Hash.New(crypto.SHA1)\n\tm := apikit.Params(structs.Map(req))\n\tb := sortedParams(removeKeys(m, \"sign\", \"sign_type\"))\n\th.Write(removeQuote(b.Bytes()))\n\tsum := h.Sum(nil)\n\tif sign, err = base64.StdEncoding.DecodeString(string(sign)); err != nil {\n\t\treturn err\n\t}\n\treturn rsa.VerifyPKCS1v15(pub.(*rsa.PublicKey), crypto.SHA1, sum, sign)\n}", "func (f *Factory) Sign(name string, txBuilder sdk.TxBuilder) error {\n\tsignMode := f.signMode\n\tif signMode == signing.SignMode_SIGN_MODE_UNSPECIFIED {\n\t\t// use the SignModeHandler's default mode if unspecified\n\t\tsignMode = f.txConfig.SignModeHandler().DefaultMode()\n\t}\n\tsignerData := sdk.SignerData{\n\t\tChainID: f.chainID,\n\t\tAccountNumber: f.accountNumber,\n\t\tSequence: f.sequence,\n\t}\n\n\tpubkey, _, err := f.keyManager.Find(name, f.password)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// For SIGN_MODE_DIRECT, calling SetSignatures calls setSignerInfos on\n\t// Factory under the hood, and SignerInfos is needed to generated the\n\t// sign bytes. This is the reason for setting SetSignatures here, with a\n\t// nil signature.\n\t//\n\t// Note: this line is not needed for SIGN_MODE_LEGACY_AMINO, but putting it\n\t// also doesn't affect its generated sign bytes, so for code's simplicity\n\t// sake, we put it here.\n\tsigData := signing.SingleSignatureData{\n\t\tSignMode: signMode,\n\t\tSignature: nil,\n\t}\n\tsig := signing.SignatureV2{\n\t\tPubKey: pubkey,\n\t\tData: &sigData,\n\t\tSequence: f.Sequence(),\n\t}\n\tif err := txBuilder.SetSignatures(sig); err != nil {\n\t\treturn err\n\t}\n\n\t// Generate the bytes to be signed.\n\tsignBytes, err := f.signModeHandler.GetSignBytes(signMode, signerData, txBuilder.GetTx())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Sign those bytes\n\tsigBytes, _, err := f.keyManager.Sign(name, f.password, signBytes)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Construct the SignatureV2 struct\n\tsigData = signing.SingleSignatureData{\n\t\tSignMode: signMode,\n\t\tSignature: sigBytes,\n\t}\n\tsig = signing.SignatureV2{\n\t\tPubKey: pubkey,\n\t\tData: &sigData,\n\t\tSequence: f.Sequence(),\n\t}\n\n\t// And here the tx is populated with the signature\n\treturn txBuilder.SetSignatures(sig)\n}", "func (mr *MockSignerDecrypterMockRecorder) Sign(arg0, arg1, arg2 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Sign\", reflect.TypeOf((*MockSignerDecrypter)(nil).Sign), arg0, arg1, arg2)\n}", "func Test_CanSign_NoUnspentTransactionMatches(t *testing.T) {\n\n\t// prepare input\n\tvar transactionInput *TransactionInput = &TransactionInput{\n\t\tOutputID: \"outID\",\n\t\tOutputIndex: 10,\n\t}\n\tvar unspentTransactions = []*UnspentTransactionOutput{\n\t\t{\n\t\t\tOutputID: \"outID1\",\n\t\t\tOutputIndex: 100,\n\t\t\tAddress: \"addressX\",\n\t\t},\n\t}\n\tvar publicKey = \"public_key\"\n\n\t// call can sign\n\tresult := CanSign(unspentTransactions, transactionInput, publicKey)\n\n\t// result should false\n\tif result {\n\t\tt.Errorf(\"when no unspent transaction matches the result should be false\")\n\t}\n}", "func (s *Service) Sign(ctx context.Context, credentials *checker.Credentials, accountName string, pubKey []byte, data *ruler.SignData) (core.RulesResult, []byte) {\n\tspan, ctx := opentracing.StartSpanFromContext(ctx, \"service.signer.Sign\")\n\tdefer span.Finish()\n\tlog := log.With().Str(\"action\", \"Sign\").Logger()\n\tlog.Debug().Msg(\"Request received\")\n\n\tif data == nil {\n\t\treturn core.DENIED, nil\n\t}\n\twallet, account, checkRes := s.preCheck(ctx, credentials, accountName, pubKey, ruler.ActionSign)\n\tif checkRes != core.APPROVED {\n\t\treturn checkRes, nil\n\t}\n\taccountName = fmt.Sprintf(\"%s/%s\", wallet.Name(), account.Name())\n\tlog = log.With().Str(\"account\", accountName).Logger()\n\n\t// Confirm approval via rules.\n\tresult := s.ruler.RunRules(ctx, ruler.ActionSign, wallet.Name(), account.Name(), account.PublicKey().Marshal(), data)\n\tswitch result {\n\tcase core.DENIED:\n\t\tlog.Debug().Str(\"result\", \"denied\").Msg(\"Denied by rules\")\n\t\treturn core.DENIED, nil\n\tcase core.FAILED:\n\t\tlog.Warn().Str(\"result\", \"failed\").Msg(\"Rules check failed\")\n\t\treturn core.FAILED, nil\n\t}\n\n\t// Sign it.\n\tsigningRoot, err := generateSigningRootFromRoot(ctx, data.Data, data.Domain)\n\tif err != nil {\n\t\tlog.Warn().Err(err).Str(\"result\", \"failed\").Msg(\"Failed to generate signing root\")\n\t\treturn core.FAILED, nil\n\t}\n\tspan, _ = opentracing.StartSpanFromContext(ctx, \"service.signer.Sign/Sign\")\n\tsignature, err := account.Sign(signingRoot[:])\n\tif err != nil {\n\t\tlog.Warn().Err(err).Str(\"result\", \"failed\").Msg(\"Failed to sign\")\n\t\tspan.Finish()\n\t\treturn core.FAILED, nil\n\t}\n\tspan.Finish()\n\n\tlog.Debug().Str(\"result\", \"succeeded\").Msg(\"Success\")\n\treturn core.APPROVED, signature.Marshal()\n}", "func (t *SuiteSuite) VerifyMethodsWrongSignatureSkipped2() int {\n\tt.Fatalf(\"This should never run.\")\n\treturn 0\n}", "func (c CryptoServiceTester) TestSignNoMatchingKeys(t *testing.T) {\n\tcryptoService := c.cryptoServiceFactory()\n\n\tprivKey, err := utils.GenerateECDSAKey(rand.Reader)\n\trequire.NoError(t, err, c.errorMsg(\"error creating key\"))\n\n\t// Test Sign\n\t_, _, err = cryptoService.GetPrivateKey(privKey.ID())\n\trequire.Error(t, err, c.errorMsg(\"Should not have found private key\"))\n}", "func TmSign(publicKey PublicKey, privateKey PrivateKey, digest Digest) Seal { panic(\"\") }", "func (k Keeper) handleValidatorSignature(ctx sdk.Context, addr crypto.Address, power int64, signed bool) {\n\tlogger := ctx.Logger().With(\"module\", \"x/slashing\")\n\theight := ctx.BlockHeight()\n\taddress := sdk.ValAddress(addr)\n\tpubkey, err := k.getPubkey(ctx, addr)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"Validator address %v not found\", addr))\n\t}\n\t// Local index, so counts blocks validator *should* have signed\n\t// Will use the 0-value default signing info if not present, except for start height\n\tsignInfo, found := k.getValidatorSigningInfo(ctx, address)\n\tif !found {\n\t\t// If this validator has never been seen before, construct a new SigningInfo with the correct start height\n\t\tsignInfo = NewValidatorSigningInfo(height, 0, time.Unix(0, 0), 0)\n\t}\n\tindex := signInfo.IndexOffset % k.SignedBlocksWindow(ctx)\n\tsignInfo.IndexOffset++\n\n\t// Update signed block bit array & counter\n\t// This counter just tracks the sum of the bit array\n\t// That way we avoid needing to read/write the whole array each time\n\tprevious := k.getValidatorSigningBitArray(ctx, address, index)\n\tif previous == signed {\n\t\t// Array value at this index has not changed, no need to update counter\n\t} else if previous && !signed {\n\t\t// Array value has changed from signed to unsigned, decrement counter\n\t\tk.setValidatorSigningBitArray(ctx, address, index, false)\n\t\tsignInfo.SignedBlocksCounter--\n\t} else if !previous && signed {\n\t\t// Array value has changed from unsigned to signed, increment counter\n\t\tk.setValidatorSigningBitArray(ctx, address, index, true)\n\t\tsignInfo.SignedBlocksCounter++\n\t}\n\n\tif !signed {\n\t\tlogger.Info(fmt.Sprintf(\"Absent validator %s at height %d, %d signed, threshold %d\", addr, height, signInfo.SignedBlocksCounter, k.MinSignedPerWindow(ctx)))\n\t}\n\tminHeight := signInfo.StartHeight + k.SignedBlocksWindow(ctx)\n\tif height > minHeight && signInfo.SignedBlocksCounter < k.MinSignedPerWindow(ctx) {\n\t\tvalidator := k.validatorSet.ValidatorByPubKey(ctx, pubkey)\n\t\tif validator != nil && !validator.GetRevoked() {\n\t\t\t// Downtime confirmed, slash, revoke, and jail the validator\n\t\t\tlogger.Info(fmt.Sprintf(\"Validator %s past min height of %d and below signed blocks threshold of %d\",\n\t\t\t\tpubkey.Address(), minHeight, k.MinSignedPerWindow(ctx)))\n\t\t\tk.validatorSet.Slash(ctx, pubkey, height, power, k.SlashFractionDowntime(ctx))\n\t\t\tk.validatorSet.Revoke(ctx, pubkey)\n\t\t\tsignInfo.JailedUntil = ctx.BlockHeader().Time.Add(k.DowntimeUnbondDuration(ctx))\n\t\t} else {\n\t\t\t// Validator was (a) not found or (b) already revoked, don't slash\n\t\t\tlogger.Info(fmt.Sprintf(\"Validator %s would have been slashed for downtime, but was either not found in store or already revoked\",\n\t\t\t\tpubkey.Address()))\n\t\t}\n\t}\n\n\t// Set the updated signing info\n\tk.setValidatorSigningInfo(ctx, address, signInfo)\n}", "func (auth *AuthManager) Sign(signables ...msgjson.Signable) error {\n\tfor i, signable := range signables {\n\t\tsigMsg, err := signable.Serialize()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"signature message for signable index %d: %v\", i, err)\n\t\t}\n\t\tsig, err := auth.signer.Sign(sigMsg)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"signature error: %v\", err)\n\t\t}\n\t\tsignable.SetSig(sig.Serialize())\n\t}\n\treturn nil\n}", "func checkMultipleSigners(tx authsigning.Tx) error {\n\tdirectSigners := 0\n\tsigsV2, err := tx.GetSignaturesV2()\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, sig := range sigsV2 {\n\t\tdirectSigners += countDirectSigners(sig.Data)\n\t\tif directSigners > 1 {\n\t\t\treturn sdkerrors.ErrNotSupported.Wrap(\"txs signed with CLI can have maximum 1 DIRECT signer\")\n\t\t}\n\t}\n\n\treturn nil\n}", "func (m *MetricsProvider) WitnessVerifyVCTSignature(value time.Duration) {\n}", "func (m *SignatureKeyHolderMock) CheckMocksCalled() {\n\tm.Finish()\n}", "func verifyTransaction(inc *Transaction) {\n\tif verifySignature(inc) {\n\t\t\texecuteTransaction(inc)\n\t} else {\n\t\treturn\n\t}\n}", "func VerifySigningKeyInput(keyFile string, isPublic bool) string {\n\tkeyFile = verifySigningKeyInputHelper(keyFile, isPublic, false)\n\tif _, err := os.Stat(keyFile); os.IsNotExist(err) {\n\t\tkeyFile = verifySigningKeyInputHelper(keyFile, isPublic, true)\n\t\tif _, err := os.Stat(keyFile); os.IsNotExist(err) {\n\t\t\tFatal(CLI_GENERAL_ERROR, i18n.GetMessagePrinter().Sprintf(\"%v. Please create the signing key.\", err))\n\t\t}\n\t}\n\n\treturn keyFile\n}", "func (mr *MockSignerMockRecorder) Check(arg0, arg1, arg2 interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Check\", reflect.TypeOf((*MockSigner)(nil).Check), arg0, arg1, arg2)\n}", "func (_RandomBeacon *RandomBeaconTransactorSession) ReportUnauthorizedSigning(signedMsgSender []byte, groupId uint64, groupMembers []uint32) (*types.Transaction, error) {\n\treturn _RandomBeacon.Contract.ReportUnauthorizedSigning(&_RandomBeacon.TransactOpts, signedMsgSender, groupId, groupMembers)\n}", "func SignCheckDeliver(\n\tt *testing.T, cdc *codec.Codec, app *baseapp.BaseApp, header abci.Header, msgs []sdk.Msg,\n\taccNums, seq []uint64, expSimPass, expPass bool, priv ...crypto.PrivKey,\n) sdk.Result {\n\n\ttx := GenTx(msgs, accNums, seq, priv...)\n\n\ttxBytes, err := cdc.MarshalBinaryLengthPrefixed(tx)\n\trequire.Nil(t, err)\n\n\t// Must simulate now as CheckTx doesn't run Msgs anymore\n\tres := app.Simulate(txBytes, tx)\n\n\tif expSimPass {\n\t\trequire.Equal(t, sdk.CodeOK, res.Code, res.Log)\n\t} else {\n\t\trequire.NotEqual(t, sdk.CodeOK, res.Code, res.Log)\n\t}\n\n\t// Simulate a sending a transaction and committing a block\n\tapp.BeginBlock(abci.RequestBeginBlock{Header: header})\n\tres = app.Deliver(tx)\n\n\tif expPass {\n\t\trequire.Equal(t, sdk.CodeOK, res.Code, res.Log)\n\t} else {\n\t\trequire.NotEqual(t, sdk.CodeOK, res.Code, res.Log)\n\t}\n\n\tapp.EndBlock(abci.RequestEndBlock{})\n\tapp.Commit()\n\n\treturn res\n}", "func Test_CanSign_UnspentTransactionWrongAddress(t *testing.T) {\n\n\t// prepare input\n\tvar transactionInput *TransactionInput = &TransactionInput{\n\t\tOutputID: \"outID\",\n\t\tOutputIndex: 10,\n\t}\n\tvar unspentTransactions = []*UnspentTransactionOutput{\n\t\t{\n\t\t\tOutputID: \"outID\",\n\t\t\tOutputIndex: 10,\n\t\t\tAddress: \"addressX\",\n\t\t},\n\t}\n\tvar publicKey = \"public_key\"\n\n\t// call can sign\n\tresult := CanSign(unspentTransactions, transactionInput, publicKey)\n\n\t// result should false\n\tif result {\n\t\tt.Errorf(\"when unspent transaction address is not the same as public key the result should be false\")\n\t}\n}", "func Test_CanSign_Correct(t *testing.T) {\n\n\t// prepare input\n\tvar transactionInput *TransactionInput = &TransactionInput{\n\t\tOutputID: \"outID\",\n\t\tOutputIndex: 10,\n\t}\n\tvar unspentTransactions = []*UnspentTransactionOutput{\n\t\t{\n\t\t\tOutputID: \"outID-1\",\n\t\t\tOutputIndex: 1000,\n\t\t\tAddress: \"addressX\",\n\t\t},\n\t\t{\n\t\t\tOutputID: \"outID\",\n\t\t\tOutputIndex: 10,\n\t\t\tAddress: \"public_key\",\n\t\t},\n\t}\n\tvar publicKey = \"public_key\"\n\n\t// call can sign\n\tresult := CanSign(unspentTransactions, transactionInput, publicKey)\n\n\t// result should false\n\tif !result {\n\t\tt.Errorf(\"The result must be true when there is unspent transaction and adddress is the same the public key\")\n\t}\n}", "func TestSenderRequest_Verify(t *testing.T) {\r\n\r\n\t// Create key\r\n\tkey, err := bitcoin.CreatePrivateKeyString()\r\n\tassert.NoError(t, err)\r\n\tassert.NotNil(t, key)\r\n\r\n\t// Create the request / message\r\n\tsenderRequest := &SenderRequest{\r\n\t\tDt: time.Now().UTC().Format(time.RFC3339),\r\n\t\tSenderHandle: testAlias + \"@\" + testDomain,\r\n\t\tSenderName: testName,\r\n\t\tPurpose: testMessage,\r\n\t}\r\n\r\n\t// Sign\r\n\tvar signature string\r\n\tsignature, err = senderRequest.Sign(key)\r\n\tassert.NoError(t, err)\r\n\tassert.NotEqual(t, 0, len(signature))\r\n\r\n\t// Get address from private key\r\n\tvar address string\r\n\taddress, err = bitcoin.GetAddressFromPrivateKeyString(key, false)\r\n\tassert.NoError(t, err)\r\n\tassert.NotNil(t, address)\r\n\r\n\tt.Run(\"valid verification\", func(t *testing.T) {\r\n\t\terr = senderRequest.Verify(address, signature)\r\n\t\tassert.NoError(t, err)\r\n\t})\r\n\r\n\tt.Run(\"invalid - empty address\", func(t *testing.T) {\r\n\t\terr = senderRequest.Verify(\"\", signature)\r\n\t\tassert.Error(t, err)\r\n\t})\r\n\r\n\tt.Run(\"invalid - empty signature\", func(t *testing.T) {\r\n\t\terr = senderRequest.Verify(address, \"\")\r\n\t\tassert.Error(t, err)\r\n\t})\r\n\r\n\tt.Run(\"invalid - wrong signature - hex short\", func(t *testing.T) {\r\n\t\terr = senderRequest.Verify(address, \"0\")\r\n\t\tassert.Error(t, err)\r\n\t})\r\n\r\n\tt.Run(\"invalid - wrong signature\", func(t *testing.T) {\r\n\t\terr = senderRequest.Verify(address, \"73646661736466736466617364667364666173646673646661736466\")\r\n\t\tassert.Error(t, err)\r\n\t})\r\n}", "func (d *identityManager) Sign(message []byte) ([]byte, error) {\n\treturn Sign(d.key.PrivateKey, message)\n}", "func (_RandomBeacon *RandomBeaconSession) ReportUnauthorizedSigning(signedMsgSender []byte, groupId uint64, groupMembers []uint32) (*types.Transaction, error) {\n\treturn _RandomBeacon.Contract.ReportUnauthorizedSigning(&_RandomBeacon.TransactOpts, signedMsgSender, groupId, groupMembers)\n}", "func (ks *Keystore) CheckSignature(prefix string, signed, signature io.ReadSeeker) (*openpgp.Entity, error) {\n\treturn checkSignature(ks, prefix, signed, signature)\n}", "func verify(msgSender msgSectionSender) {\n\tlog.Info(fmt.Sprintf(\"Verify %T\", msgSender.Section), \"msgSection\", msgSender.Section)\n\tswitch msgSender.Section.(type) {\n\tcase *rainslib.AssertionSection, *rainslib.ShardSection, *rainslib.ZoneSection,\n\t\t*rainslib.AddressAssertionSection, *rainslib.AddressZoneSection:\n\t\tsectionSender := sectionWithSigSender{\n\t\t\tSection: msgSender.Section.(rainslib.MessageSectionWithSig),\n\t\t\tSender: msgSender.Sender,\n\t\t\tToken: msgSender.Token,\n\t\t}\n\t\tverifySection(sectionSender)\n\tcase *rainslib.AddressQuerySection, *rainslib.QuerySection:\n\t\tverifyQuery(msgSender.Section.(rainslib.MessageSectionQuery), msgSender)\n\tdefault:\n\t\tlog.Warn(\"Not supported Msg section to verify\", \"msgSection\", msgSender)\n\t}\n}", "func Test_VerifySigFromTass(t *testing.T) {\n\trequire := require.New(t)\n\n\t//c := &sm2.Driver{}\n\n\txBytes := common.FromHex(\"0000000000000000000000000000000000000000000000000000000000000000FD4241057FEC6CBEEC501F7E1763751B8F6DFCFB910FB634FBB76A16639EF172\")\n\tyBytes := common.FromHex(\"00000000000000000000000000000000000000000000000000000000000000001C6DA89F9C1A5EE9B6108E5A2A5FE336962630A34DBA1AF428451E1CE63BB3CF\")\n\tx := new(big.Int).SetBytes(xBytes)\n\ty := new(big.Int).SetBytes(yBytes)\n\n\tpublicKey := &gmsm_sm2.PublicKey{\n\t\tX: x,\n\t\tY: y,\n\t}\n\tvar pubSM2 sm2.PubKeySM2\n\tcopy(pubSM2[:], gmsm_sm2.Compress(publicKey))\n\n\trBytes := common.FromHex(\"00000000000000000000000000000000000000000000000000000000000000003AA29337E7149047FB8AE83F30AA00125E23173C88F284ADDED2E5B59ACAA5B9\")\n\tsBytes := common.FromHex(\"0000000000000000000000000000000000000000000000000000000000000000E2E9338109D74269578216039FD4D1C764E7F6F142CBB2E3035E7E49D375D330\")\n\tr := new(big.Int).SetBytes(rBytes)\n\ts := new(big.Int).SetBytes(sBytes)\n\n\tsignature := sm2.SignatureSM2(sm2.Serialize(r, s))\n\n\tmsg := []byte(\"112233445566112233445566112233445566112233445566\")\n\tok := pubSM2.VerifyBytes(msg, signature)\n\trequire.Equal(true, ok)\n}", "func (a *ActiveDevice) setSigningKey(g *GlobalContext, uv keybase1.UserVersion, deviceID keybase1.DeviceID,\n\tsigKey GenericKey, deviceName string) error {\n\ta.Lock()\n\tdefer a.Unlock()\n\n\tif err := a.internalUpdateUserVersionDeviceID(uv, deviceID); err != nil {\n\t\treturn err\n\t}\n\n\ta.signingKey = sigKey\n\tif len(deviceName) > 0 {\n\t\ta.deviceName = deviceName\n\t}\n\ta.nistFactory = NewNISTFactory(g, uv.Uid, deviceID, sigKey)\n\treturn nil\n}", "func (mm *MessageMaker) Signer() *MockSigner {\n\treturn mm.signer\n}", "func (mm *MessageMaker) Signer() *MockSigner {\n\treturn mm.signer\n}", "func (u *walletIdentity) Verify(msg []byte, sig []byte) error {\n\treturn errors.New(\"not implemented\")\n}", "func strictSignatureCheck(pk PublicKey, signature ByteSlice) error {\n\tswitch pk.Algorithm {\n\tcase SignatureAlgoEd25519:\n\t\tif len(pk.Key) != crypto.PublicKeySize {\n\t\t\treturn errors.New(\"invalid public key size in transaction\")\n\t\t}\n\t\tif len(signature) != crypto.SignatureSize {\n\t\t\treturn errors.New(\"invalid signature size in transaction\")\n\t\t}\n\t\treturn nil\n\tdefault:\n\t\treturn errors.New(\"unrecognized public key type in transaction\")\n\t}\n}", "func (v *Verifier) Verify(msg []byte, sig []byte) error {\n\treturn errors.New(\"NotImplemented\")\n}", "func VerifyOnChain(msg []byte, signature []byte, signers EthAddresses,\n) (types.OracleID, error) {\n\tauthor, err := crypto.SigToPub(onChainHash(msg), signature)\n\tif err != nil {\n\t\treturn types.OracleID(-1), errors.Wrapf(err, \"while trying to recover \"+\n\t\t\t\"sender from sig %x on msg %+v\", signature, msg)\n\t}\n\toid, ok := signers[(*OnChainPublicKey)(author).Address()]\n\tif ok {\n\t\treturn oid, nil\n\t} else {\n\t\treturn types.OracleID(-1), errors.Errorf(\"signer is not on whitelist\")\n\t}\n}", "func (m *SignedMessage) verifySignature(data []byte) error {\n\tsender, err := VerifyMessage(data)\n\tif err != nil {\n\t\treturn err\n\t}\n\tm.Sender = sender\n\treturn nil\n}", "func SignCheckDeliver(\n\tt *testing.T, cdc *codec.Codec, app *bam.BaseApp, header abci.Header, msgs []sdk.Msg,\n\taccNums, seq []uint64, expSimPass, expPass bool, priv ...crypto.PrivKey,\n) (sdk.GasInfo, *sdk.Result, error) {\n\n\ttx := helpers.GenTx(\n\t\tmsgs,\n\t\tsdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, 0)},\n\t\thelpers.DefaultGenTxGas,\n\t\t\"\",\n\t\taccNums,\n\t\tseq,\n\t\tpriv...,\n\t)\n\n\ttxBytes, err := cdc.MarshalBinaryBare(tx)\n\trequire.Nil(t, err)\n\n\t// Must simulate now as CheckTx doesn't run Msgs anymore\n\t_, res, err := app.Simulate(txBytes, tx)\n\n\tif expSimPass {\n\t\trequire.NoError(t, err)\n\t\trequire.NotNil(t, res)\n\t} else {\n\t\trequire.Error(t, err)\n\t\trequire.Nil(t, res)\n\t}\n\n\t// Simulate a sending a transaction and committing a block\n\tapp.BeginBlock(abci.RequestBeginBlock{Header: header})\n\tgInfo, res, err := app.Deliver(tx)\n\n\tif expPass {\n\t\trequire.NoError(t, err)\n\t\trequire.NotNil(t, res)\n\t} else {\n\t\trequire.Error(t, err)\n\t\trequire.Nil(t, res)\n\t}\n\n\tapp.EndBlock(abci.RequestEndBlock{})\n\tapp.Commit()\n\n\treturn gInfo, res, err\n}", "func (m *MetricsProvider) SignerAddLinkedDataProof(value time.Duration) {\n}", "func Test_CanSign_NilInput(t *testing.T) {\n\n\t// prepare input\n\tvar transactionInput *TransactionInput\n\tvar unspentTransactions []*UnspentTransactionOutput\n\tvar publicKey = \"\"\n\n\t// call can sign\n\tresult := CanSign(unspentTransactions, transactionInput, publicKey)\n\n\t// result should false\n\tif result {\n\t\tt.Errorf(\"result of nil transaction should be false.\")\n\t}\n}", "func (mr *MockCertificateSigningRequestEventHandlerMockRecorder) GenericCertificateSigningRequest(obj interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GenericCertificateSigningRequest\", reflect.TypeOf((*MockCertificateSigningRequestEventHandler)(nil).GenericCertificateSigningRequest), obj)\n}", "func DefaultSigVerificationGasConsumer(\n\tmeter sdk.GasMeter, sig signing.SignatureV2, params authtypes.Params,\n) error {\n\tpubkey := sig.PubKey\n\tswitch pubkey := pubkey.(type) {\n\tcase *ethsecp256k1.PubKey:\n\t\tmeter.ConsumeGas(secp256k1VerifyCost, \"ante verify: eth_secp256k1\")\n\t\treturn nil\n\n\tcase multisig.PubKey:\n\t\t// Multisig keys\n\t\tmultisignature, ok := sig.Data.(*signing.MultiSignatureData)\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"expected %T, got, %T\", &signing.MultiSignatureData{}, sig.Data)\n\t\t}\n\t\treturn ConsumeMultisignatureVerificationGas(meter, multisignature, pubkey, params, sig.Sequence)\n\n\tdefault:\n\t\treturn authante.DefaultSigVerificationGasConsumer(meter, sig, params)\n\t}\n}", "func (account *NothingAccount) CheckSignature(message []byte, signature Signature) error {\n\treturn fault.InvalidSignature\n}", "func (s *Service) addSigner(signer network.ServerIdentityID, proof *gpr.SignatureResponse, e int) error {\n\tif proof != nil {\n\t\tif e < 0 {\n\t\t\treturn errors.New(\"Epoch cannot be negative\")\n\t\t}\n\t\ts.storage.Lock()\n\n\t\tif e > len(s.storage.Signers) {\n\t\t\tlog.LLvl1(\" Error in add signer ? \")\n\t\t\treturn errors.New(\"Epoch is too in the future\")\n\t\t}\n\n\t\tif e == len(s.storage.Signers) {\n\t\t\ts.storage.Signers = append(s.storage.Signers, make(SignersSet))\n\t\t}\n\n\t\tif s.e > Epoch(e) {\n\t\t\treturn errors.New(\" Error in add signer - Cannot sign for previous epochs \")\n\t\t}\n\t\tif s.Cycle.GetTimeTillNextEpoch() < TIME_FOR_CONSENCUS || s.Cycle.GetEpoch() >= Epoch(e) {\n\t\t\treturn errors.New(\" Error in add signer - Cannot sign for previous epochs \")\n\t\t}\n\n\t\ts.storage.Signers[Epoch(e)][signer] = *proof\n\t\ts.storage.Unlock()\n\t\treturn nil\n\t}\n\treturn fmt.Errorf(\"Addsigner cannot be completed for %v as %v did not send a signature\", s.Name, signer)\n\n}", "func SignHandler(w http.ResponseWriter, r *http.Request) ErrorResponse {\n\n\t// Check that we have an authorised API key header\n\terr := checkAPIKey(r.Header.Get(\"api-key\"))\n\tif err != nil {\n\t\tlogMessage(\"SIGN\", \"invalid-api-key\", \"Invalid API key used\")\n\t\treturn ErrorInvalidAPIKey\n\t}\n\n\tif r.Body == nil {\n\t\tlogMessage(\"SIGN\", \"invalid-assertion\", \"Uninitialized POST data\")\n\t\treturn ErrorNilData\n\t}\n\n\t// Read the full request body\n\tdata, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\tlogMessage(\"SIGN\", \"invalid-assertion\", err.Error())\n\t\treturn ErrorResponse{false, \"error-sign-read\", \"\", err.Error(), http.StatusBadRequest}\n\t}\n\tif len(data) == 0 {\n\t\tlogMessage(\"SIGN\", \"invalid-assertion\", \"No data supplied for signing\")\n\t\treturn ErrorEmptyData\n\t}\n\n\tdefer r.Body.Close()\n\n\t// Use the snapd assertions module to decode the body and validate\n\tassertion, err := asserts.Decode(data)\n\tif err != nil {\n\t\tlogMessage(\"SIGN\", \"invalid-assertion\", err.Error())\n\t\treturn ErrorResponse{false, \"decode-assertion\", \"\", err.Error(), http.StatusBadRequest}\n\t}\n\n\t// Check that we have a serial-request assertion (the details will have been validated by Decode call)\n\tif assertion.Type() != asserts.SerialRequestType {\n\t\tlogMessage(\"SIGN\", \"invalid-type\", \"The assertion type must be 'serial-request'\")\n\t\treturn ErrorInvalidType\n\t}\n\n\t// Verify that the nonce is valid and has not expired\n\terr = Environ.DB.ValidateDeviceNonce(assertion.HeaderString(\"request-id\"))\n\tif err != nil {\n\t\tlogMessage(\"SIGN\", \"invalid-nonce\", \"Nonce is invalid or expired\")\n\t\treturn ErrorInvalidNonce\n\t}\n\n\t// Validate the model by checking that it exists on the database\n\tmodel, err := Environ.DB.FindModel(assertion.HeaderString(\"brand-id\"), assertion.HeaderString(\"model\"))\n\tif err != nil {\n\t\tlogMessage(\"SIGN\", \"invalid-model\", \"Cannot find model with the matching brand and model\")\n\t\treturn ErrorInvalidModel\n\t}\n\n\t// Check that the model has an active keypair\n\tif !model.KeyActive {\n\t\tlogMessage(\"SIGN\", \"invalid-model\", \"The model is linked with an inactive signing-key\")\n\t\treturn ErrorInactiveModel\n\t}\n\n\t// Create a basic signing log entry (without the serial number)\n\tsigningLog := SigningLog{Make: assertion.HeaderString(\"brand-id\"), Model: assertion.HeaderString(\"model\"), Fingerprint: assertion.SignKeyID()}\n\n\t// Convert the serial-request headers into a serial assertion\n\tserialAssertion, err := serialRequestToSerial(assertion, &signingLog)\n\tif err != nil {\n\t\tlogMessage(\"SIGN\", \"create-assertion\", err.Error())\n\t\treturn ErrorCreateAssertion\n\t}\n\n\t// Sign the assertion with the snapd assertions module\n\tsignedAssertion, err := Environ.KeypairDB.SignAssertion(asserts.SerialType, serialAssertion.Headers(), serialAssertion.Body(), model.AuthorityID, model.KeyID, model.SealedKey)\n\tif err != nil {\n\t\tlogMessage(\"SIGN\", \"signing-assertion\", err.Error())\n\t\treturn ErrorResponse{false, \"signing-assertion\", \"\", err.Error(), http.StatusInternalServerError}\n\t}\n\n\t// Store the serial number and device-key fingerprint in the database\n\terr = Environ.DB.CreateSigningLog(signingLog)\n\tif err != nil {\n\t\tlogMessage(\"SIGN\", \"logging-assertion\", err.Error())\n\t\treturn ErrorResponse{false, \"logging-assertion\", \"\", err.Error(), http.StatusInternalServerError}\n\t}\n\n\t// Return successful JSON response with the signed text\n\tformatSignResponse(true, \"\", \"\", \"\", signedAssertion, w)\n\treturn ErrorResponse{Success: true}\n}", "func TestCryptoSignerInterfaceBehavior(t *testing.T) {\n\tcs := NewCryptoService(trustmanager.NewKeyMemoryStore(passphraseRetriever))\n\tinterfaces.EmptyCryptoServiceInterfaceBehaviorTests(t, cs)\n\tinterfaces.CreateGetKeyCryptoServiceInterfaceBehaviorTests(t, cs, data.ECDSAKey)\n\n\tcs = NewCryptoService(trustmanager.NewKeyMemoryStore(passphraseRetriever))\n\tinterfaces.CreateListKeyCryptoServiceInterfaceBehaviorTests(t, cs, data.ECDSAKey)\n\n\tcs = NewCryptoService(trustmanager.NewKeyMemoryStore(passphraseRetriever))\n\tinterfaces.AddGetKeyCryptoServiceInterfaceBehaviorTests(t, cs, data.ECDSAKey)\n\n\tcs = NewCryptoService(trustmanager.NewKeyMemoryStore(passphraseRetriever))\n\tinterfaces.AddListKeyCryptoServiceInterfaceBehaviorTests(t, cs, data.ECDSAKey)\n}", "func (m *InternalDomainFederation) SetIsSignedAuthenticationRequestRequired(value *bool)() {\n err := m.GetBackingStore().Set(\"isSignedAuthenticationRequestRequired\", value)\n if err != nil {\n panic(err)\n }\n}", "func (c *clientImpl) VerifyTxnProposalSignature(channel sdkApi.Channel, proposalBytes []byte) error {\n\tif channel.MSPManager() == nil {\n\t\treturn errors.Errorf(errors.GeneralError, \"Channel %s GetMSPManager is nil\", channel.Name())\n\t}\n\tmsps, err := channel.MSPManager().GetMSPs()\n\tif err != nil {\n\t\treturn errors.Errorf(errors.GeneralError, \"GetMSPs return error:%v\", err)\n\t}\n\tif len(msps) == 0 {\n\t\treturn errors.Errorf(errors.GeneralError, \"Channel %s MSPManager.GetMSPs is empty\", channel.Name())\n\t}\n\n\tsignedProposal := &pb.SignedProposal{}\n\tif err := proto.Unmarshal(proposalBytes, signedProposal); err != nil {\n\t\treturn errors.Wrap(errors.GeneralError, err, \"Unmarshal clientProposalBytes error\")\n\t}\n\n\tcreatorBytes, err := utils.GetCreatorFromSignedProposal(signedProposal)\n\tif err != nil {\n\t\treturn errors.Wrap(errors.GeneralError, err, \"GetCreatorFromSignedProposal return error\")\n\t}\n\n\tserializedIdentity := &protosMSP.SerializedIdentity{}\n\tif err := proto.Unmarshal(creatorBytes, serializedIdentity); err != nil {\n\t\treturn errors.Wrap(errors.GeneralError, err, \"Unmarshal creatorBytes error\")\n\t}\n\n\tmsp := msps[serializedIdentity.Mspid]\n\tif msp == nil {\n\t\treturn errors.Errorf(errors.GeneralError, \"MSP %s not found\", serializedIdentity.Mspid)\n\t}\n\n\tcreator, err := msp.DeserializeIdentity(creatorBytes)\n\tif err != nil {\n\t\treturn errors.Wrap(errors.GeneralError, err, \"Failed to deserialize creator identity\")\n\t}\n\tlogger.Debugf(\"checkSignatureFromCreator info: creator is %s\", creator.GetIdentifier())\n\t// ensure that creator is a valid certificate\n\terr = creator.Validate()\n\tif err != nil {\n\t\treturn errors.Wrap(errors.GeneralError, err, \"The creator certificate is not valid\")\n\t}\n\n\tlogger.Debugf(\"verifyTPSignature info: creator is valid\")\n\n\t// validate the signature\n\terr = creator.Verify(signedProposal.ProposalBytes, signedProposal.Signature)\n\tif err != nil {\n\t\treturn errors.Wrap(errors.GeneralError, err, \"The creator's signature over the proposal is not valid\")\n\t}\n\n\tlogger.Debugf(\"VerifyTxnProposalSignature exists successfully\")\n\n\treturn nil\n}", "func (v Vote) CheckSignature(pk []byte) error {\n\t// TODO do the actual check\n\treturn nil\n}", "func TestHandleAlreadyInactive(t *testing.T) {\n\t// initial setup\n\tapp := simapp.Setup(false)\n\tctx := app.BaseApp.NewContext(false, tmproto.Header{})\n\n\taddrDels := simapp.AddTestAddrsIncremental(app, ctx, 1, sdk.TokensFromConsensusPower(200, sdk.DefaultPowerReduction))\n\tvalAddrs := simapp.ConvertAddrsToValAddrs(addrDels)\n\tpks := simapp.CreateTestPubKeys(1)\n\taddr, val := valAddrs[0], pks[0]\n\tpower := int64(100)\n\ttstaking := teststaking.NewHelper(t, ctx, app.CustomStakingKeeper, app.CustomGovKeeper)\n\n\ttstaking.CreateValidator(addr, val, true)\n\n\tstaking.EndBlocker(ctx, app.CustomStakingKeeper)\n\n\t// 1000 first blocks OK\n\theight := int64(0)\n\tfor ; height < 1000; height++ {\n\t\tctx = ctx.WithBlockHeight(height)\n\t\tapp.CustomSlashingKeeper.HandleValidatorSignature(ctx, val.Address(), power, true)\n\t}\n\n\tproperties := app.CustomGovKeeper.GetNetworkProperties(ctx)\n\t// miss 11 blocks for mischance confidence\n\tfor ; height < 1000+int64(properties.MischanceConfidence)+1; height++ {\n\t\tctx = ctx.WithBlockHeight(height)\n\t\tapp.CustomSlashingKeeper.HandleValidatorSignature(ctx, val.Address(), power, false)\n\t}\n\n\t// info correctness after the overflow of mischance confidence\n\tinfo, found := app.CustomSlashingKeeper.GetValidatorSigningInfo(ctx, sdk.ConsAddress(val.Address()))\n\trequire.True(t, found)\n\trequire.Equal(t, int64(10), info.MischanceConfidence)\n\trequire.Equal(t, int64(1), info.Mischance)\n\trequire.Equal(t, int64(999), info.LastPresentBlock)\n\n\t// miss 110 blocks after mischance confidence happen\n\tfor ; height < 1000+int64(properties.MaxMischance+properties.MischanceConfidence)+1; height++ {\n\t\tctx = ctx.WithBlockHeight(height)\n\t\tapp.CustomSlashingKeeper.HandleValidatorSignature(ctx, val.Address(), power, false)\n\t}\n\n\t// end block\n\tstaking.EndBlocker(ctx, app.CustomStakingKeeper)\n\n\t// validator should have been inactivated\n\tvalidator, _ := app.CustomStakingKeeper.GetValidatorByConsAddr(ctx, sdk.GetConsAddress(val))\n\trequire.Equal(t, stakingtypes.Inactive, validator.GetStatus())\n\n\t// another block missed\n\tctx = ctx.WithBlockHeight(height)\n\tapp.CustomSlashingKeeper.HandleValidatorSignature(ctx, val.Address(), power, false)\n\n\t// validator should be in inactive status yet\n\tvalidator, _ = app.CustomStakingKeeper.GetValidatorByConsAddr(ctx, sdk.GetConsAddress(val))\n\trequire.Equal(t, stakingtypes.Inactive, validator.GetStatus())\n}", "func (wL *wrappedMultiVerifier) VerifySignature(s, _ io.Reader, _ ...signature.VerifyOption) error {\n\tsig, err := io.ReadAll(s)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tenv := dsse.Envelope{}\n\tif err := json.Unmarshal(sig, &env); err != nil {\n\t\treturn err\n\t}\n\n\tenvVerifier, err := dsse.NewMultiEnvelopeVerifier(wL.threshold, wL.vLAdapters...)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = envVerifier.Verify(context.Background(), &env)\n\treturn err\n}", "func (s *KeyStore) verifySignature(signed []byte, role string, signatures []Signature, filename string) error {\n\tif s == nil {\n\t\treturn nil\n\t}\n\n\t// Check for duplicate signatures.\n\thas := make(map[string]struct{})\n\tfor _, sig := range signatures {\n\t\tif _, ok := has[sig.KeyID]; ok {\n\t\t\treturn newSignatureError(filename, errors.Errorf(\"signature section of %s contains duplicate signatures\", filename))\n\t\t}\n\t\thas[sig.KeyID] = struct{}{}\n\t}\n\n\tks, ok := s.Load(role)\n\tif !ok {\n\t\treturn errors.Errorf(\"Unknown role %s\", role)\n\t}\n\tkeys := ks.(roleKeys)\n\n\tvar validSigs uint\n\tfor _, sig := range signatures {\n\t\tkey, ok := keys.keys.Load(sig.KeyID)\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\t\terr := key.(crypto.PubKey).VerifySignature(signed, sig.Sig)\n\t\tif err != nil {\n\t\t\treturn newSignatureError(filename, err)\n\t\t}\n\t\tvalidSigs++\n\t}\n\n\t// We may need to verify the root manifest with old keys. Once the most up to date root is found and verified, then\n\t// the keys used to do so should be checked for expiry.\n\tif role != ManifestTypeRoot {\n\t\tif err := CheckExpiry(filename, keys.expiry); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tif validSigs < keys.threshold {\n\t\treturn newSignatureError(filename, errors.Errorf(\"not enough signatures (%v) for threshold %v in %s\", validSigs, keys.threshold, filename))\n\t}\n\n\treturn nil\n}", "func TestValidateRootRotationMissingOrigSig(t *testing.T) {\n\ttestValidateRootRotationMissingOrigSig(t, data.ECDSAKey, data.ECDSAx509Key)\n\tif !testing.Short() {\n\t\ttestValidateRootRotationMissingOrigSig(t, data.RSAKey, data.RSAx509Key)\n\t}\n}", "func TestValidateRootSigMissing(t *testing.T) {\n\tkdb, repo, cs := testutils.EmptyRepo()\n\tstore := storage.NewMemStorage()\n\n\tdelete(repo.Root.Signed.Roles, \"snapshot\")\n\n\tr, tg, sn, ts, err := testutils.Sign(repo)\n\tassert.NoError(t, err)\n\n\tr.Signatures = nil\n\n\troot, targets, snapshot, timestamp, err := getUpdates(r, tg, sn, ts)\n\tassert.NoError(t, err)\n\n\tupdates := []storage.MetaUpdate{root, targets, snapshot, timestamp}\n\n\tcopyTimestampKey(t, kdb, store, \"testGUN\")\n\t_, err = validateUpdate(cs, \"testGUN\", updates, store)\n\tassert.Error(t, err)\n\tassert.IsType(t, validation.ErrBadRoot{}, err)\n}", "func (m *MetricsProvider) AddProofSign(value time.Duration) {\n}", "func (m *PacketParserMock) MinimockGetPacketSignatureDone() bool {\n\tfor _, e := range m.GetPacketSignatureMock.expectations {\n\t\tif mm_atomic.LoadUint64(&e.Counter) < 1 {\n\t\t\treturn false\n\t\t}\n\t}\n\n\t// if default expectation was set then invocations count should be greater than zero\n\tif m.GetPacketSignatureMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterGetPacketSignatureCounter) < 1 {\n\t\treturn false\n\t}\n\t// if func was set then invocations count should be greater than zero\n\tif m.funcGetPacketSignature != nil && mm_atomic.LoadUint64(&m.afterGetPacketSignatureCounter) < 1 {\n\t\treturn false\n\t}\n\treturn true\n}", "func (mr *MockProvidersMockRecorder) IdentityManager(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"IdentityManager\", reflect.TypeOf((*MockProviders)(nil).IdentityManager), arg0)\n}", "func Test_CanSign_NoUnspentTransactions(t *testing.T) {\n\n\t// prepare input\n\tvar transactionInput *TransactionInput = &TransactionInput{\n\t\tOutputID: \"outID\",\n\t\tOutputIndex: 10,\n\t}\n\tvar unspentTransactions []*UnspentTransactionOutput\n\tvar publicKey = \"\"\n\n\t// call can sign\n\tresult := CanSign(unspentTransactions, transactionInput, publicKey)\n\n\t// result should false\n\tif result {\n\t\tt.Errorf(\"result when there are no unspent transactions should be false.\")\n\t}\n}", "func (o MfaPingidOutput) UseSignature() pulumi.BoolOutput {\n\treturn o.ApplyT(func(v *MfaPingid) pulumi.BoolOutput { return v.UseSignature }).(pulumi.BoolOutput)\n}", "func (mmSignWith *mDigestHolderMockSignWith) Set(f func(signer DigestSigner) (s1 SignedDigestHolder)) *DigestHolderMock {\n\tif mmSignWith.defaultExpectation != nil {\n\t\tmmSignWith.mock.t.Fatalf(\"Default expectation is already set for the DigestHolder.SignWith method\")\n\t}\n\n\tif len(mmSignWith.expectations) > 0 {\n\t\tmmSignWith.mock.t.Fatalf(\"Some expectations are already set for the DigestHolder.SignWith method\")\n\t}\n\n\tmmSignWith.mock.funcSignWith = f\n\treturn mmSignWith.mock\n}", "func (auth *Manager) Signed(service core.APIService) core.APIService {\n\treturn &wrapped{\n\t\tinfoService: service.InfoService,\n\t\tconfigService: func(ctx context.Context, config *v0.Config) (*v0.Response, error) {\n\t\t\tok, wrongSig, err := auth.Check(config)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tif !ok {\n\t\t\t\treturn response.MSG(v0.Code_BadRequest, fmt.Sprintf(\"incorrect signature for: %s\", wrongSig)), nil\n\t\t\t}\n\t\t\treturn service.ConfigService(ctx, config)\n\t\t},\n\t}\n}", "func (m *ActiveNodeMock) GetSignatureVerifierFinished() bool {\n\t// if expectation series were set then invocations count should be equal to expectations count\n\tif len(m.GetSignatureVerifierMock.expectationSeries) > 0 {\n\t\treturn atomic.LoadUint64(&m.GetSignatureVerifierCounter) == uint64(len(m.GetSignatureVerifierMock.expectationSeries))\n\t}\n\n\t// if main expectation was set then invocations count should be greater than zero\n\tif m.GetSignatureVerifierMock.mainExpectation != nil {\n\t\treturn atomic.LoadUint64(&m.GetSignatureVerifierCounter) > 0\n\t}\n\n\t// if func was set then invocations count should be greater than zero\n\tif m.GetSignatureVerifierFunc != nil {\n\t\treturn atomic.LoadUint64(&m.GetSignatureVerifierCounter) > 0\n\t}\n\n\treturn true\n}", "func (mr *MockTransactionApiMockRecorder) SignWithPrivkey(tx, outpoint, privkey, sighashType, utxoList interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"SignWithPrivkey\", reflect.TypeOf((*MockTransactionApi)(nil).SignWithPrivkey), tx, outpoint, privkey, sighashType, utxoList)\n}", "func TestTokenSignature(t *testing.T) {\n\tdb.InitDB()\n\tvar router *gin.Engine = routes.SetupRouter()\n\n\tvar user models.UserCreate = utils.CreateUser(\"Tom\", \"qwerty1234\", t, router)\n\tuser.Token = utils.ConnectUser(\"Tom\", \"qwerty1234\", t, router)\n\n\tsplittedToken := strings.Split(user.Token, \".\")\n\tif len(splittedToken) != 3 {\n\t\tlog.Fatal(\"Bad token.\")\n\t\tt.Fail()\n\t}\n\n\theader := splittedToken[0]\n\tpayload := splittedToken[1]\n\tsignature := splittedToken[2]\n\tsignature = signature + \"modif\"\n\tmodifiedToken := header + \".\" + payload + \".\" + signature\n\n\tvar url string = \"/v1/user/\" + strconv.Itoa(user.ID)\n\tvar bearer = \"Bearer \" + modifiedToken\n\trecord := httptest.NewRecorder()\n\trequest, _ := http.NewRequest(\"GET\", url, nil)\n\trequest.Header.Add(\"Content-Type\", \"application/json\")\n\trequest.Header.Add(\"Authorization\", bearer)\n\n\trouter.ServeHTTP(record, request)\n\n\tvar message Message\n\terr := json.Unmarshal([]byte(record.Body.String()), &message)\n\tif err != nil {\n\t\tlog.Fatal(\"Bad output: \", err.Error())\n\t\tt.Fail()\n\t}\n\n\tassert.Equal(t, record.Code, 403)\n\tassert.Equal(t, message.Message, \"Bad signature\")\n\n\tuser.Token = utils.ConnectUser(\"Tom\", \"qwerty1234\", t, router)\n\tutils.CleanUser(user.ID, user.Token, t, router)\n\tdb.CloseDB()\n}", "func (_Authority *AuthorityTransactorSession) MarkPubKeySignAsUsed(sha256Sign [32]byte, sender common.Address) (*types.Transaction, error) {\n\treturn _Authority.Contract.MarkPubKeySignAsUsed(&_Authority.TransactOpts, sha256Sign, sender)\n}", "func TestReSign(t *testing.T) {\n\tcs := NewEd25519()\n\tkey, err := cs.Create(data.CanonicalRootRole, \"\", data.ED25519Key)\n\trequire.NoError(t, err)\n\ttestData := data.Signed{\n\t\tSigned: &json.RawMessage{},\n\t}\n\n\tSign(cs, &testData, key)\n\tSign(cs, &testData, key)\n\n\tif len(testData.Signatures) != 1 {\n\t\tt.Fatalf(\"Incorrect number of signatures: %d\", len(testData.Signatures))\n\t}\n\n\tif testData.Signatures[0].KeyID != key.ID() {\n\t\tt.Fatalf(\"Wrong signature ID returned: %s\", testData.Signatures[0].KeyID)\n\t}\n\n}" ]
[ "0.7177863", "0.6207512", "0.6117189", "0.6066826", "0.59165514", "0.56492317", "0.5569576", "0.55575526", "0.5550145", "0.55306005", "0.552737", "0.55094844", "0.5454164", "0.54317886", "0.5427068", "0.5407418", "0.5390146", "0.5378672", "0.53569645", "0.53116786", "0.5305595", "0.5268303", "0.5244145", "0.5238336", "0.52184844", "0.520407", "0.5185799", "0.5148392", "0.51437426", "0.51396483", "0.5129109", "0.5112165", "0.5107577", "0.5080153", "0.5054569", "0.5041749", "0.50398403", "0.5033105", "0.5030526", "0.5029927", "0.50281894", "0.50249565", "0.50211805", "0.501766", "0.5003009", "0.49943078", "0.49933338", "0.49918306", "0.49728608", "0.49606454", "0.49450478", "0.4922855", "0.49120402", "0.49075782", "0.49052715", "0.48994243", "0.48976415", "0.4896487", "0.48942262", "0.4887769", "0.4887463", "0.48845938", "0.48789382", "0.48749533", "0.48669884", "0.48669884", "0.4866774", "0.4859764", "0.4854274", "0.48540056", "0.48504815", "0.4848591", "0.48407307", "0.48401943", "0.48397017", "0.48343047", "0.48323882", "0.48274526", "0.4824451", "0.48196918", "0.48141095", "0.48130715", "0.48109984", "0.4810143", "0.48091614", "0.4809057", "0.48008445", "0.4799265", "0.47991708", "0.4796841", "0.4796003", "0.4789852", "0.47885895", "0.47877133", "0.47860423", "0.47837284", "0.47821406", "0.4781181", "0.47789618", "0.47760293" ]
0.7240038
0
UserStore mocks base method
func (m *MockProviders) UserStore() msp.UserStore { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "UserStore") ret0, _ := ret[0].(msp.UserStore) return ret0 }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func TestUserstorage(t *testing.T) {\n t.Log(\"*** User data storage and retrieval test ***\")\n\n // initialize user\n u, err := InitUser(\"alice\",\"fubar\")\n if err != nil {\n t.Error(\"Failed to initialize user (\", err, \")\")\n } else {\n t.Log(\"Successfully stored user\", u)\n }\n\n // retrieve user \n v, err := GetUser(\"alice\", \"fubar\")\n if err != nil {\n t.Error(\"Failed to reload user\", err)\n } else {\n t.Log(\"Correctly retrieved user\", v)\n }\n}", "func (m *MockClient) UserStore() msp.UserStore {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"UserStore\")\n\tret0, _ := ret[0].(msp.UserStore)\n\treturn ret0\n}", "func (m *MockUserRepository) Store(arg0 *sweeper.User) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Store\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockRepository) Store(user *User) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Store\", user)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (_m *UsersRepository) Store(users *entities.User) error {\n\tret := _m.Called(users)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(*entities.User) error); ok {\n\t\tr0 = rf(users)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (userRepo *mockUserRepo) Initialize(ctx context.Context, db *sql.DB) {}", "func TestMySQLStore(t *testing.T) {\n\t//create a new sql mock\n\tdb, mock, err := sqlmock.New()\n\tif err != nil {\n\t\tt.Fatalf(\"error creating sql mock: %v\", err)\n\t}\n\t//ensure it's closed at the end of the test\n\tdefer db.Close()\n\n\tnewUser := CreateNewUser()\n\n\texpectedUser, _ := newUser.ToUser()\n\t//construct a new MySQLStore using the mock db\n\tstore := NewMySQLStore(db)\n\n\trows := sqlmock.NewRows([]string{\"id\", \"email\", \"passhash\", \"username\", \"firstname\", \"lastname\", \"photourl\"})\n\trows.AddRow(expectedUser.ID, expectedUser.Email, expectedUser.PassHash, expectedUser.UserName, expectedUser.FirstName, expectedUser.LastName, expectedUser.PhotoURL)\n\n\t// test insert function\n\tmock.ExpectExec(regexp.QuoteMeta(sqlInsertUser)).\n\t\tWithArgs(expectedUser.Email, expectedUser.PassHash, expectedUser.UserName, expectedUser.FirstName, expectedUser.LastName, expectedUser.PhotoURL).\n\t\tWillReturnResult(sqlmock.NewResult(1, 1))\n\n\t_, err = store.Insert(expectedUser)\n\tif err != nil {\n\t\tt.Errorf(\"unexpected error occurs when inserting new user: %v\", err)\n\t}\n\n\t//ensure we didn't have any unmet expectations\n\tif err := mock.ExpectationsWereMet(); err != nil {\n\t\tt.Errorf(\"unmet sqlmock expectations: %v\", err)\n\t}\n\n\tmock.ExpectExec(regexp.QuoteMeta(sqlInsertUser)).\n\t\tWithArgs(expectedUser.Email, expectedUser.PassHash, expectedUser.UserName, expectedUser.FirstName, expectedUser.LastName, expectedUser.PhotoURL).\n\t\tWillReturnError(fmt.Errorf(\"test DMBS error\"))\n\n\t_, err = store.Insert(expectedUser)\n\tif err == nil {\n\t\tt.Errorf(\"expected error does not occurs when inserting new user: %v\", err)\n\t}\n\n\t//ensure we didn't have any unmet expectations\n\tif err := mock.ExpectationsWereMet(); err != nil {\n\t\tt.Errorf(\"unmet sqlmock expectations: %v\", err)\n\t}\n\n\t// test get function\n\t// test get by id\n\tmock.ExpectQuery(regexp.QuoteMeta(sqlSelectUserByID)).\n\t\tWithArgs(expectedUser.ID).\n\t\tWillReturnRows(rows)\n\n\t_, err = store.GetByID(expectedUser.ID)\n\tif err != nil {\n\t\tt.Errorf(\"unexpected error occurs when get user by ID: %v\", err)\n\t}\n\n\tmock.ExpectQuery(regexp.QuoteMeta(sqlSelectUserByID)).\n\t\tWithArgs(expectedUser.ID).\n\t\tWillReturnError(fmt.Errorf(\"test DMBS error\"))\n\n\t_, err = store.GetByID(expectedUser.ID)\n\tif err == nil {\n\t\tt.Errorf(\"expected does not error occurs when getting user by id: %v\", err)\n\t}\n\n\t//ensure we didn't have any unmet expectations\n\tif err := mock.ExpectationsWereMet(); err != nil {\n\t\tt.Errorf(\"unmet sqlmock expectations: %v\", err)\n\t}\n\n\t// test get by email\n\trows = sqlmock.NewRows([]string{\"id\", \"email\", \"passhash\", \"username\", \"firstname\", \"lastname\", \"photourl\"})\n\trows.AddRow(expectedUser.ID, expectedUser.Email, expectedUser.PassHash, expectedUser.UserName, expectedUser.FirstName, expectedUser.LastName, expectedUser.PhotoURL)\n\n\tmock.ExpectQuery(regexp.QuoteMeta(sqlSelectUserByEmail)).\n\t\tWithArgs(expectedUser.Email).\n\t\tWillReturnRows(rows)\n\n\t_, err = store.GetByEmail(expectedUser.Email)\n\tif err != nil {\n\t\tt.Errorf(\"unexpected error occurs when get user by email: %v\", err)\n\t}\n\n\tmock.ExpectQuery(regexp.QuoteMeta(sqlSelectUserByEmail)).\n\t\tWithArgs(expectedUser.Email).\n\t\tWillReturnError(fmt.Errorf(\"test DMBS error\"))\n\n\t_, err = store.GetByEmail(expectedUser.Email)\n\tif err == nil {\n\t\tt.Errorf(\"expected does not error occurs when getting user by email: %v\", err)\n\t}\n\n\t//ensure we didn't have any unmet expectations\n\tif err := mock.ExpectationsWereMet(); err != nil {\n\t\tt.Errorf(\"unmet sqlmock expectations: %v\", err)\n\t}\n\n\t// test get by user name\n\trows = sqlmock.NewRows([]string{\"id\", \"email\", \"passhash\", \"username\", \"firstname\", \"lastname\", \"photourl\"})\n\trows.AddRow(expectedUser.ID, expectedUser.Email, expectedUser.PassHash, expectedUser.UserName, expectedUser.FirstName, expectedUser.LastName, expectedUser.PhotoURL)\n\n\tmock.ExpectQuery(regexp.QuoteMeta(sqlSelectUserByUserName)).\n\t\tWithArgs(expectedUser.UserName).\n\t\tWillReturnRows(rows)\n\n\t_, err = store.GetByUserName(expectedUser.UserName)\n\tif err != nil {\n\t\tt.Errorf(\"unexpected error occurs when get user by UserName: %v\", err)\n\t}\n\n\tmock.ExpectQuery(regexp.QuoteMeta(sqlSelectUserByUserName)).\n\t\tWithArgs(expectedUser.UserName).\n\t\tWillReturnError(fmt.Errorf(\"test DMBS error\"))\n\n\t_, err = store.GetByUserName(expectedUser.UserName)\n\tif err == nil {\n\t\tt.Errorf(\"expected does not error occurs when getting user by UserName: %v\", err)\n\t}\n\n\t//ensure we didn't have any unmet expectations\n\tif err := mock.ExpectationsWereMet(); err != nil {\n\t\tt.Errorf(\"unmet sqlmock expectations: %v\", err)\n\t}\n\n\t// Test update\n\tupdate := &Updates{\n\t\tFirstName: \"updatedFirstName\",\n\t\tLastName: \"updatedLastName\",\n\t}\n\t// updatedRows := sqlmock.NewRows([]string{\"id\", \"email\", \"passhash\", \"UserName\", \"FirstName\", \"LastName\", \"photourl\"})\n\t// rows.AddRow(expectedUser.ID, expectedUser.Email, expectedUser.PassHash, expectedUser.UserName, update.FirstName, update.LastName, expectedUser.PhotoURL)\n\n\tmock.ExpectExec(regexp.QuoteMeta(sqlUpdate)).\n\t\tWithArgs(update.FirstName, update.LastName, expectedUser.ID).\n\t\tWillReturnResult(sqlmock.NewResult(1, 1))\n\n\terr = store.Update(expectedUser.ID, update)\n\n\tif err != nil {\n\t\tt.Errorf(\"unexpected error occurs when update user: %v\", err)\n\t}\n\n\tmock.ExpectExec(regexp.QuoteMeta(sqlUpdate)).\n\t\tWithArgs(update.FirstName, update.LastName, expectedUser.ID).\n\t\tWillReturnError(fmt.Errorf(\"test DMBS error\"))\n\n\terr = store.Update(expectedUser.ID, update)\n\tif err == nil {\n\t\tt.Errorf(\"expected does not error occurs when update user: %v\", err)\n\t}\n\n\t//ensure we didn't have any unmet expectations\n\tif err := mock.ExpectationsWereMet(); err != nil {\n\t\tt.Errorf(\"unmet sqlmock expectations: %v\", err)\n\t}\n\n\t//Test delete\n\n\tmock.ExpectExec(regexp.QuoteMeta(sqlDelete)).\n\t\tWithArgs(expectedUser.ID).\n\t\tWillReturnResult(sqlmock.NewResult(1, 1))\n\n\terr = store.Delete(expectedUser.ID)\n\tif err != nil {\n\t\tt.Errorf(\"unexpected error occurs when deleting user: %v\", err)\n\t}\n\n\t//ensure we didn't have any unmet expectations\n\tif err := mock.ExpectationsWereMet(); err != nil {\n\t\tt.Errorf(\"unmet sqlmock expectations: %v\", err)\n\t}\n\n\tmock.ExpectExec(regexp.QuoteMeta(sqlDelete)).\n\t\tWithArgs(expectedUser.ID).\n\t\tWillReturnError(fmt.Errorf(\"test DMBS error\"))\n\n\terr = store.Delete(expectedUser.ID)\n\tif err == nil {\n\t\tt.Errorf(\"expected error does not occurs when deleting user: %v\", err)\n\t}\n\n\t//ensure we didn't have any unmet expectations\n\tif err := mock.ExpectationsWereMet(); err != nil {\n\t\tt.Errorf(\"unmet sqlmock expectations: %v\", err)\n\t}\n}", "func MockUserItemStorage() *mongoDB.UserItemStorage {\n\treturn &mongoDB.UserItemStorage{\n\t\tUserID: \"Test\",\n\t\tPrices: make(map[string]models.UserPrices),\n\t\tProfits: make(map[string]models.UserProfits),\n\t}\n}", "func (m *MockUserStore) Get(arg0 context.Context, arg1 *sql.Tx, arg2 []byte) (*proto.User, error) {\n\tret := m.ctrl.Call(m, \"Get\", arg0, arg1, arg2)\n\tret0, _ := ret[0].(*proto.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (suite *StoreTestSuite) Test001_User() {\n\tusername := \"foo\"\n\temail := \"bar\"\n\tpw := \"baz\"\n\trole := 1337\n\n\t// Test CreateUser\n\tnewUser := &schema.User{\n\t\tUsername: &username,\n\t\tEmail: &email,\n\t\tPassword: &pw,\n\t\tRole: &role,\n\t}\n\terr := suite.store.CreateUser(newUser)\n\tsuite.Nil(err)\n\n\t// Test GetUserByUsername\n\tuser, err := suite.store.GetUserByUsername(username)\n\tsuite.Nil(err)\n\tsuite.NotNil(user)\n\tsuite.Equal(username, user.Username)\n\tsuite.Equal(email, user.Email)\n\n\tid := user.ID.Hex()\n\n\t// Test GetUserByEmail\n\tuser, err = suite.store.GetUserByEmail(email)\n\tsuite.Nil(err)\n\tsuite.NotNil(user)\n\tsuite.Equal(username, user.Username)\n\tsuite.Equal(email, user.Email)\n\n\t// Test GetUserByPassword\n\tuser, err = suite.store.GetUserByCreds(username, pw)\n\tsuite.Nil(err)\n\tsuite.NotNil(user)\n\tsuite.Equal(username, user.Username)\n\tsuite.Equal(email, user.Email)\n\n\t// Test CreateUser with conflict\n\terr = suite.store.CreateUser(newUser)\n\tsuite.NotNil(err)\n\tsuite.Equal(\"user with username as foo already exists\", err.Error())\n\n\t// Test UpdateUser\n\tnewUsername := \"foobar\"\n\tuserPatch := &schema.User{Username: &newUsername}\n\tuser, err = suite.store.UpdateUser(id, userPatch)\n\tsuite.Nil(err)\n\tsuite.Equal(newUsername, user.Username)\n\tsuite.Equal(email, user.Email)\n\tsuite.Equal(role, user.Role)\n\n\t// Add second user\n\terr = suite.store.CreateUser(newUser)\n\tsuite.Nil(err)\n\n\t// Try to update second user\n\tu, err := suite.store.GetUserByUsername(*newUser.Username)\n\tsuite.Nil(err)\n\n\tuser, err = suite.store.UpdateUser(u.ID.Hex(), userPatch)\n\tsuite.Nil(user)\n\tsuite.True(mgo.IsDup(err))\n\n\t// Test GetAllUsers\n\tusers, err := suite.store.GetAllUsers()\n\tsuite.Nil(err)\n\tsuite.Equal(len(users), 2)\n\n\t// Test DeleteUser\n\tuser, err = suite.store.DeleteUser(id)\n\tsuite.Nil(err)\n\tsuite.NotNil(user)\n\tsuite.Equal(newUsername, user.Username)\n\tsuite.Equal(email, user.Email)\n}", "func testInMemoryDataStore() IDataStore {\n return NewInMemoryDataStore();\n}", "func NewMockStore() *MockStore {\n\treturn &MockStore{\n\t\tid: map[int]User{},\n\t\tname: map[string]User{},\n\t\temail: map[string]User{},\n\t\tconfirm: map[string]ConfirmToken{},\n\t\trecover: map[string]RecoverToken{},\n\t}\n}", "func TestStore_CreateUser(t *testing.T) {\n\tt.Parallel()\n\ts := MustOpenStore()\n\tdefer s.Close()\n\n\t// Create user.\n\tif ui, err := s.CreateUser(\"susy\", \"pass\", true); err != nil {\n\t\tt.Fatal(err)\n\t} else if ui.Name != \"susy\" || ui.Hash == \"\" || ui.Admin != true {\n\t\tt.Fatalf(\"unexpected user: %#v\", ui)\n\t}\n}", "func TestStore_UpdateUser(t *testing.T) {\n\tt.Parallel()\n\ts := MustOpenStore()\n\tdefer s.Close()\n\n\t// Create users.\n\tif _, err := s.CreateUser(\"susy\", \"pass\", true); err != nil {\n\t\tt.Fatal(err)\n\t} else if _, err := s.CreateUser(\"bob\", \"pass\", true); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// Store password hash for bob.\n\tui, err := s.User(\"bob\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// Update user.\n\tif err := s.UpdateUser(\"bob\", \"XXX\"); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// Verify password hash was updated.\n\tif other, err := s.User(\"bob\"); err != nil {\n\t\tt.Fatal(err)\n\t} else if ui.Hash == other.Hash {\n\t\tt.Fatal(\"password hash did not change\")\n\t}\n}", "func TestDbInterfaceMethods(t *testing.T) {\n\ttestUser := models.User{\n\t\tAccount: models.Account{\n\t\t\tType: \"email\",\n\t\t\tAccountID: \"test@test.com\",\n\t\t\tPassword: \"testhashedpassword-youcantreadme\",\n\t\t},\n\t\tRoles: []string{\"TEST\"},\n\t\tTimestamps: models.Timestamps{\n\t\t\tCreatedAt: time.Now().Unix(),\n\t\t},\n\t}\n\n\tt.Run(\"Testing create user\", func(t *testing.T) {\n\t\tid, err := testDBService.AddUser(testInstanceID, testUser)\n\t\tif err != nil {\n\t\t\tt.Errorf(err.Error())\n\t\t\treturn\n\t\t}\n\t\tif len(id) == 0 {\n\t\t\tt.Errorf(\"id is missing\")\n\t\t\treturn\n\t\t}\n\t\t_id, _ := primitive.ObjectIDFromHex(id)\n\t\ttestUser.ID = _id\n\t})\n\n\tt.Run(\"Testing creating existing user\", func(t *testing.T) {\n\t\ttestUser2 := testUser\n\t\ttestUser2.Roles = []string{\"TEST2\"}\n\t\t_, err := testDBService.AddUser(testInstanceID, testUser2)\n\t\tif err == nil {\n\t\t\tt.Errorf(\"user already existed, but created again\")\n\t\t\treturn\n\t\t}\n\t\tu, e := testDBService.GetUserByAccountID(testInstanceID, testUser2.Account.AccountID)\n\t\tif e != nil {\n\t\t\tt.Errorf(e.Error())\n\t\t\treturn\n\t\t}\n\t\tif len(u.Roles) > 0 && u.Roles[0] == \"TEST2\" {\n\t\t\tt.Error(\"user should not be updated\")\n\t\t}\n\t})\n\n\tt.Run(\"Testing find existing user by id\", func(t *testing.T) {\n\t\tuser, err := testDBService.GetUserByID(testInstanceID, testUser.ID.Hex())\n\t\tif err != nil {\n\t\t\tt.Errorf(err.Error())\n\t\t\treturn\n\t\t}\n\t\tif user.Account.AccountID != testUser.Account.AccountID {\n\t\t\tt.Errorf(\"found user is not matching test user\")\n\t\t\treturn\n\t\t}\n\t})\n\n\tt.Run(\"Testing find not existing user by id\", func(t *testing.T) {\n\t\t_, err := testDBService.GetUserByID(testInstanceID, testUser.ID.Hex()+\"1\")\n\t\tif err == nil {\n\t\t\tt.Errorf(\"user should not be found\")\n\t\t\treturn\n\t\t}\n\t})\n\n\tt.Run(\"Testing find existing user by email\", func(t *testing.T) {\n\t\tuser, err := testDBService.GetUserByAccountID(testInstanceID, testUser.Account.AccountID)\n\t\tif err != nil {\n\t\t\tt.Errorf(err.Error())\n\t\t\treturn\n\t\t}\n\t\tif user.Account.AccountID != testUser.Account.AccountID {\n\t\t\tt.Errorf(\"found user is not matching test user\")\n\t\t\treturn\n\t\t}\n\t})\n\n\tt.Run(\"Testing find not existing user by email\", func(t *testing.T) {\n\t\t_, err := testDBService.GetUserByAccountID(testInstanceID, testUser.Account.AccountID+\"1\")\n\t\tif err == nil {\n\t\t\tt.Errorf(\"user should not be found\")\n\t\t\treturn\n\t\t}\n\t})\n\n\tt.Run(\"Testing updating existing user's attributes\", func(t *testing.T) {\n\t\ttestUser.Account.AccountConfirmedAt = time.Now().Unix()\n\t\t_, err := testDBService.UpdateUser(testInstanceID, testUser)\n\t\tif err != nil {\n\t\t\tt.Errorf(err.Error())\n\t\t\treturn\n\t\t}\n\t})\n\n\tt.Run(\"Testing updating not existing user's attributes\", func(t *testing.T) {\n\t\ttestUser.Account.AccountConfirmedAt = time.Now().Unix()\n\t\tcurrentUser := testUser\n\t\twrongID := testUser.ID.Hex()[:len(testUser.ID.Hex())-2] + \"00\"\n\t\tid, err := primitive.ObjectIDFromHex(wrongID)\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t\treturn\n\t\t}\n\t\tcurrentUser.ID = id\n\t\t_, err = testDBService.UpdateUser(testInstanceID, currentUser)\n\t\tif err == nil {\n\t\t\tt.Errorf(\"cannot update not existing user\")\n\t\t\treturn\n\t\t}\n\t})\n\n\tt.Run(\"Testing counting recently added users\", func(t *testing.T) {\n\t\tcount, err := testDBService.CountRecentlyCreatedUsers(testInstanceID, 20)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"unexpected error: %v\", err)\n\t\t\treturn\n\n\t\t}\n\t\tlogger.Debug.Println(count)\n\t\tif count < 1 {\n\t\t\tt.Error(\"at least one user should be found\")\n\t\t}\n\t})\n\n\tt.Run(\"Testing deleting existing user\", func(t *testing.T) {\n\t\terr := testDBService.DeleteUser(testInstanceID, testUser.ID.Hex())\n\t\tif err != nil {\n\t\t\tt.Errorf(err.Error())\n\t\t\treturn\n\t\t}\n\t})\n\n\tt.Run(\"Testing deleting not existing user\", func(t *testing.T) {\n\t\terr := testDBService.DeleteUser(testInstanceID, testUser.ID.Hex()+\"1\")\n\t\tif err == nil {\n\t\t\tt.Errorf(\"user should not be found - error expected\")\n\t\t\treturn\n\t\t}\n\t})\n}", "func (m *MockRepository) Store(ctx context.Context, data *users.Domain) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Store\", ctx, data)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func Test2(t *testing.T) {\n alice,_ := InitUser(\"alice\",\"fubar\")\n // Having previously created a user \"alice\" with password \"fubar\"...\n alice, _ = GetUser(\"alice\", \"fubar\")\n also_alice, _ := GetUser(\"alice\", \"fubar\")\n\n alice.StoreFile(\"todo\", []byte(\"write tests\"))\n todo, _ := also_alice.LoadFile(\"todo\")\n if string(todo) != \"write tests\" {\n t.Error(\"Same user and password could not access file: \", todo)\n }\n}", "func (m *MockUseCase) Store(ctx context.Context, data *users.Domain) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Store\", ctx, data)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func TestStore_UserCount(t *testing.T) {\n\tt.Parallel()\n\ts := MustOpenStore()\n\tdefer s.Close()\n\n\tif count, err := s.UserCount(); count != 0 && err != nil {\n\t\tt.Fatalf(\"expected user count to be 0 but was %d\", count)\n\t}\n\n\t// Create users.\n\tif _, err := s.CreateUser(\"susy\", \"pass\", true); err != nil {\n\t\tt.Fatal(err)\n\t} else if _, err := s.CreateUser(\"bob\", \"pass\", true); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif count, err := s.UserCount(); count != 2 && err != nil {\n\t\tt.Fatalf(\"expected user count to be 2 but was %d\", count)\n\t}\n}", "func (userAfhRepo *mockUserAfhRepo) Initialize(ctx context.Context, db *sql.DB) {}", "func TestInitAndGetBasics(t *testing.T) {\n\tuserlib.SetDebugStatus(false)\n\tuserlib.DatastoreClear()\n\tuserlib.KeystoreClear()\n\tdatastore := userlib.DatastoreGetMap()\n\tkeystore := userlib.KeystoreGetMap()\n\t_, _ = datastore, keystore\n\n\tbob, err := InitUser(\"bob\", \"fubar\")\n\tif bob == nil || err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\tgetBob, err := GetUser(\"bob\", \"fubar\")\n\tif getBob == nil || err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\n\tbobBytes, _ := json.Marshal(bob)\n\tgetBobBytes, _ := json.Marshal(getBob)\n\tif !reflect.DeepEqual(bobBytes, getBobBytes) {\n\t\tt.Error(\"Init and Get userdata are not the same.\")\n\t\treturn\n\t}\n\n\t_, err = GetUser(\"bob\", \"wrong\")\n\tif err == nil {\n\t\tt.Error(\"Got a user that is suppose to not exist.\")\n\t\treturn\n\t}\n\n\t_, err = GetUser(\"wrong\", \"fubar\")\n\tif err == nil {\n\t\tt.Error(\"Got a user that is suppose to not exist.\")\n\t\treturn\n\t}\n\n\tvar keys []userlib.UUID\n\tvar vals [][]byte\n\tfor k, v := range datastore {\n\t\tkeys = append(keys, k)\n\t\tvals = append(vals, v)\n\t}\n\n\tfor val := range vals {\n\t\tif strings.Contains(\"bob\", string(val)) || strings.Contains(\"alice\", string(val)) {\n\t\t\tt.Error(\"Username is not obscured.\")\n\t\t\treturn\n\t\t}\n\t}\n\n}", "func (m *MockUserLogic) UserGet(userName string) (*domain.User, string, error) {\n\tret := m.ctrl.Call(m, \"UserGet\", userName)\n\tret0, _ := ret[0].(*domain.User)\n\tret1, _ := ret[1].(string)\n\tret2, _ := ret[2].(error)\n\treturn ret0, ret1, ret2\n}", "func TestReadUser(t *testing.T) {\r\n/////////////////////////////////// MOCKING ////////////////////////////////////////////\r\n\tvar batches = []string{\r\n\t\t`CREATE TABLE Users (Id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, Name TEXT NOT NULL UNIQUE);`,\r\n\t\t`INSERT INTO Users (Id,Name) VALUES (1,'anonymous');`,\r\n\t}\r\n\t//open pseudo database for function\r\n\tdb, err := sql.Open(\"ramsql\", \"TestReadUser\")\r\n\tif err != nil {\r\n\t\tt.Fatalf(\"Error creating mock sql : %s\\n\", err)\r\n\t}\r\n\tdefer db.Close()\r\n\r\n\t// Exec every line of batch and create database\r\n\tfor _, b := range batches {\r\n\t\t_, err = db.Exec(b)\r\n\t\tif err != nil {\r\n\t\t\tt.Fatalf(\"Error exec query in query: %s\\n Error:%s\", b, err)\r\n\t\t}\r\n\t}\r\n/////////////////////////////////// MOCKING ////////////////////////////////////////////\r\n\r\n\t// Specify test variables and expected results.\r\n\ttests := []struct {\r\n\t\tid int\r\n\t\t// we need to use models.User for passing to object.This is different with \"database.User\".\r\n\t\tresult models.User\r\n\t\terr error\r\n\t}{\r\n\t\t// When give to first parameter(id) 1 , We expect result :1 error nil\r\n\t\t{id: 1, result: models.User{Id: 1, Name: \"anonymous\"}, err: nil},\r\n\t\t// When give to first parameter(id) 1 , We expect result :1 error nil\r\n\t\t//{id: 2, result: models.User{Id: 2, Name: \"test\"}, err: nil},\r\n\t}\r\n\r\n\t// test all of the variables.\r\n\tfor _, test := range tests {\r\n\t\t//get result after test.\r\n\t\ts, err := u.ReadUser(db, test.id)\r\n\t\t// if expected error type nil we need to compare with actual error different way.\r\n\t\tif test.err == nil {\r\n\t\t\t// If test fails give error.It checks expected result and expected error\r\n\t\t\tif err != test.err || s != test.result {\r\n\t\t\t\t// Compare expected error and actual error\r\n\t\t\t\tt.Errorf(\"Error is: %v . Expected: %v\", err, test.err)\r\n\t\t\t\t// Compare expected result and actual result\r\n\t\t\t\tt.Errorf(\"Result is: %v . Expected: %v\", s, test.result)\r\n\t\t\t}\r\n\t\t\t// if expected error type is not nil we need to compare with actual error different way.\r\n\t\t} else {\r\n\t\t\tif err.Error() != test.err.Error() || s != test.result {\r\n\t\t\t\t// Compare expected error and actual error\r\n\t\t\t\tt.Errorf(\"Error is: %v . Expected: %v\", err, test.err)\r\n\t\t\t\t// Compare expected result and actual result\r\n\t\t\t\tt.Errorf(\"Result is: %v . Expected: %v\", s, test.result)\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}", "func (m *MockHandler) UserGet(userName string) (*domain.User, string, error) {\n\tret := m.ctrl.Call(m, \"UserGet\", userName)\n\tret0, _ := ret[0].(*domain.User)\n\tret1, _ := ret[1].(string)\n\tret2, _ := ret[2].(error)\n\treturn ret0, ret1, ret2\n}", "func TestPostgresStore(t *testing.T) {\n\t//Preparing a Postgres data abstraction for later use\n\tpsdb, err := sql.Open(\"postgres\", \"user=pgstest dbname=devourpg sslmode=disable\")\n\tif err != nil {\n\t\tt.Errorf(\"error starting db: %v\", err)\n\t}\n\t//Creates the store structure\n\tstore := &PGStore{\n\t\tDB: psdb,\n\t}\n\n\tusrStore := &users.PGStore{\n\t\tDB: psdb,\n\t}\n\t//Pings the DB-- establishes a connection to the db\n\terr = psdb.Ping()\n\tif err != nil {\n\t\tt.Errorf(\"error pinging db %v\", err)\n\t}\n\n\tnewUser := &users.NewUser{\n\t\tEmail: \"test@test.com\",\n\t\tPassword: \"password\",\n\t\tPasswordConf: \"password\",\n\t\tDOB: \"12/12/1990\",\n\t\tFirstName: \"test\",\n\t\tLastName: \"tester\",\n\t}\n\tnu2 := &users.NewUser{\n\t\tEmail: \"best@best.com\",\n\t\tPassword: \"password\",\n\t\tPasswordConf: \"password\",\n\t\tDOB: \"12/20/2000\",\n\t\tFirstName: \"best\",\n\t\tLastName: \"bester\",\n\t}\n\n\t//reset the auto increment counter and clears previous test users in the DB\n\t_, err = psdb.Exec(\"ALTER SEQUENCE users_id_seq RESTART\")\n\t_, err = psdb.Exec(\"ALTER SEQUENCE user_diet_type_id_seq RESTART\")\n\t_, err = psdb.Exec(\"ALTER SEQUENCE user_allergy_type_id_seq RESTART\")\n\t_, err = psdb.Exec(\"ALTER SEQUENCE grocery_list_id_seq RESTART\")\n\t_, err = psdb.Exec(\"ALTER SEQUENCE user_like_list_id_seq RESTART\")\n\t_, err = psdb.Exec(\"ALTER SEQUENCE friends_list_id_seq RESTART\")\n\t_, err = psdb.Exec(\"ALTER SEQUENCE event_attendance_id_seq RESTART\")\n\t_, err = psdb.Exec(\"ALTER SEQUENCE events_id_seq RESTART\")\n\t_, err = psdb.Exec(\"ALTER SEQUENCE recipe_suggestions_id_seq RESTART\")\n\t_, err = psdb.Exec(\"DELETE FROM users\")\n\t_, err = psdb.Exec(\"DELETE FROM user_diet_type\")\n\t_, err = psdb.Exec(\"DELETE FROM user_allergy_type\")\n\t_, err = psdb.Exec(\"DELETE FROM grocery_list\")\n\t_, err = psdb.Exec(\"DELETE FROM user_like_list\")\n\t_, err = psdb.Exec(\"DELETE FROM friends_list\")\n\t_, err = psdb.Exec(\"DELETE FROM event_attendance\")\n\t_, err = psdb.Exec(\"DELETE FROM events\")\n\t_, err = psdb.Exec(\"DELETE FROM recipe_suggestions\")\n\n\t//start of insert\n\tuser, err := usrStore.Insert(newUser)\n\tif err != nil {\n\t\tt.Errorf(\"error inserting user: %v\\n\", err)\n\t}\n\t//means that ToUser() probably was not implemented correctly\n\tif nil == user {\n\t\tt.Fatalf(\"Nil returned from store.Insert()\\n\")\n\t}\n\t//start of insert\n\tuser2, err := usrStore.Insert(nu2)\n\tif err != nil {\n\t\tt.Errorf(\"error inserting user: %v\\n\", err)\n\t}\n\t//means that ToUser() probably was not implemented correctly\n\tif nil == user2 {\n\t\tt.Fatalf(\"Nil returned from store.Insert()\\n\")\n\t}\n\n\tnewEvt := &NewEvent{\n\t\tName: \"testEVENT\",\n\t\tDescription: \"testDescription\",\n\t\tStartTime: \"March 5, 2017 at 4:00pm (PST)\",\n\t\tEndTime: \"March 5, 2017 at 7:00pm (PST)\",\n\t\tEventType: \"Formal\",\n\t\tMoodType: \"Fancy\",\n\t}\n\tnewJuneEvt := &NewEvent{\n\t\tName: \"testFutureEVENT\",\n\t\tDescription: \"testFutureDescription\",\n\t\tStartTime: \"June 5, 2017 at 4:00pm (PST)\",\n\t\tEndTime: \"June 5, 2017 at 7:00pm (PST)\",\n\t\tEventType: \"Formal\",\n\t\tMoodType: \"Fancy\",\n\t}\n\n\t//insert event\n\tevt, err := store.InsertEvent(newEvt, user)\n\tif err != nil {\n\t\tt.Errorf(\"error inserting new event %v\\n\", err)\n\t}\n\tif evt.Name != \"testEVENT\" {\n\t\tt.Errorf(\"error making event expected creator %s but got %s\", \"testEvent\", evt.Name)\n\t}\n\n\tevt2, err := store.InsertEvent(newJuneEvt, user)\n\tif err != nil {\n\t\tt.Errorf(\"error inserting new event %v\\n\", err)\n\t}\n\n\t//invite user to the event\n\tatn, err := store.InviteUserToEvent(user2, evt)\n\tif err != nil {\n\t\tt.Errorf(\"error inviting user to event %v\\n\", err)\n\t}\n\n\t//Getting user attendance status\n\tatnStat, err := store.GetUserAttendanceStatus(user2, evt)\n\tif err != nil {\n\t\tt.Errorf(\"Error getting user's attendance status\")\n\t}\n\n\tif atnStat.AttendanceStatus != \"Pending\" {\n\t\tt.Errorf(\"Error getting the attendance status expected %s but got %s\", \"Pending\", atnStat.AttendanceStatus)\n\t}\n\n\tif atn.StatusID != atnStat.ID {\n\t\tt.Errorf(\"Error getting the correct attendance status ID expected %d but got %d\", atn.StatusID, atnStat.ID)\n\t}\n\n\t//Lets first reject that invite\n\terr = store.RejectInvite(evt, user2)\n\tif err != nil {\n\t\tt.Errorf(\"Error rejecting the invite %v\\n\", err)\n\t}\n\n\t//Now invite the user again\n\tatn, err = store.InviteUserToEvent(user2, evt)\n\tif err != nil {\n\t\tt.Errorf(\"error inviting user to event %v\\n\", err)\n\t}\n\n\t//Updating attendance status\n\terr = store.UpdateAttendanceStatus(user2, evt, \"Attending\")\n\tif err != nil {\n\t\tt.Errorf(\"Error getting an updated attendance status\")\n\t}\n\n\t//Getting the updated attendance status\n\tatnStat, err = store.GetUserAttendanceStatus(user2, evt)\n\tif err != nil {\n\t\tt.Errorf(\"Error getting user's attendance status\")\n\t}\n\tif atnStat.AttendanceStatus != \"Attending\" {\n\t\tt.Errorf(\"Error getting the correct UPDATED status: expected Attending but got %s\", atnStat.AttendanceStatus)\n\t}\n\n\t//Updating attendance status\n\terr = store.UpdateAttendanceStatus(user2, evt, \"Pending\")\n\tif err != nil {\n\t\tt.Errorf(\"Error getting an updated attendance status\")\n\t}\n\n\t//updating event stuff\n\terr = store.UpdateEventName(evt, \"UpdatedTestName\")\n\tif err != nil {\n\t\tt.Errorf(\"Error updating event name %v\", err)\n\t}\n\n\terr = store.UpdateEventDescription(evt, \"UpdatedDescription\")\n\tif err != nil {\n\t\tt.Errorf(\"Error updating event description %v\", err)\n\t}\n\n\terr = store.UpdateEventMood(evt, \"Focused\")\n\tif err != nil {\n\t\tt.Errorf(\"Error updating event mood %v\", err)\n\t}\n\n\terr = store.UpdateEventType(evt, \"Other\")\n\tif err != nil {\n\t\tt.Errorf(\"Error updating event type %v\", err)\n\t}\n\n\terr = store.UpdateEventEnd(evt, \"March 6, 2017 at 12:00pm (PST)\")\n\tif err != nil {\n\t\tt.Errorf(\"Error updating event end %v\", err)\n\t}\n\n\terr = store.UpdateEventStart(evt, \"March 1, 2017 at 2:20pm (PST)\")\n\tif err != nil {\n\t\tt.Errorf(\"Error updating event start %v\", err)\n\t}\n\n\tupEvents, err := store.GetAllHostedEvents(user)\n\tif err != nil {\n\t\tt.Errorf(\"Error getting all of the users store: %v\", err)\n\t}\n\tif upEvents[0].Name != \"UpdatedTestName\" {\n\t\tt.Errorf(\"Error updating stuffs %v\", err)\n\t}\n\n\t//Adding a Recipe to an event, recipes are strings\n\tRecipeName := \"French-Onion-Soup\"\n\n\t//Adding two recipes into event\n\tsugg, err := store.AddRecipeToEvent(evt, user, RecipeName)\n\tif err != nil {\n\t\tt.Errorf(\"Error adding recipe to an event: %v\\n\", err)\n\t}\n\t_, err = store.AddRecipeToEvent(evt, user2, RecipeName)\n\tif err != nil {\n\t\tt.Errorf(\"Error adding recipe to an event: %v\\n\", err)\n\t}\n\n\t//Getting all recipes in event\n\trecipes, err := store.GetAllRecipesInEvent(evt)\n\tif err != nil {\n\t\tt.Errorf(\"Error getting all recipes in an event: %v\\n\", err)\n\t}\n\tif recipes[0] != sugg.Recipe {\n\t\tt.Errorf(\"Error with getting recipes expected %s but got %s\", sugg.Recipe, recipes[0])\n\t}\n\n\t//Removing user2's recipe from the event\n\terr = store.RemoveRecipeFromEvent(evt, user2, RecipeName)\n\tif err != nil {\n\t\tt.Errorf(\"Error deleting recipe from the event: %v\\n\", err)\n\t}\n\n\t//Getting all of the users in the event\n\t_, err = store.GetAllUsersInEvent(evt)\n\tif err != nil {\n\t\tt.Errorf(\"Error getting all users %v\\n\", err)\n\t}\n\n\t//Gets all pending events that a user has\n\tpendingEvts, err := store.GetAllPendingEvents(user2)\n\tif err != nil {\n\t\tt.Errorf(\"Error getting all pending events: %v\\n\", err)\n\t}\n\tif pendingEvts[0].ID != evt.ID {\n\t\tt.Errorf(\"Error getting the correct event: expected %d and got %d\", pendingEvts[0].ID, evt.ID)\n\t}\n\n\t//Getting past and upcoming events\n\tpastEvts, err := store.GetPastEvents(user)\n\tif err != nil {\n\t\tt.Errorf(\"Error getting past events %v\\n\", err)\n\t}\n\tupcomingEvts, err := store.GetUpcomingEvents(user)\n\tif err != nil {\n\t\tt.Errorf(\"Error getting upcoming events %v\\n\", err)\n\t}\n\n\tif pastEvts[0].ID != evt.ID {\n\t\tt.Errorf(\"Error getting the correct Event: expected %d but got %d\", evt.ID, pastEvts[0].ID)\n\t}\n\tif upcomingEvts[0].ID != evt2.ID {\n\t\tt.Errorf(\"Error getting the correct Event: expected %d but got %d\", evt2.ID, pastEvts[0].ID)\n\t}\n\n\t//Getting all of the users events (attending or hosting)\n\t_, err = store.GetAllUserEvents(user)\n\tif err != nil {\n\t\tt.Errorf(\"Error getting all user events %v\\n\", err)\n\t}\n\n\t_, err = usrStore.AddFriend(user, user2)\n\tif err != nil {\n\t\tt.Errorf(\"Error adding friend %v\\n\", err)\n\t}\n\n\t//Getting all the friends of a user of user going to the event\n\t_, err = store.GetAllFriendsInEvent(user, evt)\n\tif err != nil {\n\t\tt.Errorf(\"Error getting friends in the event %v\\n\", err)\n\t}\n\n\t//Finished updated all things and now delete\n\terr = store.DeleteEvent(evt)\n\tif err != nil {\n\t\tt.Errorf(\"error deleting event %v\", err)\n\t}\n\n}", "func (m *MockPersister) GetUser(username, password string) (User, error) {\n\tret := m.ctrl.Call(m, \"GetUser\", username, password)\n\tret0, _ := ret[0].(User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (mmGetUser *mStorageMockGetUser) Set(f func(ctx context.Context, userID int64) (up1 *db_storage.User, err error)) *StorageMock {\n\tif mmGetUser.defaultExpectation != nil {\n\t\tmmGetUser.mock.t.Fatalf(\"Default expectation is already set for the storage.GetUser method\")\n\t}\n\n\tif len(mmGetUser.expectations) > 0 {\n\t\tmmGetUser.mock.t.Fatalf(\"Some expectations are already set for the storage.GetUser method\")\n\t}\n\n\tmmGetUser.mock.funcGetUser = f\n\treturn mmGetUser.mock\n}", "func mockNoopStore(id string, key string, value interface{}) {}", "func (m *MockUserStore) BySet(arg0 context.Context, arg1 *sql.Tx, arg2 string) ([]*proto.User, error) {\n\tret := m.ctrl.Call(m, \"BySet\", arg0, arg1, arg2)\n\tret0, _ := ret[0].([]*proto.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockUserStore) Alter(arg0 context.Context, arg1 *sql.Tx, arg2 proto.User) error {\n\tret := m.ctrl.Call(m, \"Alter\", arg0, arg1, arg2)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockUserStore) Create(arg0 context.Context, arg1 *sql.Tx, arg2 proto.User) error {\n\tret := m.ctrl.Call(m, \"Create\", arg0, arg1, arg2)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func TestUser(t *testing.T) {\n\tu := new(entity.User)\n\tu.Userid = \"1111\" //\n\thas, err := Engine.Get(u)\n\tt.Log(has, err)\n}", "func TestCreatingStore(t *testing.T) {\n\tstore := setUp(t)\n\ttearDown(store, t)\n}", "func (m *MockUserUsecase) GetAll() ([]*model.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetAll\")\n\tret0, _ := ret[0].([]*model.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockDB) Get(key string) (*minesweepersvc.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Get\", key)\n\tret0, _ := ret[0].(*minesweepersvc.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockAdmin) User() User {\n\tret := m.ctrl.Call(m, \"User\")\n\tret0, _ := ret[0].(User)\n\treturn ret0\n}", "func (m *MockIUserStore) Save(user *dto.User) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Save\", user)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (mmSaveUser *mStorageMockSaveUser) Set(f func(ctx context.Context, user *db_storage.User) (err error)) *StorageMock {\n\tif mmSaveUser.defaultExpectation != nil {\n\t\tmmSaveUser.mock.t.Fatalf(\"Default expectation is already set for the storage.SaveUser method\")\n\t}\n\n\tif len(mmSaveUser.expectations) > 0 {\n\t\tmmSaveUser.mock.t.Fatalf(\"Some expectations are already set for the storage.SaveUser method\")\n\t}\n\n\tmmSaveUser.mock.funcSaveUser = f\n\treturn mmSaveUser.mock\n}", "func (s MockStore) Put(u User) error {\n\ts.id[u.ID] = u\n\ts.name[u.Name] = u\n\ts.email[u.Email] = u\n\n\treturn nil\n}", "func (userClassesRepo *mockUserClassRepo) Initialize(ctx context.Context, db *sql.DB) {}", "func TestStore(t *testing.T) {\r\n\tsetup()\r\n\tp := Person{\r\n\t\tFirstname: firstname,\r\n\t\tLastname: lastname,\r\n\t}\r\n\tresult, err := p.Store(client)\r\n\t_id = result.InsertedID.(primitive.ObjectID)\r\n\r\n\tif err != nil {\r\n\t\tt.Fatalf(\"Failed store test %s\", err)\r\n\t}\r\n\r\n\tif p.Firstname != firstname {\r\n\t\tt.Fatalf(\"Failed store test %s\", err)\r\n\t}\r\n\r\n\tt.Log(\"Person was successfully stored : \"+p.Firstname+\" \"+p.Lastname+\" inserted id: \", _id)\r\n\r\n\tif err != nil {\r\n\t\tt.Fatalf(\"Failed store test %s\", err)\r\n\t}\r\n\r\n}", "func (as *ActionSuite) TestUserQuery() {\n\tt := as.T()\n\n\tf := fixturesForUserQuery(as)\n\n\ttype testCase struct {\n\t\tName string\n\t\tPayload string\n\t\tTestUser models.User\n\t\tExpectError bool\n\t\tTest func(t *testing.T)\n\t}\n\n\tvar resp UserResponse\n\n\ttestCases := []testCase{\n\t\t{\n\t\t\tName: \"all fields\",\n\t\t\tPayload: `{user(id: \"` + f.Users[1].UUID.String() + `\") {` + allUserFields + \"}}\",\n\t\t\tTestUser: f.Users[0],\n\t\t\tTest: func(t *testing.T) {\n\t\t\t\tif err := as.DB.Load(&(f.Users[1]), \"PhotoFile\"); err != nil {\n\t\t\t\t\tt.Errorf(\"failed to load user fixture, %s\", err)\n\t\t\t\t}\n\t\t\t\tas.Equal(f.Users[1].UUID.String(), resp.User.ID, \"incorrect ID\")\n\t\t\t\tas.Equal(f.Users[1].Email, resp.User.Email, \"incorrect Email\")\n\t\t\t\tas.Equal(f.Users[1].Nickname, resp.User.Nickname, \"incorrect Nickname\")\n\t\t\t\tas.Equal(f.Users[1].AdminRole, resp.User.AdminRole, \"incorrect AdminRole\")\n\t\t\t\tas.Equal(f.Users[1].PhotoFile.URL, resp.User.AvatarURL, \"incorrect AvatarURL\")\n\t\t\t\tas.Equal(f.Users[1].PhotoFile.UUID.String(), resp.User.PhotoID, \"incorrect PhotoID\")\n\t\t\t\tas.Regexp(\"^https?\", resp.User.AvatarURL, \"invalid AvatarURL\")\n\n\t\t\t\tas.Equal(strings.ToUpper(f.UserPreferences[0].Value), *resp.User.Preferences.Language,\n\t\t\t\t\t\"incorrect preference - language\")\n\t\t\t\tas.Equal(f.UserPreferences[1].Value, *resp.User.Preferences.TimeZone,\n\t\t\t\t\t\"incorrect preference - time zone\")\n\t\t\t\tas.Equal(strings.ToUpper(f.UserPreferences[2].Value), *resp.User.Preferences.WeightUnit,\n\t\t\t\t\t\"incorrect preference - weight unit\")\n\n\t\t\t\tas.Equal(f.Locations[1].Description, resp.User.Location.Description, \"incorrect location\")\n\t\t\t\tas.Equal(f.Locations[1].Country, resp.User.Location.Country, \"incorrect country\")\n\t\t\t\tas.InDelta(f.Locations[1].Latitude.Float64, resp.User.Location.Lat, 0.0001, \"incorrect latitude\")\n\t\t\t\tas.InDelta(f.Locations[1].Longitude.Float64, resp.User.Location.Long, 0.0001, \"incorrect longitude\")\n\n\t\t\t\tas.Equal(1, len(resp.User.Organizations), \"wrong number of Organizations\")\n\t\t\t\tas.Equal(f.Organization.UUID.String(), resp.User.Organizations[0].ID, \"incorrect Organization ID\")\n\n\t\t\t\tas.Equal(1, len(resp.User.Requests), \"wrong number of requests\")\n\t\t\t\tas.Equal(f.Requests[0].UUID.String(), resp.User.Requests[0].ID, \"incorrect Request ID\")\n\n\t\t\t\tas.Equal(1, len(resp.User.MeetingsAsParticipant), \"wrong number of meetings\")\n\t\t\t\tas.Equal(f.Meetings[0].UUID.String(), resp.User.MeetingsAsParticipant[0].ID, \"incorrect Meeting ID\")\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName: \"current user\",\n\t\t\tPayload: `{user {` + allUserFields + \"}}\",\n\t\t\tTestUser: f.Users[1],\n\t\t\tTest: func(t *testing.T) {\n\t\t\t\tas.Equal(f.Users[1].UUID.String(), resp.User.ID, \"incorrect ID\")\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName: \"not allowed\",\n\t\t\tPayload: `{user(id: \"` + f.Users[0].UUID.String() + `\"){` + allUserFields + \"}}\",\n\t\t\tTestUser: f.Users[1],\n\t\t\tTest: func(t *testing.T) {},\n\t\t\tExpectError: true,\n\t\t},\n\t}\n\n\tfor _, test := range testCases {\n\t\terr := as.testGqlQuery(test.Payload, test.TestUser.Nickname, &resp)\n\n\t\tif test.ExpectError {\n\t\t\tas.Error(err)\n\t\t} else {\n\t\t\tas.NoError(err)\n\t\t}\n\t\tt.Run(test.Name, test.Test)\n\t}\n}", "func NewUserStore(m *mock.Mocker, db api.IDatabase, q *query.Q) UserStore {\n\treturn UserStore{\n\t\tmock: m,\n\t\tdb: db,\n\t\tQ: q,\n\t}\n}", "func TestLauncher_SetupWithUsers(t *testing.T) {\n\tl := launcher.RunTestLauncherOrFail(t, ctx)\n\tl.SetupOrFail(t)\n\tdefer l.ShutdownOrFail(t, ctx)\n\n\tr, err := nethttp.NewRequest(\"POST\", l.URL()+\"/api/v2/signin\", nil)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tr.SetBasicAuth(\"USER\", \"PASSWORD\")\n\n\tresp, err := nethttp.DefaultClient.Do(r)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif err := resp.Body.Close(); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif resp.StatusCode != nethttp.StatusNoContent {\n\t\tt.Fatalf(\"unexpected status code: %d, body: %s, headers: %v\", resp.StatusCode, body, resp.Header)\n\t}\n\n\tcookies := resp.Cookies()\n\tif len(cookies) != 1 {\n\t\tt.Fatalf(\"expected 1 cookie but received %d\", len(cookies))\n\t}\n\n\tuser2 := &platform.User{\n\t\tName: \"USER2\",\n\t}\n\n\tb, _ := json.Marshal(user2)\n\tr = l.NewHTTPRequestOrFail(t, \"POST\", \"/api/v2/users\", l.Auth.Token, string(b))\n\n\tresp, err = nethttp.DefaultClient.Do(r)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tbody, err = ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif err := resp.Body.Close(); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif resp.StatusCode != nethttp.StatusCreated {\n\t\tt.Fatalf(\"unexpected status code: %d, body: %s, headers: %v\", resp.StatusCode, body, resp.Header)\n\t}\n\n\tr, err = nethttp.NewRequest(\"GET\", l.URL()+\"/api/v2/users\", nil)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tr.AddCookie(cookies[0])\n\n\tresp, err = nethttp.DefaultClient.Do(r)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tbody, err = ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif err := resp.Body.Close(); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif resp.StatusCode != nethttp.StatusOK {\n\t\tt.Fatalf(\"unexpected status code: %d, body: %s, headers: %v\", resp.StatusCode, body, resp.Header)\n\t}\n\n\texp := struct {\n\t\tUsers []platform.User `json:\"users\"`\n\t}{}\n\terr = json.Unmarshal(body, &exp)\n\tif err != nil {\n\t\tt.Fatalf(\"unexpected error unmarshaling user: %v\", err)\n\t}\n\tif len(exp.Users) != 2 {\n\t\tt.Fatalf(\"unexpected 2 users: %#+v\", exp)\n\t}\n}", "func (m *MockHandler) UserCreate(username, email, password string) (*domain.User, string, error) {\n\tret := m.ctrl.Call(m, \"UserCreate\", username, email, password)\n\tret0, _ := ret[0].(*domain.User)\n\tret1, _ := ret[1].(string)\n\tret2, _ := ret[2].(error)\n\treturn ret0, ret1, ret2\n}", "func (m_2 *MockUserRepository) List(m *model.User) (model.Users, error) {\n\tm_2.ctrl.T.Helper()\n\tret := m_2.ctrl.Call(m_2, \"List\", m)\n\tret0, _ := ret[0].(model.Users)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m_2 *MockUserUsecaser) List(c context.Context, m *model.User) (model.Users, error) {\n\tm_2.ctrl.T.Helper()\n\tret := m_2.ctrl.Call(m_2, \"List\", c, m)\n\tret0, _ := ret[0].(model.Users)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockUserLogic) UserCreate(username, email, password string) (*domain.User, string, error) {\n\tret := m.ctrl.Call(m, \"UserCreate\", username, email, password)\n\tret0, _ := ret[0].(*domain.User)\n\tret1, _ := ret[1].(string)\n\tret2, _ := ret[2].(error)\n\treturn ret0, ret1, ret2\n}", "func (m_2 *MockUserUsecaser) Create(c context.Context, m *model.User) (*model.User, error) {\n\tm_2.ctrl.T.Helper()\n\tret := m_2.ctrl.Call(m_2, \"Create\", c, m)\n\tret0, _ := ret[0].(*model.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockDB) GetUser(arg0 uint) (*User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUser\", arg0)\n\tret0, _ := ret[0].(*User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (mmGetUser *mStorageMockGetUser) Return(up1 *db_storage.User, err error) *StorageMock {\n\tif mmGetUser.mock.funcGetUser != nil {\n\t\tmmGetUser.mock.t.Fatalf(\"StorageMock.GetUser mock is already set by Set\")\n\t}\n\n\tif mmGetUser.defaultExpectation == nil {\n\t\tmmGetUser.defaultExpectation = &StorageMockGetUserExpectation{mock: mmGetUser.mock}\n\t}\n\tmmGetUser.defaultExpectation.results = &StorageMockGetUserResults{up1, err}\n\treturn mmGetUser.mock\n}", "func (mmSaveUser *mStorageMockSaveUser) When(ctx context.Context, user *db_storage.User) *StorageMockSaveUserExpectation {\n\tif mmSaveUser.mock.funcSaveUser != nil {\n\t\tmmSaveUser.mock.t.Fatalf(\"StorageMock.SaveUser mock is already set by Set\")\n\t}\n\n\texpectation := &StorageMockSaveUserExpectation{\n\t\tmock: mmSaveUser.mock,\n\t\tparams: &StorageMockSaveUserParams{ctx, user},\n\t}\n\tmmSaveUser.expectations = append(mmSaveUser.expectations, expectation)\n\treturn expectation\n}", "func (s *UserStore) GenericStore() *kallax.Store {\n\treturn s.Store\n}", "func TestInitAndGetWithCorruptDatastore(t *testing.T) {\n\tuserlib.SetDebugStatus(false)\n\tuserlib.DatastoreClear()\n\tuserlib.KeystoreClear()\n\tdatastore := userlib.DatastoreGetMap()\n\tkeystore := userlib.KeystoreGetMap()\n\t_, _ = datastore, keystore\n\n\t_, err := InitUser(\"bob\", \"fubar\")\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\t_, err = InitUser(\"alice\", \"fubar\")\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\n\tvar keys []userlib.UUID\n\tvar vals [][]byte\n\tfor k, v := range datastore {\n\t\tkeys = append(keys, k)\n\t\tvals = append(vals, v)\n\t}\n\tuserlib.DatastoreSet(keys[0], vals[1])\n\tfor i := 1; i < len(keys); i++ {\n\t\tuserlib.DatastoreSet(keys[i], vals[0])\n\t}\n\n\t_, err = GetUser(\"alice\", \"fubar\")\n\tif err == nil {\n\t\tt.Error(\"Datastore was corrupted for alice but still got user.\")\n\t\treturn\n\t}\n\t_, err = GetUser(\"bob\", \"fubar\")\n\tif err == nil {\n\t\tt.Error(\"Datastore was corrupted for bob but still got user.\")\n\t\treturn\n\t}\n\n\tuserlib.DatastoreClear()\n\tuserlib.KeystoreClear()\n\n\t_, err = InitUser(\"bob\", \"fubar\")\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\tuserlib.DatastoreClear()\n\t_, err = GetUser(\"bob\", \"fubar\")\n\tif err == nil {\n\t\tt.Error(\"Datastore was empty but still got user.\")\n\t\treturn\n\t}\n\n\tuserlib.DatastoreClear()\n\tuserlib.KeystoreClear()\n\tdatastore = userlib.DatastoreGetMap()\n\n\t_, err = InitUser(\"bob\", \"fubar\")\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\t_, err = InitUser(\"alice\", \"fubar\")\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\n\tvar keys1 []userlib.UUID\n\tvar vals1 [][]byte\n\tfor k, v := range datastore {\n\t\tkeys1 = append(keys1, k)\n\t\tvals1 = append(vals1, v)\n\t}\n\tdatastore[keys1[0]] = userlib.RandomBytes(len(keys1[0]))\n\n\t_, err0 := GetUser(\"bob\", \"fubar\")\n\t_, err1 := GetUser(\"alice\", \"fubar\")\n\tif err0 == nil && err1 == nil {\n\t\tt.Error(\"successfully got all users when datastore was corrupted.\")\n\t}\n}", "func MockUserBackend() {\n\tdefer wg.Done()\n\t// Define Pluto Server\n\tgrpcSrv := server.New(\n\t\tserver.Addr(\":65080\"),\n\t\tserver.GRPCRegister(func(g *grpc.Server) {\n\t\t\tpbu.RegisterUserServiceServer(g, &MockUser{})\n\t\t}),\n\t)\n\t// Define Pluto Service\n\ts := pluto.New(\n\t\tpluto.Name(\"MockUserBackend\"),\n\t\tpluto.Servers(grpcSrv),\n\t\tpluto.HealthAddr(\":9094\"),\n\t)\n\t// Run service\n\tif err := s.Run(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}", "func (m *MockStore) GetUserByEmail(arg0 context.Context, arg1 string) (db.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUserByEmail\", arg0, arg1)\n\tret0, _ := ret[0].(db.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockStore) GetUserById(arg0 context.Context, arg1 uuid.UUID) (db.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUserById\", arg0, arg1)\n\tret0, _ := ret[0].(db.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m_2 *MockUserRepository) Create(m *model.User) (*model.User, error) {\n\tm_2.ctrl.T.Helper()\n\tret := m_2.ctrl.Call(m_2, \"Create\", m)\n\tret0, _ := ret[0].(*model.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func TestAuthenticate_Success(t *testing.T) {\n\tdb, mock, err := sqlmock.New()\n\tif err != nil {\n\t\tt.Fatalf(\"an error '%s' was not expected when opening a stub database connection\", err)\n\t}\n\tdefer db.Close()\n\n\tuser := models.User{\n\t\tID: 1,\n\t\tEmail: \"personia@personio.com\",\n\t\tPassword: \"personia\",\n\t}\n\n\trows := sqlmock.NewRows([]string{\"id\", \"email\"}).AddRow(user.ID, user.Email)\n\tmock.ExpectQuery(regexp.QuoteMeta(constants.LoginDetailsSelectQuery)).WithArgs(user.Email, user.Password).WillReturnRows(rows)\n\n\tloginRepository := NewLoginRepository(db)\n\n\tloginModel := &models.Login{\n\t\tEmail: \"personia@personio.com\",\n\t\tPassword: \"personia\",\n\t}\n\n\tcntx := context.Background()\n\tdbuser, err := loginRepository.Authenticate(cntx, loginModel)\n\tassert.Nil(t, err)\n\tassert.Equal(t, user.ID, dbuser.ID)\n\tassert.Equal(t, user.Email, dbuser.Email)\n}", "func (m_2 *MockUserUsecaser) Get(c context.Context, m *model.User) (*model.User, error) {\n\tm_2.ctrl.T.Helper()\n\tret := m_2.ctrl.Call(m_2, \"Get\", c, m)\n\tret0, _ := ret[0].(*model.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockStore) UpdateUser(arg0 context.Context, arg1 db.UpdateUserParams) (db.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"UpdateUser\", arg0, arg1)\n\tret0, _ := ret[0].(db.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockUser) Index(filters ...UserFilter) (api.Users, error) {\n\tvarargs := []interface{}{}\n\tfor _, a := range filters {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"Index\", varargs...)\n\tret0, _ := ret[0].(api.Users)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func mockMapStore(storage map[string]interface{}) ResultStoreFn {\n\treturn func(id string, key string, value interface{}) {\n\t\tutil.SetNestedField(storage, value, id, key)\n\t}\n}", "func TestCreateUser(t *testing.T) {\n user := User{\n Name: \"Mohammd Osama\",\n Password: \"helloworld\",\n Email: \"mohammeadosama@ieee.org\",\n }\n if user.ID == 0 {\n t.Errorf(\"Expected ID > 0, Received %d\", user.ID)\n }\n}", "func NewMockUser() sqlmock.Sqlmock {\n\tdb, mock, err := sqlmock.New()\n\tif err != nil {\n\t\tlog.Fatalf(\"an error '%s' was not expected when opening a stub database connection\", err)\n\t}\n\n\tdbMockUsers = db\n\tconnMockUser = &database.Data{\n\t\tDB: dbMockUsers,\n\t}\n\n\tuserRepositoryMock = repo.NewPostgresUserRepo(connMockUser)\n\n\t/*userRepositoryMock = &repo.UserRepository{\n\t\tData: &connMockUser,\n\t}*/\n\n\treturn mock\n}", "func (m *MockUserStore) EXPECT() *MockUserStoreMockRecorder {\n\treturn m.recorder\n}", "func (m *MockUser) Get(userKey api.UserKey) (api.User, error) {\n\tret := m.ctrl.Call(m, \"Get\", userKey)\n\tret0, _ := ret[0].(api.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockIUserService) QueryUserByName(name string) (*model.UserDB, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"QueryUserByName\", name)\n\tret0, _ := ret[0].(*model.UserDB)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (mmSaveUser *mStorageMockSaveUser) Return(err error) *StorageMock {\n\tif mmSaveUser.mock.funcSaveUser != nil {\n\t\tmmSaveUser.mock.t.Fatalf(\"StorageMock.SaveUser mock is already set by Set\")\n\t}\n\n\tif mmSaveUser.defaultExpectation == nil {\n\t\tmmSaveUser.defaultExpectation = &StorageMockSaveUserExpectation{mock: mmSaveUser.mock}\n\t}\n\tmmSaveUser.defaultExpectation.results = &StorageMockSaveUserResults{err}\n\treturn mmSaveUser.mock\n}", "func (m *MockUserRepositoryInterface) GetUsersWhereUserIDs(arg0 []uint64) ([]*db.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUsersWhereUserIDs\", arg0)\n\tret0, _ := ret[0].([]*db.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *Client) GetUser(arg0 context.Context, arg1 int64) (zendesk.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUser\", arg0, arg1)\n\tret0, _ := ret[0].(zendesk.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (cli *Store) User() *UserRepository {\n\t// TODO: add test store for testing\n\tif cli.userRepository != nil {\n\t\treturn cli.userRepository\n\t}\n\n\tcli.userRepository = &UserRepository{\n\t\tstore: cli,\n\t}\n\n\treturn cli.userRepository\n}", "func (accountRepo *mockAccountRepo) Initialize(ctx context.Context, db *sql.DB) {}", "func (su *SimulatedUser) UserMock(s State) Action {\n\treturn su.vsa[s.Get()]\n}", "func (m *MockUser) Create(ctx context.Context, db repo.DB, username string, hashedPassword []byte, now time.Time) (int, *internal.E) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Create\", ctx, db, username, hashedPassword, now)\n\tret0, _ := ret[0].(int)\n\tret1, _ := ret[1].(*internal.E)\n\treturn ret0, ret1\n}", "func (m_2 *MockUserRepository) Get(m *model.User) (*model.User, error) {\n\tm_2.ctrl.T.Helper()\n\tret := m_2.ctrl.Call(m_2, \"Get\", m)\n\tret0, _ := ret[0].(*model.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (_m *Repository) Store(_a0 *account.Account) error {\n\tret := _m.Called(_a0)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(*account.Account) error); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (m *MockIUserRepository) GetUser(arg0 uuid.UUID) *model.User {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUser\", arg0)\n\tret0, _ := ret[0].(*model.User)\n\treturn ret0\n}", "func (m *MockManager) Read(ctx context.Context, token string) (*model.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Read\", ctx, token)\n\tret0, _ := ret[0].(*model.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockUserTokenService) GetUser(arg0 context.Context, arg1 string) (*model.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUser\", arg0, arg1)\n\tret0, _ := ret[0].(*model.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (c *Provider) UserStore() msp.UserStore {\n\treturn c.userStore\n}", "func (_m *MockService) GetUser(ctx context.Context, id string) (*User, error) {\n\tret := _m.ctrl.Call(_m, \"GetUser\", ctx, id)\n\tret0, _ := ret[0].(*User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockUnitOfWork) GetUserRepository() repositories.User {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUserRepository\")\n\tret0, _ := ret[0].(repositories.User)\n\treturn ret0\n}", "func (m *MockPersister) GetUsers() (MultipleUsers, error) {\n\tret := m.ctrl.Call(m, \"GetUsers\")\n\tret0, _ := ret[0].(MultipleUsers)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (transactionRepo *mockTransactionRepo) Initialize(ctx context.Context, db *sql.DB) {}", "func (mmGetUserLocation *mStorageMockGetUserLocation) Set(f func(ctx context.Context, userID int64) (up1 *db_storage.UserLocation, err error)) *StorageMock {\n\tif mmGetUserLocation.defaultExpectation != nil {\n\t\tmmGetUserLocation.mock.t.Fatalf(\"Default expectation is already set for the storage.GetUserLocation method\")\n\t}\n\n\tif len(mmGetUserLocation.expectations) > 0 {\n\t\tmmGetUserLocation.mock.t.Fatalf(\"Some expectations are already set for the storage.GetUserLocation method\")\n\t}\n\n\tmmGetUserLocation.mock.funcGetUserLocation = f\n\treturn mmGetUserLocation.mock\n}", "func (m *MockIUser) GetUser(arg0 uint) (*User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUser\", arg0)\n\tret0, _ := ret[0].(*User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockStore) CreateUser(arg0 context.Context, arg1 db.CreateUserParams) (db.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"CreateUser\", arg0, arg1)\n\tret0, _ := ret[0].(db.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockPersister) AddUser(username, email, password string, isSysAdmin, overwrite bool) error {\n\tret := m.ctrl.Call(m, \"AddUser\", username, email, password, isSysAdmin, overwrite)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockIUserRepository) GetUsers() []*model.User {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUsers\")\n\tret0, _ := ret[0].([]*model.User)\n\treturn ret0\n}", "func (m *MockUserRepository) FindUser(query string, params ...interface{}) (easyalert.User, error) {\n\tvarargs := []interface{}{query}\n\tfor _, a := range params {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"FindUser\", varargs...)\n\tret0, _ := ret[0].(easyalert.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (mmSaveUser *mStorageMockSaveUser) Expect(ctx context.Context, user *db_storage.User) *mStorageMockSaveUser {\n\tif mmSaveUser.mock.funcSaveUser != nil {\n\t\tmmSaveUser.mock.t.Fatalf(\"StorageMock.SaveUser mock is already set by Set\")\n\t}\n\n\tif mmSaveUser.defaultExpectation == nil {\n\t\tmmSaveUser.defaultExpectation = &StorageMockSaveUserExpectation{}\n\t}\n\n\tmmSaveUser.defaultExpectation.params = &StorageMockSaveUserParams{ctx, user}\n\tfor _, e := range mmSaveUser.expectations {\n\t\tif minimock.Equal(e.params, mmSaveUser.defaultExpectation.params) {\n\t\t\tmmSaveUser.mock.t.Fatalf(\"Expectation set by When has same params: %#v\", *mmSaveUser.defaultExpectation.params)\n\t\t}\n\t}\n\n\treturn mmSaveUser\n}", "func (m *MockUserRepo) FindAll() ([]app.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"FindAll\")\n\tret0, _ := ret[0].([]app.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockUserRepositoryInterface) GetUserWhereUsername(arg0 string) (*db.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUserWhereUsername\", arg0)\n\tret0, _ := ret[0].(*db.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockUserRepositoryInterface) GetUserWhereUserID(arg0 uint64) (*db.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUserWhereUserID\", arg0)\n\tret0, _ := ret[0].(*db.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func TestGetUserService (t *testing.T){\n\tuser1, err := GetUserService(user_01.SocialNumber)\n\tassert.Equal(t, 200, err.HTTPStatus)\n\tassert.Equal(t, user_01, user1)\n\n\tuser2, err := GetUserService(user_01.SocialNumber)\n\tassert.Equal(t, 200, err.HTTPStatus)\n\tassert.Equal(t, user_01, user2)\n\n\tuser3, err := GetUserService(user_01.SocialNumber)\n\tassert.Equal(t, 200, err.HTTPStatus)\n\tassert.Equal(t, user_01, user3)\n\n\tuser4, err := GetUserService(user_01.SocialNumber)\n\tassert.Equal(t, 200, err.HTTPStatus)\n\tassert.Equal(t, user_01, user4)\n}", "func (m *MockUserUsecase) GetUser(id int64) entity.User {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUser\", id)\n\tret0, _ := ret[0].(entity.User)\n\treturn ret0\n}", "func TestServer_GetUserById(t *testing.T) {\n\ttests := []struct {\n\t\tName string\n\t\tIn *models.User\n\t\tExp *pb.User\n\t}{\n\t\t{\n\t\t\tName: \"Get a User\",\n\t\t\tIn: &models.User{\n\t\t\t\tModel: gorm.Model{\n\t\t\t\t\tID: 100,\n\t\t\t\t},\n\t\t\t\tFirstName: \"foo\",\n\t\t\t\tLastName: \"bar\",\n\t\t\t},\n\t\t\tExp: &pb.User{\n\t\t\t\tId: 100,\n\t\t\t\tFirstName: \"foo\",\n\t\t\t\tLastName: \"bar\",\n\t\t\t},\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.Name, func(t *testing.T) {\n\n\t\t\t//============ Start Test Setup ============\n\n\t\t\t// Connect to local MYSQL database for testing\n\t\t\tname := fmt.Sprintf(\"./%d.db\", rand.Int())\n\t\t\tr := setupTestDb(t, name)\n\t\t\tdefer os.Remove(name)\n\n\t\t\t// Clean up test data at the end\n\t\t\t// Note: we use Unscoped delete to remove the record permanently\n\t\t\t// - Not using unscoped means the record will still exist and occupy the primary key, even though its marked as deleted\n\t\t\tdefer r.DB.Unscoped().Delete(tt.In)\n\n\t\t\t// Delete user if it exists so we have a clean test\n\t\t\terr := r.DB.Unscoped().Delete(tt.In).Error\n\t\t\trequire.NoError(t, err)\n\t\t\trequire.NoError(t, r.DB.Create(tt.In).Error)\n\t\t\t//============ End Test Setup ============\n\n\t\t\t// ============Start Test ============\n\n\t\t\tserv := grpc.NewServerWithRepo(r, \"\", \"\")\n\n\t\t\tgot, rErr := serv.GetUserById(context.Background(), &pb.Id{Id: int64(tt.In.ID)})\n\t\t\trequire.NoError(t, rErr)\n\t\t\trequire.Equal(t, tt.Exp, got)\n\n\t\t})\n\t}\n}", "func (u *mockUserProfileService) Save(profile decision.UserProfile) {\n}", "func (m_2 *MockUserUsecaser) Update(c context.Context, m *model.User) (*model.User, error) {\n\tm_2.ctrl.T.Helper()\n\tret := m_2.ctrl.Call(m_2, \"Update\", c, m)\n\tret0, _ := ret[0].(*model.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}" ]
[ "0.7232572", "0.70759726", "0.6947042", "0.65885407", "0.6443902", "0.63073105", "0.62877065", "0.6251729", "0.6233818", "0.6186411", "0.61615545", "0.6143569", "0.60569364", "0.6051291", "0.60378027", "0.60374254", "0.6020175", "0.59906864", "0.5951722", "0.59318924", "0.59068274", "0.59052396", "0.59025973", "0.58771396", "0.5852417", "0.58499384", "0.58248997", "0.58199763", "0.5813077", "0.5812539", "0.5803299", "0.5799304", "0.5771078", "0.57254833", "0.5716467", "0.5716214", "0.5708382", "0.569013", "0.56759614", "0.56718093", "0.5670532", "0.5667096", "0.56620353", "0.5645879", "0.5637085", "0.56110173", "0.56083685", "0.56023645", "0.55869335", "0.55812025", "0.557766", "0.5571984", "0.5563085", "0.556144", "0.55489486", "0.5545549", "0.5541322", "0.55294365", "0.5529192", "0.5527929", "0.5524556", "0.5520626", "0.551725", "0.55172104", "0.55025405", "0.5502517", "0.54956985", "0.54736817", "0.5466689", "0.54475605", "0.54468954", "0.54344547", "0.5433548", "0.5423236", "0.5422902", "0.5418866", "0.54109514", "0.53957033", "0.53907", "0.5388381", "0.5388117", "0.538768", "0.53832734", "0.5379956", "0.5378206", "0.5372153", "0.536765", "0.53673494", "0.53641003", "0.5361359", "0.5360361", "0.5349143", "0.5348971", "0.5347519", "0.53410184", "0.53394604", "0.53343034", "0.53261024", "0.53232765", "0.5322061" ]
0.70885456
1
UserStore indicates an expected call of UserStore
func (mr *MockProvidersMockRecorder) UserStore() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UserStore", reflect.TypeOf((*MockProviders)(nil).UserStore)) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (mr *MockClientMockRecorder) UserStore() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"UserStore\", reflect.TypeOf((*MockClient)(nil).UserStore))\n}", "func (mr *MockRepositoryMockRecorder) Store(user interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Store\", reflect.TypeOf((*MockRepository)(nil).Store), user)\n}", "func TestStore_CreateUser(t *testing.T) {\n\tt.Parallel()\n\ts := MustOpenStore()\n\tdefer s.Close()\n\n\t// Create user.\n\tif ui, err := s.CreateUser(\"susy\", \"pass\", true); err != nil {\n\t\tt.Fatal(err)\n\t} else if ui.Name != \"susy\" || ui.Hash == \"\" || ui.Admin != true {\n\t\tt.Fatalf(\"unexpected user: %#v\", ui)\n\t}\n}", "func TestStore_UserCount(t *testing.T) {\n\tt.Parallel()\n\ts := MustOpenStore()\n\tdefer s.Close()\n\n\tif count, err := s.UserCount(); count != 0 && err != nil {\n\t\tt.Fatalf(\"expected user count to be 0 but was %d\", count)\n\t}\n\n\t// Create users.\n\tif _, err := s.CreateUser(\"susy\", \"pass\", true); err != nil {\n\t\tt.Fatal(err)\n\t} else if _, err := s.CreateUser(\"bob\", \"pass\", true); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif count, err := s.UserCount(); count != 2 && err != nil {\n\t\tt.Fatalf(\"expected user count to be 2 but was %d\", count)\n\t}\n}", "func (mr *MockUserRepositoryMockRecorder) Store(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Store\", reflect.TypeOf((*MockUserRepository)(nil).Store), arg0)\n}", "func (suite *StoreTestSuite) Test001_User() {\n\tusername := \"foo\"\n\temail := \"bar\"\n\tpw := \"baz\"\n\trole := 1337\n\n\t// Test CreateUser\n\tnewUser := &schema.User{\n\t\tUsername: &username,\n\t\tEmail: &email,\n\t\tPassword: &pw,\n\t\tRole: &role,\n\t}\n\terr := suite.store.CreateUser(newUser)\n\tsuite.Nil(err)\n\n\t// Test GetUserByUsername\n\tuser, err := suite.store.GetUserByUsername(username)\n\tsuite.Nil(err)\n\tsuite.NotNil(user)\n\tsuite.Equal(username, user.Username)\n\tsuite.Equal(email, user.Email)\n\n\tid := user.ID.Hex()\n\n\t// Test GetUserByEmail\n\tuser, err = suite.store.GetUserByEmail(email)\n\tsuite.Nil(err)\n\tsuite.NotNil(user)\n\tsuite.Equal(username, user.Username)\n\tsuite.Equal(email, user.Email)\n\n\t// Test GetUserByPassword\n\tuser, err = suite.store.GetUserByCreds(username, pw)\n\tsuite.Nil(err)\n\tsuite.NotNil(user)\n\tsuite.Equal(username, user.Username)\n\tsuite.Equal(email, user.Email)\n\n\t// Test CreateUser with conflict\n\terr = suite.store.CreateUser(newUser)\n\tsuite.NotNil(err)\n\tsuite.Equal(\"user with username as foo already exists\", err.Error())\n\n\t// Test UpdateUser\n\tnewUsername := \"foobar\"\n\tuserPatch := &schema.User{Username: &newUsername}\n\tuser, err = suite.store.UpdateUser(id, userPatch)\n\tsuite.Nil(err)\n\tsuite.Equal(newUsername, user.Username)\n\tsuite.Equal(email, user.Email)\n\tsuite.Equal(role, user.Role)\n\n\t// Add second user\n\terr = suite.store.CreateUser(newUser)\n\tsuite.Nil(err)\n\n\t// Try to update second user\n\tu, err := suite.store.GetUserByUsername(*newUser.Username)\n\tsuite.Nil(err)\n\n\tuser, err = suite.store.UpdateUser(u.ID.Hex(), userPatch)\n\tsuite.Nil(user)\n\tsuite.True(mgo.IsDup(err))\n\n\t// Test GetAllUsers\n\tusers, err := suite.store.GetAllUsers()\n\tsuite.Nil(err)\n\tsuite.Equal(len(users), 2)\n\n\t// Test DeleteUser\n\tuser, err = suite.store.DeleteUser(id)\n\tsuite.Nil(err)\n\tsuite.NotNil(user)\n\tsuite.Equal(newUsername, user.Username)\n\tsuite.Equal(email, user.Email)\n}", "func (mr *MockUserLogicMockRecorder) UserGet(userName interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"UserGet\", reflect.TypeOf((*MockUserLogic)(nil).UserGet), userName)\n}", "func TestStore_DropUser(t *testing.T) {\n\tt.Parallel()\n\ts := MustOpenStore()\n\tdefer s.Close()\n\n\t// Create users.\n\tif _, err := s.CreateUser(\"susy\", \"pass\", true); err != nil {\n\t\tt.Fatal(err)\n\t} else if _, err := s.CreateUser(\"bob\", \"pass\", true); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// Remove user.\n\tif err := s.DropUser(\"bob\"); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// Verify user was removed.\n\tif a, err := s.Users(); err != nil {\n\t\tt.Fatal(err)\n\t} else if len(a) != 1 {\n\t\tt.Fatalf(\"unexpected user count: %d\", len(a))\n\t} else if a[0].Name != \"susy\" {\n\t\tt.Fatalf(\"unexpected user: %s\", a[0].Name)\n\t}\n}", "func (m *MockProviders) UserStore() msp.UserStore {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"UserStore\")\n\tret0, _ := ret[0].(msp.UserStore)\n\treturn ret0\n}", "func (m *MockClient) UserStore() msp.UserStore {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"UserStore\")\n\tret0, _ := ret[0].(msp.UserStore)\n\treturn ret0\n}", "func (mr *MockHandlerMockRecorder) UserGet(userName interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"UserGet\", reflect.TypeOf((*MockHandler)(nil).UserGet), userName)\n}", "func TestStore_UpdateUser(t *testing.T) {\n\tt.Parallel()\n\ts := MustOpenStore()\n\tdefer s.Close()\n\n\t// Create users.\n\tif _, err := s.CreateUser(\"susy\", \"pass\", true); err != nil {\n\t\tt.Fatal(err)\n\t} else if _, err := s.CreateUser(\"bob\", \"pass\", true); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// Store password hash for bob.\n\tui, err := s.User(\"bob\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// Update user.\n\tif err := s.UpdateUser(\"bob\", \"XXX\"); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// Verify password hash was updated.\n\tif other, err := s.User(\"bob\"); err != nil {\n\t\tt.Fatal(err)\n\t} else if ui.Hash == other.Hash {\n\t\tt.Fatal(\"password hash did not change\")\n\t}\n}", "func (c *Provider) UserStore() msp.UserStore {\n\treturn c.userStore\n}", "func TestSync_StoreError(t *testing.T) {\n\tcontroller := gomock.NewController(t)\n\tdefer controller.Finish()\n\n\tuser := &core.User{ID: 1}\n\tuserStore := mock.NewMockUserStore(controller)\n\tuserStore.EXPECT().Update(gomock.Any(), user).Return(nil)\n\tuserStore.EXPECT().Update(gomock.Any(), user).Return(nil)\n\n\trepoService := mock.NewMockRepositoryService(controller)\n\trepoService.EXPECT().List(gomock.Any(), user).Return([]*core.Repository{}, nil)\n\n\trepoStore := mock.NewMockRepositoryStore(controller)\n\trepoStore.EXPECT().List(gomock.Any(), gomock.Any()).Return(nil, sql.ErrNoRows)\n\n\ts := Synchronizer{\n\t\trepoz: repoService,\n\t\tusers: userStore,\n\t\trepos: repoStore,\n\t}\n\t_, err := s.Sync(context.Background(), user)\n\tif got, want := err, sql.ErrNoRows; got != want {\n\t\tt.Errorf(\"Want error %s, got %s\", want, got)\n\t}\n}", "func UserOwnsStore(userID, storeID int) (bool, error) {\n\tkey := stringutil.Build(\"userid:\", strconv.Itoa(userID), \":storeids\")\n\treturn IsSetMember(key, storeID)\n}", "func TestUserstorage(t *testing.T) {\n t.Log(\"*** User data storage and retrieval test ***\")\n\n // initialize user\n u, err := InitUser(\"alice\",\"fubar\")\n if err != nil {\n t.Error(\"Failed to initialize user (\", err, \")\")\n } else {\n t.Log(\"Successfully stored user\", u)\n }\n\n // retrieve user \n v, err := GetUser(\"alice\", \"fubar\")\n if err != nil {\n t.Error(\"Failed to reload user\", err)\n } else {\n t.Log(\"Correctly retrieved user\", v)\n }\n}", "func (s *UserSuite) TestUserAttachedToRequestAuthenticatedNoUseridentifierHasBeenRegistered(c *C) {\n\thandler := u.Handler()\n\n\treq, _ := http.NewRequest(\"GET\", \"http://127.0.0.1:8000/auth-status\", nil)\n\tresp := httptest.NewRecorder()\n\thandler(resp, req)\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tc.Assert(err, IsNil)\n\tc.Assert(string(body), Equals, \"false\")\n}", "func TestUser(t *testing.T) {\n\tu := new(entity.User)\n\tu.Userid = \"1111\" //\n\thas, err := Engine.Get(u)\n\tt.Log(has, err)\n}", "func (mr *MockAdminMockRecorder) User() *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"User\", reflect.TypeOf((*MockAdmin)(nil).User))\n}", "func (e *Entity) AssertUser() {\n\tif e.data.Kind != member.User {\n\t\tpanic(\"AssertUser\")\n\t}\n}", "func InitUserDBStore(ds db.IDataStore) {\n\tds.SetIndex(mgo.Index{\n\t\tName: \"email_unqkey\",\n\t\tKey: []string{\"email\"},\n\t\tUnique: true,\n\t\tDropDups: false,\n\t\tBackground: true,\n\t\tSparse: true,\n\t})\n}", "func (_mr *MockServiceMockRecorder) GetUser(arg0, arg1 interface{}) *gomock.Call {\n\treturn _mr.mock.ctrl.RecordCallWithMethodType(_mr.mock, \"GetUser\", reflect.TypeOf((*MockService)(nil).GetUser), arg0, arg1)\n}", "func (e UserRequired) IsUserRequired() {}", "func (mr *MockPersisterMockRecorder) GetUser(username, password interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetUser\", reflect.TypeOf((*MockPersister)(nil).GetUser), username, password)\n}", "func (mr *MockStoreMockRecorder) CreateUser(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"CreateUser\", reflect.TypeOf((*MockStore)(nil).CreateUser), arg0, arg1)\n}", "func ValidateStoredUser(result *StoredUser) (err error) {\n\tswitch result.View {\n\tcase \"default\", \"\":\n\t\terr = ValidateStoredUserView(result.Projected)\n\tdefault:\n\t\terr = goa.InvalidEnumValueError(\"view\", result.View, []interface{}{\"default\"})\n\t}\n\treturn\n}", "func (mr *MockIUserStoreMockRecorder) Save(user interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Save\", reflect.TypeOf((*MockIUserStore)(nil).Save), user)\n}", "func (s *VaultUserStore) Store(user *msp.UserData) error {\n\t_, err := s.client.Logical().Write(\n\t\t\"fabric/kv/users/\"+strings.ToLower(user.ID)+\"@\"+strings.ToLower(user.MSPID),\n\n\t\tmap[string]interface{}{\n\t\t\t\"value\": string(user.EnrollmentCertificate),\n\t\t})\n\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to store user data into vault\")\n\t}\n\n\treturn nil\n}", "func (mr *MockStoreMockRecorder) UpdateUser(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"UpdateUser\", reflect.TypeOf((*MockStore)(nil).UpdateUser), arg0, arg1)\n}", "func (mr *MockDBMockRecorder) GetUser(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetUser\", reflect.TypeOf((*MockDB)(nil).GetUser), arg0)\n}", "func (d *PostgresDatabase) Store(u model.User) error {\n\topMetric.WithLabelValues(\"store-user\").Inc()\n\n\tostart := time.Now()\n\tdefer opDuration.WithLabelValues(\"store-user\").Observe(time.Since(ostart).Seconds())\n\n\tdob, err := time.Parse(\"2006-01-02\", u.DOB)\n\tif err != nil {\n\t\topErrMetric.WithLabelValues(\"store-user\").Inc()\n\t\treturn err\n\t}\n\t_, err = d.Get(u.Username)\n\t// if the user is not present we insert\n\tif err == ErrUserNotFound {\n\t\t_, err := d.db.Query(queryInsertUser, u.Username, dob)\n\t\tif err != nil {\n\t\t\topErrMetric.WithLabelValues(\"store-user\").Inc()\n\t\t\treturn err\n\t\t}\n\t\topMetric.WithLabelValues(\"store-user\").Inc()\n\t\treturn nil\n\t} else if err != nil {\n\t\topErrMetric.WithLabelValues(\"store-user\").Inc()\n\t\treturn err\n\t}\n\n\t// if we got here, the user is already present and we should do an update\n\tstmt, err := d.db.Prepare(queryUpdateUser)\n\t_, err = stmt.Exec(dob, u.Username)\n\tif err != nil {\n\t\topErrMetric.WithLabelValues(\"store-user\").Inc()\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (s *Service) Verify(username string) bool {\n\treturn s.store.FindUser(username) != DoesNotExist\n}", "func storeInContext(ctx *gin.Context, user models.User) error {\n\tctx.Set(utils.TatHeaderUsername, user.Username)\n\tctx.Set(utils.TatCtxIsAdmin, user.IsAdmin)\n\tctx.Set(utils.TatCtxIsSystem, user.IsSystem)\n\n\tif user.IsAdmin {\n\t\tlog.Debugf(\"user %s isAdmin\", user.Username)\n\t}\n\n\tif user.IsSystem {\n\t\tlog.Debugf(\"user %s isSystem\", user.Username)\n\t}\n\n\treturn nil\n}", "func (mr *MockUserRepositoryInterfaceMockRecorder) InsertUser(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"InsertUser\", reflect.TypeOf((*MockUserRepositoryInterface)(nil).InsertUser), arg0)\n}", "func (r *UserRepository) Store(user *model.User) {\n\tr.users = append(r.users, user)\n}", "func (mr *MockStoreMockRecorder) GetUserById(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetUserById\", reflect.TypeOf((*MockStore)(nil).GetUserById), arg0, arg1)\n}", "func (m *MockUserRepository) Store(arg0 *sweeper.User) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Store\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (mr *MockEventRepositoryMockRecorder) Store(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Store\", reflect.TypeOf((*MockEventRepository)(nil).Store), arg0)\n}", "func VerifyStoreAccount(c *gin.Context) {\n\n\tverificationToken := c.Param(\"token\")\n\n\tvar itemUser models.User\n\tvar itemStore models.Store\n\n\tif config.DB.First(&itemStore, \"verification_token = ?\", verificationToken).RecordNotFound() {\n\t\tc.JSON(404, gin.H{\n\t\t\t\"status\": \"error\",\n\t\t\t\"message\": \"record not found\"})\n\t\tc.Abort()\n\t\treturn\n\t}\n\n\tif config.DB.First(&itemUser, \"id = ?\", itemStore.UserID).RecordNotFound() {\n\t\tc.JSON(404, gin.H{\n\t\t\t\"status\": \"error\",\n\t\t\t\"message\": \"user record not found\"})\n\t\tc.Abort()\n\t\treturn\n\t}\n\n\tconfig.DB.Model(&itemUser).Where(\"id = ?\", itemUser.ID).Updates(models.User{\n\t\tIsActivate: true,\n\t\tHaveStore: true,\n\t})\n\n\tconfig.DB.Model(&itemStore).Where(\"id = ?\", itemStore.ID).Updates(models.Store{\n\t\tIsActivate: true,\n\t})\n\n\tc.JSON(200, gin.H{\n\t\t\"status\": \"Success, your account is now active. Please Login to your account\",\n\t})\n\n}", "func (mr *MockPersisterMockRecorder) AddUser(username, email, password, isSysAdmin, overwrite interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"AddUser\", reflect.TypeOf((*MockPersister)(nil).AddUser), username, email, password, isSysAdmin, overwrite)\n}", "func (_mr *MockServiceMockRecorder) AddUser(arg0, arg1 interface{}) *gomock.Call {\n\treturn _mr.mock.ctrl.RecordCallWithMethodType(_mr.mock, \"AddUser\", reflect.TypeOf((*MockService)(nil).AddUser), arg0, arg1)\n}", "func (l *StandardLogger) NoUserSet(user string) {\n\tl.Errorf(noUserSet.message, user)\n}", "func (mr *MockUserServerMockRecorder) GetUser(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetUser\", reflect.TypeOf((*MockUserServer)(nil).GetUser), arg0, arg1)\n}", "func (mr *MockConnMockRecorder) UserID() *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"UserID\", reflect.TypeOf((*MockConn)(nil).UserID))\n}", "func (e *BadSpotError) IsShowToUser() {}", "func TestIfAddUserInfoToMapChangesInfo(t *testing.T) {\n\tsuite := testsuite.NewTestSuite(t)\n\tMockUserItemStorage := MockUserItemStorage()\n\tMockUserSubmissionData := MockUserSubmissionData()\n\tmongoDB.AddUserInfoToMap(MockUserItemStorage, MockUserSubmissionData)\n\n\t// We need to generate what the result would look like\n\tResultUserItemStorage := mongoDB.UserItemStorage{\n\t\tUserID: \"Test\",\n\t\t// These are the important things that need info\n\t\tPrices: make(map[string]models.UserPrices),\n\t\tProfits: make(map[string]models.UserProfits),\n\t}\n\n\t// If it changes, then that should mean that we're editing info\n\tsuite.AssertNotEqual(ResultUserItemStorage, *MockUserItemStorage)\n}", "func TestUpdateUserNotValid(t *testing.T) {\n\tdb := database.Connect()\n\tu := User{\n\t\tEmail: \"test4@example.com\",\n\t}\n\tr := u.Update(db)\n\tif r != false {\n\t\tt.Errorf(\"Expected failed update, got %t\", r)\n\t}\n}", "func (mr *MockUserLogicMockRecorder) UserLogin(email, password interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"UserLogin\", reflect.TypeOf((*MockUserLogic)(nil).UserLogin), email, password)\n}", "func (mr *MockArticleRepositoryMockRecorder) Store(a interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Store\", reflect.TypeOf((*MockArticleRepository)(nil).Store), a)\n}", "func TestUserIsSet(t *testing.T) {\n\tconfiguration := ReadConfig()\n\tuser := configuration.User\n\n\tif user == \"\" {\n\t\tt.Error(\"User misconfigured\")\n\t} else {\n\t\tt.Log(\"User set\")\n\t}\n}", "func (mr *MockUserLogicMockRecorder) UserCreate(username, email, password interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"UserCreate\", reflect.TypeOf((*MockUserLogic)(nil).UserCreate), username, email, password)\n}", "func (mr *MockIUserRepositoryMockRecorder) GetUser(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetUser\", reflect.TypeOf((*MockIUserRepository)(nil).GetUser), arg0)\n}", "func (mr *MockUserServiceMockRecorder) Save(ctx, user interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Save\", reflect.TypeOf((*MockUserService)(nil).Save), ctx, user)\n}", "func TestStore(t *testing.T) {\r\n\tsetup()\r\n\tp := Person{\r\n\t\tFirstname: firstname,\r\n\t\tLastname: lastname,\r\n\t}\r\n\tresult, err := p.Store(client)\r\n\t_id = result.InsertedID.(primitive.ObjectID)\r\n\r\n\tif err != nil {\r\n\t\tt.Fatalf(\"Failed store test %s\", err)\r\n\t}\r\n\r\n\tif p.Firstname != firstname {\r\n\t\tt.Fatalf(\"Failed store test %s\", err)\r\n\t}\r\n\r\n\tt.Log(\"Person was successfully stored : \"+p.Firstname+\" \"+p.Lastname+\" inserted id: \", _id)\r\n\r\n\tif err != nil {\r\n\t\tt.Fatalf(\"Failed store test %s\", err)\r\n\t}\r\n\r\n}", "func (m *StorageMock) MinimockSaveUserInspect() {\n\tfor _, e := range m.SaveUserMock.expectations {\n\t\tif mm_atomic.LoadUint64(&e.Counter) < 1 {\n\t\t\tm.t.Errorf(\"Expected call to StorageMock.SaveUser with params: %#v\", *e.params)\n\t\t}\n\t}\n\n\t// if default expectation was set then invocations count should be greater than zero\n\tif m.SaveUserMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterSaveUserCounter) < 1 {\n\t\tif m.SaveUserMock.defaultExpectation.params == nil {\n\t\t\tm.t.Error(\"Expected call to StorageMock.SaveUser\")\n\t\t} else {\n\t\t\tm.t.Errorf(\"Expected call to StorageMock.SaveUser with params: %#v\", *m.SaveUserMock.defaultExpectation.params)\n\t\t}\n\t}\n\t// if func was set then invocations count should be greater than zero\n\tif m.funcSaveUser != nil && mm_atomic.LoadUint64(&m.afterSaveUserCounter) < 1 {\n\t\tm.t.Error(\"Expected call to StorageMock.SaveUser\")\n\t}\n}", "func TestInitAndGetWithCorruptDatastore(t *testing.T) {\n\tuserlib.SetDebugStatus(false)\n\tuserlib.DatastoreClear()\n\tuserlib.KeystoreClear()\n\tdatastore := userlib.DatastoreGetMap()\n\tkeystore := userlib.KeystoreGetMap()\n\t_, _ = datastore, keystore\n\n\t_, err := InitUser(\"bob\", \"fubar\")\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\t_, err = InitUser(\"alice\", \"fubar\")\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\n\tvar keys []userlib.UUID\n\tvar vals [][]byte\n\tfor k, v := range datastore {\n\t\tkeys = append(keys, k)\n\t\tvals = append(vals, v)\n\t}\n\tuserlib.DatastoreSet(keys[0], vals[1])\n\tfor i := 1; i < len(keys); i++ {\n\t\tuserlib.DatastoreSet(keys[i], vals[0])\n\t}\n\n\t_, err = GetUser(\"alice\", \"fubar\")\n\tif err == nil {\n\t\tt.Error(\"Datastore was corrupted for alice but still got user.\")\n\t\treturn\n\t}\n\t_, err = GetUser(\"bob\", \"fubar\")\n\tif err == nil {\n\t\tt.Error(\"Datastore was corrupted for bob but still got user.\")\n\t\treturn\n\t}\n\n\tuserlib.DatastoreClear()\n\tuserlib.KeystoreClear()\n\n\t_, err = InitUser(\"bob\", \"fubar\")\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\tuserlib.DatastoreClear()\n\t_, err = GetUser(\"bob\", \"fubar\")\n\tif err == nil {\n\t\tt.Error(\"Datastore was empty but still got user.\")\n\t\treturn\n\t}\n\n\tuserlib.DatastoreClear()\n\tuserlib.KeystoreClear()\n\tdatastore = userlib.DatastoreGetMap()\n\n\t_, err = InitUser(\"bob\", \"fubar\")\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\t_, err = InitUser(\"alice\", \"fubar\")\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\n\tvar keys1 []userlib.UUID\n\tvar vals1 [][]byte\n\tfor k, v := range datastore {\n\t\tkeys1 = append(keys1, k)\n\t\tvals1 = append(vals1, v)\n\t}\n\tdatastore[keys1[0]] = userlib.RandomBytes(len(keys1[0]))\n\n\t_, err0 := GetUser(\"bob\", \"fubar\")\n\t_, err1 := GetUser(\"alice\", \"fubar\")\n\tif err0 == nil && err1 == nil {\n\t\tt.Error(\"successfully got all users when datastore was corrupted.\")\n\t}\n}", "func (c UserInfo) Store(UserSubmission *models.UserSubmission) revel.Result {\n\n\t// AUTHENTICATION\n\t// Checks if there is a session for this user.\n\tuserID, _ := c.Session.Get(\"DiscordUserID\")\n\tif userID == nil {\n\t\t// Forbidden\n\t\tc.Response.Status = 403\n\t\treturn c.Render()\n\t}\n\n\t// STORAGE\n\t// Adds or updates a user's storage.\n\tUserItemStorage := UserStorageCollection.FindUserItemStorage(userID.(string))\n\tif UserItemStorage == nil {\n\t\tUserStorageCollection.InsertNewUserItemStorage(UserSubmission, userID.(string))\n\t} else {\n\t\tUserStorageCollection.AddUserItem(UserItemStorage, userID.(string), UserSubmission)\n\t}\n\n\t// 201 - CREATED\n\tc.Response.Status = 201\n\treturn c.Render()\n}", "func NopUserDB() UserDB { return nopUserDB{} }", "func (mr *MockClientMockRecorder) GetUser(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetUser\", reflect.TypeOf((*MockClient)(nil).GetUser), arg0)\n}", "func (mr *MockClientMockRecorder) GetUser(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetUser\", reflect.TypeOf((*MockClient)(nil).GetUser), arg0)\n}", "func (mr *MockHandlerMockRecorder) UserCreate(username, email, password interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"UserCreate\", reflect.TypeOf((*MockHandler)(nil).UserCreate), username, email, password)\n}", "func (mr *MockIUserMockRecorder) GetUser(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetUser\", reflect.TypeOf((*MockIUser)(nil).GetUser), arg0)\n}", "func (mr *MockHandlerMockRecorder) UserLogin(email, password interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"UserLogin\", reflect.TypeOf((*MockHandler)(nil).UserLogin), email, password)\n}", "func (s *Storage) StoreUser(userID int64, screenName, description string, protected bool, blob []byte) {\n\tchQueryArgs <- &queryArgs{\"INSERT OR IGNORE INTO users (user_id, screen_name, description, protected, blob) VALUES (?, ?, ?, ?, ?)\",\n\t\t[]interface{}{userID, screenName, description, protected, blob}}\n}", "func (s MockStore) Put(u User) error {\n\ts.id[u.ID] = u\n\ts.name[u.Name] = u\n\ts.email[u.Email] = u\n\n\treturn nil\n}", "func (mr *MockRepositoryMockRecorder) Store(ctx, coffeesDomain interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Store\", reflect.TypeOf((*MockRepository)(nil).Store), ctx, coffeesDomain)\n}", "func (mr *MockUserUsecaseMockRecorder) GetUser(id interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetUser\", reflect.TypeOf((*MockUserUsecase)(nil).GetUser), id)\n}", "func (mr *MockDatabaseMockRecorder) SaveUser(user interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"SaveUser\", reflect.TypeOf((*MockDatabase)(nil).SaveUser), user)\n}", "func (mr *MockUserTokenServiceMockRecorder) GetUser(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetUser\", reflect.TypeOf((*MockUserTokenService)(nil).GetUser), arg0, arg1)\n}", "func (mr *MockUnitOfWorkMockRecorder) GetUserRepository() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetUserRepository\", reflect.TypeOf((*MockUnitOfWork)(nil).GetUserRepository))\n}", "func (u *User) StoreUser() error {\n\terr := database.DB.Create(&u).Error\n\treturn err\n}", "func (mr *MockUseCaseMockRecorder) Store(ctx, data interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Store\", reflect.TypeOf((*MockUseCase)(nil).Store), ctx, data)\n}", "func (mr *MockDBMockRecorder) GetOrCreateUser(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetOrCreateUser\", reflect.TypeOf((*MockDB)(nil).GetOrCreateUser), arg0, arg1)\n}", "func (mr *MockUserRepositoryMockRecorder) ExistUser(email interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"ExistUser\", reflect.TypeOf((*MockUserRepository)(nil).ExistUser), email)\n}", "func (s *Store) UserExist(token string) bool {\n\texists, err := s.ES.IndexExists(token).Do()\n\tif err != nil || !exists {\n\t\treturn false\n\t}\n\treturn true\n}", "func (mr *MockContentRepositoryMockRecorder) Store(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Store\", reflect.TypeOf((*MockContentRepository)(nil).Store), arg0)\n}", "func MarkedUser(err error) bool {\n\treturn Marked(err, User)\n}", "func (mr *MockIUserMockRecorder) GetOrCreateUser(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetOrCreateUser\", reflect.TypeOf((*MockIUser)(nil).GetOrCreateUser), arg0, arg1)\n}", "func (as *ActionSuite) TestUserQuery() {\n\tt := as.T()\n\n\tf := fixturesForUserQuery(as)\n\n\ttype testCase struct {\n\t\tName string\n\t\tPayload string\n\t\tTestUser models.User\n\t\tExpectError bool\n\t\tTest func(t *testing.T)\n\t}\n\n\tvar resp UserResponse\n\n\ttestCases := []testCase{\n\t\t{\n\t\t\tName: \"all fields\",\n\t\t\tPayload: `{user(id: \"` + f.Users[1].UUID.String() + `\") {` + allUserFields + \"}}\",\n\t\t\tTestUser: f.Users[0],\n\t\t\tTest: func(t *testing.T) {\n\t\t\t\tif err := as.DB.Load(&(f.Users[1]), \"PhotoFile\"); err != nil {\n\t\t\t\t\tt.Errorf(\"failed to load user fixture, %s\", err)\n\t\t\t\t}\n\t\t\t\tas.Equal(f.Users[1].UUID.String(), resp.User.ID, \"incorrect ID\")\n\t\t\t\tas.Equal(f.Users[1].Email, resp.User.Email, \"incorrect Email\")\n\t\t\t\tas.Equal(f.Users[1].Nickname, resp.User.Nickname, \"incorrect Nickname\")\n\t\t\t\tas.Equal(f.Users[1].AdminRole, resp.User.AdminRole, \"incorrect AdminRole\")\n\t\t\t\tas.Equal(f.Users[1].PhotoFile.URL, resp.User.AvatarURL, \"incorrect AvatarURL\")\n\t\t\t\tas.Equal(f.Users[1].PhotoFile.UUID.String(), resp.User.PhotoID, \"incorrect PhotoID\")\n\t\t\t\tas.Regexp(\"^https?\", resp.User.AvatarURL, \"invalid AvatarURL\")\n\n\t\t\t\tas.Equal(strings.ToUpper(f.UserPreferences[0].Value), *resp.User.Preferences.Language,\n\t\t\t\t\t\"incorrect preference - language\")\n\t\t\t\tas.Equal(f.UserPreferences[1].Value, *resp.User.Preferences.TimeZone,\n\t\t\t\t\t\"incorrect preference - time zone\")\n\t\t\t\tas.Equal(strings.ToUpper(f.UserPreferences[2].Value), *resp.User.Preferences.WeightUnit,\n\t\t\t\t\t\"incorrect preference - weight unit\")\n\n\t\t\t\tas.Equal(f.Locations[1].Description, resp.User.Location.Description, \"incorrect location\")\n\t\t\t\tas.Equal(f.Locations[1].Country, resp.User.Location.Country, \"incorrect country\")\n\t\t\t\tas.InDelta(f.Locations[1].Latitude.Float64, resp.User.Location.Lat, 0.0001, \"incorrect latitude\")\n\t\t\t\tas.InDelta(f.Locations[1].Longitude.Float64, resp.User.Location.Long, 0.0001, \"incorrect longitude\")\n\n\t\t\t\tas.Equal(1, len(resp.User.Organizations), \"wrong number of Organizations\")\n\t\t\t\tas.Equal(f.Organization.UUID.String(), resp.User.Organizations[0].ID, \"incorrect Organization ID\")\n\n\t\t\t\tas.Equal(1, len(resp.User.Requests), \"wrong number of requests\")\n\t\t\t\tas.Equal(f.Requests[0].UUID.String(), resp.User.Requests[0].ID, \"incorrect Request ID\")\n\n\t\t\t\tas.Equal(1, len(resp.User.MeetingsAsParticipant), \"wrong number of meetings\")\n\t\t\t\tas.Equal(f.Meetings[0].UUID.String(), resp.User.MeetingsAsParticipant[0].ID, \"incorrect Meeting ID\")\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName: \"current user\",\n\t\t\tPayload: `{user {` + allUserFields + \"}}\",\n\t\t\tTestUser: f.Users[1],\n\t\t\tTest: func(t *testing.T) {\n\t\t\t\tas.Equal(f.Users[1].UUID.String(), resp.User.ID, \"incorrect ID\")\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName: \"not allowed\",\n\t\t\tPayload: `{user(id: \"` + f.Users[0].UUID.String() + `\"){` + allUserFields + \"}}\",\n\t\t\tTestUser: f.Users[1],\n\t\t\tTest: func(t *testing.T) {},\n\t\t\tExpectError: true,\n\t\t},\n\t}\n\n\tfor _, test := range testCases {\n\t\terr := as.testGqlQuery(test.Payload, test.TestUser.Nickname, &resp)\n\n\t\tif test.ExpectError {\n\t\t\tas.Error(err)\n\t\t} else {\n\t\t\tas.NoError(err)\n\t\t}\n\t\tt.Run(test.Name, test.Test)\n\t}\n}", "func (mr *MockRepositoryMockRecorder) Store(ctx, data interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Store\", reflect.TypeOf((*MockRepository)(nil).Store), ctx, data)\n}", "func (mr *MockUsecaseMockRecorder) Store(ctx, coffeesDomain interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Store\", reflect.TypeOf((*MockUsecase)(nil).Store), ctx, coffeesDomain)\n}", "func (mr *MockUserRepositoryMockRecorder) CreateUser(user interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"CreateUser\", reflect.TypeOf((*MockUserRepository)(nil).CreateUser), user)\n}", "func (u User) StoreLogin(r *http.Request, db *sql.DB) error {\n\t// language=PostgreSQL\n\treturn UpdateErr(tdb.Exec(r, db, `UPDATE users\n\tSET last_login = NOW(), app_version = $1, is_connected = true, firebase_token = $2\n\tWHERE credentials = $3 AND UUID = $4`, u.AppVersion, u.FirebaseToken, crypt.Hash(u.Credentials.Value), crypt.Hash(u.UUID)))\n}", "func (m *StorageMock) MinimockSaveUserDone() bool {\n\tfor _, e := range m.SaveUserMock.expectations {\n\t\tif mm_atomic.LoadUint64(&e.Counter) < 1 {\n\t\t\treturn false\n\t\t}\n\t}\n\n\t// if default expectation was set then invocations count should be greater than zero\n\tif m.SaveUserMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterSaveUserCounter) < 1 {\n\t\treturn false\n\t}\n\t// if func was set then invocations count should be greater than zero\n\tif m.funcSaveUser != nil && mm_atomic.LoadUint64(&m.afterSaveUserCounter) < 1 {\n\t\treturn false\n\t}\n\treturn true\n}", "func (cli *Store) User() *UserRepository {\n\t// TODO: add test store for testing\n\tif cli.userRepository != nil {\n\t\treturn cli.userRepository\n\t}\n\n\tcli.userRepository = &UserRepository{\n\t\tstore: cli,\n\t}\n\n\treturn cli.userRepository\n}", "func (mr *MockStorageMockRecorder) UpdateStore(ctx, store interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"UpdateStore\", reflect.TypeOf((*MockStorage)(nil).UpdateStore), ctx, store)\n}", "func (me TxsdImpactSimpleContentExtensionType) IsUser() bool { return me.String() == \"user\" }", "func (mr *MockInterfaceMockRecorder) AddUser(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"AddUser\", reflect.TypeOf((*MockInterface)(nil).AddUser), arg0)\n}", "func (m *MockRepository) Store(user *User) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Store\", user)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (mr *MockUserStoreMockRecorder) Alter(arg0, arg1, arg2 interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Alter\", reflect.TypeOf((*MockUserStore)(nil).Alter), arg0, arg1, arg2)\n}", "func TestCreateUser(t *testing.T) {\n user := User{\n Name: \"Mohammd Osama\",\n Password: \"helloworld\",\n Email: \"mohammeadosama@ieee.org\",\n }\n if user.ID == 0 {\n t.Errorf(\"Expected ID > 0, Received %d\", user.ID)\n }\n}", "func (userRepo *PostUserRepository) StoreUser(u entity.User) error {\n\n\t_, err := userRepo.conn.Exec(\"INSERT INTO users (firstname,lastname,email,password)\"+\n\t\t\" values($1, $2, $3, $4)\", u.FirstName, u.LastName, u.Email, u.Password)\n\n\tif err != nil {\n\t\t//panic(err)\n\t\treturn errors.New(\"Insertion has failed\")\n\t}\n\n\treturn nil\n}", "func TestTx_SaveUser(t *testing.T) {\n\tdb := NewTestDB()\n\tdefer db.Close()\n\n\tok(t, db.Update(func(tx *gist.Tx) error {\n\t\tok(t, tx.SaveUser(&gist.User{ID: 100, Username: \"john\", AccessToken: \"1234\"}))\n\t\treturn nil\n\t}))\n\n\tok(t, db.View(func(tx *gist.Tx) error {\n\t\tu, _ := tx.User(100)\n\t\tequals(t, &gist.User{ID: 100, Username: \"john\", AccessToken: \"1234\"}, u)\n\t\treturn nil\n\t}))\n}", "func GetUserOrUnexpected(c appengine.Context, w http.ResponseWriter,\n\tr *http.Request) (*user.User, bool) {\n\n\t// Get the current user.\n\tu := user.Current(c)\n\tif u == nil {\n\t\tLogAndUnexpected(c, w, r,\n\t\t\tfmt.Errorf(\"no user found, but auth is required.\"))\n\t\treturn nil, false\n\t}\n\n\treturn u, true\n\n}", "func (mr *MockStorageMockRecorder) GetStore(ctx, storeID interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetStore\", reflect.TypeOf((*MockStorage)(nil).GetStore), ctx, storeID)\n}", "func (mr *MockStorageMockRecorder) CreateStore(ctx, store interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"CreateStore\", reflect.TypeOf((*MockStorage)(nil).CreateStore), ctx, store)\n}", "func (mr *MockUserDBMockRecorder) AddUser(user interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"AddUser\", reflect.TypeOf((*MockUserDB)(nil).AddUser), user)\n}", "func (s *UserStore) GenericStore() *kallax.Store {\n\treturn s.Store\n}", "func (_m *UsersRepository) Store(users *entities.User) error {\n\tret := _m.Called(users)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(*entities.User) error); ok {\n\t\tr0 = rf(users)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (user *User) BeforeCreate(transaction *gorm.DB) error {\n return nil\n}" ]
[ "0.6904999", "0.6263283", "0.6232765", "0.608845", "0.6082111", "0.5844576", "0.5816186", "0.5799217", "0.5766557", "0.5741474", "0.5723449", "0.56327105", "0.5601462", "0.5558767", "0.55289537", "0.5518658", "0.55183864", "0.54979676", "0.5496519", "0.5475322", "0.5435955", "0.5397871", "0.5394055", "0.53912264", "0.53697747", "0.5324571", "0.5320105", "0.53121537", "0.5293352", "0.52831036", "0.52757627", "0.5271449", "0.5268307", "0.52661455", "0.52631015", "0.5249058", "0.5232955", "0.5227467", "0.5227217", "0.52240026", "0.5196453", "0.51931584", "0.51741844", "0.515857", "0.5154339", "0.5143459", "0.5142041", "0.51407", "0.51375777", "0.51311004", "0.51116145", "0.51093745", "0.5105206", "0.5103081", "0.5091967", "0.5083534", "0.5078837", "0.50665283", "0.5066393", "0.5066393", "0.506508", "0.5059571", "0.5059277", "0.50585765", "0.50530756", "0.5050275", "0.50480944", "0.50475043", "0.5047364", "0.50445133", "0.50431645", "0.5036772", "0.5032907", "0.5030728", "0.50284934", "0.5027189", "0.50223476", "0.501189", "0.50112367", "0.50096947", "0.500593", "0.5000221", "0.49988985", "0.4990093", "0.49876934", "0.49803114", "0.4979999", "0.49752635", "0.49719083", "0.4969741", "0.49646938", "0.49497765", "0.49415177", "0.4933322", "0.49320555", "0.49283147", "0.49280432", "0.4920434", "0.49151656", "0.49096164" ]
0.69241685
0
NewMockClient creates a new mock instance
func NewMockClient(ctrl *gomock.Controller) *MockClient { mock := &MockClient{ctrl: ctrl} mock.recorder = &MockClientMockRecorder{mock} return mock }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func NewMock() Client {\n\treturn &mockClient{}\n}", "func NewClient(t mockConstructorTestingTNewClient) *Client {\n\tmock := &Client{}\n\tmock.Mock.Test(t)\n\n\tt.Cleanup(func() { mock.AssertExpectations(t) })\n\n\treturn mock\n}", "func NewClient(t mockConstructorTestingTNewClient) *Client {\n\tmock := &Client{}\n\tmock.Mock.Test(t)\n\n\tt.Cleanup(func() { mock.AssertExpectations(t) })\n\n\treturn mock\n}", "func NewClient(t mockConstructorTestingTNewClient) *Client {\n\tmock := &Client{}\n\tmock.Mock.Test(t)\n\n\tt.Cleanup(func() { mock.AssertExpectations(t) })\n\n\treturn mock\n}", "func NewClient(t mockConstructorTestingTNewClient) *Client {\n\tmock := &Client{}\n\tmock.Mock.Test(t)\n\n\tt.Cleanup(func() { mock.AssertExpectations(t) })\n\n\treturn mock\n}", "func newMockClient(doer func(*http.Request) (*http.Response, error)) *http.Client {\n\treturn &http.Client{\n\t\tTransport: transportFunc(doer),\n\t}\n}", "func NewClientMock(t minimock.Tester) *ClientMock {\n\tm := &ClientMock{t: t}\n\tif controller, ok := t.(minimock.MockController); ok {\n\t\tcontroller.RegisterMocker(m)\n\t}\n\n\tm.ActivatePrototypeMock = mClientMockActivatePrototype{mock: m}\n\tm.ActivatePrototypeMock.callArgs = []*ClientMockActivatePrototypeParams{}\n\n\tm.DeployCodeMock = mClientMockDeployCode{mock: m}\n\tm.DeployCodeMock.callArgs = []*ClientMockDeployCodeParams{}\n\n\tm.GetAbandonedRequestMock = mClientMockGetAbandonedRequest{mock: m}\n\tm.GetAbandonedRequestMock.callArgs = []*ClientMockGetAbandonedRequestParams{}\n\n\tm.GetCodeMock = mClientMockGetCode{mock: m}\n\tm.GetCodeMock.callArgs = []*ClientMockGetCodeParams{}\n\n\tm.GetObjectMock = mClientMockGetObject{mock: m}\n\tm.GetObjectMock.callArgs = []*ClientMockGetObjectParams{}\n\n\tm.GetPendingsMock = mClientMockGetPendings{mock: m}\n\tm.GetPendingsMock.callArgs = []*ClientMockGetPendingsParams{}\n\n\tm.HasPendingsMock = mClientMockHasPendings{mock: m}\n\tm.HasPendingsMock.callArgs = []*ClientMockHasPendingsParams{}\n\n\tm.InjectCodeDescriptorMock = mClientMockInjectCodeDescriptor{mock: m}\n\tm.InjectCodeDescriptorMock.callArgs = []*ClientMockInjectCodeDescriptorParams{}\n\n\tm.InjectFinishMock = mClientMockInjectFinish{mock: m}\n\n\tm.InjectObjectDescriptorMock = mClientMockInjectObjectDescriptor{mock: m}\n\tm.InjectObjectDescriptorMock.callArgs = []*ClientMockInjectObjectDescriptorParams{}\n\n\tm.RegisterIncomingRequestMock = mClientMockRegisterIncomingRequest{mock: m}\n\tm.RegisterIncomingRequestMock.callArgs = []*ClientMockRegisterIncomingRequestParams{}\n\n\tm.RegisterOutgoingRequestMock = mClientMockRegisterOutgoingRequest{mock: m}\n\tm.RegisterOutgoingRequestMock.callArgs = []*ClientMockRegisterOutgoingRequestParams{}\n\n\tm.RegisterResultMock = mClientMockRegisterResult{mock: m}\n\tm.RegisterResultMock.callArgs = []*ClientMockRegisterResultParams{}\n\n\tm.StateMock = mClientMockState{mock: m}\n\n\treturn m\n}", "func NewMock(r ...MockResponse) *http.Client {\n\treturn &http.Client{\n\t\tTransport: newRoundTripper(r...),\n\t}\n}", "func NewMock(serverHost string) (*MockClient, error) {\n\treturn &MockClient{}, nil\n}", "func NewMock() MockClient {\n\treturn NewMockWithLogger(&noopLogger{})\n}", "func NewMockClient() MockClient {\n\tvar ret = MockClient{}\n\tret.Data = make(map[string][]http.Response)\n\treturn ret\n}", "func NewMock() *Mock {\n\tc := &Mock{\n\t\tFakeIncoming: func() chan []byte {\n\t\t\treturn make(chan []byte, 2)\n\t\t},\n\t\tFakeName: func() string {\n\t\t\treturn \"TestClient\"\n\t\t},\n\t\tFakeGame: func() string {\n\t\t\treturn \"test\"\n\t\t},\n\t\tFakeClose: func() {\n\t\t\t// Do nothing\n\t\t},\n\t\tFakeStopTimer: func() {\n\t\t\t// Do nothing\n\t\t},\n\t\tFakeRoom: func() interfaces.Room {\n\t\t\treturn nil\n\t\t},\n\t\tFakeSetRoom: func(interfaces.Room) {\n\n\t\t},\n\t}\n\n\tc.FakeWritePump = func() {\n\t\tfor range c.Incoming() {\n\t\t\t// Do nothing\n\t\t}\n\t}\n\n\tc.FakeSetName = func(string) interfaces.Client {\n\t\treturn c\n\t}\n\treturn c\n}", "func newMockClient(doer func(*http.Request) (*http.Response, error)) *http.Client {\n\tv := &http.Transport{\n\t\tProxy: http.ProxyFromEnvironment,\n\t\tDialContext: (&net.Dialer{\n\t\t\tTimeout: 30 * time.Second,\n\t\t\tKeepAlive: 30 * time.Second,\n\t\t\tDualStack: true,\n\t\t}).DialContext,\n\t\tMaxIdleConns: 100,\n\t\tIdleConnTimeout: 90 * time.Second,\n\t\tTLSHandshakeTimeout: 10 * time.Second,\n\t\tExpectContinueTimeout: 1 * time.Second,\n\t}\n\tv.RegisterProtocol(\"http\", transportFunc(doer))\n\treturn &http.Client{\n\t\tTransport: http.RoundTripper(v),\n\t}\n}", "func newFakeClient() client.Client {\n\treturn fakeclient.NewFakeClient()\n}", "func NewMock(opts ...ClientOpt) (*client, error) {\n\t// create new Docker runtime client\n\tc, err := New(opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// create Docker client from the mock client\n\t//\n\t// https://pkg.go.dev/github.com/go-vela/mock/docker#New\n\t_docker, err := mock.New()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// set the Docker client in the runtime client\n\tc.Docker = _docker\n\n\treturn c, nil\n}", "func NewClientMock(t minimock.Tester) *ClientMock {\n\tm := &ClientMock{t: t}\n\tif controller, ok := t.(minimock.MockController); ok {\n\t\tcontroller.RegisterMocker(m)\n\t}\n\n\tm.SendMock = mClientMockSend{mock: m}\n\tm.SendMock.callArgs = []*ClientMockSendParams{}\n\n\treturn m\n}", "func NewMockClient(opts ...MockClientOption) *MockClient {\n\tc := &MockClient{}\n\tfor _, o := range opts {\n\t\tc.ApplyOption(o)\n\t}\n\treturn c\n}", "func NewMockClient(obj ...runtime.Object) *kube.K8sClient {\n\tclient := &kube.K8sClient{\n\t\tClient: fake.NewSimpleClientset(obj...),\n\t}\n\n\treturn client\n}", "func NewMockClient() cortex_cache.Cache {\n\treturn &mockClient{\n\t\tclient: map[string][]byte{},\n\t}\n}", "func NewMock(t *testing.T) *MockT { return &MockT{t: t} }", "func NewMockClient() fab.FabricClient {\n\tchannels := make(map[string]fab.Channel)\n\tc := &MockClient{channels: channels, cryptoSuite: nil, stateStore: nil, userContext: nil, config: NewMockConfig()}\n\treturn c\n}", "func NewMockClient(response interface{}, err error) utils.EndpointRequester {\n\treturn &mockClient{\n\t\tresponse: response,\n\t\terr: err,\n\t}\n}", "func NewMockWithLogger(logger Logger) MockClient {\n\ttestCluster := generateTestCluster()\n\ttestHost := generateTestHost(testCluster)\n\ttestStorageDomain := generateTestStorageDomain()\n\tsecondaryStorageDomain := generateTestStorageDomain()\n\ttestDatacenter := generateTestDatacenter(testCluster)\n\ttestNetwork := generateTestNetwork(testDatacenter)\n\ttestVNICProfile := generateTestVNICProfile(testNetwork)\n\tblankTemplate := &template{\n\t\tnil,\n\t\tDefaultBlankTemplateID,\n\t\t\"Blank\",\n\t\t\"Blank template\",\n\t\tTemplateStatusOK,\n\t\t&vmCPU{\n\t\t\t&vmCPUTopo{\n\t\t\t\tcores: 1,\n\t\t\t\tthreads: 1,\n\t\t\t\tsockets: 1,\n\t\t\t},\n\t\t},\n\t}\n\n\tclient := getClient(\n\t\tlogger,\n\t\ttestStorageDomain,\n\t\tsecondaryStorageDomain,\n\t\ttestCluster,\n\t\ttestHost,\n\t\tblankTemplate,\n\t\ttestVNICProfile,\n\t\ttestNetwork,\n\t\ttestDatacenter,\n\t)\n\n\ttestCluster.client = client\n\ttestHost.client = client\n\tblankTemplate.client = client\n\ttestStorageDomain.client = client\n\tsecondaryStorageDomain.client = client\n\ttestDatacenter.client = client\n\ttestNetwork.client = client\n\ttestVNICProfile.client = client\n\n\treturn client\n}", "func NewClient() *client.Client {\n\tclnt := newMockClient(mockDoer)\n\tc, err := client.NewClient(\"tcp://127.0.0.1:2333\", mockAPIVersion, clnt, nil)\n\tif err != nil {\n\t\ttestlogF(err)\n\t\tpanic(err)\n\t}\n\treturn c\n}", "func NewClient() dns.Interface {\n\treturn &mockClient{\n\t\tzoneStore: map[string]dns.Zone{},\n\t\trecordSetStore: map[string]dns.RecordSet{},\n\t}\n}", "func New() *Mock {\n\treturn &Mock{\n\t\tm: mockMap{},\n\t\toldTransport: http.DefaultTransport,\n\t}\n}", "func NewMock(path string, nodes uint, replicas uint, vbuckets uint, specs ...BucketSpec) (m *Mock, err error) {\n\tvar lsn *net.TCPListener\n\tchAccept := make(chan bool)\n\tm = &Mock{}\n\n\tdefer func() {\n\t\tclose(chAccept)\n\t\tif lsn != nil {\n\t\t\tif err := lsn.Close(); err != nil {\n\t\t\t\tlog.Printf(\"Failed to close listener: %v\", err)\n\t\t\t}\n\t\t}\n\t\texc := recover()\n\n\t\tif exc == nil {\n\t\t\t// No errors, everything is OK\n\t\t\treturn\n\t\t}\n\n\t\t// Close mock on error, destroying resources\n\t\tm.Close()\n\t\tif mExc, ok := exc.(mockError); !ok {\n\t\t\tpanic(mExc)\n\t\t} else {\n\t\t\tm = nil\n\t\t\terr = mExc\n\t\t}\n\t}()\n\n\tif lsn, err = net.ListenTCP(\"tcp\", &net.TCPAddr{Port: 0}); err != nil {\n\t\tthrowMockError(\"Couldn't set up listening socket\", err)\n\t}\n\t_, ctlPort, err := net.SplitHostPort(lsn.Addr().String())\n\tif err != nil {\n\t\tlog.Fatalf(\"Failed to split host and port: %v\", err)\n\t}\n\tlog.Printf(\"Listening for control connection at %s\\n\", ctlPort)\n\n\tgo func() {\n\t\tvar err error\n\n\t\tdefer func() {\n\t\t\tchAccept <- false\n\t\t}()\n\t\tif m.conn, err = lsn.Accept(); err != nil {\n\t\t\tthrowMockError(\"Couldn't accept incoming control connection from mock\", err)\n\t\t\treturn\n\t\t}\n\t}()\n\n\tif len(specs) == 0 {\n\t\tspecs = []BucketSpec{{Name: \"default\", Type: BCouchbase}}\n\t}\n\n\toptions := []string{\n\t\t\"-jar\", path, \"--harakiri-monitor\", \"localhost:\" + ctlPort, \"--port\", \"0\",\n\t\t\"--replicas\", strconv.Itoa(int(replicas)),\n\t\t\"--vbuckets\", strconv.Itoa(int(vbuckets)),\n\t\t\"--nodes\", strconv.Itoa(int(nodes)),\n\t\t\"--buckets\", m.buildSpecStrings(specs),\n\t}\n\n\tlog.Printf(\"Invoking java %s\", strings.Join(options, \" \"))\n\tm.cmd = exec.Command(\"java\", options...)\n\n\tm.cmd.Stdout = os.Stdout\n\tm.cmd.Stderr = os.Stderr\n\n\tif err = m.cmd.Start(); err != nil {\n\t\tm.cmd = nil\n\t\tthrowMockError(\"Couldn't start command\", err)\n\t}\n\n\tselect {\n\tcase <-chAccept:\n\t\tbreak\n\n\tcase <-time.After(mockInitTimeout):\n\t\tthrowMockError(\"Timed out waiting for initialization\", errors.New(\"timeout\"))\n\t}\n\n\tm.rw = bufio.NewReadWriter(bufio.NewReader(m.conn), bufio.NewWriter(m.conn))\n\n\t// Read the port buffer, which is delimited by a NUL byte\n\tif portBytes, err := m.rw.ReadBytes(0); err != nil {\n\t\tthrowMockError(\"Couldn't get port information\", err)\n\t} else {\n\t\tportBytes = portBytes[:len(portBytes)-1]\n\t\tif entryPort, err := strconv.Atoi(string(portBytes)); err != nil {\n\t\t\tthrowMockError(\"Incorrectly formatted port from mock\", err)\n\t\t} else {\n\t\t\tm.EntryPort = uint16(entryPort)\n\t\t}\n\t}\n\n\tlog.Printf(\"Mock HTTP port at %d\\n\", m.EntryPort)\n\treturn\n}", "func NewMockApiClient() *MockApiClient {\n\treturn &MockApiClient{}\n}", "func NewDeviceClient(t mockConstructorTestingTNewDeviceClient) *DeviceClient {\n\tmock := &DeviceClient{}\n\tmock.Mock.Test(t)\n\n\tt.Cleanup(func() { mock.AssertExpectations(t) })\n\n\treturn mock\n}", "func NewMockClient(fn RoundTripFunc) *http.Client {\n\treturn &http.Client{\n\t\tTransport: RoundTripFunc(fn),\n\t}\n}", "func NewMock(now time.Time) *Mock {\n\treturn &Mock{\n\t\tnow: now,\n\t\tmockTimers: &timerHeap{},\n\t}\n}", "func NewMock() *Mock {\n\treturn &Mock{now: time.Unix(0, 0)}\n}", "func Mock(objects ...runtime.Object) KubernetesClientLambda {\n\tfakePool, fakeClient := NewFakes(objects...)\n\treturn &kubernetesClientLambdaImpl{\n\t\tclientPool: fakePool,\n\t\tinformerFactory: informers.NewSharedInformerFactory(fakeClient, 0),\n\t}\n}", "func InitMock() error {\n\tmwc := newMockClient(networksMock())\n\tc, err := client.NewClient(\"http://127.0.0.1:2375\", \"v1.21\", mwc, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdockerClient = c\n\n\treturn nil\n}", "func newTestClient(fn roundTripFunc) *http.Client {\n\treturn &http.Client{\n\t\tTransport: fn,\n\t}\n}", "func NewhttpClientMock(valid bool) *HTTPClientMock {\n\treturn &HTTPClientMock{\n\t\tapiKeyPublic: \"apiKeyPublic\",\n\t\tapiKeyPrivate: \"apiKeyPrivate\",\n\t\tclient: http.DefaultClient,\n\t\tvalidCreds: valid,\n\t\tfx: fixtures.New(),\n\t\tCallFunc: func() (int, int, error) {\n\t\t\tif valid == true {\n\t\t\t\treturn 1, 1, nil\n\t\t\t}\n\t\t\treturn 0, 0, errors.New(\"Unexpected error: Unexpected server response code: 401: EOF\")\n\t\t},\n\t\tSendMailV31Func: func(req *http.Request) (*http.Response, error) {\n\t\t\treturn nil, errors.New(\"mock send mail function not implemented yet\")\n\t\t},\n\t}\n}", "func newTestClient(fn RoundTripFunc) *http.Client {\n\treturn &http.Client{\n\t\tTransport: fn,\n\t}\n}", "func NewClient() *Client {\n\treturn &Client{\n\t\tisMocked: false,\n\t\tbaseURL: \"http://jsonplaceholder.typicode.com\",\n\t\tclient: &http.Client{},\n\t}\n}", "func newClient(token string) *Client {\n\treturn &Client{\n\t\tToken: token,\n\t}\n}", "func newClient(httpClient *http.Client) (c *Client) {\n\tc = &Client{httpClient: httpClient}\n\tc.service.client = c\n\tc.Auth = (*AuthService)(&c.service)\n\tc.Providers = (*ProvidersService)(&c.service)\n\tc.Projects = (*ProjectsService)(&c.service)\n\tc.Releases = (*ReleasesService)(&c.service)\n\tc.SlackChannels = (*SlackChannelsService)(&c.service)\n\tc.TelegramChats = (*TelegramChatsService)(&c.service)\n\tc.DiscordChannels = (*DiscordChannelsService)(&c.service)\n\tc.HangoutsChatWebhooks = (*HangoutsChatWebhooksService)(&c.service)\n\tc.MicrosoftTeamsWebhooks = (*MicrosoftTeamsWebhooksService)(&c.service)\n\tc.MattermostWebhooks = (*MattermostWebhooksService)(&c.service)\n\tc.RocketchatWebhooks = (*RocketchatWebhooksService)(&c.service)\n\tc.MatrixRooms = (*MatrixRoomsService)(&c.service)\n\tc.Webhooks = (*WebhooksService)(&c.service)\n\tc.Tags = (*TagsService)(&c.service)\n\treturn c\n}", "func newClient(uri string, hc *http.Client, opts jsonclient.Options, log *entitylist.LogInfo) (*LogClient, error) {\n\tlogClient, err := jsonclient.New(uri, hc, opts)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &LogClient{*logClient, *log}, err\n}", "func NewMockClient() *GCSClient {\n\treturn &GCSClient{}\n}", "func New() (*mock, error) {\n\treturn &mock{\n\t\tConfigService: ConfigService{},\n\t\tContainerService: ContainerService{},\n\t\tDistributionService: DistributionService{},\n\t\tImageService: ImageService{},\n\t\tNetworkService: NetworkService{},\n\t\tNodeService: NodeService{},\n\t\tPluginService: PluginService{},\n\t\tSecretService: SecretService{},\n\t\tServiceService: ServiceService{},\n\t\tSystemService: SystemService{},\n\t\tSwarmService: SwarmService{},\n\t\tVolumeService: VolumeService{},\n\t\tVersion: Version,\n\t}, nil\n}", "func FakeNew() (*Client, *FakeClientset) {\n\treturn FakeNewWithIngressSupports(false, true)\n}", "func NewMock() *Mock {\n\treturn &Mock{VolumesMock: &VolumesServiceMock{}}\n}", "func newTestGitHubClient() *Client {\n\tgclient := github.NewClient(nil)\n\tclient := Client{\n\t\tclient: gclient,\n\t}\n\treturn &client\n}", "func NewClient(ctrl *gomock.Controller) *Client {\n\tmock := &Client{ctrl: ctrl}\n\tmock.recorder = &ClientMockRecorder{mock}\n\treturn mock\n}", "func NewCommandClient(t mockConstructorTestingTNewCommandClient) *CommandClient {\n\tmock := &CommandClient{}\n\tmock.Mock.Test(t)\n\n\tt.Cleanup(func() { mock.AssertExpectations(t) })\n\n\treturn mock\n}", "func (f *FactoryFake) New(address string) (client.Interface, error) {\n\tc, _ := f.Clients[address]\n\treturn c, nil\n}", "func NewMock(response string) *Operator {\n\treturn &Operator{cli: client.NewMock(response)}\n}", "func NewMock() *Mock {\n\treturn &Mock{\n\t\tData: MockData{\n\t\t\tUptime: true,\n\t\t\tFile: true,\n\t\t\tTCPResponse: true,\n\t\t\tHTTPStatus: true,\n\t\t},\n\t}\n}", "func NewSecretClient(t mockConstructorTestingTNewSecretClient) *SecretClient {\n\tmock := &SecretClient{}\n\tmock.Mock.Test(t)\n\n\tt.Cleanup(func() { mock.AssertExpectations(t) })\n\n\treturn mock\n}", "func newClient() (client *Client) {\n\n\tclient = new(Client)\n\n\tid := <-uuidBuilder\n\tclient.Id = id.String()\n\tclient.subscriptions = make(map[string]bool)\n\n\tclients[client.Id] = client\n\n\tlog.WithField(\"clientID\", id.String()).Info(\"Created new Client\")\n\treturn\n}", "func NewMock(middleware []Middleware) OrganizationService {\n\tvar svc OrganizationService = NewBasicOrganizationServiceServiceMock()\n\tfor _, m := range middleware {\n\t\tsvc = m(svc)\n\t}\n\treturn svc\n}", "func (c *client) newClient() *gitea.Client {\n\treturn c.newClientToken(\"\")\n}", "func NewGitClient(t mockConstructorTestingTNewGitClient) *GitClient {\n\tmock := &GitClient{}\n\tmock.Mock.Test(t)\n\n\tt.Cleanup(func() { mock.AssertExpectations(t) })\n\n\treturn mock\n}", "func newMockNetworks() (*MockNetwork, *MockNetwork) {\n\tc := mockCon.NewConn()\n\treturn &MockNetwork{c.Client}, &MockNetwork{c.Server}\n}", "func newBaseClient() *baseClient {\n\treturn &baseClient{\n\t\thttpClient: http.DefaultClient,\n\t\tmethod: \"GET\",\n\t\theader: make(http.Header),\n\t}\n}", "func newClient(ctx context.Context, cfg v1.Github) *client {\n\tgithubToken := os.Getenv(cfg.AccessTokenEnvVar)\n\t// Setup the token for github authentication\n\tts := oauth2.StaticTokenSource(\n\t\t&oauth2.Token{AccessToken: githubToken},\n\t)\n\ttc := oauth2.NewClient(context.Background(), ts)\n\n\t// Return a client instance from github\n\tc := github.NewClient(tc)\n\treturn &client{\n\t\tctx: ctx,\n\t\tClient: c,\n\t\towner: cfg.Owner,\n\t\trepo: cfg.Repo,\n\t\tbotName: cfg.BotName,\n\t}\n}", "func NewMockclient(ctrl *gomock.Controller) *Mockclient {\n\tmock := &Mockclient{ctrl: ctrl}\n\tmock.recorder = &MockclientMockRecorder{mock}\n\treturn mock\n}", "func NewMockclient(ctrl *gomock.Controller) *Mockclient {\n\tmock := &Mockclient{ctrl: ctrl}\n\tmock.recorder = &MockclientMockRecorder{mock}\n\treturn mock\n}", "func CreateMockHTTPClient(res ...http.Response) MockHTTPClient {\n\treturn MockHTTPClient{\n\t\tresponses: &res,\n\t}\n}", "func NewMock() Cache {\n\treturn &mock{}\n}", "func MockClientWithInfo(info *chain.Info) Client {\n\treturn &MockInfoClient{info}\n}", "func GetBuildMockClient() MockClient {\n\tmc := NewMockClient()\n\n\tmc.AddData(buildHead)\n\tmc.AddData(buildPost)\n\tmc.AddData(buildGet1)\n\tmc.AddData(buildGet2)\n\tmc.AddData(buildGetTasks)\n\tmc.AddData(buildGetTask0Logs)\n\tmc.AddData(buildGetTask1Logs)\n\tmc.AddData(buildGetTask2Logs)\n\tmc.AddData(buildGetTask3Logs)\n\tmc.AddData(buildGetTask4Logs)\n\tmc.AddData(buildGetTask5Logs)\n\tmc.AddData(buildGetTask6Logs)\n\tmc.AddData(buildGetTask7Logs)\n\tmc.AddData(buildGetTask8Logs)\n\tmc.AddData(buildGetTask9Logs)\n\tmc.AddData(buildGetTask10Logs)\n\tmc.AddData(buildGetTask11Logs)\n\tmc.AddData(buildGetTask12Logs)\n\tmc.AddData(buildGetTask0Result)\n\tmc.AddData(buildGetTask1Result)\n\tmc.AddData(buildGetTask2Result)\n\tmc.AddData(buildGetTask3Result)\n\tmc.AddData(buildGetTask4Result)\n\tmc.AddData(buildGetTask5Result)\n\tmc.AddData(buildGetTask6Result)\n\tmc.AddData(buildGetTask7Result)\n\tmc.AddData(buildGetTask8Result)\n\tmc.AddData(buildGetTask9Result)\n\tmc.AddData(buildGetTask10Result)\n\tmc.AddData(buildGetTask11Result)\n\tmc.AddData(buildGetTask12Result)\n\tmc.AddData(buildGetTask11ResultMedia)\n\tmc.AddData(buildGetValues)\n\n\treturn mc\n}", "func newClient(opts *ClientOpts) (*Client, error) {\n\tbaseClient, err := newAPIClient(opts)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tclient := &Client{\n\t\tAPIClient: *baseClient,\n\t}\n\n\t// init base operator\n\tclient.Node = newNodeClient(client)\n\tclient.Namespace = newNameSpaceClient(client)\n\tclient.ConfigMap = newConfigMapClient(client)\n\tclient.Service = newServiceClient(client)\n\tclient.Pod = newPodClient(client)\n\tclient.ReplicationController = newReplicationControllerClient(client)\n\tclient.StatefulSet = newStatefulSetClient(client)\n\tclient.DaemonSet = newDaemonSetClient(client)\n\tclient.Deployment = newDeploymentClient(client)\n\tclient.ReplicaSet = newReplicaSetClient(client)\n\n\treturn client, nil\n}", "func newClient(auth azure.Authorizer) *azureClient {\n\treturn &azureClient{\n\t\tscalesetvms: newVirtualMachineScaleSetVMsClient(auth.SubscriptionID(), auth.BaseURI(), auth.Authorizer()),\n\t}\n}", "func newClient(cs ConnectionSettings) *client {\n\treturn &client{\n\t\tConnectionSettings: cs,\n\t}\n}", "func (r *Request) newClient() *http.Client {\n\treturn &http.Client{Timeout: r.timeout}\n}", "func TestNewClient_CustomHttpClient(t *testing.T) {\n\tt.Parallel()\n\n\tclient := NewClient(nil, http.DefaultClient, ProviderPreev)\n\n\tif client == nil {\n\t\tt.Fatal(\"failed to load client\")\n\t}\n\n\t// Test providers\n\tif client.Providers[0] != ProviderPreev {\n\t\tt.Fatalf(\"expected the first provider to be %d, not %d\", ProviderPreev, client.Providers[0])\n\t}\n}", "func NewFake() (*FakeClient, error) {\n\treturn &FakeClient{}, nil\n}", "func newClient(auth azure.Authorizer) *azureClient {\n\tc := newPrivateZonesClient(auth.SubscriptionID(), auth.BaseURI(), auth.Authorizer())\n\tv := newVirtualNetworkLinksClient(auth.SubscriptionID(), auth.BaseURI(), auth.Authorizer())\n\tr := newRecordSetsClient(auth.SubscriptionID(), auth.BaseURI(), auth.Authorizer())\n\treturn &azureClient{c, v, r}\n}", "func New(client client.Client, namespace string) *fakeManager {\n\treturn &fakeManager{\n\t\tclient: client,\n\t\tnamespace: namespace,\n\t}\n}", "func CreateMockHTTPClient(b []byte, statusCode int) *mock.HTTPClient {\n\tr := ioutil.NopCloser(bytes.NewReader([]byte(b)))\n\tmockHTTPClient := &mock.HTTPClient{}\n\tmockHTTPClient.DoFn = func(*http.Request) (*http.Response, error) {\n\t\treturn &http.Response{\n\t\t\tStatusCode: statusCode,\n\t\t\tBody: r,\n\t\t}, nil\n\t}\n\treturn mockHTTPClient\n}", "func NewMocktimeClient(ctrl *gomock.Controller) *MocktimeClient {\n\tmock := &MocktimeClient{ctrl: ctrl}\n\tmock.recorder = &MocktimeClientMockRecorder{mock}\n\treturn mock\n}", "func newMockTransport() *mockTransport {\n\treturn &mockTransport{\n\t\turlToResponseAndError: make(map[string]mockTransportResponse),\n\t\trequestURLsReceived: make([]string, 0),\n\t}\n}", "func NewClient() *Client {\n baseURL, _ := url.Parse(defaultBaseURL)\n return &Client{client: http.DefaultClient, BaseURL: baseURL, UserAgent: userAgent}\n}", "func MockGithubClient(responses []MockResponse) ClientWrapper {\n\treturn Client(NewTestClient(&MockRoundTripper{\n\t\tResponses: responses,\n\t}))\n}", "func NewK8sClient(t interface {\n\tmock.TestingT\n\tCleanup(func())\n}) *K8sClient {\n\tmock := &K8sClient{}\n\tmock.Mock.Test(t)\n\n\tt.Cleanup(func() { mock.AssertExpectations(t) })\n\n\treturn mock\n}", "func NewMDNSClientMock(t minimock.Tester) *MDNSClientMock {\n\tm := &MDNSClientMock{t: t}\n\tif controller, ok := t.(minimock.MockController); ok {\n\t\tcontroller.RegisterMocker(m)\n\t}\n\n\tm.ExchangeMock = mMDNSClientMockExchange{mock: m}\n\tm.ExchangeMock.callArgs = []*MDNSClientMockExchangeParams{}\n\n\treturn m\n}", "func MockGithubClient(statusCode int, response string) ClientWrapper {\n\treturn Client(NewTestClient(MockRoundTripper{\n\t\tStatusCode: statusCode,\n\t\tResponse: response,\n\t}))\n}", "func (vm *dockerVM) newClient() (*docker.Client, error) {\n\treturn newDockerClient()\n}" ]
[ "0.800531", "0.7601814", "0.7601814", "0.7601814", "0.7601814", "0.7583215", "0.7519331", "0.75100696", "0.74596745", "0.7398741", "0.7360916", "0.7294024", "0.7287095", "0.72698385", "0.7268576", "0.7115619", "0.7090812", "0.70029604", "0.68992126", "0.68161285", "0.6793337", "0.6790174", "0.67800784", "0.6730925", "0.66958666", "0.66781497", "0.6667481", "0.6627789", "0.6626141", "0.6618133", "0.6600781", "0.65967476", "0.6561778", "0.655353", "0.65247613", "0.6515564", "0.6513742", "0.6496845", "0.64909804", "0.6476813", "0.64664024", "0.64410627", "0.64337665", "0.6410721", "0.64102733", "0.6398632", "0.6382994", "0.6372751", "0.63624185", "0.6361347", "0.63427", "0.63307065", "0.63269985", "0.63253087", "0.63135517", "0.63130647", "0.6268285", "0.62681866", "0.6253745", "0.62424856", "0.62424856", "0.62416977", "0.62324804", "0.62270224", "0.6216402", "0.6211384", "0.6195334", "0.61831367", "0.61661315", "0.6163307", "0.61556655", "0.613744", "0.6124755", "0.609219", "0.60875666", "0.60818326", "0.6077205", "0.60703564", "0.605265", "0.6051522", "0.6043404", "0.6035903" ]
0.60894334
84
EXPECT returns an object that allows the caller to indicate expected use
func (m *MockClient) EXPECT() *MockClientMockRecorder { return m.recorder }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (mmGetObject *mClientMockGetObject) Expect(ctx context.Context, head insolar.Reference) *mClientMockGetObject {\n\tif mmGetObject.mock.funcGetObject != nil {\n\t\tmmGetObject.mock.t.Fatalf(\"ClientMock.GetObject mock is already set by Set\")\n\t}\n\n\tif mmGetObject.defaultExpectation == nil {\n\t\tmmGetObject.defaultExpectation = &ClientMockGetObjectExpectation{}\n\t}\n\n\tmmGetObject.defaultExpectation.params = &ClientMockGetObjectParams{ctx, head}\n\tfor _, e := range mmGetObject.expectations {\n\t\tif minimock.Equal(e.params, mmGetObject.defaultExpectation.params) {\n\t\t\tmmGetObject.mock.t.Fatalf(\"Expectation set by When has same params: %#v\", *mmGetObject.defaultExpectation.params)\n\t\t}\n\t}\n\n\treturn mmGetObject\n}", "func (r Requester) Assert(actual, expected interface{}) Requester {\n\t//r.actualResponse = actual\n\t//r.expectedResponse = expected\n\treturn r\n}", "func (r *Request) Expect(t *testing.T) *Response {\n\tr.apiTest.t = t\n\treturn r.apiTest.response\n}", "func (m *MockNotary) Notarize(arg0 string) (map[string]interface{}, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Notarize\", arg0)\n\tret0, _ := ret[0].(map[string]interface{})\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (tc TestCases) expect() {\n\tfmt.Println(cnt)\n\tcnt++\n\tif !reflect.DeepEqual(tc.resp, tc.respExp) {\n\t\ttc.t.Error(fmt.Sprintf(\"\\nRequested: \", tc.req, \"\\nExpected: \", tc.respExp, \"\\nFound: \", tc.resp))\n\t}\n}", "func (r *Request) Expect(t TestingT) *Response {\n\tr.apiTest.t = t\n\treturn r.apiTest.response\n}", "func Expect(t cbtest.T, actual interface{}, matcher matcher.Matcher, labelAndArgs ...interface{}) {\n\tt.Helper()\n\tres := ExpectE(t, actual, matcher, labelAndArgs...)\n\tif !res {\n\t\tt.FailNow()\n\t}\n}", "func (m *MockisObject_Obj) EXPECT() *MockisObject_ObjMockRecorder {\n\treturn m.recorder\n}", "func Expect(t *testing.T, v, m interface{}) {\n\tvt, vok := v.(Equaler)\n\tmt, mok := m.(Equaler)\n\n\tvar state bool\n\tif vok && mok {\n\t\tstate = vt.Equal(mt)\n\t} else {\n\t\tstate = reflect.DeepEqual(v, m)\n\t}\n\n\tif state {\n\t\tflux.FatalFailed(t, \"Value %+v and %+v are not a match\", v, m)\n\t\treturn\n\t}\n\tflux.LogPassed(t, \"Value %+v and %+v are a match\", v, m)\n}", "func (mmState *mClientMockState) Expect() *mClientMockState {\n\tif mmState.mock.funcState != nil {\n\t\tmmState.mock.t.Fatalf(\"ClientMock.State mock is already set by Set\")\n\t}\n\n\tif mmState.defaultExpectation == nil {\n\t\tmmState.defaultExpectation = &ClientMockStateExpectation{}\n\t}\n\n\treturn mmState\n}", "func (mmProvide *mContainerMockProvide) Expect(constructor interface{}) *mContainerMockProvide {\n\tif mmProvide.mock.funcProvide != nil {\n\t\tmmProvide.mock.t.Fatalf(\"ContainerMock.Provide mock is already set by Set\")\n\t}\n\n\tif mmProvide.defaultExpectation == nil {\n\t\tmmProvide.defaultExpectation = &ContainerMockProvideExpectation{}\n\t}\n\n\tmmProvide.defaultExpectation.params = &ContainerMockProvideParams{constructor}\n\tfor _, e := range mmProvide.expectations {\n\t\tif minimock.Equal(e.params, mmProvide.defaultExpectation.params) {\n\t\t\tmmProvide.mock.t.Fatalf(\"Expectation set by When has same params: %#v\", *mmProvide.defaultExpectation.params)\n\t\t}\n\t}\n\n\treturn mmProvide\n}", "func Mock() Env {\n\treturn mock.New()\n}", "func (mmGetCode *mClientMockGetCode) Expect(ctx context.Context, ref insolar.Reference) *mClientMockGetCode {\n\tif mmGetCode.mock.funcGetCode != nil {\n\t\tmmGetCode.mock.t.Fatalf(\"ClientMock.GetCode mock is already set by Set\")\n\t}\n\n\tif mmGetCode.defaultExpectation == nil {\n\t\tmmGetCode.defaultExpectation = &ClientMockGetCodeExpectation{}\n\t}\n\n\tmmGetCode.defaultExpectation.params = &ClientMockGetCodeParams{ctx, ref}\n\tfor _, e := range mmGetCode.expectations {\n\t\tif minimock.Equal(e.params, mmGetCode.defaultExpectation.params) {\n\t\t\tmmGetCode.mock.t.Fatalf(\"Expectation set by When has same params: %#v\", *mmGetCode.defaultExpectation.params)\n\t\t}\n\t}\n\n\treturn mmGetCode\n}", "func (_m *MockOStream) EXPECT() *MockOStreamMockRecorder {\n\treturn _m.recorder\n}", "func expect(t *testing.T, method, url string, testieOptions ...func(*http.Request)) *testie {\n\treq, err := http.NewRequest(method, url, nil)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tfor _, opt := range testieOptions {\n\t\topt(req)\n\t}\n\n\treturn testReq(t, req)\n}", "func (mmGetUser *mStorageMockGetUser) Expect(ctx context.Context, userID int64) *mStorageMockGetUser {\n\tif mmGetUser.mock.funcGetUser != nil {\n\t\tmmGetUser.mock.t.Fatalf(\"StorageMock.GetUser mock is already set by Set\")\n\t}\n\n\tif mmGetUser.defaultExpectation == nil {\n\t\tmmGetUser.defaultExpectation = &StorageMockGetUserExpectation{}\n\t}\n\n\tmmGetUser.defaultExpectation.params = &StorageMockGetUserParams{ctx, userID}\n\tfor _, e := range mmGetUser.expectations {\n\t\tif minimock.Equal(e.params, mmGetUser.defaultExpectation.params) {\n\t\t\tmmGetUser.mock.t.Fatalf(\"Expectation set by When has same params: %#v\", *mmGetUser.defaultExpectation.params)\n\t\t}\n\t}\n\n\treturn mmGetUser\n}", "func (mmGetObject *mClientMockGetObject) Return(o1 ObjectDescriptor, err error) *ClientMock {\n\tif mmGetObject.mock.funcGetObject != nil {\n\t\tmmGetObject.mock.t.Fatalf(\"ClientMock.GetObject mock is already set by Set\")\n\t}\n\n\tif mmGetObject.defaultExpectation == nil {\n\t\tmmGetObject.defaultExpectation = &ClientMockGetObjectExpectation{mock: mmGetObject.mock}\n\t}\n\tmmGetObject.defaultExpectation.results = &ClientMockGetObjectResults{o1, err}\n\treturn mmGetObject.mock\n}", "func (mmGather *mGathererMockGather) Expect() *mGathererMockGather {\n\tif mmGather.mock.funcGather != nil {\n\t\tmmGather.mock.t.Fatalf(\"GathererMock.Gather mock is already set by Set\")\n\t}\n\n\tif mmGather.defaultExpectation == nil {\n\t\tmmGather.defaultExpectation = &GathererMockGatherExpectation{}\n\t}\n\n\treturn mmGather\n}", "func (m *MockParser) EXPECT() *MockParserMockRecorder {\n\treturn m.recorder\n}", "func (m *MockParser) EXPECT() *MockParserMockRecorder {\n\treturn m.recorder\n}", "func (mmWriteTo *mDigestHolderMockWriteTo) Expect(w io.Writer) *mDigestHolderMockWriteTo {\n\tif mmWriteTo.mock.funcWriteTo != nil {\n\t\tmmWriteTo.mock.t.Fatalf(\"DigestHolderMock.WriteTo mock is already set by Set\")\n\t}\n\n\tif mmWriteTo.defaultExpectation == nil {\n\t\tmmWriteTo.defaultExpectation = &DigestHolderMockWriteToExpectation{}\n\t}\n\n\tmmWriteTo.defaultExpectation.params = &DigestHolderMockWriteToParams{w}\n\tfor _, e := range mmWriteTo.expectations {\n\t\tif minimock.Equal(e.params, mmWriteTo.defaultExpectation.params) {\n\t\t\tmmWriteTo.mock.t.Fatalf(\"Expectation set by When has same params: %#v\", *mmWriteTo.defaultExpectation.params)\n\t\t}\n\t}\n\n\treturn mmWriteTo\n}", "func (rb *RequestBuilder) EXPECT() *ResponseAsserter {\n\treq := httptest.NewRequest(rb.method, rb.path, rb.body)\n\tfor k, v := range rb.hdr {\n\t\treq.Header[k] = v\n\t}\n\n\trec := httptest.NewRecorder()\n\trb.cas.h.ServeHTTP(rec, req)\n\n\treturn &ResponseAsserter{\n\t\trec: rec,\n\t\treq: req,\n\t\tb: rb,\n\t\tfail: rb.fail.\n\t\t\tCopy().\n\t\t\tWithRequest(req).\n\t\t\tWithResponse(rec),\n\t}\n}", "func (mmGetState *mGatewayMockGetState) Expect() *mGatewayMockGetState {\n\tif mmGetState.mock.funcGetState != nil {\n\t\tmmGetState.mock.t.Fatalf(\"GatewayMock.GetState mock is already set by Set\")\n\t}\n\n\tif mmGetState.defaultExpectation == nil {\n\t\tmmGetState.defaultExpectation = &GatewayMockGetStateExpectation{}\n\t}\n\n\treturn mmGetState\n}", "func (m *mParcelMockGetSign) Expect() *mParcelMockGetSign {\n\tm.mock.GetSignFunc = nil\n\tm.expectationSeries = nil\n\n\tif m.mainExpectation == nil {\n\t\tm.mainExpectation = &ParcelMockGetSignExpectation{}\n\t}\n\n\treturn m\n}", "func (mmCreateTag *mTagCreatorMockCreateTag) Expect(t1 semantic.Tag) *mTagCreatorMockCreateTag {\n\tif mmCreateTag.mock.funcCreateTag != nil {\n\t\tmmCreateTag.mock.t.Fatalf(\"TagCreatorMock.CreateTag mock is already set by Set\")\n\t}\n\n\tif mmCreateTag.defaultExpectation == nil {\n\t\tmmCreateTag.defaultExpectation = &TagCreatorMockCreateTagExpectation{}\n\t}\n\n\tmmCreateTag.defaultExpectation.params = &TagCreatorMockCreateTagParams{t1}\n\tfor _, e := range mmCreateTag.expectations {\n\t\tif minimock.Equal(e.params, mmCreateTag.defaultExpectation.params) {\n\t\t\tmmCreateTag.mock.t.Fatalf(\"Expectation set by When has same params: %#v\", *mmCreateTag.defaultExpectation.params)\n\t\t}\n\t}\n\n\treturn mmCreateTag\n}", "func (m *MockActorUsecase) EXPECT() *MockActorUsecaseMockRecorder {\n\treturn m.recorder\n}", "func (m *mParcelMockGetCaller) Expect() *mParcelMockGetCaller {\n\tm.mock.GetCallerFunc = nil\n\tm.expectationSeries = nil\n\n\tif m.mainExpectation == nil {\n\t\tm.mainExpectation = &ParcelMockGetCallerExpectation{}\n\t}\n\n\treturn m\n}", "func mockAlwaysRun() bool { return true }", "func (m *MockArg) EXPECT() *MockArgMockRecorder {\n\treturn m.recorder\n}", "func (m *MockUsecase) EXPECT() *MockUsecaseMockRecorder {\n\treturn m.recorder\n}", "func (m *MockUsecase) EXPECT() *MockUsecaseMockRecorder {\n\treturn m.recorder\n}", "func (m *MockUsecase) EXPECT() *MockUsecaseMockRecorder {\n\treturn m.recorder\n}", "func (m *MockUsecase) EXPECT() *MockUsecaseMockRecorder {\n\treturn m.recorder\n}", "func (m *MockUsecase) EXPECT() *MockUsecaseMockRecorder {\n\treturn m.recorder\n}", "func (m *MockUsecase) EXPECT() *MockUsecaseMockRecorder {\n\treturn m.recorder\n}", "func (m *MockUsecase) EXPECT() *MockUsecaseMockRecorder {\n\treturn m.recorder\n}", "func (m *MockUsecase) EXPECT() *MockUsecaseMockRecorder {\n\treturn m.recorder\n}", "func (st *SDKTester) Test(resp interface{}) {\n\tif resp == nil || st.respWant == nil {\n\t\tst.t.Logf(\"response want/got is nil, abort\\n\")\n\t\treturn\n\t}\n\n\trespMap := st.getFieldMap(resp)\n\tfor i, v := range st.respWant {\n\t\tif reflect.DeepEqual(v, respMap[i]) {\n\t\t\tcontinue\n\t\t}\n\t\tswitch x := respMap[i].(type) {\n\t\tcase Stringer:\n\t\t\tif !assert.Equal(st.t, v, x.String()) {\n\t\t\t\tst.t.Errorf(\"%s want %v, got %v\", i, v, respMap[i])\n\t\t\t}\n\t\tcase map[string]interface{}:\n\t\t\tif value, ok := x[\"Value\"]; ok {\n\t\t\t\tif !assert.Equal(st.t, v, value) {\n\t\t\t\t\tst.t.Errorf(\"%s want %v, got %v\", i, v, respMap[i])\n\t\t\t\t}\n\t\t\t}\n\t\tcase Inter:\n\t\t\tif !assert.Equal(st.t, v, x.Int()) {\n\t\t\t\tst.t.Errorf(\"%s want %v, got %v\", i, v, respMap[i])\n\t\t\t}\n\t\tdefault:\n\t\t\tif !assert.Equal(st.t, v, respMap[i]) {\n\t\t\t\tst.t.Errorf(\"%s want %v, got %v\", i, v, respMap[i])\n\t\t\t}\n\t\t}\n\t}\n}", "func (m *MockCreator) EXPECT() *MockCreatorMockRecorder {\n\treturn m.recorder\n}", "func (m *MockCreator) EXPECT() *MockCreatorMockRecorder {\n\treturn m.recorder\n}", "func TestCallFunc_arguments(t *testing.T) {\n\n}", "func (m *mParcelMockGetSender) Expect() *mParcelMockGetSender {\n\tm.mock.GetSenderFunc = nil\n\tm.expectationSeries = nil\n\n\tif m.mainExpectation == nil {\n\t\tm.mainExpectation = &ParcelMockGetSenderExpectation{}\n\t}\n\n\treturn m\n}", "func TestGetNone4A(t *testing.T) {\n}", "func expectEqual(value, expected interface{}) {\n\tif value != expected {\n\t\tfmt.Printf(\"Fehler: %v bekommen, erwartet war aber %v.\\n\", value, expected)\n\t} else {\n\t\tfmt.Printf(\"OK: %v bekommen, erwartet war aber %v.\\n\", value, expected)\n\t}\n}", "func (mmGetPacketSignature *mPacketParserMockGetPacketSignature) Expect() *mPacketParserMockGetPacketSignature {\n\tif mmGetPacketSignature.mock.funcGetPacketSignature != nil {\n\t\tmmGetPacketSignature.mock.t.Fatalf(\"PacketParserMock.GetPacketSignature mock is already set by Set\")\n\t}\n\n\tif mmGetPacketSignature.defaultExpectation == nil {\n\t\tmmGetPacketSignature.defaultExpectation = &PacketParserMockGetPacketSignatureExpectation{}\n\t}\n\n\treturn mmGetPacketSignature\n}", "func (mmHasPendings *mClientMockHasPendings) Expect(ctx context.Context, object insolar.Reference) *mClientMockHasPendings {\n\tif mmHasPendings.mock.funcHasPendings != nil {\n\t\tmmHasPendings.mock.t.Fatalf(\"ClientMock.HasPendings mock is already set by Set\")\n\t}\n\n\tif mmHasPendings.defaultExpectation == nil {\n\t\tmmHasPendings.defaultExpectation = &ClientMockHasPendingsExpectation{}\n\t}\n\n\tmmHasPendings.defaultExpectation.params = &ClientMockHasPendingsParams{ctx, object}\n\tfor _, e := range mmHasPendings.expectations {\n\t\tif minimock.Equal(e.params, mmHasPendings.defaultExpectation.params) {\n\t\t\tmmHasPendings.mock.t.Fatalf(\"Expectation set by When has same params: %#v\", *mmHasPendings.defaultExpectation.params)\n\t\t}\n\t}\n\n\treturn mmHasPendings\n}", "func Run(t testing.TB, cloud cloud.Client, src string, opts ...RunOption) {\n\n\tif cloud == nil {\n\t\tcloud = mockcloud.Client(nil)\n\t}\n\n\tvm := otto.New()\n\n\tpkg, err := godotto.Apply(context.Background(), vm, cloud)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tvm.Set(\"cloud\", pkg)\n\tvm.Set(\"equals\", func(call otto.FunctionCall) otto.Value {\n\t\tvm := call.Otto\n\t\tgot, err := call.Argument(0).Export()\n\t\tif err != nil {\n\t\t\tottoutil.Throw(vm, err.Error())\n\t\t}\n\t\twant, err := call.Argument(1).Export()\n\t\tif err != nil {\n\t\t\tottoutil.Throw(vm, err.Error())\n\t\t}\n\t\tok, cause := deepEqual(got, want)\n\t\tif ok {\n\t\t\treturn otto.UndefinedValue()\n\t\t}\n\t\tmsg := \"assertion failed!\\n\" + cause\n\n\t\tif len(call.ArgumentList) > 2 {\n\t\t\tformat, err := call.ArgumentList[2].ToString()\n\t\t\tif err != nil {\n\t\t\t\tottoutil.Throw(vm, err.Error())\n\t\t\t}\n\t\t\tmsg += \"\\n\" + format\n\t\t}\n\t\tottoutil.Throw(vm, msg)\n\t\treturn otto.UndefinedValue()\n\t})\n\tvm.Set(\"assert\", func(call otto.FunctionCall) otto.Value {\n\t\tvm := call.Otto\n\t\tv, err := call.Argument(0).ToBoolean()\n\t\tif err != nil {\n\t\t\tottoutil.Throw(vm, err.Error())\n\t\t}\n\t\tif v {\n\t\t\treturn otto.UndefinedValue()\n\t\t}\n\t\tmsg := \"assertion failed!\"\n\t\tif len(call.ArgumentList) > 1 {\n\t\t\tformat, err := call.ArgumentList[1].ToString()\n\t\t\tif err != nil {\n\t\t\t\tottoutil.Throw(vm, err.Error())\n\t\t\t}\n\t\t\tmsg += \"\\n\" + format\n\t\t}\n\t\tottoutil.Throw(vm, msg)\n\t\treturn otto.UndefinedValue()\n\t})\n\tscript, err := vm.Compile(\"\", src)\n\tif err != nil {\n\t\tt.Fatalf(\"invalid code: %v\", err)\n\t}\n\n\tfor _, opt := range opts {\n\t\tif err := opt(vm); err != nil {\n\t\t\tt.Fatalf(\"can't apply option: %v\", err)\n\t\t}\n\t}\n\n\tif _, err := vm.Run(script); err != nil {\n\t\tif oe, ok := err.(*otto.Error); ok {\n\t\t\tt.Fatal(oe.String())\n\t\t} else {\n\t\t\tt.Fatal(err)\n\t\t}\n\t}\n}", "func TestSetGoodArgs(t *testing.T) {\n\tfmt.Println(\"Entering the test method for SetGoodArgs\")\n\tprovcc := new(SimpleAsset)\n\tstub := shim.NewMockStub(\"ANY_PARAM\", provcc)\n\n\t// Testing the init. It always return true. No parameters in init. \n\t\n\tcheckInit(t, stub, [][]byte{[]byte(\"init\")})\n\n\tres := stub.MockInvoke(\"1\", [][]byte{[]byte(\"set\"), []byte(\"S52fkpF2rCEArSuwqyDA9tVjawUdrkGzbNQLaa7xJfA=\"),\n\t[]byte(\"agentInfo.atype\"),[]byte(\"1.2.3.4\"),\n\t[]byte(\"agentInfo.id\"),[]byte(\"agentidentifier\"),\n\t[]byte(\"agentinfo.name\"),[]byte(\"7.8.9\"),\n\t[]byte(\"agentinfo.idp\"),[]byte(\"urn:tiani-spirit:sts\"),\n\t[]byte(\"locationInfo.id\"),[]byte(\"urn:oid:1.2.3\"),\n\t[]byte(\"locationInfo.name\"),[]byte(\"General Hospital\"),\n\t[]byte(\"locationInfo.locality\"),[]byte(\"Nashville, TN\"),\n\t[]byte(\"locationInfo.docid\"),[]byte(\"1.2.3\"),\n\t[]byte(\"action\"),[]byte(\"ex:CREATE\"),\n\t[]byte(\"date\"),[]byte(\"2018-11-10T12:15:55.028Z\")})\n\n\tif res.Status != shim.OK {\n\t\tfmt.Println(\"Invoke failed\", string(res.Message))\n\t\tt.FailNow()\n\t}\n\t\n}", "func (mmRegisterResult *mClientMockRegisterResult) Expect(ctx context.Context, request insolar.Reference, result RequestResult) *mClientMockRegisterResult {\n\tif mmRegisterResult.mock.funcRegisterResult != nil {\n\t\tmmRegisterResult.mock.t.Fatalf(\"ClientMock.RegisterResult mock is already set by Set\")\n\t}\n\n\tif mmRegisterResult.defaultExpectation == nil {\n\t\tmmRegisterResult.defaultExpectation = &ClientMockRegisterResultExpectation{}\n\t}\n\n\tmmRegisterResult.defaultExpectation.params = &ClientMockRegisterResultParams{ctx, request, result}\n\tfor _, e := range mmRegisterResult.expectations {\n\t\tif minimock.Equal(e.params, mmRegisterResult.defaultExpectation.params) {\n\t\t\tmmRegisterResult.mock.t.Fatalf(\"Expectation set by When has same params: %#v\", *mmRegisterResult.defaultExpectation.params)\n\t\t}\n\t}\n\n\treturn mmRegisterResult\n}", "func (m *MockS3API) EXPECT() *MockS3APIMockRecorder {\n\treturn m.recorder\n}", "func Mock() Cluster { return mockCluster{} }", "func mockedGranter(kubeutil *kube.Kube, app *v1.RadixRegistration, namespace string, serviceAccount *corev1.ServiceAccount) error {\n\treturn nil\n}", "func (mmGetPendings *mClientMockGetPendings) Expect(ctx context.Context, objectRef insolar.Reference) *mClientMockGetPendings {\n\tif mmGetPendings.mock.funcGetPendings != nil {\n\t\tmmGetPendings.mock.t.Fatalf(\"ClientMock.GetPendings mock is already set by Set\")\n\t}\n\n\tif mmGetPendings.defaultExpectation == nil {\n\t\tmmGetPendings.defaultExpectation = &ClientMockGetPendingsExpectation{}\n\t}\n\n\tmmGetPendings.defaultExpectation.params = &ClientMockGetPendingsParams{ctx, objectRef}\n\tfor _, e := range mmGetPendings.expectations {\n\t\tif minimock.Equal(e.params, mmGetPendings.defaultExpectation.params) {\n\t\t\tmmGetPendings.mock.t.Fatalf(\"Expectation set by When has same params: %#v\", *mmGetPendings.defaultExpectation.params)\n\t\t}\n\t}\n\n\treturn mmGetPendings\n}", "func (m *MockOrg) EXPECT() *MockOrgMockRecorder {\n\treturn m.recorder\n}", "func (mmGetUserLocation *mStorageMockGetUserLocation) Expect(ctx context.Context, userID int64) *mStorageMockGetUserLocation {\n\tif mmGetUserLocation.mock.funcGetUserLocation != nil {\n\t\tmmGetUserLocation.mock.t.Fatalf(\"StorageMock.GetUserLocation mock is already set by Set\")\n\t}\n\n\tif mmGetUserLocation.defaultExpectation == nil {\n\t\tmmGetUserLocation.defaultExpectation = &StorageMockGetUserLocationExpectation{}\n\t}\n\n\tmmGetUserLocation.defaultExpectation.params = &StorageMockGetUserLocationParams{ctx, userID}\n\tfor _, e := range mmGetUserLocation.expectations {\n\t\tif minimock.Equal(e.params, mmGetUserLocation.defaultExpectation.params) {\n\t\t\tmmGetUserLocation.mock.t.Fatalf(\"Expectation set by When has same params: %#v\", *mmGetUserLocation.defaultExpectation.params)\n\t\t}\n\t}\n\n\treturn mmGetUserLocation\n}", "func (mmCreate *mPaymentRepositoryMockCreate) Expect(ctx context.Context, from int64, to int64, amount int64) *mPaymentRepositoryMockCreate {\n\tif mmCreate.mock.funcCreate != nil {\n\t\tmmCreate.mock.t.Fatalf(\"PaymentRepositoryMock.Create mock is already set by Set\")\n\t}\n\n\tif mmCreate.defaultExpectation == nil {\n\t\tmmCreate.defaultExpectation = &PaymentRepositoryMockCreateExpectation{}\n\t}\n\n\tmmCreate.defaultExpectation.params = &PaymentRepositoryMockCreateParams{ctx, from, to, amount}\n\tfor _, e := range mmCreate.expectations {\n\t\tif minimock.Equal(e.params, mmCreate.defaultExpectation.params) {\n\t\t\tmmCreate.mock.t.Fatalf(\"Expectation set by When has same params: %#v\", *mmCreate.defaultExpectation.params)\n\t\t}\n\t}\n\n\treturn mmCreate\n}", "func (mmAuther *mGatewayMockAuther) Expect() *mGatewayMockAuther {\n\tif mmAuther.mock.funcAuther != nil {\n\t\tmmAuther.mock.t.Fatalf(\"GatewayMock.Auther mock is already set by Set\")\n\t}\n\n\tif mmAuther.defaultExpectation == nil {\n\t\tmmAuther.defaultExpectation = &GatewayMockAutherExpectation{}\n\t}\n\n\treturn mmAuther\n}", "func (mmInvoke *mContainerMockInvoke) Expect(function interface{}) *mContainerMockInvoke {\n\tif mmInvoke.mock.funcInvoke != nil {\n\t\tmmInvoke.mock.t.Fatalf(\"ContainerMock.Invoke mock is already set by Set\")\n\t}\n\n\tif mmInvoke.defaultExpectation == nil {\n\t\tmmInvoke.defaultExpectation = &ContainerMockInvokeExpectation{}\n\t}\n\n\tmmInvoke.defaultExpectation.params = &ContainerMockInvokeParams{function}\n\tfor _, e := range mmInvoke.expectations {\n\t\tif minimock.Equal(e.params, mmInvoke.defaultExpectation.params) {\n\t\t\tmmInvoke.mock.t.Fatalf(\"Expectation set by When has same params: %#v\", *mmInvoke.defaultExpectation.params)\n\t\t}\n\t}\n\n\treturn mmInvoke\n}", "func TestObjectsMeetReq(t *testing.T) {\n\tvar kr verifiable.StorageReader\n\tvar kw verifiable.StorageWriter\n\n\tvar m verifiable.MutatorService\n\n\tvar o verifiable.AuthorizationOracle\n\n\tkr = &memory.TransientStorage{}\n\tkw = &memory.TransientStorage{}\n\n\tkr = &bolt.Storage{}\n\tkw = &bolt.Storage{}\n\n\tkr = &badger.Storage{}\n\tkw = &badger.Storage{}\n\n\tm = &instant.Mutator{}\n\tm = (&batch.Mutator{}).MustCreate()\n\n\to = policy.Open\n\to = &policy.Static{}\n\n\tlog.Println(kr, kw, m, o) // \"use\" these so that go compiler will be quiet\n}", "func (mmGetPosition *mStoreMockGetPosition) Expect(account string, contractID string) *mStoreMockGetPosition {\n\tif mmGetPosition.mock.funcGetPosition != nil {\n\t\tmmGetPosition.mock.t.Fatalf(\"StoreMock.GetPosition mock is already set by Set\")\n\t}\n\n\tif mmGetPosition.defaultExpectation == nil {\n\t\tmmGetPosition.defaultExpectation = &StoreMockGetPositionExpectation{}\n\t}\n\n\tmmGetPosition.defaultExpectation.params = &StoreMockGetPositionParams{account, contractID}\n\tfor _, e := range mmGetPosition.expectations {\n\t\tif minimock.Equal(e.params, mmGetPosition.defaultExpectation.params) {\n\t\t\tmmGetPosition.mock.t.Fatalf(\"Expectation set by When has same params: %#v\", *mmGetPosition.defaultExpectation.params)\n\t\t}\n\t}\n\n\treturn mmGetPosition\n}", "func (mmGetAbandonedRequest *mClientMockGetAbandonedRequest) Expect(ctx context.Context, objectRef insolar.Reference, reqRef insolar.Reference) *mClientMockGetAbandonedRequest {\n\tif mmGetAbandonedRequest.mock.funcGetAbandonedRequest != nil {\n\t\tmmGetAbandonedRequest.mock.t.Fatalf(\"ClientMock.GetAbandonedRequest mock is already set by Set\")\n\t}\n\n\tif mmGetAbandonedRequest.defaultExpectation == nil {\n\t\tmmGetAbandonedRequest.defaultExpectation = &ClientMockGetAbandonedRequestExpectation{}\n\t}\n\n\tmmGetAbandonedRequest.defaultExpectation.params = &ClientMockGetAbandonedRequestParams{ctx, objectRef, reqRef}\n\tfor _, e := range mmGetAbandonedRequest.expectations {\n\t\tif minimock.Equal(e.params, mmGetAbandonedRequest.defaultExpectation.params) {\n\t\t\tmmGetAbandonedRequest.mock.t.Fatalf(\"Expectation set by When has same params: %#v\", *mmGetAbandonedRequest.defaultExpectation.params)\n\t\t}\n\t}\n\n\treturn mmGetAbandonedRequest\n}", "func expectEqual(actual interface{}, extra interface{}, explain ...interface{}) {\n\tgomega.ExpectWithOffset(1, actual).To(gomega.Equal(extra), explain...)\n}", "func (mmSend *mSenderMockSend) Expect(ctx context.Context, email Email) *mSenderMockSend {\n\tif mmSend.mock.funcSend != nil {\n\t\tmmSend.mock.t.Fatalf(\"SenderMock.Send mock is already set by Set\")\n\t}\n\n\tif mmSend.defaultExpectation == nil {\n\t\tmmSend.defaultExpectation = &SenderMockSendExpectation{}\n\t}\n\n\tmmSend.defaultExpectation.params = &SenderMockSendParams{ctx, email}\n\tfor _, e := range mmSend.expectations {\n\t\tif minimock.Equal(e.params, mmSend.defaultExpectation.params) {\n\t\t\tmmSend.mock.t.Fatalf(\"Expectation set by When has same params: %#v\", *mmSend.defaultExpectation.params)\n\t\t}\n\t}\n\n\treturn mmSend\n}", "func (m *Mockrequester) EXPECT() *MockrequesterMockRecorder {\n\treturn m.recorder\n}", "func callAndVerify(msg string, client pb.GreeterClient, shouldFail bool) error {\n\tctx, cancel := context.WithTimeout(context.Background(), time.Second)\n\tdefer cancel()\n\t_, err := client.SayHello(ctx, &pb.HelloRequest{Name: msg})\n\tif want, got := shouldFail == true, err != nil; got != want {\n\t\treturn fmt.Errorf(\"want and got mismatch, want shouldFail=%v, got fail=%v, rpc error: %v\", want, got, err)\n\t}\n\treturn nil\n}", "func (m *MockstackDescriber) EXPECT() *MockstackDescriberMockRecorder {\n\treturn m.recorder\n}", "func (req *outgoingRequest) Assert(t *testing.T, fixture *fixture) {\n\tassert.Equal(t, req.path, fixture.calledPath, \"called path not as expected\")\n\tassert.Equal(t, req.method, fixture.calledMethod, \"called path not as expected\")\n\tassert.Equal(t, req.body, fixture.requestBody, \"call body no as expected\")\n}", "func (mmVerify *mDelegationTokenFactoryMockVerify) Expect(parcel mm_insolar.Parcel) *mDelegationTokenFactoryMockVerify {\n\tif mmVerify.mock.funcVerify != nil {\n\t\tmmVerify.mock.t.Fatalf(\"DelegationTokenFactoryMock.Verify mock is already set by Set\")\n\t}\n\n\tif mmVerify.defaultExpectation == nil {\n\t\tmmVerify.defaultExpectation = &DelegationTokenFactoryMockVerifyExpectation{}\n\t}\n\n\tmmVerify.defaultExpectation.params = &DelegationTokenFactoryMockVerifyParams{parcel}\n\tfor _, e := range mmVerify.expectations {\n\t\tif minimock.Equal(e.params, mmVerify.defaultExpectation.params) {\n\t\t\tmmVerify.mock.t.Fatalf(\"Expectation set by When has same params: %#v\", *mmVerify.defaultExpectation.params)\n\t\t}\n\t}\n\n\treturn mmVerify\n}", "func (mmRead *mDigestHolderMockRead) Expect(p []byte) *mDigestHolderMockRead {\n\tif mmRead.mock.funcRead != nil {\n\t\tmmRead.mock.t.Fatalf(\"DigestHolderMock.Read mock is already set by Set\")\n\t}\n\n\tif mmRead.defaultExpectation == nil {\n\t\tmmRead.defaultExpectation = &DigestHolderMockReadExpectation{}\n\t}\n\n\tmmRead.defaultExpectation.params = &DigestHolderMockReadParams{p}\n\tfor _, e := range mmRead.expectations {\n\t\tif minimock.Equal(e.params, mmRead.defaultExpectation.params) {\n\t\t\tmmRead.mock.t.Fatalf(\"Expectation set by When has same params: %#v\", *mmRead.defaultExpectation.params)\n\t\t}\n\t}\n\n\treturn mmRead\n}", "func (mmSend *mClientMockSend) Expect(ctx context.Context, n *Notification) *mClientMockSend {\n\tif mmSend.mock.funcSend != nil {\n\t\tmmSend.mock.t.Fatalf(\"ClientMock.Send mock is already set by Set\")\n\t}\n\n\tif mmSend.defaultExpectation == nil {\n\t\tmmSend.defaultExpectation = &ClientMockSendExpectation{}\n\t}\n\n\tmmSend.defaultExpectation.params = &ClientMockSendParams{ctx, n}\n\tfor _, e := range mmSend.expectations {\n\t\tif minimock.Equal(e.params, mmSend.defaultExpectation.params) {\n\t\t\tmmSend.mock.t.Fatalf(\"Expectation set by When has same params: %#v\", *mmSend.defaultExpectation.params)\n\t\t}\n\t}\n\n\treturn mmSend\n}", "func (mmAsByteString *mDigestHolderMockAsByteString) Expect() *mDigestHolderMockAsByteString {\n\tif mmAsByteString.mock.funcAsByteString != nil {\n\t\tmmAsByteString.mock.t.Fatalf(\"DigestHolderMock.AsByteString mock is already set by Set\")\n\t}\n\n\tif mmAsByteString.defaultExpectation == nil {\n\t\tmmAsByteString.defaultExpectation = &DigestHolderMockAsByteStringExpectation{}\n\t}\n\n\treturn mmAsByteString\n}", "func Expect(msg string) error {\n\tif msg != \"\" {\n\t\treturn errors.New(msg)\n\t} else {\n\t\treturn nil\n\t}\n}", "func (mmEncrypt *mRingMockEncrypt) Expect(t1 secrets.Text) *mRingMockEncrypt {\n\tif mmEncrypt.mock.funcEncrypt != nil {\n\t\tmmEncrypt.mock.t.Fatalf(\"RingMock.Encrypt mock is already set by Set\")\n\t}\n\n\tif mmEncrypt.defaultExpectation == nil {\n\t\tmmEncrypt.defaultExpectation = &RingMockEncryptExpectation{}\n\t}\n\n\tmmEncrypt.defaultExpectation.params = &RingMockEncryptParams{t1}\n\tfor _, e := range mmEncrypt.expectations {\n\t\tif minimock.Equal(e.params, mmEncrypt.defaultExpectation.params) {\n\t\t\tmmEncrypt.mock.t.Fatalf(\"Expectation set by When has same params: %#v\", *mmEncrypt.defaultExpectation.params)\n\t\t}\n\t}\n\n\treturn mmEncrypt\n}", "func (mmBootstrapper *mGatewayMockBootstrapper) Expect() *mGatewayMockBootstrapper {\n\tif mmBootstrapper.mock.funcBootstrapper != nil {\n\t\tmmBootstrapper.mock.t.Fatalf(\"GatewayMock.Bootstrapper mock is already set by Set\")\n\t}\n\n\tif mmBootstrapper.defaultExpectation == nil {\n\t\tmmBootstrapper.defaultExpectation = &GatewayMockBootstrapperExpectation{}\n\t}\n\n\treturn mmBootstrapper\n}", "func (m *MockNotary) EXPECT() *MockNotaryMockRecorder {\n\treturn m.recorder\n}", "func (m *mParcelMockSetSender) Expect(p insolar.Reference) *mParcelMockSetSender {\n\tm.mock.SetSenderFunc = nil\n\tm.expectationSeries = nil\n\n\tif m.mainExpectation == nil {\n\t\tm.mainExpectation = &ParcelMockSetSenderExpectation{}\n\t}\n\tm.mainExpectation.input = &ParcelMockSetSenderInput{p}\n\treturn m\n}", "func (mmGetPacketType *mPacketParserMockGetPacketType) Expect() *mPacketParserMockGetPacketType {\n\tif mmGetPacketType.mock.funcGetPacketType != nil {\n\t\tmmGetPacketType.mock.t.Fatalf(\"PacketParserMock.GetPacketType mock is already set by Set\")\n\t}\n\n\tif mmGetPacketType.defaultExpectation == nil {\n\t\tmmGetPacketType.defaultExpectation = &PacketParserMockGetPacketTypeExpectation{}\n\t}\n\n\treturn mmGetPacketType\n}", "func (mmParsePacketBody *mPacketParserMockParsePacketBody) Expect() *mPacketParserMockParsePacketBody {\n\tif mmParsePacketBody.mock.funcParsePacketBody != nil {\n\t\tmmParsePacketBody.mock.t.Fatalf(\"PacketParserMock.ParsePacketBody mock is already set by Set\")\n\t}\n\n\tif mmParsePacketBody.defaultExpectation == nil {\n\t\tmmParsePacketBody.defaultExpectation = &PacketParserMockParsePacketBodyExpectation{}\n\t}\n\n\treturn mmParsePacketBody\n}", "func (mmAsBytes *mDigestHolderMockAsBytes) Expect() *mDigestHolderMockAsBytes {\n\tif mmAsBytes.mock.funcAsBytes != nil {\n\t\tmmAsBytes.mock.t.Fatalf(\"DigestHolderMock.AsBytes mock is already set by Set\")\n\t}\n\n\tif mmAsBytes.defaultExpectation == nil {\n\t\tmmAsBytes.defaultExpectation = &DigestHolderMockAsBytesExpectation{}\n\t}\n\n\treturn mmAsBytes\n}", "func (mmKey *mIteratorMockKey) Expect() *mIteratorMockKey {\n\tif mmKey.mock.funcKey != nil {\n\t\tmmKey.mock.t.Fatalf(\"IteratorMock.Key mock is already set by Set\")\n\t}\n\n\tif mmKey.defaultExpectation == nil {\n\t\tmmKey.defaultExpectation = &IteratorMockKeyExpectation{}\n\t}\n\n\treturn mmKey\n}", "func (m *MockArticleLogic) EXPECT() *MockArticleLogicMockRecorder {\n\treturn m.recorder\n}", "func (m *MockFactory) EXPECT() *MockFactoryMockRecorder {\n\treturn m.recorder\n}", "func (m *MockFactory) EXPECT() *MockFactoryMockRecorder {\n\treturn m.recorder\n}", "func (m *MockFactory) EXPECT() *MockFactoryMockRecorder {\n\treturn m.recorder\n}", "func (m *mOutboundMockCanAccept) Expect(p Inbound) *mOutboundMockCanAccept {\n\tm.mock.CanAcceptFunc = nil\n\tm.expectationSeries = nil\n\n\tif m.mainExpectation == nil {\n\t\tm.mainExpectation = &OutboundMockCanAcceptExpectation{}\n\t}\n\tm.mainExpectation.input = &OutboundMockCanAcceptInput{p}\n\treturn m\n}", "func (m *MockLoaderFactory) EXPECT() *MockLoaderFactoryMockRecorder {\n\treturn m.recorder\n}", "func (m *MockPKG) EXPECT() *MockPKGMockRecorder {\n\treturn m.recorder\n}", "func (m *MockbucketDescriber) EXPECT() *MockbucketDescriberMockRecorder {\n\treturn m.recorder\n}", "func (m *mParcelMockType) Expect() *mParcelMockType {\n\tm.mock.TypeFunc = nil\n\tm.expectationSeries = nil\n\n\tif m.mainExpectation == nil {\n\t\tm.mainExpectation = &ParcelMockTypeExpectation{}\n\t}\n\n\treturn m\n}", "func (m *MockKeystore) EXPECT() *MockKeystoreMockRecorder {\n\treturn m.recorder\n}", "func (m *MockKeystore) EXPECT() *MockKeystoreMockRecorder {\n\treturn m.recorder\n}", "func (mmExchange *mMDNSClientMockExchange) Expect(msg *mdns.Msg, address string) *mMDNSClientMockExchange {\n\tif mmExchange.mock.funcExchange != nil {\n\t\tmmExchange.mock.t.Fatalf(\"MDNSClientMock.Exchange mock is already set by Set\")\n\t}\n\n\tif mmExchange.defaultExpectation == nil {\n\t\tmmExchange.defaultExpectation = &MDNSClientMockExchangeExpectation{}\n\t}\n\n\tmmExchange.defaultExpectation.params = &MDNSClientMockExchangeParams{msg, address}\n\tfor _, e := range mmExchange.expectations {\n\t\tif minimock.Equal(e.params, mmExchange.defaultExpectation.params) {\n\t\t\tmmExchange.mock.t.Fatalf(\"Expectation set by When has same params: %#v\", *mmExchange.defaultExpectation.params)\n\t\t}\n\t}\n\n\treturn mmExchange\n}", "func (m *MockStream) EXPECT() *MockStreamMockRecorder {\n\treturn m.recorder\n}", "func (c Chkr) Expect(v validator, args ...interface{}) {\n\tif c.runTest(v, args...) {\n\t\tc.Fail()\n\t}\n}", "func (mmClone *mStorageMockClone) Expect(ctx context.Context, from insolar.PulseNumber, to insolar.PulseNumber, keepActual bool) *mStorageMockClone {\n\tif mmClone.mock.funcClone != nil {\n\t\tmmClone.mock.t.Fatalf(\"StorageMock.Clone mock is already set by Set\")\n\t}\n\n\tif mmClone.defaultExpectation == nil {\n\t\tmmClone.defaultExpectation = &StorageMockCloneExpectation{}\n\t}\n\n\tmmClone.defaultExpectation.params = &StorageMockCloneParams{ctx, from, to, keepActual}\n\tfor _, e := range mmClone.expectations {\n\t\tif minimock.Equal(e.params, mmClone.defaultExpectation.params) {\n\t\t\tmmClone.mock.t.Fatalf(\"Expectation set by When has same params: %#v\", *mmClone.defaultExpectation.params)\n\t\t}\n\t}\n\n\treturn mmClone\n}", "func (m *MockCodeGenerator) EXPECT() *MockCodeGeneratorMockRecorder {\n\treturn m.recorder\n}", "func (m *MockNodeAttestor) EXPECT() *MockNodeAttestorMockRecorder {\n\treturn m.recorder\n}", "func (m *MockNodeAttestor) EXPECT() *MockNodeAttestorMockRecorder {\n\treturn m.recorder\n}", "func (_m *MockIStream) EXPECT() *MockIStreamMockRecorder {\n\treturn _m.recorder\n}", "func (m *mOutboundMockGetEndpointType) Expect() *mOutboundMockGetEndpointType {\n\tm.mock.GetEndpointTypeFunc = nil\n\tm.expectationSeries = nil\n\n\tif m.mainExpectation == nil {\n\t\tm.mainExpectation = &OutboundMockGetEndpointTypeExpectation{}\n\t}\n\n\treturn m\n}", "func (m *MockAZInfoProvider) EXPECT() *MockAZInfoProviderMockRecorder {\n\treturn m.recorder\n}" ]
[ "0.58169925", "0.571553", "0.5674476", "0.5640405", "0.562928", "0.5574723", "0.556962", "0.5530448", "0.550884", "0.5488494", "0.5474579", "0.5464561", "0.54615927", "0.54421943", "0.544173", "0.5407415", "0.54029363", "0.5390068", "0.53847593", "0.53847593", "0.5371173", "0.536972", "0.5359692", "0.534205", "0.5340419", "0.53292346", "0.5323524", "0.5313875", "0.530878", "0.5308145", "0.5308145", "0.5308145", "0.5308145", "0.5308145", "0.5308145", "0.5308145", "0.5308145", "0.5303667", "0.52966684", "0.52966684", "0.52915996", "0.5283216", "0.5282378", "0.52789223", "0.52753484", "0.5274766", "0.5265833", "0.5260114", "0.52583355", "0.5256263", "0.5255503", "0.5248704", "0.52430737", "0.52425617", "0.5239578", "0.5237592", "0.52367103", "0.52288496", "0.52258", "0.5223699", "0.52156955", "0.52140796", "0.5213764", "0.5213052", "0.52121735", "0.5209883", "0.5195822", "0.51916826", "0.51895916", "0.5188694", "0.5188263", "0.51853484", "0.5183852", "0.5176936", "0.5174346", "0.5170227", "0.5168422", "0.5164617", "0.5162764", "0.516157", "0.51612335", "0.5145313", "0.5145313", "0.5145313", "0.5145004", "0.5144547", "0.5140501", "0.5135879", "0.5135229", "0.51350814", "0.51350814", "0.51314574", "0.51309603", "0.5130878", "0.51252097", "0.5123687", "0.51181895", "0.51181895", "0.5116335", "0.5115415", "0.5110061" ]
0.0
-1
ChannelProvider mocks base method
func (m *MockClient) ChannelProvider() fab.ChannelProvider { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ChannelProvider") ret0, _ := ret[0].(fab.ChannelProvider) return ret0 }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (m *MockProviders) ChannelProvider() fab.ChannelProvider {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ChannelProvider\")\n\tret0, _ := ret[0].(fab.ChannelProvider)\n\treturn ret0\n}", "func (m *MockRConnectionInterface) Channel() (*amqp.Channel, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Channel\")\n\tret0, _ := ret[0].(*amqp.Channel)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func NewMockChannelProvider(ctx fab.Context) (*MockChannelProvider, error) {\n\tchannels := make(map[string]fab.Channel)\n\n\t// Create a mock client with the mock channel\n\tcp := MockChannelProvider{\n\t\tctx,\n\t\tchannels,\n\t}\n\treturn &cp, nil\n}", "func (suite *KeeperTestSuite) TestChanCloseInit() {\n\tvar (\n\t\tpath *ibctesting.Path\n\t\tchannelCap *capabilitytypes.Capability\n\t)\n\n\ttestCases := []testCase{\n\t\t{\"success\", func() {\n\t\t\tsuite.coordinator.Setup(path)\n\t\t\tchannelCap = suite.chainA.GetChannelCapability(path.EndpointA.ChannelConfig.PortID, path.EndpointA.ChannelID)\n\t\t}, true},\n\t\t{\"channel doesn't exist\", func() {\n\t\t\t// any non-nil values work for connections\n\t\t\tpath.EndpointA.ConnectionID = ibctesting.FirstConnectionID\n\t\t\tpath.EndpointB.ConnectionID = ibctesting.FirstConnectionID\n\n\t\t\tpath.EndpointA.ChannelID = ibctesting.FirstChannelID\n\t\t\tpath.EndpointB.ChannelID = ibctesting.FirstChannelID\n\n\t\t\t// ensure channel capability check passes\n\t\t\tsuite.chainA.CreateChannelCapability(suite.chainA.GetSimApp().ScopedIBCMockKeeper, path.EndpointA.ChannelConfig.PortID, path.EndpointA.ChannelID)\n\t\t\tchannelCap = suite.chainA.GetChannelCapability(path.EndpointA.ChannelConfig.PortID, path.EndpointA.ChannelID)\n\t\t}, false},\n\t\t{\"channel state is CLOSED\", func() {\n\t\t\tsuite.coordinator.Setup(path)\n\t\t\tchannelCap = suite.chainA.GetChannelCapability(path.EndpointA.ChannelConfig.PortID, path.EndpointA.ChannelID)\n\n\t\t\t// close channel\n\t\t\terr := path.EndpointA.SetChannelClosed()\n\t\t\tsuite.Require().NoError(err)\n\t\t}, false},\n\t\t{\"connection not found\", func() {\n\t\t\tsuite.coordinator.Setup(path)\n\t\t\tchannelCap = suite.chainA.GetChannelCapability(path.EndpointA.ChannelConfig.PortID, path.EndpointA.ChannelID)\n\n\t\t\t// set the channel's connection hops to wrong connection ID\n\t\t\tchannel := path.EndpointA.GetChannel()\n\t\t\tchannel.ConnectionHops[0] = \"doesnotexist\"\n\t\t\tsuite.chainA.App.GetIBCKeeper().ChannelKeeper.SetChannel(suite.chainA.GetContext(), path.EndpointA.ChannelConfig.PortID, path.EndpointA.ChannelID, channel)\n\t\t}, false},\n\t\t{\"connection is not OPEN\", func() {\n\t\t\tsuite.coordinator.SetupClients(path)\n\n\t\t\terr := path.EndpointA.ConnOpenInit()\n\t\t\tsuite.Require().NoError(err)\n\n\t\t\t// create channel in init\n\t\t\tpath.SetChannelOrdered()\n\t\t\terr = path.EndpointA.ChanOpenInit()\n\n\t\t\t// ensure channel capability check passes\n\t\t\tsuite.chainA.CreateChannelCapability(suite.chainA.GetSimApp().ScopedIBCMockKeeper, path.EndpointA.ChannelConfig.PortID, path.EndpointA.ChannelID)\n\t\t\tchannelCap = suite.chainA.GetChannelCapability(path.EndpointA.ChannelConfig.PortID, path.EndpointA.ChannelID)\n\t\t}, false},\n\t\t{\"channel capability not found\", func() {\n\t\t\tsuite.coordinator.Setup(path)\n\t\t\tchannelCap = capabilitytypes.NewCapability(3)\n\t\t}, false},\n\t}\n\n\tfor _, tc := range testCases {\n\t\ttc := tc\n\t\tsuite.Run(fmt.Sprintf(\"Case %s\", tc.msg), func() {\n\t\t\tsuite.SetupTest() // reset\n\t\t\tpath = ibctesting.NewPath(suite.chainA, suite.chainB)\n\n\t\t\ttc.malleate()\n\n\t\t\terr := suite.chainA.App.GetIBCKeeper().ChannelKeeper.ChanCloseInit(\n\t\t\t\tsuite.chainA.GetContext(), path.EndpointA.ChannelConfig.PortID, ibctesting.FirstChannelID, channelCap,\n\t\t\t)\n\n\t\t\tif tc.expPass {\n\t\t\t\tsuite.Require().NoError(err)\n\t\t\t} else {\n\t\t\t\tsuite.Require().Error(err)\n\t\t\t}\n\t\t})\n\t}\n}", "func TestChannelStore(t *testing.T) {\n\t// mock Insert function\n\tfn := func(_ context.Context, v are_hub.Archetype) error {\n\t\treturn nil\n\t}\n\n\t// create mock repo and controller\n\trepo := &mock.ChannelRepo{InsertFunc: fn}\n\tcontroller := NewChannel(repo)\n\n\t// create and embed a new channel\n\tmsport := are_hub.Channel{Name: \"Bentley Team M-Sport\", Password: \"abc123\"}\n\n\t// create a mock request\n\treq, e := http.NewRequest(http.MethodPost, \"/channel\", nil)\n\n\tif e != nil {\n\t\tt.Fatal(e)\n\t}\n\n\t// update the request's context with the channel\n\treq = req.WithContext(msport.ToCtx(req.Context()))\n\n\t// create a response recorder and run the controller method\n\tw := httptest.NewRecorder()\n\te = controller.Store(w, req)\n\n\tif e != nil {\n\t\tt.Fatal(e)\n\t}\n\n\t// check if the repo was hit\n\tif !repo.InsertCalled {\n\t\tt.Error(\"Did not call repo.Insert\")\n\t}\n\n\t// get the response\n\tres := w.Result()\n\n\t// ensure the content type is application/json\n\tcheckCT(res, t)\n\n\t// extract the returned channel\n\tdefer res.Body.Close()\n\tresBody, e := io.ReadAll(res.Body)\n\n\tif e != nil {\n\t\tt.Fatal(e)\n\t}\n\n\t// unmarshal the response body\n\treceived := are_hub.Channel{}\n\te = json.Unmarshal(resBody, &received)\n\n\tif e != nil {\n\t\tt.Fatal(e)\n\t}\n\n\t// compare the sent and received channels\n\tif msport.Name != received.Name {\n\t\tt.Fatalf(\"Expected: %+v. Actual: %+v\", msport, received)\n\t}\n}", "func (_m *KenContext) Channel() (*discordgo.Channel, error) {\n\tret := _m.Called()\n\n\tvar r0 *discordgo.Channel\n\tvar r1 error\n\tif rf, ok := ret.Get(0).(func() (*discordgo.Channel, error)); ok {\n\t\treturn rf()\n\t}\n\tif rf, ok := ret.Get(0).(func() *discordgo.Channel); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*discordgo.Channel)\n\t\t}\n\t}\n\n\tif rf, ok := ret.Get(1).(func() error); ok {\n\t\tr1 = rf()\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func TestConsumerChannel(t *testing.T) {\n\tconsumerTestWithCommits(t, \"Channel Consumer\", 0, true, eventTestChannelConsumer, nil)\n}", "func testChannel(t *testing.T, src, dst *Chain) {\n\tchans, err := src.QueryChannels(1, 1000)\n\trequire.NoError(t, err)\n\trequire.Equal(t, 1, len(chans))\n\trequire.Equal(t, chans[0].GetOrdering().String(), \"ORDERED\")\n\trequire.Equal(t, chans[0].GetState().String(), \"OPEN\")\n\trequire.Equal(t, chans[0].GetCounterparty().GetChannelID(), dst.PathEnd.ChannelID)\n\trequire.Equal(t, chans[0].GetCounterparty().GetPortID(), dst.PathEnd.PortID)\n\n\th, err := src.Client.Status()\n\trequire.NoError(t, err)\n\n\tch, err := src.QueryChannel(h.SyncInfo.LatestBlockHeight)\n\trequire.NoError(t, err)\n\trequire.Equal(t, ch.Channel.GetOrdering().String(), \"ORDERED\")\n\trequire.Equal(t, ch.Channel.GetState().String(), \"OPEN\")\n\trequire.Equal(t, ch.Channel.GetCounterparty().GetChannelID(), dst.PathEnd.ChannelID)\n\trequire.Equal(t, ch.Channel.GetCounterparty().GetPortID(), dst.PathEnd.PortID)\n}", "func (suite *KeeperTestSuite) TestSetChannel() {\n\t// create client and connections on both chains\n\tpath := ibctesting.NewPath(suite.chainA, suite.chainB)\n\tsuite.coordinator.SetupConnections(path)\n\n\t// check for channel to be created on chainA\n\t_, found := suite.chainA.App.GetIBCKeeper().ChannelKeeper.GetChannel(suite.chainA.GetContext(), path.EndpointA.ChannelConfig.PortID, path.EndpointA.ChannelID)\n\tsuite.False(found)\n\n\tpath.SetChannelOrdered()\n\n\t// init channel\n\terr := path.EndpointA.ChanOpenInit()\n\tsuite.NoError(err)\n\n\tstoredChannel, found := suite.chainA.App.GetIBCKeeper().ChannelKeeper.GetChannel(suite.chainA.GetContext(), path.EndpointA.ChannelConfig.PortID, path.EndpointA.ChannelID)\n\t// counterparty channel id is empty after open init\n\texpectedCounterparty := types.NewCounterparty(path.EndpointB.ChannelConfig.PortID, \"\")\n\n\tsuite.True(found)\n\tsuite.Equal(types.INIT, storedChannel.State)\n\tsuite.Equal(types.ORDERED, storedChannel.Ordering)\n\tsuite.Equal(expectedCounterparty, storedChannel.Counterparty)\n}", "func (c *Provider) ChannelProvider() fab.ChannelProvider {\n\treturn c.channelProvider\n}", "func (_m *Knapsack) UpdateChannel() string {\n\tret := _m.Called()\n\n\tvar r0 string\n\tif rf, ok := ret.Get(0).(func() string); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tr0 = ret.Get(0).(string)\n\t}\n\n\treturn r0\n}", "func newMockListener(endpoint net.Conn) *mockListener {\n \n c := make(chan net.Conn, 1)\n c <- endpoint\n listener := &mockListener{\n connChannel: c,\n serverEndpoint: endpoint,\n }\n return listener\n}", "func (m *MockCallResult) Channel() <-chan *Result {\n\targs := m.MethodCalled(\"Channel\")\n\n\tif resultChan := args.Get(0); resultChan != nil {\n\t\treturn resultChan.(<-chan *Result)\n\t}\n\n\treturn nil\n}", "func NewMockInterfaceProvider(managedInterfacesRegexp string, autoRefresh bool) (nt.InterfaceProvider,\n\tchan time.Time, error) {\n\tch := make(chan time.Time)\n\tip, err := nt.NewChanInterfaceProvider(ch, &MockInterfaceLister{}, managedInterfacesRegexp,\n\t\tautoRefresh)\n\treturn ip, ch, err\n}", "func TestChannelUpdate(t *testing.T) {\n\t// mock UpdateID function\n\tfn := func(_ context.Context, str string, v are_hub.Archetype) error {\n\t\t_, e := findChannelID(nil, str)\n\n\t\t// the update itself has no bearing on the test so simply return\n\t\t// the error (if there was one)\n\t\treturn e\n\t}\n\n\t// create mock repo and controller\n\trepo := &mock.ChannelRepo{UpdateIDFunc: fn}\n\tcontroller := NewChannel(repo)\n\n\t// mock channel\n\twrt := are_hub.Channel{Name: \"Belgian Audi Club WRT\", Password: \"abc123\"}\n\n\t// create mock request\n\tp := httprouter.Param{Key: \"id\", Value: \"1\"}\n\treq, e := http.NewRequest(http.MethodPut, \"/channel/\"+p.Value, nil)\n\n\tif e != nil {\n\t\tt.Fatal(e)\n\t}\n\n\t// embed the updated channel in the request's context\n\treq = req.WithContext(wrt.ToCtx(req.Context()))\n\n\t// embed parameters in the request's context\n\tuf.EmbedParams(req, p)\n\n\t// create a response recorder run the update method\n\tw := httptest.NewRecorder()\n\te = controller.Update(w, req)\n\n\tif e != nil {\n\t\tt.Fatal(e)\n\t}\n\n\tres := w.Result()\n\n\t// check if repo was hit\n\tif !repo.UpdateIDCalled {\n\t\tt.Error(\"Did not call repo.UpdateID\")\n\t}\n\n\t// ensure the content type is applicaton/json\n\tcheckCT(res, t)\n\n\t// read and unmarshal the body\n\tdefer res.Body.Close()\n\tresBody, e := io.ReadAll(res.Body)\n\n\tif e != nil {\n\t\tt.Fatal(e)\n\t}\n\n\treceived := are_hub.Channel{}\n\te = json.Unmarshal(resBody, &received)\n\n\tif e != nil {\n\t\tt.Fatal(e)\n\t}\n\n\t// compare the sent and received channels\n\tif wrt.Name != received.Name {\n\t\tt.Fatalf(\"Expected: %+v. Actual: %+v\", wrt, received)\n\t}\n\n\t// check if Update returns a 404 error on an invalid ID\n\tp = httprouter.Param{Key: \"id\", Value: \"-1\"}\n\treq, e = http.NewRequest(http.MethodPut, \"/channel/\"+p.Value, nil)\n\n\tif e != nil {\n\t\tt.Fatal(e)\n\t}\n\n\t// embed non-existant channel into the request's context\n\tgpx := are_hub.Channel{Name: \"Grand Prix Extreme\", Password: \"porsche\"}\n\treq = req.WithContext(gpx.ToCtx(req.Context()))\n\n\t// embed parameters\n\tuf.EmbedParams(req, p)\n\n\t// create a new response recorder and call the update method\n\tw = httptest.NewRecorder()\n\te = controller.Update(w, req)\n\n\tif e == nil {\n\t\tt.Fatal(\"Expected: 404 Not found error. Actual: nil\")\n\t}\n\n\the, ok := e.(uf.HttpError)\n\n\tif !ok {\n\t\tt.Fatalf(\"Expected: 404 Not Found error. Actual: %+v\", e)\n\t}\n\n\tif he.Code != http.StatusNotFound {\n\t\tt.Fatalf(\"Expected: %d. Actual: %d\", http.StatusNotFound, he.Code)\n\t}\n}", "func TestChannelIndex(t *testing.T) {\n\t// mock All function\n\tfn := func(_ context.Context) ([]are_hub.Channel, error) {\n\t\treturn channels, nil\n\t}\n\n\t// create the mock repo and controller\n\trepo := &mock.ChannelRepo{AllFunc: fn}\n\tcontroller := NewChannel(repo)\n\n\t// create a mock request\n\treq, e := http.NewRequest(http.MethodGet, \"/channel\", nil)\n\n\tif e != nil {\n\t\tt.Fatal(e)\n\t}\n\n\t// create a response recorder and run the controller method\n\tw := httptest.NewRecorder()\n\te = controller.Index(w, req)\n\n\tif e != nil {\n\t\tt.Fatal(e)\n\t}\n\n\t// get the response\n\tres := w.Result()\n\n\t// check if the repo was hit\n\tif !repo.AllCalled {\n\t\tt.Error(\"Did not call repo.All\")\n\t}\n\n\t// ensure the content type is application/json\n\tcheckCT(res, t)\n\n\t// extract the body and confirm all data was returned\n\tdefer res.Body.Close()\n\tbody, e := io.ReadAll(res.Body)\n\n\tif e != nil {\n\t\tt.Fatal(e)\n\t}\n\n\tvar received []are_hub.Channel\n\te = json.Unmarshal(body, &received)\n\n\tif e != nil {\n\t\tt.Fatal(e)\n\t}\n\n\tlr := len(received)\n\tlc := len(channels)\n\n\t// check that all channels were returned\n\tif lr != lc {\n\t\tt.Fatalf(\"Expected: %d channels. Actual: %d.\", lc, lr)\n\t}\n\n\t// loop and ensure the data is correct\n\tfor i := 0; i < lr; i++ {\n\t\tif received[i].Name != channels[i].Name {\n\t\t\tt.Fatalf(\"Expected: %s. Actual: %s.\", channels[i].Name, received[i].Name)\n\t\t}\n\t}\n}", "func (m *MockFullNode) PaychGet(arg0 context.Context, arg1, arg2 address.Address, arg3 big.Int) (*types0.ChannelInfo, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"PaychGet\", arg0, arg1, arg2, arg3)\n\tret0, _ := ret[0].(*types0.ChannelInfo)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func TestChannelFactoryPattern(t *testing.T) {\n\tsuck(pump(5))\n\ttime.Sleep(1e9)\n}", "func (m *MockAMQPChannel) NotifyCancel(arg0 chan string) chan string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"NotifyCancel\", arg0)\n\tret0, _ := ret[0].(chan string)\n\treturn ret0\n}", "func (m *MockKubeCoreCache) Subscribe() <-chan struct{} {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Subscribe\")\n\tret0, _ := ret[0].(<-chan struct{})\n\treturn ret0\n}", "func (suite *KeeperTestSuite) TestChanOpenInit() {\n\tvar (\n\t\tpath *ibctesting.Path\n\t\tfeatures []string\n\t\tportCap *capabilitytypes.Capability\n\t)\n\n\ttestCases := []testCase{\n\t\t{\"success\", func() {\n\t\t\tsuite.coordinator.SetupConnections(path)\n\t\t\tfeatures = []string{\"ORDER_ORDERED\", \"ORDER_UNORDERED\"}\n\t\t\tsuite.chainA.CreatePortCapability(suite.chainA.GetSimApp().ScopedIBCMockKeeper, ibctesting.MockPort)\n\t\t\tportCap = suite.chainA.GetPortCapability(ibctesting.MockPort)\n\t\t}, true},\n\t\t{\"channel already exists\", func() {\n\t\t\tsuite.coordinator.Setup(path)\n\t\t}, false},\n\t\t{\"connection doesn't exist\", func() {\n\t\t\t// any non-empty values\n\t\t\tpath.EndpointA.ConnectionID = \"connection-0\"\n\t\t\tpath.EndpointB.ConnectionID = \"connection-0\"\n\t\t}, false},\n\t\t{\"capability is incorrect\", func() {\n\t\t\tsuite.coordinator.SetupConnections(path)\n\t\t\tfeatures = []string{\"ORDER_ORDERED\", \"ORDER_UNORDERED\"}\n\t\t\tportCap = capabilitytypes.NewCapability(3)\n\t\t}, false},\n\t\t{\"connection version not negotiated\", func() {\n\t\t\tsuite.coordinator.SetupConnections(path)\n\n\t\t\t// modify connA versions\n\t\t\tconn := path.EndpointA.GetConnection()\n\n\t\t\tversion := connectiontypes.NewVersion(\"2\", []string{\"ORDER_ORDERED\", \"ORDER_UNORDERED\"})\n\t\t\tconn.Versions = append(conn.Versions, version)\n\n\t\t\tsuite.chainA.App.GetIBCKeeper().ConnectionKeeper.SetConnection(\n\t\t\t\tsuite.chainA.GetContext(),\n\t\t\t\tpath.EndpointA.ConnectionID, conn,\n\t\t\t)\n\t\t\tfeatures = []string{\"ORDER_ORDERED\", \"ORDER_UNORDERED\"}\n\t\t\tsuite.chainA.CreatePortCapability(suite.chainA.GetSimApp().ScopedIBCMockKeeper, ibctesting.MockPort)\n\t\t\tportCap = suite.chainA.GetPortCapability(ibctesting.MockPort)\n\t\t}, false},\n\t\t{\"connection does not support ORDERED channels\", func() {\n\t\t\tsuite.coordinator.SetupConnections(path)\n\n\t\t\t// modify connA versions to only support UNORDERED channels\n\t\t\tconn := path.EndpointA.GetConnection()\n\n\t\t\tversion := connectiontypes.NewVersion(\"1\", []string{\"ORDER_UNORDERED\"})\n\t\t\tconn.Versions = []*connectiontypes.Version{version}\n\n\t\t\tsuite.chainA.App.GetIBCKeeper().ConnectionKeeper.SetConnection(\n\t\t\t\tsuite.chainA.GetContext(),\n\t\t\t\tpath.EndpointA.ConnectionID, conn,\n\t\t\t)\n\t\t\t// NOTE: Opening UNORDERED channels is still expected to pass but ORDERED channels should fail\n\t\t\tfeatures = []string{\"ORDER_UNORDERED\"}\n\t\t\tsuite.chainA.CreatePortCapability(suite.chainA.GetSimApp().ScopedIBCMockKeeper, ibctesting.MockPort)\n\t\t\tportCap = suite.chainA.GetPortCapability(ibctesting.MockPort)\n\t\t}, true},\n\t}\n\n\tfor _, tc := range testCases {\n\t\ttc := tc\n\t\tsuite.Run(fmt.Sprintf(\"Case %s\", tc.msg), func() {\n\t\t\t// run test for all types of ordering\n\t\t\tfor _, order := range []types.Order{types.UNORDERED, types.ORDERED} {\n\t\t\t\tsuite.SetupTest() // reset\n\t\t\t\tpath = ibctesting.NewPath(suite.chainA, suite.chainB)\n\t\t\t\tpath.EndpointA.ChannelConfig.Order = order\n\t\t\t\tpath.EndpointB.ChannelConfig.Order = order\n\n\t\t\t\ttc.malleate()\n\n\t\t\t\tcounterparty := types.NewCounterparty(ibctesting.MockPort, ibctesting.FirstChannelID)\n\n\t\t\t\tchannelID, cap, err := suite.chainA.App.GetIBCKeeper().ChannelKeeper.ChanOpenInit(\n\t\t\t\t\tsuite.chainA.GetContext(), path.EndpointA.ChannelConfig.Order, []string{path.EndpointA.ConnectionID},\n\t\t\t\t\tpath.EndpointA.ChannelConfig.PortID, portCap, counterparty, path.EndpointA.ChannelConfig.Version,\n\t\t\t\t)\n\n\t\t\t\t// check if order is supported by channel to determine expected behaviour\n\t\t\t\torderSupported := false\n\t\t\t\tfor _, f := range features {\n\t\t\t\t\tif f == order.String() {\n\t\t\t\t\t\torderSupported = true\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// Testcase must have expectedPass = true AND channel order supported before\n\t\t\t\t// asserting the channel handshake initiation succeeded\n\t\t\t\tif tc.expPass && orderSupported {\n\t\t\t\t\tsuite.Require().NoError(err)\n\t\t\t\t\tsuite.Require().NotNil(cap)\n\t\t\t\t\tsuite.Require().Equal(types.FormatChannelIdentifier(0), channelID)\n\n\t\t\t\t\tchanCap, ok := suite.chainA.App.GetScopedIBCKeeper().GetCapability(\n\t\t\t\t\t\tsuite.chainA.GetContext(),\n\t\t\t\t\t\thost.ChannelCapabilityPath(path.EndpointA.ChannelConfig.PortID, channelID),\n\t\t\t\t\t)\n\t\t\t\t\tsuite.Require().True(ok, \"could not retrieve channel capability after successful ChanOpenInit\")\n\t\t\t\t\tsuite.Require().Equal(chanCap.String(), cap.String(), \"channel capability is not correct\")\n\t\t\t\t} else {\n\t\t\t\t\tsuite.Require().Error(err)\n\t\t\t\t\tsuite.Require().Nil(cap)\n\t\t\t\t\tsuite.Require().Equal(\"\", channelID)\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n}", "func New(fabricProvider api.FabricProvider) (*ChannelProvider, error) {\n\tcp := ChannelProvider{fabricProvider: fabricProvider}\n\treturn &cp, nil\n}", "func (m *MockProvider) Run(arg0 <-chan struct{}) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"Run\", arg0)\n}", "func (m *MockWebsocketClientStore) Channels(clientID wspubsub.UUID) ([]string, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Channels\", clientID)\n\tret0, _ := ret[0].([]string)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (a *MockAction) ChannelClient() (*channel.Client, error) {\n\tpanic(\"not implemented\")\n}", "func (m *MockProvider) Provide(arg0 string) blobclient.Client {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Provide\", arg0)\n\tret0, _ := ret[0].(blobclient.Client)\n\treturn ret0\n}", "func (suite KeeperTestSuite) TestGetAllChannels() {\n\tpath := ibctesting.NewPath(suite.chainA, suite.chainB)\n\tsuite.coordinator.Setup(path)\n\t// channel0 on first connection on chainA\n\tcounterparty0 := types.Counterparty{\n\t\tPortId: path.EndpointB.ChannelConfig.PortID,\n\t\tChannelId: path.EndpointB.ChannelID,\n\t}\n\n\t// path1 creates a second channel on first connection on chainA\n\tpath1 := ibctesting.NewPath(suite.chainA, suite.chainB)\n\tpath1.SetChannelOrdered()\n\tpath1.EndpointA.ClientID = path.EndpointA.ClientID\n\tpath1.EndpointB.ClientID = path.EndpointB.ClientID\n\tpath1.EndpointA.ConnectionID = path.EndpointA.ConnectionID\n\tpath1.EndpointB.ConnectionID = path.EndpointB.ConnectionID\n\n\tsuite.coordinator.CreateMockChannels(path1)\n\tcounterparty1 := types.Counterparty{\n\t\tPortId: path1.EndpointB.ChannelConfig.PortID,\n\t\tChannelId: path1.EndpointB.ChannelID,\n\t}\n\n\tpath2 := ibctesting.NewPath(suite.chainA, suite.chainB)\n\tsuite.coordinator.SetupConnections(path2)\n\n\t// path2 creates a second channel on chainA\n\terr := path2.EndpointA.ChanOpenInit()\n\tsuite.Require().NoError(err)\n\n\t// counterparty channel id is empty after open init\n\tcounterparty2 := types.Counterparty{\n\t\tPortId: path2.EndpointB.ChannelConfig.PortID,\n\t\tChannelId: \"\",\n\t}\n\n\tchannel0 := types.NewChannel(\n\t\ttypes.OPEN, types.UNORDERED,\n\t\tcounterparty0, []string{path.EndpointA.ConnectionID}, path.EndpointA.ChannelConfig.Version,\n\t)\n\tchannel1 := types.NewChannel(\n\t\ttypes.OPEN, types.ORDERED,\n\t\tcounterparty1, []string{path1.EndpointA.ConnectionID}, path1.EndpointA.ChannelConfig.Version,\n\t)\n\tchannel2 := types.NewChannel(\n\t\ttypes.INIT, types.UNORDERED,\n\t\tcounterparty2, []string{path2.EndpointA.ConnectionID}, path2.EndpointA.ChannelConfig.Version,\n\t)\n\n\texpChannels := []types.IdentifiedChannel{\n\t\ttypes.NewIdentifiedChannel(path.EndpointA.ChannelConfig.PortID, path.EndpointA.ChannelID, channel0),\n\t\ttypes.NewIdentifiedChannel(path1.EndpointA.ChannelConfig.PortID, path1.EndpointA.ChannelID, channel1),\n\t\ttypes.NewIdentifiedChannel(path2.EndpointA.ChannelConfig.PortID, path2.EndpointA.ChannelID, channel2),\n\t}\n\n\tctxA := suite.chainA.GetContext()\n\n\tchannels := suite.chainA.App.GetIBCKeeper().ChannelKeeper.GetAllChannels(ctxA)\n\tsuite.Require().Len(channels, len(expChannels))\n\tsuite.Require().Equal(expChannels, channels)\n}", "func (m *MockFullNode) MpoolSub(arg0 context.Context) (<-chan types0.MpoolUpdate, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"MpoolSub\", arg0)\n\tret0, _ := ret[0].(<-chan types0.MpoolUpdate)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockAcceptor) GetConnChan() chan net.Conn {\n\tret := m.ctrl.Call(m, \"GetConnChan\")\n\tret0, _ := ret[0].(chan net.Conn)\n\treturn ret0\n}", "func TestChannelClientBasic(t *testing.T) {\n\tc := make(chan *http.Response, 10)\n\tclient := cloudtest.NewChannelClient(c)\n\n\tresp := &http.Response{}\n\tresp.StatusCode = http.StatusOK\n\tresp.Status = \"OK\"\n\tc <- resp\n\tresp, err := client.Get(\"http://foobar\")\n\tlog.Printf(\"%v\\n\", resp)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tif resp.StatusCode != http.StatusOK {\n\t\tt.Error(\"Response should be OK: \", resp.Status)\n\t}\n}", "func TestChannels(t *testing.T) {\n\ttc := testutil.SystemTest(t)\n\tbuf := &bytes.Buffer{}\n\n\t// Test setup\n\n\t// Stop and delete the default channel if it exists\n\tif err := getChannel(buf, tc.ProjectID, location, channelID); err == nil {\n\t\ttestutil.Retry(t, 3, 2*time.Second, func(r *testutil.R) {\n\t\t\tif err := stopChannel(buf, tc.ProjectID, location, channelID); err != nil {\n\t\t\t\t// Ignore the error when the channel is already stopped\n\t\t\t}\n\t\t})\n\n\t\ttestutil.Retry(t, 3, 2*time.Second, func(r *testutil.R) {\n\t\t\tif err := deleteChannel(buf, tc.ProjectID, location, channelID); err != nil {\n\t\t\t\tr.Errorf(\"deleteChannel got err: %v\", err)\n\t\t\t}\n\t\t})\n\t}\n\n\t// Delete the default input if it exists\n\tif err := getInput(buf, tc.ProjectID, location, inputID); err == nil {\n\t\ttestutil.Retry(t, 3, 2*time.Second, func(r *testutil.R) {\n\t\t\tif err := deleteInput(buf, tc.ProjectID, location, inputID); err != nil {\n\t\t\t\tr.Errorf(\"deleteInput got err: %v\", err)\n\t\t\t}\n\t\t})\n\t}\n\tbuf.Reset()\n\n\t// Create a new input.\n\ttestutil.Retry(t, 3, 2*time.Second, func(r *testutil.R) {\n\t\tinputName := fmt.Sprintf(\"projects/%s/locations/%s/inputs/%s\", tc.ProjectID, location, inputID)\n\t\tif err := createInput(buf, tc.ProjectID, location, inputID); err != nil {\n\t\t\tr.Errorf(\"createInput got err: %v\", err)\n\t\t}\n\t\tif got := buf.String(); !strings.Contains(got, inputName) {\n\t\t\tr.Errorf(\"createInput got\\n----\\n%v\\n----\\nWant to contain:\\n----\\n%v\\n----\\n\", got, inputName)\n\t\t}\n\t})\n\tbuf.Reset()\n\n\t// Tests\n\n\t// Create a new channel.\n\ttestutil.Retry(t, 3, 2*time.Second, func(r *testutil.R) {\n\t\tchannelName := fmt.Sprintf(\"projects/%s/locations/%s/channels/%s\", tc.ProjectID, location, channelID)\n\t\tif err := createChannel(buf, tc.ProjectID, location, channelID, inputID, outputURI); err != nil {\n\t\t\tr.Errorf(\"createChannel got err: %v\", err)\n\t\t}\n\t\tif got := buf.String(); !strings.Contains(got, channelName) {\n\t\t\tr.Errorf(\"createChannel got\\n----\\n%v\\n----\\nWant to contain:\\n----\\n%v\\n----\\n\", got, channelName)\n\t\t}\n\t})\n\tbuf.Reset()\n\n\t// List the channels for a given location.\n\ttestutil.Retry(t, 3, 2*time.Second, func(r *testutil.R) {\n\t\tchannelName := fmt.Sprintf(\"projects/%s/locations/%s/channels/%s\", tc.ProjectID, location, channelID)\n\t\tif err := listChannels(buf, tc.ProjectID, location); err != nil {\n\t\t\tr.Errorf(\"listChannels got err: %v\", err)\n\t\t}\n\t\tif got := buf.String(); !strings.Contains(got, channelName) {\n\t\t\tr.Errorf(\"listChannels got\\n----\\n%v\\n----\\nWant to contain:\\n----\\n%v\\n----\\n\", got, channelName)\n\t\t}\n\t})\n\tbuf.Reset()\n\n\t// Update an existing channel.\n\ttestutil.Retry(t, 3, 2*time.Second, func(r *testutil.R) {\n\t\tchannelName := fmt.Sprintf(\"projects/%s/locations/%s/channels/%s\", tc.ProjectID, location, channelID)\n\t\tif err := updateChannel(buf, tc.ProjectID, location, channelID, inputID); err != nil {\n\t\t\tr.Errorf(\"updateChannel got err: %v\", err)\n\t\t}\n\t\tif got := buf.String(); !strings.Contains(got, channelName) {\n\t\t\tr.Errorf(\"updateChannel got\\n----\\n%v\\n----\\nWant to contain:\\n----\\n%v\\n----\\n\", got, channelName)\n\t\t}\n\t})\n\tbuf.Reset()\n\n\t// Get the updated channel.\n\ttestutil.Retry(t, 3, 2*time.Second, func(r *testutil.R) {\n\t\tchannelName := fmt.Sprintf(\"projects/%s/locations/%s/channels/%s\", tc.ProjectID, location, channelID)\n\t\tif err := getChannel(buf, tc.ProjectID, location, channelID); err != nil {\n\t\t\tr.Errorf(\"getChannel got err: %v\", err)\n\t\t}\n\t\tif got := buf.String(); !strings.Contains(got, channelName) {\n\t\t\tr.Errorf(\"getChannel got\\n----\\n%v\\n----\\nWant to contain:\\n----\\n%v\\n----\\n\", got, channelName)\n\t\t}\n\t})\n\tbuf.Reset()\n\n\t// Start the channel.\n\ttestutil.Retry(t, 3, 2*time.Second, func(r *testutil.R) {\n\t\tif err := startChannel(buf, tc.ProjectID, location, channelID); err != nil {\n\t\t\tr.Errorf(\"startChannel got err: %v\", err)\n\t\t}\n\t\tif got := buf.String(); !strings.Contains(got, startChannelResponse) {\n\t\t\tr.Errorf(\"startChannel got\\n----\\n%v\\n----\\nWant to contain:\\n----\\n%v\\n----\\n\", got, startChannelResponse)\n\t\t}\n\t})\n\tbuf.Reset()\n\n\t// Stop the channel.\n\ttestutil.Retry(t, 3, 2*time.Second, func(r *testutil.R) {\n\t\tif err := stopChannel(buf, tc.ProjectID, location, channelID); err != nil {\n\t\t\tr.Errorf(\"stopChannel got err: %v\", err)\n\t\t}\n\t\tif got := buf.String(); !strings.Contains(got, stopChannelResponse) {\n\t\t\tr.Errorf(\"stopChannel got\\n----\\n%v\\n----\\nWant to contain:\\n----\\n%v\\n----\\n\", got, stopChannelResponse)\n\t\t}\n\t})\n\tbuf.Reset()\n\n\t// Delete the channel.\n\ttestutil.Retry(t, 3, 2*time.Second, func(r *testutil.R) {\n\t\tif err := deleteChannel(buf, tc.ProjectID, location, channelID); err != nil {\n\t\t\tr.Errorf(\"deleteChannel got err: %v\", err)\n\t\t}\n\t\tif got := buf.String(); !strings.Contains(got, deleteChannelResponse) {\n\t\t\tr.Errorf(\"deleteChannel got\\n----\\n%v\\n----\\nWant to contain:\\n----\\n%v\\n----\\n\", got, deleteChannelResponse)\n\t\t}\n\t})\n\tbuf.Reset()\n\n\t// Create a new channel with backup input.\n\ttestutil.Retry(t, 3, 2*time.Second, func(r *testutil.R) {\n\t\tchannelName := fmt.Sprintf(\"projects/%s/locations/%s/channels/%s\", tc.ProjectID, location, channelID)\n\t\tif err := createChannelWithBackupInput(buf, tc.ProjectID, location, channelID, inputID, backupInputID, outputURI); err != nil {\n\t\t\tr.Errorf(\"createChannel got err: %v\", err)\n\t\t}\n\t\tif got := buf.String(); !strings.Contains(got, channelName) {\n\t\t\tr.Errorf(\"createChannel got\\n----\\n%v\\n----\\nWant to contain:\\n----\\n%v\\n----\\n\", got, channelName)\n\t\t}\n\t})\n\tbuf.Reset()\n\n\t// Clean up\n\n\t// Delete the channel with backup input.\n\ttestutil.Retry(t, 3, 2*time.Second, func(r *testutil.R) {\n\t\tif err := deleteChannel(buf, tc.ProjectID, location, channelID); err != nil {\n\t\t\tr.Errorf(\"deleteChannel got err: %v\", err)\n\t\t}\n\t\tif got := buf.String(); !strings.Contains(got, deleteChannelResponse) {\n\t\t\tr.Errorf(\"deleteChannel got\\n----\\n%v\\n----\\nWant to contain:\\n----\\n%v\\n----\\n\", got, deleteChannelResponse)\n\t\t}\n\t})\n\n\t// Delete the input.\n\ttestutil.Retry(t, 3, 2*time.Second, func(r *testutil.R) {\n\t\tif err := deleteInput(buf, tc.ProjectID, location, inputID); err != nil {\n\t\t\tr.Errorf(\"deleteInput got err: %v\", err)\n\t\t}\n\t\tif got := buf.String(); !strings.Contains(got, deleteInputResponse) {\n\t\t\tr.Errorf(\"deleteInput got\\n----\\n%v\\n----\\nWant to contain:\\n----\\n%v\\n----\\n\", got, deleteInputResponse)\n\t\t}\n\t})\n\n\t// Delete the backup input.\n\ttestutil.Retry(t, 3, 2*time.Second, func(r *testutil.R) {\n\t\tif err := deleteInput(buf, tc.ProjectID, location, backupInputID); err != nil {\n\t\t\tr.Errorf(\"deleteInput got err: %v\", err)\n\t\t}\n\t\tif got := buf.String(); !strings.Contains(got, deleteInputResponse) {\n\t\t\tr.Errorf(\"deleteInput got\\n----\\n%v\\n----\\nWant to contain:\\n----\\n%v\\n----\\n\", got, deleteInputResponse)\n\t\t}\n\t})\n\tt.Logf(\"\\nTestChannels() completed\\n\")\n}", "func (suite *KeeperTestSuite) TestChanOpenAck() {\n\tvar (\n\t\tpath *ibctesting.Path\n\t\tcounterpartyChannelID string\n\t\tchannelCap *capabilitytypes.Capability\n\t\theightDiff uint64\n\t)\n\n\ttestCases := []testCase{\n\t\t{\"success\", func() {\n\t\t\tsuite.coordinator.SetupConnections(path)\n\t\t\tpath.SetChannelOrdered()\n\t\t\terr := path.EndpointA.ChanOpenInit()\n\t\t\tsuite.Require().NoError(err)\n\n\t\t\terr = path.EndpointB.ChanOpenTry()\n\t\t\tsuite.Require().NoError(err)\n\n\t\t\tchannelCap = suite.chainA.GetChannelCapability(path.EndpointA.ChannelConfig.PortID, path.EndpointA.ChannelID)\n\t\t}, true},\n\t\t{\"success with empty stored counterparty channel ID\", func() {\n\t\t\tsuite.coordinator.SetupConnections(path)\n\t\t\tpath.SetChannelOrdered()\n\n\t\t\terr := path.EndpointA.ChanOpenInit()\n\t\t\tsuite.Require().NoError(err)\n\n\t\t\terr = path.EndpointB.ChanOpenTry()\n\t\t\tsuite.Require().NoError(err)\n\n\t\t\t// set the channel's counterparty channel identifier to empty string\n\t\t\tchannel := path.EndpointA.GetChannel()\n\t\t\tchannel.Counterparty.ChannelId = \"\"\n\n\t\t\t// use a different channel identifier\n\t\t\tcounterpartyChannelID = path.EndpointB.ChannelID\n\n\t\t\tsuite.chainA.App.GetIBCKeeper().ChannelKeeper.SetChannel(suite.chainA.GetContext(), path.EndpointA.ChannelConfig.PortID, path.EndpointA.ChannelID, channel)\n\n\t\t\tchannelCap = suite.chainA.GetChannelCapability(path.EndpointA.ChannelConfig.PortID, path.EndpointA.ChannelID)\n\t\t}, true},\n\t\t{\"channel doesn't exist\", func() {}, false},\n\t\t{\"channel state is not INIT or TRYOPEN\", func() {\n\t\t\t// create fully open channels on both chains\n\t\t\tsuite.coordinator.Setup(path)\n\t\t\tchannelCap = suite.chainA.GetChannelCapability(path.EndpointA.ChannelConfig.PortID, path.EndpointA.ChannelID)\n\t\t}, false},\n\t\t{\"connection not found\", func() {\n\t\t\tsuite.coordinator.SetupConnections(path)\n\t\t\tpath.SetChannelOrdered()\n\t\t\terr := path.EndpointA.ChanOpenInit()\n\t\t\tsuite.Require().NoError(err)\n\n\t\t\terr = path.EndpointB.ChanOpenTry()\n\t\t\tsuite.Require().NoError(err)\n\n\t\t\tchannelCap = suite.chainA.GetChannelCapability(path.EndpointA.ChannelConfig.PortID, path.EndpointA.ChannelID)\n\n\t\t\t// set the channel's connection hops to wrong connection ID\n\t\t\tchannel := path.EndpointA.GetChannel()\n\t\t\tchannel.ConnectionHops[0] = \"doesnotexist\"\n\t\t\tsuite.chainA.App.GetIBCKeeper().ChannelKeeper.SetChannel(suite.chainA.GetContext(), path.EndpointA.ChannelConfig.PortID, path.EndpointA.ChannelID, channel)\n\t\t}, false},\n\t\t{\"connection is not OPEN\", func() {\n\t\t\tsuite.coordinator.SetupClients(path)\n\n\t\t\terr := path.EndpointA.ConnOpenInit()\n\t\t\tsuite.Require().NoError(err)\n\n\t\t\t// create channel in init\n\t\t\tpath.SetChannelOrdered()\n\n\t\t\terr = path.EndpointA.ChanOpenInit()\n\t\t\tsuite.Require().NoError(err)\n\n\t\t\tsuite.chainA.CreateChannelCapability(suite.chainA.GetSimApp().ScopedIBCMockKeeper, path.EndpointA.ChannelConfig.PortID, path.EndpointA.ChannelID)\n\t\t\tchannelCap = suite.chainA.GetChannelCapability(path.EndpointA.ChannelConfig.PortID, path.EndpointA.ChannelID)\n\t\t}, false},\n\t\t{\"consensus state not found\", func() {\n\t\t\tsuite.coordinator.SetupConnections(path)\n\t\t\tpath.SetChannelOrdered()\n\n\t\t\terr := path.EndpointA.ChanOpenInit()\n\t\t\tsuite.Require().NoError(err)\n\n\t\t\terr = path.EndpointB.ChanOpenTry()\n\t\t\tsuite.Require().NoError(err)\n\n\t\t\tchannelCap = suite.chainA.GetChannelCapability(path.EndpointA.ChannelConfig.PortID, path.EndpointA.ChannelID)\n\n\t\t\theightDiff = 3 // consensus state doesn't exist at this height\n\t\t}, false},\n\t\t{\"invalid counterparty channel identifier\", func() {\n\t\t\tsuite.coordinator.SetupConnections(path)\n\t\t\tpath.SetChannelOrdered()\n\n\t\t\terr := path.EndpointA.ChanOpenInit()\n\t\t\tsuite.Require().NoError(err)\n\n\t\t\terr = path.EndpointB.ChanOpenTry()\n\t\t\tsuite.Require().NoError(err)\n\n\t\t\tcounterpartyChannelID = \"otheridentifier\"\n\n\t\t\tchannelCap = suite.chainA.GetChannelCapability(path.EndpointA.ChannelConfig.PortID, path.EndpointA.ChannelID)\n\t\t}, false},\n\t\t{\"channel verification failed\", func() {\n\t\t\t// chainB is INIT, chainA in TRYOPEN\n\t\t\tsuite.coordinator.SetupConnections(path)\n\t\t\tpath.SetChannelOrdered()\n\n\t\t\terr := path.EndpointB.ChanOpenInit()\n\t\t\tsuite.Require().NoError(err)\n\n\t\t\terr = path.EndpointA.ChanOpenTry()\n\t\t\tsuite.Require().NoError(err)\n\n\t\t\tchannelCap = suite.chainA.GetChannelCapability(path.EndpointA.ChannelConfig.PortID, path.EndpointA.ChannelID)\n\t\t}, false},\n\t\t{\"channel capability not found\", func() {\n\t\t\tsuite.coordinator.SetupConnections(path)\n\t\t\tpath.SetChannelOrdered()\n\t\t\terr := path.EndpointA.ChanOpenInit()\n\t\t\tsuite.Require().NoError(err)\n\n\t\t\tpath.EndpointB.ChanOpenTry()\n\n\t\t\tchannelCap = capabilitytypes.NewCapability(6)\n\t\t}, false},\n\t}\n\n\tfor _, tc := range testCases {\n\t\ttc := tc\n\t\tsuite.Run(fmt.Sprintf(\"Case %s\", tc.msg), func() {\n\t\t\tsuite.SetupTest() // reset\n\t\t\tcounterpartyChannelID = \"\" // must be explicitly changed in malleate\n\t\t\theightDiff = 0 // must be explicitly changed\n\t\t\tpath = ibctesting.NewPath(suite.chainA, suite.chainB)\n\n\t\t\ttc.malleate()\n\n\t\t\tif counterpartyChannelID == \"\" {\n\t\t\t\tcounterpartyChannelID = ibctesting.FirstChannelID\n\t\t\t}\n\n\t\t\tif path.EndpointA.ClientID != \"\" {\n\t\t\t\t// ensure client is up to date\n\t\t\t\terr := path.EndpointA.UpdateClient()\n\t\t\t\tsuite.Require().NoError(err)\n\t\t\t}\n\n\t\t\tchannelKey := host.ChannelKey(path.EndpointB.ChannelConfig.PortID, ibctesting.FirstChannelID)\n\t\t\tproof, proofHeight := suite.chainB.QueryProof(channelKey)\n\n\t\t\terr := suite.chainA.App.GetIBCKeeper().ChannelKeeper.ChanOpenAck(\n\t\t\t\tsuite.chainA.GetContext(), path.EndpointA.ChannelConfig.PortID, path.EndpointA.ChannelID, channelCap, path.EndpointB.ChannelConfig.Version, counterpartyChannelID,\n\t\t\t\tproof, malleateHeight(proofHeight, heightDiff),\n\t\t\t)\n\n\t\t\tif tc.expPass {\n\t\t\t\tsuite.Require().NoError(err)\n\t\t\t} else {\n\t\t\t\tsuite.Require().Error(err)\n\t\t\t}\n\t\t})\n\t}\n}", "func (_m *ISession) Channel(channelID string, options ...discordgo.RequestOption) (*discordgo.Channel, error) {\n\t_va := make([]interface{}, len(options))\n\tfor _i := range options {\n\t\t_va[_i] = options[_i]\n\t}\n\tvar _ca []interface{}\n\t_ca = append(_ca, channelID)\n\t_ca = append(_ca, _va...)\n\tret := _m.Called(_ca...)\n\n\tvar r0 *discordgo.Channel\n\tvar r1 error\n\tif rf, ok := ret.Get(0).(func(string, ...discordgo.RequestOption) (*discordgo.Channel, error)); ok {\n\t\treturn rf(channelID, options...)\n\t}\n\tif rf, ok := ret.Get(0).(func(string, ...discordgo.RequestOption) *discordgo.Channel); ok {\n\t\tr0 = rf(channelID, options...)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*discordgo.Channel)\n\t\t}\n\t}\n\n\tif rf, ok := ret.Get(1).(func(string, ...discordgo.RequestOption) error); ok {\n\t\tr1 = rf(channelID, options...)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func TestBasicMethodChannelStringCodecHandle(t *testing.T) {\n\tcodec := StringCodec{}\n\tmessenger := NewTestingBinaryMessenger()\n\tchannel := NewBasicMessageChannel(messenger, \"ch\", codec)\n\tchannel.HandleFunc(func(message interface{}) (reply interface{}, err error) {\n\t\tmessageString, ok := message.(string)\n\t\tif !ok {\n\t\t\treturn nil, errors.New(\"message is invalid type, expected string\")\n\t\t}\n\t\treply = messageString + \" world\"\n\t\treturn reply, nil\n\t})\n\tencodedMessage, err := codec.EncodeMessage(\"hello\")\n\tif err != nil {\n\t\tt.Fatalf(\"failed to encode message: %v\", err)\n\t}\n\tencodedReply, err := messenger.MockSend(\"ch\", encodedMessage)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\treply, err := codec.DecodeMessage(encodedReply)\n\tif err != nil {\n\t\tt.Fatalf(\"failed to decode reply: %v\", err)\n\t}\n\tt.Log(spew.Sdump(reply))\n\treplyString, ok := reply.(string)\n\tif !ok {\n\t\tt.Fatal(\"reply is invalid type, expected string\")\n\t}\n\tEqual(t, \"hello world\", replyString)\n}", "func (m *MockSource) TcpSessionChan() chan *types.TcpSession {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"TcpSessionChan\")\n\tret0, _ := ret[0].(chan *types.TcpSession)\n\treturn ret0\n}", "func (_m *MockMessageProducer) ProduceChannel() chan *kafka.Message {\n\tret := _m.Called()\n\n\tvar r0 chan *kafka.Message\n\tif rf, ok := ret.Get(0).(func() chan *kafka.Message); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(chan *kafka.Message)\n\t\t}\n\t}\n\n\treturn r0\n}", "func TestBasicMethodChannelStringCodecSend(t *testing.T) {\n\tcodec := StringCodec{}\n\tmessenger := NewTestingBinaryMessenger()\n\tmessenger.MockSetChannelHandler(\"ch\", func(encodedMessage []byte, r ResponseSender) error {\n\t\tmessage, err := codec.DecodeMessage(encodedMessage)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"failed to decode message\")\n\t\t}\n\t\tmessageString, ok := message.(string)\n\t\tif !ok {\n\t\t\treturn errors.New(\"message is invalid type, expected string\")\n\t\t}\n\t\treply := messageString + \" world\"\n\t\tencodedReply, err := codec.EncodeMessage(reply)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"failed to encode message\")\n\t\t}\n\t\tr.Send(encodedReply)\n\t\treturn nil\n\t})\n\tchannel := NewBasicMessageChannel(messenger, \"ch\", codec)\n\treply, err := channel.SendWithReply(\"hello\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tt.Log(spew.Sdump(reply))\n\treplyString, ok := reply.(string)\n\tif !ok {\n\t\tt.Fatal(\"reply is invalid type, expected string\")\n\t}\n\tEqual(t, \"hello world\", replyString)\n}", "func (_m *Socket) ReadChannel() <-chan *packet.Packet {\n\tret := _m.Called()\n\n\tvar r0 <-chan *packet.Packet\n\tif rf, ok := ret.Get(0).(func() <-chan *packet.Packet); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(<-chan *packet.Packet)\n\t\t}\n\t}\n\n\treturn r0\n}", "func (m *mockedChannel) GetRequestChannel() chan<- *govppapi.VppRequest {\n\treturn m.channel.GetRequestChannel()\n}", "func (m *MockChoriaProvider) Connector() inter.Connector {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Connector\")\n\tret0, _ := ret[0].(inter.Connector)\n\treturn ret0\n}", "func (_m *Knapsack) SetUpdateChannel(channel string) error {\n\tret := _m.Called(channel)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(string) error); ok {\n\t\tr0 = rf(channel)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (_m *Socket) WriteChannel() chan<- *packet.Packet {\n\tret := _m.Called()\n\n\tvar r0 chan<- *packet.Packet\n\tif rf, ok := ret.Get(0).(func() chan<- *packet.Packet); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(chan<- *packet.Packet)\n\t\t}\n\t}\n\n\treturn r0\n}", "func (m *MockWebsocketClientStore) Count(channels ...string) int {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{}\n\tfor _, a := range channels {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"Count\", varargs...)\n\tret0, _ := ret[0].(int)\n\treturn ret0\n}", "func (_m *ChannelRepository) UpdateChannel(channel *model.Channel) error {\n\tret := _m.Called(channel)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(*model.Channel) error); ok {\n\t\tr0 = rf(channel)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func TestGetChannel(t *testing.T) {\n\tclearTable()\n\taddChannel(1)\n\t// Generate JWT for authorization.\n\tvalidToken, err := auth.GenerateJWT()\n\tif err != nil {\n\t\tt.Error(\"Failed to generate token\")\n\t}\n\n\treq, _ := http.NewRequest(\"GET\", \"/api/channel/\"+channelTestID.String(), nil)\n\t// Add \"Token\" header to request with generated token.\n\treq.Header.Add(\"Token\", validToken)\n\tresponse := executeRequest(req)\n\n\tcheckResponseCode(t, http.StatusOK, response.Code)\n}", "func (suite *KeeperTestSuite) TestChanOpenTry() {\n\tvar (\n\t\tpath *ibctesting.Path\n\t\tpreviousChannelID string\n\t\tportCap *capabilitytypes.Capability\n\t\theightDiff uint64\n\t)\n\n\ttestCases := []testCase{\n\t\t{\"success\", func() {\n\t\t\tsuite.coordinator.SetupConnections(path)\n\t\t\tpath.SetChannelOrdered()\n\t\t\tpath.EndpointA.ChanOpenInit()\n\n\t\t\tsuite.chainB.CreatePortCapability(suite.chainB.GetSimApp().ScopedIBCMockKeeper, ibctesting.MockPort)\n\t\t\tportCap = suite.chainB.GetPortCapability(ibctesting.MockPort)\n\t\t}, true},\n\t\t{\"success with crossing hello\", func() {\n\t\t\tsuite.coordinator.SetupConnections(path)\n\t\t\tpath.SetChannelOrdered()\n\t\t\terr := suite.coordinator.ChanOpenInitOnBothChains(path)\n\t\t\tsuite.Require().NoError(err)\n\n\t\t\tpreviousChannelID = path.EndpointB.ChannelID\n\t\t\tportCap = suite.chainB.GetPortCapability(ibctesting.MockPort)\n\t\t}, true},\n\t\t{\"previous channel with invalid state\", func() {\n\t\t\tsuite.coordinator.SetupConnections(path)\n\n\t\t\t// make previous channel have wrong ordering\n\t\t\tpath.EndpointA.ChanOpenInit()\n\t\t}, false},\n\t\t{\"connection doesn't exist\", func() {\n\t\t\tpath.EndpointA.ConnectionID = ibctesting.FirstConnectionID\n\t\t\tpath.EndpointB.ConnectionID = ibctesting.FirstConnectionID\n\n\t\t\t// pass capability check\n\t\t\tsuite.chainB.CreatePortCapability(suite.chainB.GetSimApp().ScopedIBCMockKeeper, ibctesting.MockPort)\n\t\t\tportCap = suite.chainB.GetPortCapability(ibctesting.MockPort)\n\t\t}, false},\n\t\t{\"connection is not OPEN\", func() {\n\t\t\tsuite.coordinator.SetupClients(path)\n\t\t\t// pass capability check\n\t\t\tsuite.chainB.CreatePortCapability(suite.chainB.GetSimApp().ScopedIBCMockKeeper, ibctesting.MockPort)\n\t\t\tportCap = suite.chainB.GetPortCapability(ibctesting.MockPort)\n\n\t\t\terr := path.EndpointB.ConnOpenInit()\n\t\t\tsuite.Require().NoError(err)\n\t\t}, false},\n\t\t{\"consensus state not found\", func() {\n\t\t\tsuite.coordinator.SetupConnections(path)\n\t\t\tpath.SetChannelOrdered()\n\t\t\tpath.EndpointA.ChanOpenInit()\n\n\t\t\tsuite.chainB.CreatePortCapability(suite.chainB.GetSimApp().ScopedIBCMockKeeper, ibctesting.MockPort)\n\t\t\tportCap = suite.chainB.GetPortCapability(ibctesting.MockPort)\n\n\t\t\theightDiff = 3 // consensus state doesn't exist at this height\n\t\t}, false},\n\t\t{\"channel verification failed\", func() {\n\t\t\t// not creating a channel on chainA will result in an invalid proof of existence\n\t\t\tsuite.coordinator.SetupConnections(path)\n\t\t\tportCap = suite.chainB.GetPortCapability(ibctesting.MockPort)\n\t\t}, false},\n\t\t{\"port capability not found\", func() {\n\t\t\tsuite.coordinator.SetupConnections(path)\n\t\t\tpath.SetChannelOrdered()\n\t\t\tpath.EndpointA.ChanOpenInit()\n\n\t\t\tportCap = capabilitytypes.NewCapability(3)\n\t\t}, false},\n\t\t{\"connection version not negotiated\", func() {\n\t\t\tsuite.coordinator.SetupConnections(path)\n\t\t\tpath.SetChannelOrdered()\n\t\t\tpath.EndpointA.ChanOpenInit()\n\n\t\t\t// modify connB versions\n\t\t\tconn := path.EndpointB.GetConnection()\n\n\t\t\tversion := connectiontypes.NewVersion(\"2\", []string{\"ORDER_ORDERED\", \"ORDER_UNORDERED\"})\n\t\t\tconn.Versions = append(conn.Versions, version)\n\n\t\t\tsuite.chainB.App.GetIBCKeeper().ConnectionKeeper.SetConnection(\n\t\t\t\tsuite.chainB.GetContext(),\n\t\t\t\tpath.EndpointB.ConnectionID, conn,\n\t\t\t)\n\t\t\tsuite.chainB.CreatePortCapability(suite.chainB.GetSimApp().ScopedIBCMockKeeper, ibctesting.MockPort)\n\t\t\tportCap = suite.chainB.GetPortCapability(ibctesting.MockPort)\n\t\t}, false},\n\t\t{\"connection does not support ORDERED channels\", func() {\n\t\t\tsuite.coordinator.SetupConnections(path)\n\t\t\tpath.SetChannelOrdered()\n\t\t\tpath.EndpointA.ChanOpenInit()\n\n\t\t\t// modify connA versions to only support UNORDERED channels\n\t\t\tconn := path.EndpointA.GetConnection()\n\n\t\t\tversion := connectiontypes.NewVersion(\"1\", []string{\"ORDER_UNORDERED\"})\n\t\t\tconn.Versions = []*connectiontypes.Version{version}\n\n\t\t\tsuite.chainA.App.GetIBCKeeper().ConnectionKeeper.SetConnection(\n\t\t\t\tsuite.chainA.GetContext(),\n\t\t\t\tpath.EndpointA.ConnectionID, conn,\n\t\t\t)\n\t\t\tsuite.chainA.CreatePortCapability(suite.chainA.GetSimApp().ScopedIBCMockKeeper, ibctesting.MockPort)\n\t\t\tportCap = suite.chainA.GetPortCapability(ibctesting.MockPort)\n\t\t}, false},\n\t}\n\n\tfor _, tc := range testCases {\n\t\ttc := tc\n\t\tsuite.Run(fmt.Sprintf(\"Case %s\", tc.msg), func() {\n\t\t\tsuite.SetupTest() // reset\n\t\t\theightDiff = 0 // must be explicitly changed in malleate\n\t\t\tpreviousChannelID = \"\"\n\t\t\tpath = ibctesting.NewPath(suite.chainA, suite.chainB)\n\n\t\t\ttc.malleate()\n\n\t\t\tif path.EndpointB.ClientID != \"\" {\n\t\t\t\t// ensure client is up to date\n\t\t\t\terr := path.EndpointB.UpdateClient()\n\t\t\t\tsuite.Require().NoError(err)\n\t\t\t}\n\n\t\t\tcounterparty := types.NewCounterparty(path.EndpointB.ChannelConfig.PortID, ibctesting.FirstChannelID)\n\n\t\t\tchannelKey := host.ChannelKey(counterparty.PortId, counterparty.ChannelId)\n\t\t\tproof, proofHeight := suite.chainA.QueryProof(channelKey)\n\n\t\t\tchannelID, cap, err := suite.chainB.App.GetIBCKeeper().ChannelKeeper.ChanOpenTry(\n\t\t\t\tsuite.chainB.GetContext(), types.ORDERED, []string{path.EndpointB.ConnectionID},\n\t\t\t\tpath.EndpointB.ChannelConfig.PortID, previousChannelID, portCap, counterparty, path.EndpointB.ChannelConfig.Version, path.EndpointA.ChannelConfig.Version,\n\t\t\t\tproof, malleateHeight(proofHeight, heightDiff),\n\t\t\t)\n\n\t\t\tif tc.expPass {\n\t\t\t\tsuite.Require().NoError(err)\n\t\t\t\tsuite.Require().NotNil(cap)\n\n\t\t\t\tchanCap, ok := suite.chainB.App.GetScopedIBCKeeper().GetCapability(\n\t\t\t\t\tsuite.chainB.GetContext(),\n\t\t\t\t\thost.ChannelCapabilityPath(path.EndpointB.ChannelConfig.PortID, channelID),\n\t\t\t\t)\n\t\t\t\tsuite.Require().True(ok, \"could not retrieve channel capapbility after successful ChanOpenTry\")\n\t\t\t\tsuite.Require().Equal(chanCap.String(), cap.String(), \"channel capability is not correct\")\n\t\t\t} else {\n\t\t\t\tsuite.Require().Error(err)\n\t\t\t}\n\t\t})\n\t}\n}", "func TestChannelEvents(t *testing.T) {\n\ttc := testutil.SystemTest(t)\n\tbuf := &bytes.Buffer{}\n\n\t// Test setup\n\n\t// Stop and delete the default channel if it exists\n\tif err := getChannel(buf, tc.ProjectID, location, channelID); err == nil {\n\t\ttestutil.Retry(t, 3, 2*time.Second, func(r *testutil.R) {\n\t\t\tif err := stopChannel(buf, tc.ProjectID, location, channelID); err != nil {\n\t\t\t\t// Ignore the error when the channel is already stopped.\n\t\t\t}\n\t\t})\n\n\t\ttestutil.Retry(t, 3, 2*time.Second, func(r *testutil.R) {\n\t\t\tif err := deleteChannel(buf, tc.ProjectID, location, channelID); err != nil {\n\t\t\t\tr.Errorf(\"deleteChannel got err: %v\", err)\n\t\t\t}\n\t\t})\n\t}\n\n\t// Delete the default input if it exists\n\tif err := getInput(buf, tc.ProjectID, location, inputID); err == nil {\n\t\ttestutil.Retry(t, 3, 2*time.Second, func(r *testutil.R) {\n\t\t\tif err := deleteInput(buf, tc.ProjectID, location, inputID); err != nil {\n\t\t\t\tr.Errorf(\"deleteInput got err: %v\", err)\n\t\t\t}\n\t\t})\n\t}\n\n\t// Create a new input.\n\ttestutil.Retry(t, 3, 2*time.Second, func(r *testutil.R) {\n\t\tinputName := fmt.Sprintf(\"projects/%s/locations/%s/inputs/%s\", tc.ProjectID, location, inputID)\n\t\tif err := createInput(buf, tc.ProjectID, location, inputID); err != nil {\n\t\t\tr.Errorf(\"createInput got err: %v\", err)\n\t\t}\n\t\tif got := buf.String(); !strings.Contains(got, inputName) {\n\t\t\tr.Errorf(\"createInput got\\n----\\n%v\\n----\\nWant to contain:\\n----\\n%v\\n----\\n\", got, inputName)\n\t\t}\n\t})\n\n\t// Create a new channel.\n\ttestutil.Retry(t, 3, 2*time.Second, func(r *testutil.R) {\n\t\tchannelName := fmt.Sprintf(\"projects/%s/locations/%s/channels/%s\", tc.ProjectID, location, channelID)\n\t\tif err := createChannel(buf, tc.ProjectID, location, channelID, inputID, outputURI); err != nil {\n\t\t\tr.Errorf(\"createChannel got err: %v\", err)\n\t\t}\n\t\tif got := buf.String(); !strings.Contains(got, channelName) {\n\t\t\tr.Errorf(\"createChannel got\\n----\\n%v\\n----\\nWant to contain:\\n----\\n%v\\n----\\n\", got, channelName)\n\t\t}\n\t})\n\n\t// Start the channel.\n\ttestutil.Retry(t, 3, 2*time.Second, func(r *testutil.R) {\n\t\tif err := startChannel(buf, tc.ProjectID, location, channelID); err != nil {\n\t\t\tr.Errorf(\"startChannel got err: %v\", err)\n\t\t}\n\t\tif got := buf.String(); !strings.Contains(got, startChannelResponse) {\n\t\t\tr.Errorf(\"startChannel got\\n----\\n%v\\n----\\nWant to contain:\\n----\\n%v\\n----\\n\", got, startChannelResponse)\n\t\t}\n\t})\n\n\tbuf.Reset()\n\n\t// Tests\n\n\t// Create a new channel event.\n\ttestutil.Retry(t, 3, 2*time.Second, func(r *testutil.R) {\n\t\teventName := fmt.Sprintf(\"projects/%s/locations/%s/channels/%s/events/%s\", tc.ProjectID, location, channelID, eventID)\n\t\tif err := createChannelEvent(buf, tc.ProjectID, location, channelID, eventID); err != nil {\n\t\t\tr.Errorf(\"createChannelEvent got err: %v\", err)\n\t\t}\n\t\tif got := buf.String(); !strings.Contains(got, eventName) {\n\t\t\tr.Errorf(\"createChannelEvent got\\n----\\n%v\\n----\\nWant to contain:\\n----\\n%v\\n----\\n\", got, eventName)\n\t\t}\n\t})\n\tbuf.Reset()\n\n\t// List the channel events for a given channel.\n\ttestutil.Retry(t, 3, 2*time.Second, func(r *testutil.R) {\n\t\teventName := fmt.Sprintf(\"projects/%s/locations/%s/channels/%s/events/%s\", tc.ProjectID, location, channelID, eventID)\n\t\tif err := listChannelEvents(buf, tc.ProjectID, location, channelID); err != nil {\n\t\t\tr.Errorf(\"listChannelEvents got err: %v\", err)\n\t\t}\n\t\tif got := buf.String(); !strings.Contains(got, eventName) {\n\t\t\tr.Errorf(\"listChannelEvents got\\n----\\n%v\\n----\\nWant to contain:\\n----\\n%v\\n----\\n\", got, eventName)\n\t\t}\n\t})\n\tbuf.Reset()\n\n\t// Get the channel event.\n\ttestutil.Retry(t, 3, 2*time.Second, func(r *testutil.R) {\n\t\teventName := fmt.Sprintf(\"projects/%s/locations/%s/channels/%s/events/%s\", tc.ProjectID, location, channelID, eventID)\n\t\tif err := getChannelEvent(buf, tc.ProjectID, location, channelID, eventID); err != nil {\n\t\t\tr.Errorf(\"getChannelEvent got err: %v\", err)\n\t\t}\n\t\tif got := buf.String(); !strings.Contains(got, eventName) {\n\t\t\tr.Errorf(\"getChannelEvent got\\n----\\n%v\\n----\\nWant to contain:\\n----\\n%v\\n----\\n\", got, eventName)\n\t\t}\n\t})\n\tbuf.Reset()\n\n\t// Delete the channel event.\n\ttestutil.Retry(t, 3, 2*time.Second, func(r *testutil.R) {\n\t\tif err := deleteChannelEvent(buf, tc.ProjectID, location, channelID, eventID); err != nil {\n\t\t\tr.Errorf(\"deleteChannelEvent got err: %v\", err)\n\t\t}\n\t\tif got := buf.String(); !strings.Contains(got, deleteChannelEventResponse) {\n\t\t\tr.Errorf(\"deleteChannelEvent got\\n----\\n%v\\n----\\nWant to contain:\\n----\\n%v\\n----\\n\", got, deleteChannelEventResponse)\n\t\t}\n\t})\n\n\t// Clean up\n\n\t// Stop the channel.\n\ttestutil.Retry(t, 3, 2*time.Second, func(r *testutil.R) {\n\t\tif err := stopChannel(buf, tc.ProjectID, location, channelID); err != nil {\n\t\t\tr.Errorf(\"stopChannel got err: %v\", err)\n\t\t}\n\t\tif got := buf.String(); !strings.Contains(got, stopChannelResponse) {\n\t\t\tr.Errorf(\"stopChannel got\\n----\\n%v\\n----\\nWant to contain:\\n----\\n%v\\n----\\n\", got, stopChannelResponse)\n\t\t}\n\t})\n\n\t// Delete the channel.\n\ttestutil.Retry(t, 3, 2*time.Second, func(r *testutil.R) {\n\t\tif err := deleteChannel(buf, tc.ProjectID, location, channelID); err != nil {\n\t\t\tr.Errorf(\"deleteChannel got err: %v\", err)\n\t\t}\n\t\tif got := buf.String(); !strings.Contains(got, deleteChannelResponse) {\n\t\t\tr.Errorf(\"deleteChannel got\\n----\\n%v\\n----\\nWant to contain:\\n----\\n%v\\n----\\n\", got, deleteChannelResponse)\n\t\t}\n\t})\n\n\t// Delete the input.\n\ttestutil.Retry(t, 3, 2*time.Second, func(r *testutil.R) {\n\t\tif err := deleteInput(buf, tc.ProjectID, location, inputID); err != nil {\n\t\t\tr.Errorf(\"deleteInput got err: %v\", err)\n\t\t}\n\t\tif got := buf.String(); !strings.Contains(got, deleteInputResponse) {\n\t\t\tr.Errorf(\"deleteInput got\\n----\\n%v\\n----\\nWant to contain:\\n----\\n%v\\n----\\n\", got, deleteInputResponse)\n\t\t}\n\t})\n\tt.Logf(\"\\nTestChannelEvents() completed\\n\")\n}", "func (m *MockCall) ResultChan() chan hrpc.RPCResult {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ResultChan\")\n\tret0, _ := ret[0].(chan hrpc.RPCResult)\n\treturn ret0\n}", "func (_m *WebSocketServer) GetChannels(topic string) (chan<- interface{}, chan<- interface{}, <-chan error, <-chan struct{}) {\n\tret := _m.Called(topic)\n\n\tvar r0 chan<- interface{}\n\tif rf, ok := ret.Get(0).(func(string) chan<- interface{}); ok {\n\t\tr0 = rf(topic)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(chan<- interface{})\n\t\t}\n\t}\n\n\tvar r1 chan<- interface{}\n\tif rf, ok := ret.Get(1).(func(string) chan<- interface{}); ok {\n\t\tr1 = rf(topic)\n\t} else {\n\t\tif ret.Get(1) != nil {\n\t\t\tr1 = ret.Get(1).(chan<- interface{})\n\t\t}\n\t}\n\n\tvar r2 <-chan error\n\tif rf, ok := ret.Get(2).(func(string) <-chan error); ok {\n\t\tr2 = rf(topic)\n\t} else {\n\t\tif ret.Get(2) != nil {\n\t\t\tr2 = ret.Get(2).(<-chan error)\n\t\t}\n\t}\n\n\tvar r3 <-chan struct{}\n\tif rf, ok := ret.Get(3).(func(string) <-chan struct{}); ok {\n\t\tr3 = rf(topic)\n\t} else {\n\t\tif ret.Get(3) != nil {\n\t\t\tr3 = ret.Get(3).(<-chan struct{})\n\t\t}\n\t}\n\n\treturn r0, r1, r2, r3\n}", "func (_m *ChannelStore) Update(channel *model.Channel) (*model.Channel, error) {\n\tret := _m.Called(channel)\n\n\tvar r0 *model.Channel\n\tif rf, ok := ret.Get(0).(func(*model.Channel) *model.Channel); ok {\n\t\tr0 = rf(channel)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*model.Channel)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(*model.Channel) error); ok {\n\t\tr1 = rf(channel)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func TestChannelDelete(t *testing.T) {\n\t// delete this channel\n\twrt := channels[0]\n\n\t// create the mock repo and controller.\n\t// the deletion itself has no bearing on the test\n\t// so just use the findID function which has the the same signature\n\t// and performs the operation we need\n\trepo := &mock.ChannelRepo{DeleteIDFunc: findChannelID}\n\tcontroller := NewChannel(repo)\n\n\t// create a mock request\n\tp := httprouter.Param{Key: \"id\", Value: \"1\"}\n\treq, e := http.NewRequest(http.MethodDelete, \"/channel/\"+p.Value, nil)\n\n\tif e != nil {\n\t\tt.Fatal(e)\n\t}\n\n\t// embed params necessary for controller function\n\tuf.EmbedParams(req, p)\n\n\t// create a response recorder and call the delete method\n\tw := httptest.NewRecorder()\n\te = controller.Delete(w, req)\n\n\tif e != nil {\n\t\tt.Fatal(e)\n\t}\n\n\tres := w.Result()\n\n\t// check if the repo was hit\n\tif !repo.DeleteIDCalled {\n\t\tt.Error(\"Did not call repo.DeleteID\")\n\t}\n\n\t// ensure the content type is application/json\n\tcheckCT(res, t)\n\n\t// extract the body and check the correct channel was returned\n\tdefer res.Body.Close()\n\tbody, e := io.ReadAll(res.Body)\n\n\tif e != nil {\n\t\tt.Fatal(e)\n\t}\n\n\treceived := &are_hub.Channel{}\n\te = json.Unmarshal(body, received)\n\n\tif e != nil {\n\t\tt.Fatal(e)\n\t}\n\n\tif received.Name != wrt.Name {\n\t\tt.Fatalf(\"Expected: %v. Actual: %v.\", wrt, received)\n\t}\n\n\t// check delete returns 404 for an invalid ID\n\tp = httprouter.Param{Key: \"id\", Value: \"-1\"}\n\ttest404(t, http.MethodDelete, \"/channel/\"+p.Value, nil, controller.Delete, p)\n}", "func (m *MockCache) Watch(ch chan<- stream.Event, replay bool) (stream.Context, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Watch\", ch, replay)\n\tret0, _ := ret[0].(stream.Context)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func TestChannelShow(t *testing.T) {\n\t// expecting this channel\n\twrt := channels[0]\n\n\t// create the mock repo and controller\n\trepo := &mock.ChannelRepo{FindIDFunc: findChannelID}\n\tcontroller := NewChannel(repo)\n\n\t// create a mock request\n\tp := httprouter.Param{Key: \"id\", Value: \"1\"}\n\treq, e := http.NewRequest(http.MethodGet, \"/channel/\"+p.Value, nil)\n\n\tif e != nil {\n\t\tt.Fatal(e)\n\t}\n\n\t// embed the channel ID in the request's\n\t// context (necessary for controller.Show to function)\n\tuf.EmbedParams(req, httprouter.Param{Key: \"id\", Value: \"1\"})\n\n\t// create a response recorder and call the show method\n\tw := httptest.NewRecorder()\n\te = controller.Show(w, req)\n\n\tif e != nil {\n\t\tt.Fatal(e)\n\t}\n\n\t// check the repo was hit\n\tif !repo.FindIDCalled {\n\t\tt.Error(\"Did not call repo.FindID\")\n\t}\n\n\tres := w.Result()\n\n\t// ensure the content type is application/json\n\tcheckCT(res, t)\n\n\t// read and unmarshal the body\n\tdefer res.Body.Close()\n\tbody, e := io.ReadAll(res.Body)\n\n\tif e != nil {\n\t\tt.Fatal(e)\n\t}\n\n\treceived := are_hub.Channel{}\n\te = json.Unmarshal(body, &received)\n\n\tif e != nil {\n\t\tt.Fatal(e)\n\t}\n\n\t// compare the expected and received channels\n\tif received.Name != wrt.Name {\n\t\tt.Fatalf(\"Expected: %+v. Actual: %+v.\", wrt, received)\n\t}\n\n\t// check show returns 404 for an invalid ID\n\tp = httprouter.Param{Key: \"id\", Value: \"-1\"}\n\ttest404(t, http.MethodGet, \"/channel/\"+p.Value, nil, controller.Show, p)\n}", "func (m *MockClientStreamConnection) Dispatch(buffer buffer.IoBuffer) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"Dispatch\", buffer)\n}", "func (m *MockAMQPChan) Close() {\n\tm.ctrl.Call(m, \"Close\")\n}", "func (m *MockWebsocketClientStore) Find(fn wspubsub.IterateFunc, channels ...string) error {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{fn}\n\tfor _, a := range channels {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"Find\", varargs...)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (res channelBase) Channel() *types.Channel {\n\treturn res.channel\n}", "func (m *mockedChannel) GetReplyChannel() <-chan *govppapi.VppReply {\n\treturn m.channel.GetReplyChannel()\n}", "func (m *MockStreamConnection) Dispatch(buffer buffer.IoBuffer) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"Dispatch\", buffer)\n}", "func TestCollateralizedChannels(t *testing.T) {\n\trequire := require.New(t)\n\n\t// Accounts\n\taccountFunding := []struct {\n\t\tPrivateKey string\n\t\tBalanceEth uint\n\t}{\n\t\t{\"0x50b4713b4ba55b6fbcb826ae04e66c03a12fc62886a90ca57ab541959337e897\", 10}, // Contract Deployer\n\t\t{\"0x1af2e950272dd403de7a5760d41c6e44d92b6d02797e51810795ff03cc2cda4f\", 100}, // Client1\n\t\t{\"0xf63d7d8e930bccd74e93cf5662fde2c28fd8be95edb70c73f1bdd863d07f412e\", 200}, // Client2\n\t}\n\n\t// Ganache config\n\tganacheCmd := os.Getenv(\"GANACHE_CMD\")\n\tif len(ganacheCmd) == 0 {\n\t\tganacheCmd = \"ganache-cli\"\n\t}\n\tganacheCfg := ganache.GanacheConfig{\n\t\tCmd: ganacheCmd,\n\t\tHost: \"127.0.0.1\",\n\t\tPort: 8545,\n\t\tBlockTime: 1 * time.Second,\n\t\tFunding: accountFunding,\n\t\tStartupTime: 3 * time.Second,\n\t}\n\n\t// More test parameters\n\tvar (\n\t\tdefaultContextTimeout = 30 * time.Second\n\t\tcollateralWithdrawalDelay = 10 * ganacheCfg.BlockTime\n\t\thostClient1 = \"127.0.0.1:8546\"\n\t\thostClient2 = \"127.0.0.1:8547\"\n\t\tcollateralClient1 = eth.EthToWei(big.NewFloat(50))\n\t\tpayment1Client1ToClient2 = eth.EthToWei(big.NewFloat(5))\n\t\tchannelFundingClient1 = eth.EthToWei(big.NewFloat(25))\n\t\tpayment2Client1ToClient2 = eth.EthToWei(big.NewFloat(10))\n\t)\n\n\t// Start ganache blockchain with prefunded accounts\n\tlog.Print(\"Starting local blockchain...\")\n\tganache, err := ganache.StartGanacheWithPrefundedAccounts(ganacheCfg)\n\trequire.NoError(err, \"starting ganache\")\n\tdefer ganache.Shutdown()\n\n\t// Deploy contracts\n\tlog.Print(\"Deploying contracts...\")\n\tnodeURL := fmt.Sprintf(\"ws://%s:%d\", ganacheCfg.Host, ganacheCfg.Port)\n\tdeploymentKey := ganache.Accounts[0].PrivateKey\n\tcontracts, err := deployContracts(nodeURL, deploymentKey, defaultContextTimeout, collateralWithdrawalDelay)\n\trequire.NoError(err, \"deploying contracts\")\n\n\t// Helper function for client setup\n\tgenClientDef := func(privateKey *ecdsa.PrivateKey, host string, peerAddress common.Address, peerHost string) client.ClientConfig {\n\t\treturn client.ClientConfig{\n\t\t\tClientConfig: perun.ClientConfig{\n\t\t\t\tPrivateKey: privateKey,\n\t\t\t\tHost: host,\n\t\t\t\tETHNodeURL: nodeURL,\n\t\t\t\tAdjudicatorAddr: contracts.AdjudicatorAddr,\n\t\t\t\tAssetHolderAddr: contracts.AssetHolderAddr,\n\t\t\t\tDialerTimeout: 1 * time.Second,\n\t\t\t\tPeerAddresses: []perun.PeerWithAddress{\n\t\t\t\t\t{\n\t\t\t\t\t\tPeer: wallet.AsWalletAddr(peerAddress),\n\t\t\t\t\t\tAddress: peerHost,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tChallengeDuration: collateralWithdrawalDelay / 2,\n\t\t\tAppAddress: contracts.AppAddr,\n\t\t\tContextTimeout: defaultContextTimeout,\n\t\t}\n\t}\n\n\tlog.Print(\"Setting up clients...\")\n\t// Setup Client1\n\tclientDef1 := genClientDef(\n\t\tganache.Accounts[1].PrivateKey, hostClient1,\n\t\tganache.Accounts[2].Address(), hostClient2,\n\t)\n\tpaymentAcceptancePolicy1 := func(\n\t\tamount, collateral, funding, balance *big.Int,\n\t\thasOverdrawn bool,\n\t) (ok bool) {\n\t\treturn true\n\t}\n\tc1, err := client.SetupClient(\n\t\tclientDef1,\n\t\tpaymentAcceptancePolicy1,\n\t)\n\trequire.NoError(err, \"Client1 setup\")\n\n\t// Setup Client2\n\tclientDef2 := genClientDef(ganache.\n\t\tAccounts[2].PrivateKey, hostClient2,\n\t\tganache.Accounts[1].Address(), hostClient1,\n\t)\n\tpaymentAcceptancePolicy2 := func(\n\t\tamount, collateral, funding, balance *big.Int,\n\t\thasOverdrawn bool,\n\t) (ok bool) {\n\t\t// We reject unfunded payments if they exceed 10% of the collateral.\n\t\tbalanceFundingDiff := new(big.Int).Sub(funding, balance)\n\t\tcollateral10percent := new(big.Int).Div(collateral, big.NewInt(10))\n\t\tif balanceFundingDiff.Sign() < 0 && balanceFundingDiff.Cmp(collateral10percent) < 0 {\n\t\t\treturn false\n\t\t}\n\n\t\t// We accept all other payments.\n\t\treturn true\n\t}\n\tc2, err := client.SetupClient(\n\t\tclientDef2,\n\t\tpaymentAcceptancePolicy2,\n\t)\n\trequire.NoError(err, \"Client2 setup\")\n\n\te := &Environment{map[common.Address]string{\n\t\tc1.Address(): \"Client1\",\n\t\tc2.Address(): \"Client2\",\n\t}}\n\te.logAccountBalance(c1, c2)\n\tlog.Print(\"Setup done.\")\n\n\t// Deposit Client1 collateral\n\tlog.Printf(\"Client1: Depositing %v as collateral...\", toEth(collateralClient1))\n\terr = c1.IncreaseCollateral(collateralClient1)\n\trequire.NoError(err, \"increasing Client1 collateral\")\n\te.logAccountBalance(c1)\n\n\t// Send payment from Client1 to Client2\n\tlog.Printf(\"Client1: Sending %v to Client2...\", toEth(payment1Client1ToClient2))\n\terr = c1.SendPayment(c2.Address(), payment1Client1ToClient2) // open unfunded channel, handle channel proposal, transfer amount, handle update\n\trequire.NoError(err, \"Client1 sending payment to Client2\")\n\te.logChannelBalances(c1, c2)\n\n\t// Client1 deposits channel funding\n\tlog.Printf(\"Client1: Depositing %v as channel funding...\", toEth(channelFundingClient1))\n\terr = c1.IncreaseChannelCollateral(c2.Address(), channelFundingClient1)\n\trequire.NoError(err, \"Client1 increasing channel funding\")\n\te.logAccountBalance(c1)\n\te.logChannelBalances(c1)\n\n\t// Client1 sends another payment to Client2\n\tlog.Printf(\"Client1: Sending %v to Client2...\", toEth(payment2Client1ToClient2))\n\terr = c1.SendPayment(c2.Address(), payment2Client1ToClient2) // send another payment\n\trequire.NoError(err, \"Client1 sending another payment to Client2\")\n\te.logChannelBalances(c1, c2)\n\n\t// Client2 settles the channel and withdraws the received payments\n\tlog.Print(\"Client2: Settling channel...\")\n\terr = c2.Settle(c1.Address()) // c2 settles channel with c1\n\trequire.NoError(err, \"Client2 settling the channel\")\n\te.logAccountBalance(c2)\n\n\tlog.Print(\"Done.\")\n}", "func (m *MockServerStreamConnection) Dispatch(buffer buffer.IoBuffer) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"Dispatch\", buffer)\n}", "func (m *MockisTcpCbKeyHandle_KeyOrHandle) isTcpCbKeyHandle_KeyOrHandle() {\n\tm.ctrl.Call(m, \"isTcpCbKeyHandle_KeyOrHandle\")\n}", "func (_m *ISession) ThreadStart(channelID string, name string, typ discordgo.ChannelType, archiveDuration int, options ...discordgo.RequestOption) (*discordgo.Channel, error) {\n\t_va := make([]interface{}, len(options))\n\tfor _i := range options {\n\t\t_va[_i] = options[_i]\n\t}\n\tvar _ca []interface{}\n\t_ca = append(_ca, channelID, name, typ, archiveDuration)\n\t_ca = append(_ca, _va...)\n\tret := _m.Called(_ca...)\n\n\tvar r0 *discordgo.Channel\n\tvar r1 error\n\tif rf, ok := ret.Get(0).(func(string, string, discordgo.ChannelType, int, ...discordgo.RequestOption) (*discordgo.Channel, error)); ok {\n\t\treturn rf(channelID, name, typ, archiveDuration, options...)\n\t}\n\tif rf, ok := ret.Get(0).(func(string, string, discordgo.ChannelType, int, ...discordgo.RequestOption) *discordgo.Channel); ok {\n\t\tr0 = rf(channelID, name, typ, archiveDuration, options...)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*discordgo.Channel)\n\t\t}\n\t}\n\n\tif rf, ok := ret.Get(1).(func(string, string, discordgo.ChannelType, int, ...discordgo.RequestOption) error); ok {\n\t\tr1 = rf(channelID, name, typ, archiveDuration, options...)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (_m *mockCopyCat) SubscribeToDataStructure(id *copycat.ID, provider copycat.SnapshotProvider) (chan<- []byte, <-chan []byte, <-chan error, copycat.SnapshotConsumer, error) {\n\tret := _m.Called(id, provider)\n\n\tvar r0 chan<- []byte\n\tif rf, ok := ret.Get(0).(func(*copycat.ID, copycat.SnapshotProvider) chan<- []byte); ok {\n\t\tr0 = rf(id, provider)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(chan<- []byte)\n\t\t}\n\t}\n\n\tvar r1 <-chan []byte\n\tif rf, ok := ret.Get(1).(func(*copycat.ID, copycat.SnapshotProvider) <-chan []byte); ok {\n\t\tr1 = rf(id, provider)\n\t} else {\n\t\tif ret.Get(1) != nil {\n\t\t\tr1 = ret.Get(1).(<-chan []byte)\n\t\t}\n\t}\n\n\tvar r2 <-chan error\n\tif rf, ok := ret.Get(2).(func(*copycat.ID, copycat.SnapshotProvider) <-chan error); ok {\n\t\tr2 = rf(id, provider)\n\t} else {\n\t\tif ret.Get(2) != nil {\n\t\t\tr2 = ret.Get(2).(<-chan error)\n\t\t}\n\t}\n\n\tvar r3 copycat.SnapshotConsumer\n\tif rf, ok := ret.Get(3).(func(*copycat.ID, copycat.SnapshotProvider) copycat.SnapshotConsumer); ok {\n\t\tr3 = rf(id, provider)\n\t} else {\n\t\tif ret.Get(3) != nil {\n\t\t\tr3 = ret.Get(3).(copycat.SnapshotConsumer)\n\t\t}\n\t}\n\n\tvar r4 error\n\tif rf, ok := ret.Get(4).(func(*copycat.ID, copycat.SnapshotProvider) error); ok {\n\t\tr4 = rf(id, provider)\n\t} else {\n\t\tr4 = ret.Error(4)\n\t}\n\n\treturn r0, r1, r2, r3, r4\n}", "func SmokeTestChannelImpl(t *testing.T) {\n\tclient := Setup(t, true)\n\tdefer TearDown(client)\n\n\tinstaller := NewInstaller(client.Dynamic, map[string]string{\n\t\t\"namespace\": client.Namespace,\n\t}, EndToEndConfigYaml([]string{\"smoke_test\", \"istio\"})...)\n\n\t// Create the resources for the test.\n\tif err := installer.Do(\"create\"); err != nil {\n\t\tt.Errorf(\"failed to create, %s\", err)\n\t\treturn\n\t}\n\n\t// Delete deferred.\n\tdefer func() {\n\t\tif err := installer.Do(\"delete\"); err != nil {\n\t\t\tt.Errorf(\"failed to create, %s\", err)\n\t\t}\n\t\t// Just chill for tick.\n\t\ttime.Sleep(10 * time.Second)\n\t}()\n\n\tif err := client.WaitForResourceReady(client.Namespace, \"e2e-smoke-test\", schema.GroupVersionResource{\n\t\tGroup: \"messaging.cloud.google.com\",\n\t\tVersion: \"v1alpha1\",\n\t\tResource: \"channels\",\n\t}); err != nil {\n\t\tt.Error(err)\n\t}\n}", "func getChannel(client fab.Resource, channelID string) (fab.Channel, error) {\n\n\tchannel, err := client.NewChannel(channelID)\n\tif err != nil {\n\t\treturn nil, errors.WithMessage(err, \"NewChannel failed\")\n\t}\n\n\tchCfg, err := client.Config().ChannelConfig(channel.Name())\n\tif err != nil || chCfg == nil {\n\t\treturn nil, errors.Errorf(\"reading channel config failed: %s\", err)\n\t}\n\n\tchOrderers, err := client.Config().ChannelOrderers(channel.Name())\n\tif err != nil {\n\t\treturn nil, errors.WithMessage(err, \"reading channel orderers failed\")\n\t}\n\n\tfor _, ordererCfg := range chOrderers {\n\n\t\torderer, err := orderer.New(client.Config(), orderer.FromOrdererConfig(&ordererCfg))\n\t\tif err != nil {\n\t\t\treturn nil, errors.WithMessage(err, \"creating orderer failed\")\n\t\t}\n\t\terr = channel.AddOrderer(orderer)\n\t\tif err != nil {\n\t\t\treturn nil, errors.WithMessage(err, \"adding orderer failed\")\n\t\t}\n\t}\n\n\treturn channel, nil\n}", "func (suite *KeeperTestSuite) TestChanOpenConfirm() {\n\tvar (\n\t\tpath *ibctesting.Path\n\t\tchannelCap *capabilitytypes.Capability\n\t\theightDiff uint64\n\t)\n\ttestCases := []testCase{\n\t\t{\"success\", func() {\n\t\t\tsuite.coordinator.SetupConnections(path)\n\t\t\tpath.SetChannelOrdered()\n\n\t\t\terr := path.EndpointA.ChanOpenInit()\n\t\t\tsuite.Require().NoError(err)\n\n\t\t\terr = path.EndpointB.ChanOpenTry()\n\t\t\tsuite.Require().NoError(err)\n\n\t\t\terr = path.EndpointA.ChanOpenAck()\n\t\t\tsuite.Require().NoError(err)\n\n\t\t\tchannelCap = suite.chainB.GetChannelCapability(path.EndpointB.ChannelConfig.PortID, path.EndpointB.ChannelID)\n\t\t}, true},\n\t\t{\"channel doesn't exist\", func() {}, false},\n\t\t{\"channel state is not TRYOPEN\", func() {\n\t\t\t// create fully open channels on both cahins\n\t\t\tsuite.coordinator.Setup(path)\n\t\t\tchannelCap = suite.chainB.GetChannelCapability(path.EndpointB.ChannelConfig.PortID, path.EndpointB.ChannelID)\n\t\t}, false},\n\t\t{\"connection not found\", func() {\n\t\t\tsuite.coordinator.SetupConnections(path)\n\t\t\tpath.SetChannelOrdered()\n\n\t\t\terr := path.EndpointA.ChanOpenInit()\n\t\t\tsuite.Require().NoError(err)\n\n\t\t\terr = path.EndpointB.ChanOpenTry()\n\t\t\tsuite.Require().NoError(err)\n\n\t\t\terr = path.EndpointA.ChanOpenAck()\n\t\t\tsuite.Require().NoError(err)\n\n\t\t\tchannelCap = suite.chainB.GetChannelCapability(path.EndpointB.ChannelConfig.PortID, path.EndpointB.ChannelID)\n\n\t\t\t// set the channel's connection hops to wrong connection ID\n\t\t\tchannel := path.EndpointB.GetChannel()\n\t\t\tchannel.ConnectionHops[0] = \"doesnotexist\"\n\t\t\tsuite.chainB.App.GetIBCKeeper().ChannelKeeper.SetChannel(suite.chainB.GetContext(), path.EndpointB.ChannelConfig.PortID, path.EndpointB.ChannelID, channel)\n\t\t}, false},\n\t\t{\"connection is not OPEN\", func() {\n\t\t\tsuite.coordinator.SetupClients(path)\n\n\t\t\terr := path.EndpointB.ConnOpenInit()\n\t\t\tsuite.Require().NoError(err)\n\n\t\t\tsuite.chainB.CreateChannelCapability(suite.chainB.GetSimApp().ScopedIBCMockKeeper, path.EndpointB.ChannelConfig.PortID, ibctesting.FirstChannelID)\n\t\t\tchannelCap = suite.chainB.GetChannelCapability(path.EndpointB.ChannelConfig.PortID, ibctesting.FirstChannelID)\n\t\t}, false},\n\t\t{\"consensus state not found\", func() {\n\t\t\tsuite.coordinator.SetupConnections(path)\n\t\t\tpath.SetChannelOrdered()\n\n\t\t\terr := path.EndpointA.ChanOpenInit()\n\t\t\tsuite.Require().NoError(err)\n\n\t\t\terr = path.EndpointB.ChanOpenTry()\n\t\t\tsuite.Require().NoError(err)\n\n\t\t\terr = path.EndpointA.ChanOpenAck()\n\t\t\tsuite.Require().NoError(err)\n\n\t\t\tchannelCap = suite.chainB.GetChannelCapability(path.EndpointB.ChannelConfig.PortID, path.EndpointB.ChannelID)\n\n\t\t\theightDiff = 3\n\t\t}, false},\n\t\t{\"channel verification failed\", func() {\n\t\t\t// chainA is INIT, chainB in TRYOPEN\n\t\t\tsuite.coordinator.SetupConnections(path)\n\t\t\tpath.SetChannelOrdered()\n\n\t\t\terr := path.EndpointA.ChanOpenInit()\n\t\t\tsuite.Require().NoError(err)\n\n\t\t\terr = path.EndpointB.ChanOpenTry()\n\t\t\tsuite.Require().NoError(err)\n\n\t\t\tchannelCap = suite.chainB.GetChannelCapability(path.EndpointB.ChannelConfig.PortID, path.EndpointB.ChannelID)\n\t\t}, false},\n\t\t{\"channel capability not found\", func() {\n\t\t\tsuite.coordinator.SetupConnections(path)\n\t\t\tpath.SetChannelOrdered()\n\n\t\t\terr := path.EndpointA.ChanOpenInit()\n\t\t\tsuite.Require().NoError(err)\n\n\t\t\terr = path.EndpointB.ChanOpenTry()\n\t\t\tsuite.Require().NoError(err)\n\n\t\t\terr = path.EndpointA.ChanOpenAck()\n\t\t\tsuite.Require().NoError(err)\n\n\t\t\tchannelCap = capabilitytypes.NewCapability(6)\n\t\t}, false},\n\t}\n\n\tfor _, tc := range testCases {\n\t\ttc := tc\n\t\tsuite.Run(fmt.Sprintf(\"Case %s\", tc.msg), func() {\n\t\t\tsuite.SetupTest() // reset\n\t\t\theightDiff = 0 // must be explicitly changed\n\t\t\tpath = ibctesting.NewPath(suite.chainA, suite.chainB)\n\n\t\t\ttc.malleate()\n\n\t\t\tif path.EndpointB.ClientID != \"\" {\n\t\t\t\t// ensure client is up to date\n\t\t\t\terr := path.EndpointB.UpdateClient()\n\t\t\t\tsuite.Require().NoError(err)\n\n\t\t\t}\n\n\t\t\tchannelKey := host.ChannelKey(path.EndpointA.ChannelConfig.PortID, ibctesting.FirstChannelID)\n\t\t\tproof, proofHeight := suite.chainA.QueryProof(channelKey)\n\n\t\t\terr := suite.chainB.App.GetIBCKeeper().ChannelKeeper.ChanOpenConfirm(\n\t\t\t\tsuite.chainB.GetContext(), path.EndpointB.ChannelConfig.PortID, ibctesting.FirstChannelID,\n\t\t\t\tchannelCap, proof, malleateHeight(proofHeight, heightDiff),\n\t\t\t)\n\n\t\t\tif tc.expPass {\n\t\t\t\tsuite.Require().NoError(err)\n\t\t\t} else {\n\t\t\t\tsuite.Require().Error(err)\n\t\t\t}\n\t\t})\n\t}\n}", "func (suite *KeeperTestSuite) TestChanCloseConfirm() {\n\tvar (\n\t\tpath *ibctesting.Path\n\t\tchannelCap *capabilitytypes.Capability\n\t\theightDiff uint64\n\t)\n\n\ttestCases := []testCase{\n\t\t{\"success\", func() {\n\t\t\tsuite.coordinator.Setup(path)\n\t\t\tchannelCap = suite.chainB.GetChannelCapability(path.EndpointB.ChannelConfig.PortID, path.EndpointB.ChannelID)\n\n\t\t\terr := path.EndpointA.SetChannelClosed()\n\t\t\tsuite.Require().NoError(err)\n\t\t}, true},\n\t\t{\"channel doesn't exist\", func() {\n\t\t\t// any non-nil values work for connections\n\t\t\tpath.EndpointA.ChannelID = ibctesting.FirstChannelID\n\t\t\tpath.EndpointB.ChannelID = ibctesting.FirstChannelID\n\n\t\t\t// ensure channel capability check passes\n\t\t\tsuite.chainB.CreateChannelCapability(suite.chainB.GetSimApp().ScopedIBCMockKeeper, path.EndpointB.ChannelConfig.PortID, ibctesting.FirstChannelID)\n\t\t\tchannelCap = suite.chainB.GetChannelCapability(path.EndpointB.ChannelConfig.PortID, ibctesting.FirstChannelID)\n\t\t}, false},\n\t\t{\"channel state is CLOSED\", func() {\n\t\t\tsuite.coordinator.Setup(path)\n\t\t\tchannelCap = suite.chainB.GetChannelCapability(path.EndpointB.ChannelConfig.PortID, path.EndpointB.ChannelID)\n\n\t\t\terr := path.EndpointB.SetChannelClosed()\n\t\t\tsuite.Require().NoError(err)\n\t\t}, false},\n\t\t{\"connection not found\", func() {\n\t\t\tsuite.coordinator.Setup(path)\n\t\t\tchannelCap = suite.chainB.GetChannelCapability(path.EndpointB.ChannelConfig.PortID, path.EndpointB.ChannelID)\n\n\t\t\t// set the channel's connection hops to wrong connection ID\n\t\t\tchannel := path.EndpointB.GetChannel()\n\t\t\tchannel.ConnectionHops[0] = \"doesnotexist\"\n\t\t\tsuite.chainB.App.GetIBCKeeper().ChannelKeeper.SetChannel(suite.chainB.GetContext(), path.EndpointB.ChannelConfig.PortID, path.EndpointB.ChannelID, channel)\n\t\t}, false},\n\t\t{\"connection is not OPEN\", func() {\n\t\t\tsuite.coordinator.SetupClients(path)\n\n\t\t\terr := path.EndpointB.ConnOpenInit()\n\t\t\tsuite.Require().NoError(err)\n\n\t\t\t// create channel in init\n\t\t\tpath.SetChannelOrdered()\n\t\t\terr = path.EndpointB.ChanOpenInit()\n\t\t\tsuite.Require().NoError(err)\n\n\t\t\t// ensure channel capability check passes\n\t\t\tsuite.chainB.CreateChannelCapability(suite.chainB.GetSimApp().ScopedIBCMockKeeper, path.EndpointB.ChannelConfig.PortID, path.EndpointB.ChannelID)\n\t\t\tchannelCap = suite.chainB.GetChannelCapability(path.EndpointB.ChannelConfig.PortID, path.EndpointB.ChannelID)\n\t\t}, false},\n\t\t{\"consensus state not found\", func() {\n\t\t\tsuite.coordinator.Setup(path)\n\t\t\tchannelCap = suite.chainB.GetChannelCapability(path.EndpointB.ChannelConfig.PortID, path.EndpointB.ChannelID)\n\n\t\t\terr := path.EndpointA.SetChannelClosed()\n\t\t\tsuite.Require().NoError(err)\n\n\t\t\theightDiff = 3\n\t\t}, false},\n\t\t{\"channel verification failed\", func() {\n\t\t\t// channel not closed\n\t\t\tsuite.coordinator.Setup(path)\n\t\t\tchannelCap = suite.chainB.GetChannelCapability(path.EndpointB.ChannelConfig.PortID, path.EndpointB.ChannelID)\n\t\t}, false},\n\t\t{\"channel capability not found\", func() {\n\t\t\tsuite.coordinator.Setup(path)\n\t\t\tchannelCap = suite.chainB.GetChannelCapability(path.EndpointB.ChannelConfig.PortID, path.EndpointB.ChannelID)\n\n\t\t\terr := path.EndpointA.SetChannelClosed()\n\t\t\tsuite.Require().NoError(err)\n\n\t\t\tchannelCap = capabilitytypes.NewCapability(3)\n\t\t}, false},\n\t}\n\n\tfor _, tc := range testCases {\n\t\ttc := tc\n\t\tsuite.Run(fmt.Sprintf(\"Case %s\", tc.msg), func() {\n\t\t\tsuite.SetupTest() // reset\n\t\t\theightDiff = 0 // must explicitly be changed\n\t\t\tpath = ibctesting.NewPath(suite.chainA, suite.chainB)\n\n\t\t\ttc.malleate()\n\n\t\t\tchannelKey := host.ChannelKey(path.EndpointA.ChannelConfig.PortID, ibctesting.FirstChannelID)\n\t\t\tproof, proofHeight := suite.chainA.QueryProof(channelKey)\n\n\t\t\terr := suite.chainB.App.GetIBCKeeper().ChannelKeeper.ChanCloseConfirm(\n\t\t\t\tsuite.chainB.GetContext(), path.EndpointB.ChannelConfig.PortID, ibctesting.FirstChannelID, channelCap,\n\t\t\t\tproof, malleateHeight(proofHeight, heightDiff),\n\t\t\t)\n\n\t\t\tif tc.expPass {\n\t\t\t\tsuite.Require().NoError(err)\n\t\t\t} else {\n\t\t\t\tsuite.Require().Error(err)\n\t\t\t}\n\t\t})\n\t}\n}", "func (_m *ISession) ChannelMessages(channelID string, limit int, beforeID string, afterID string, aroundID string, options ...discordgo.RequestOption) ([]*discordgo.Message, error) {\n\t_va := make([]interface{}, len(options))\n\tfor _i := range options {\n\t\t_va[_i] = options[_i]\n\t}\n\tvar _ca []interface{}\n\t_ca = append(_ca, channelID, limit, beforeID, afterID, aroundID)\n\t_ca = append(_ca, _va...)\n\tret := _m.Called(_ca...)\n\n\tvar r0 []*discordgo.Message\n\tvar r1 error\n\tif rf, ok := ret.Get(0).(func(string, int, string, string, string, ...discordgo.RequestOption) ([]*discordgo.Message, error)); ok {\n\t\treturn rf(channelID, limit, beforeID, afterID, aroundID, options...)\n\t}\n\tif rf, ok := ret.Get(0).(func(string, int, string, string, string, ...discordgo.RequestOption) []*discordgo.Message); ok {\n\t\tr0 = rf(channelID, limit, beforeID, afterID, aroundID, options...)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).([]*discordgo.Message)\n\t\t}\n\t}\n\n\tif rf, ok := ret.Get(1).(func(string, int, string, string, string, ...discordgo.RequestOption) error); ok {\n\t\tr1 = rf(channelID, limit, beforeID, afterID, aroundID, options...)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func getAPIChannel(c api.ChannelProvider) (api.Channel, error) {\n\tch, err := c.NewAPIChannel()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif err := ch.CheckCompatiblity(vpe.AllMessages()...); err != nil {\n\t\treturn nil, fmt.Errorf(\"compatibility check failed: %w\", err)\n\t}\n\tif err := ch.CheckCompatiblity(interfaces.AllMessages()...); err != nil {\n\t\tlogInfo(\"compatibility check failed: %v\", err)\n\t}\n\treturn ch, nil\n}", "func (m *MockClient) Send() chan []byte {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Send\")\n\tret0, _ := ret[0].(chan []byte)\n\treturn ret0\n}", "func (m *MockFile) Chown(arg0, arg1 int) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Chown\", arg0, arg1)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockFullNode) NetFindProvidersAsync(arg0 context.Context, arg1 cid.Cid, arg2 int) <-chan peer.AddrInfo {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"NetFindProvidersAsync\", arg0, arg1, arg2)\n\tret0, _ := ret[0].(<-chan peer.AddrInfo)\n\treturn ret0\n}", "func (_m *ChannelStore) Get(id string, allowFromCache bool) (*model.Channel, error) {\n\tret := _m.Called(id, allowFromCache)\n\n\tvar r0 *model.Channel\n\tif rf, ok := ret.Get(0).(func(string, bool) *model.Channel); ok {\n\t\tr0 = rf(id, allowFromCache)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*model.Channel)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(string, bool) error); ok {\n\t\tr1 = rf(id, allowFromCache)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func NewMockChannel(ctrl *gomock.Controller) *MockChannel {\n\tmock := &MockChannel{ctrl: ctrl}\n\tmock.recorder = &MockChannelMockRecorder{mock}\n\treturn mock\n}", "func (m *MockisProxycCbKeyHandle_KeyOrHandle) isProxycCbKeyHandle_KeyOrHandle() {\n\tm.ctrl.Call(m, \"isProxycCbKeyHandle_KeyOrHandle\")\n}", "func (m *MockAMQPChannel) NotifyClose(arg0 chan *amqp091.Error) chan *amqp091.Error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"NotifyClose\", arg0)\n\tret0, _ := ret[0].(chan *amqp091.Error)\n\treturn ret0\n}", "func TestGcm(t *testing.T) {\n\n\tmockResponse := testCreateGoogleCloudMsgResponse(100, 1, 0, 0)\n\ttestAddGoogleCloudMsgResponseResult(mockResponse, \"someMessageId\", nadaStr, nadaStr)\n\n\tdata, err := json.Marshal(mockResponse)\n\tif err != nil { t.Errorf(\"TestGcm json encode mock response broken - err: %v\", err); return }\n\n\thttpClient := NewHttpRequestClientMock()\n\thttpClient.(*HttpRequestClientMock).AddMock(\"https://android.googleapis.com/gcm/send\", &HttpRequestClientMockResponse{\n\t\tHttpStatusCode: 200,\n\t\tData: data,\n\t})\n\n\trequestChannel := make(chan interface{})\n\tresponseChannel := make(chan interface{})\n\n\tsvc := NewGoogleCloudMessagingSvc(\"gcm\", httpClient, requestChannel, responseChannel)\n\n\tkernel, err := baseTestStartKernel(\"gcmTest\", func(kernel *Kernel) {\n\t\tkernel.AddComponentWithStartStopMethods(\"GoogleCloudMessagingSvc\", svc, \"Start\", \"Stop\")\n\t})\n\n\tif err != nil { t.Errorf(\"TestGcm start kernel is broken: %v\", err); return }\n\n\tmsgSendCount := 10000\n\tmsgReceivedCount := 0\n\n\tvar waitGroup sync.WaitGroup\n\n\tgo func() {\n\t\twaitGroup.Add(1)\n\t\tdefer waitGroup.Done()\n\t\tfor {\n\t\t\tmsg := <- responseChannel\n\t\t\tif msg == nil { t.Errorf(\"TestGcm is broken - response message is nil\") }\n\t\t\tmsgReceivedCount++\n\t\t\tif msgReceivedCount == msgSendCount { return }\n\t\t}\n\t}()\n\n\tfor idx := 0; idx < msgSendCount; idx++ {\n\t\trequestChannel <- &GoogleCloudMsg{\n\t\t\tRegistrationIds: []string { \"someRegistrationId\" },\n\t\t\tCollapseKey: \"someCollapseKey\",\n\t\t\tDelayWhileIdle: true,\n\t\t\tTimeToLive: 300,\n\t\t\tRestrictedPackageName: \"somePackageName\",\n\t\t\tDryRun: false,\n\t\t\tData: map[string]interface{} { \"someKey\": \"someValue\" },\n\t\t}\n\t}\n\n\twaitGroup.Wait()\n\n\tclose(requestChannel)\n\n\tif err := kernel.Stop(); err != nil { t.Errorf(\"TestGcm stop kernel is broken:\", err) }\n}", "func (m *MockAMQPChannel) Consume(arg0, arg1 string, arg2, arg3, arg4, arg5 bool, arg6 amqp091.Table) (<-chan amqp091.Delivery, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Consume\", arg0, arg1, arg2, arg3, arg4, arg5, arg6)\n\tret0, _ := ret[0].(<-chan amqp091.Delivery)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (amqpSuite *AmqpSuite) ChannelConsumeTester() *amqp.ChannelTesting {\n\treturn amqpSuite.ChannelConsume().Test(amqpSuite.T())\n}", "func (m *MockIInterConnector) receiver() ISubKeyBucketReceiver {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"receiver\")\n\tret0, _ := ret[0].(ISubKeyBucketReceiver)\n\treturn ret0\n}", "func (m *MockHealthCheck) Subscribe() chan *discovery.TabletHealth {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Subscribe\")\n\tret0, _ := ret[0].(chan *discovery.TabletHealth)\n\treturn ret0\n}", "func (_m *ChannelStore) GetMoreChannels(teamID string, userID string, offset int, limit int) (model.ChannelList, error) {\n\tret := _m.Called(teamID, userID, offset, limit)\n\n\tvar r0 model.ChannelList\n\tif rf, ok := ret.Get(0).(func(string, string, int, int) model.ChannelList); ok {\n\t\tr0 = rf(teamID, userID, offset, limit)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(model.ChannelList)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(string, string, int, int) error); ok {\n\t\tr1 = rf(teamID, userID, offset, limit)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (c *ConnectionMock) Channels() []string {\n\targs := c.Called()\n\treturn args.Get(0).([]string)\n}", "func (m *MockisProxyrCbKeyHandle_KeyOrHandle) isProxyrCbKeyHandle_KeyOrHandle() {\n\tm.ctrl.Call(m, \"isProxyrCbKeyHandle_KeyOrHandle\")\n}", "func Test_Provider(t *testing.T) {\n\t// SetLogLevel(\"TRACE\")\n\t// CheckVersion()\n\n\t// Start provider API in the background\n\tgo InitProvider()\n\t// err := InitProvider()\n\t// if err != nil {\n\t// \tlog.Fatalf(\"Error initializing Provider %+v\", err)\n\t// }\n\n\tverifier := HTTPVerifier{}\n\t// Authorization middleware\n\t// This is your chance to modify the request before it hits your provider\n\t// NOTE: this should be used very carefully, as it has the potential to\n\t// _change_ the contract\n\t// f := func(next http.Handler) http.Handler {\n\t// \treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t// \t\tlog.Println(\"[DEBUG] HOOK request filter\")\n\t// \t\t// r.Header.Add(\"Authorization\", \"Bearer 1234-dynamic-value\")\n\t// \t\tnext.ServeHTTP(w, r)\n\t// \t})\n\t// }\n\n\t// Verify the Provider with local Pact Files\n\terr := verifier.VerifyProvider(t, VerifyRequest{\n\t\tProviderBaseURL: \"http://localhost:9000\",\n\t\tBrokerURL: \"http://localhost:9292\",\n\t\tProvider: \"GreetingAPI\",\n\t\tProviderVersion: \"1.0.0\",\n\t\tPublishVerificationResults: true,\n\t\t// PactFiles: []string{\n\t\t// \tfilepath.ToSlash(fmt.Sprintf(\"%s/GreetingAPIConsumer-GreetingAPI.json\", pactDir)),\n\t\t// },\n\t\t// RequestFilter: f,\n\t\t// BeforeEach: func() error {\n\t\t// \tlog.Println(\"[DEBUG] HOOK before each\")\n\t\t// \treturn nil\n\t\t// },\n\t\t// AfterEach: func() error {\n\t\t// \tlog.Println(\"[DEBUG] HOOK after each\")\n\t\t// \treturn nil\n\t\t// },\n\t\t// StateHandlers: StateHandlers{\n\t\t// \t\"User foo exists\": func(setup bool, s ProviderStateV3) (ProviderStateV3Response, error) {\n\n\t\t// \t\tif setup {\n\t\t// \t\t\tlog.Println(\"[DEBUG] HOOK calling user foo exists state handler\", s)\n\t\t// \t\t} else {\n\t\t// \t\t\tlog.Println(\"[DEBUG] HOOK teardown the 'User foo exists' state\")\n\t\t// \t\t}\n\n\t\t// \t\t// ... do something, such as create \"foo\" in the database\n\n\t\t// \t\t// Optionally (if there are generators in the pact) return provider state values to be used in the verification\n\t\t// \t\treturn ProviderStateV3Response{\"uuid\": \"1234\"}, nil\n\t\t// \t},\n\t\t// },\n\t})\n\n\tassert.NoError(t, err)\n}", "func (m *MockAergoRPCService_ListBlockStreamServer) Context() context.Context {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Context\")\n\tret0, _ := ret[0].(context.Context)\n\treturn ret0\n}", "func mockChildPackages() {\n\n\t// Fake an AWS credentials file so that the mfile package will nehave as if it is happy\n\tsetFakeCredentials()\n\n\t// Fake out the creds package into using an apparently credentials response from AWS\n\tcreds.SetGetSessionTokenFunc(func(awsService *sts.STS, input *sts.GetSessionTokenInput) (*sts.GetSessionTokenOutput, error) {\n\t\treturn getSessionTokenOutput, nil\n\t})\n\n}", "func (_m *ChannelRepository) Create(channel *model.Channel) (*model.Channel, error) {\n\tret := _m.Called(channel)\n\n\tvar r0 *model.Channel\n\tif rf, ok := ret.Get(0).(func(*model.Channel) *model.Channel); ok {\n\t\tr0 = rf(channel)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*model.Channel)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(*model.Channel) error); ok {\n\t\tr1 = rf(channel)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (m *MockMachine) JetStreamConnection() (*jsm_go.Manager, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"JetStreamConnection\")\n\tret0, _ := ret[0].(*jsm_go.Manager)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (amqpSuite *AmqpSuite) getChannel(conn *amqp.Connection) *amqp.Channel {\n\tchannel, err := conn.Channel()\n\tif err != nil {\n\t\tamqpSuite.T().Errorf(\"error getting channel: %v\", err)\n\t\tamqpSuite.T().FailNow()\n\t}\n\n\treturn channel\n}", "func (m *MockReminds) ChannelMessageSend(arg0, arg1 string) (*discordgo.Message, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ChannelMessageSend\", arg0, arg1)\n\tret0, _ := ret[0].(*discordgo.Message)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (_m *TimeTicker) C() <-chan time.Time {\n\tret := _m.Called()\n\n\tvar r0 <-chan time.Time\n\tif rf, ok := ret.Get(0).(func() <-chan time.Time); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(<-chan time.Time)\n\t\t}\n\t}\n\n\treturn r0\n}", "func TestConjur_Provider(t *testing.T) {\n\tvar err error\n\tvar provider plugin_v1.Provider\n\tname := \"conjur\"\n\n\toptions := plugin_v1.ProviderOptions{\n\t\tName: name,\n\t}\n\n\tt.Run(\"Can create the Conjur provider\", func(t *testing.T) {\n\t\tprovider, err = providers.ProviderFactories[name](options)\n\t\tassert.NoError(t, err)\n\t})\n\n\tt.Run(\"Has the expected provider name\", func(t *testing.T) {\n\t\tassert.Equal(t, \"conjur\", provider.GetName())\n\t})\n\n\tt.Run(\"Can provide an access token\", func(t *testing.T) {\n\t\tid := \"accessToken\"\n\t\tvalues, err := provider.GetValues(id)\n\n\t\tassert.NoError(t, err)\n\t\tassert.NotNil(t, values[id])\n\t\tassert.NoError(t, values[id].Error)\n\t\tassert.NotNil(t, values[id].Value)\n\n\t\ttoken := make(map[string]string)\n\t\terr = json.Unmarshal(values[id].Value, &token)\n\t\tassert.NoError(t, err)\n\t\tassert.NotNil(t, token[\"protected\"])\n\t\tassert.NotNil(t, token[\"payload\"])\n\t})\n\n\tt.Run(\"Reports an unknown value\",\n\t\ttestutils.Reports(\n\t\t\tprovider,\n\t\t\t\"foobar\",\n\t\t\t\"404 Not Found. CONJ00076E Variable dev:variable:foobar is empty or not found..\",\n\t\t),\n\t)\n\n\tt.Run(\"Provides\", func(t *testing.T) {\n\t\tfor _, testCase := range canProvideTestCases {\n\t\t\tt.Run(testCase.Description, testutils.CanProvide(provider, testCase.ID, testCase.ExpectedValue))\n\t\t}\n\t})\n}", "func (m *MockClienter) Connectable(timeout time.Duration) (bool, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Connectable\", timeout)\n\tret0, _ := ret[0].(bool)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func startMockOrchestrator(t *testing.T, reportCh chan string, triggerCh chan interface{}, doneCh chan interface{}, wg *sync.WaitGroup, logger *logrus.Logger, m messenger.Messenger, expectedStatusReportBody orchestra.StatusReportBody) chan interface{} {\n\tstatusReportCh := make(chan []byte)\n\tstatusReportSubs := m.ChanSubscribe(\"status-report\", statusReportCh)\n\torcStoppedCh := make(chan interface{})\n\n\twg.Add(1)\n\tgo func() {\n\t\tdefer func() {\n\t\t\tlogger.Infof(\"MockOrchestrator stopped.\")\n\t\t\tif err := statusReportSubs.Unsubscribe(); err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\tclose(statusReportCh)\n\t\t\tclose(orcStoppedCh)\n\t\t\twg.Done()\n\t\t}()\n\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-doneCh:\n\t\t\t\tlogger.Infof(\"MockOrchestrator shuts down.\")\n\t\t\t\treturn\n\n\t\t\tcase <-triggerCh:\n\t\t\t\tlogger.Infof(\"MockOrchestrator received 'start-trigger'.\")\n\t\t\t\tlogger.Infof(\"MockOrchestrator sends 'status-request' message.\")\n\t\t\t\tstatusRequestMsg := orchestra.NewStatusRequestMessage()\n\t\t\t\tif err := m.Publish(\"status-request\", statusRequestMsg.Encode(msgs.JSONRepresentation)); err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\t\t\t\t// TODO: Make orchestra message representations and channel names configurable\n\t\t\t\treportCh <- checkSendStatusRequest\n\n\t\t\tcase statusReportMsgBytes := <-statusReportCh:\n\t\t\t\tlogger.Infof(\"MockOrchestrator received 'status-report' message.\")\n\t\t\t\tvar statusReportMsg orchestra.StatusReport\n\t\t\t\terr := statusReportMsg.Decode(msgs.JSONRepresentation, statusReportMsgBytes)\n\t\t\t\tassert.Nil(t, err)\n\t\t\t\tassert.Equal(t, expectedStatusReportBody, statusReportMsg.Body)\n\t\t\t\treportCh <- checkStatusReportReceived\n\t\t\t}\n\t\t}\n\t}()\n\tlogger.Infof(\"Mock Orchestrator started.\")\n\n\treturn orcStoppedCh\n}", "func (s *TestSuite) TestGetChannels(c *C) {\n\tsvc := s.serviceGroup.UserService\n\tteam, _ := s.serviceGroup.TeamService.SaveTeam(msgcore.NewTeam(1, \"org\", \"team\"))\n\n\tusers := make([]*msgcore.User, 0, 0)\n\tchannels := make([]*msgcore.Channel, 0, 0)\n\tfor i := 1; i <= 10; i++ {\n\t\tcreator := msgcore.NewUser(int64(i), fmt.Sprintf(\"%d\", i), team)\n\t\t_ = svc.SaveUser(&msgcore.SaveUserRequest{nil, creator, false})\n\t\tusers = append(users, creator)\n\t\tchannel := msgcore.NewChannel(team, creator, int64(i), fmt.Sprintf(\"channel%d\", i))\n\t\tchannel, err := s.serviceGroup.ChannelService.CreateChannel(&msgcore.CreateChannelRequest{channel, nil, true})\n\t\tif err != nil {\n\t\t\tlog.Println(\"CreateChannel Error: \", err)\n\t\t}\n\t\tchannels = append(channels, channel)\n\t}\n\n\tfor i := 1; i <= 10; i++ {\n\t\t// add the creator and 4 next users as members\n\t\tmembers := make([]string, 0, 4)\n\t\tfor j := 0; j < 5; j++ {\n\t\t\tmembers = append(members, users[(i+j-1)%len(users)].Username)\n\t\t}\n\t\ts.serviceGroup.ChannelService.AddChannelMembers(&msgcore.InviteMembersRequest{nil, channels[i-1], members})\n\t}\n\n\t// Test owner filter\n\trequest := &msgcore.GetChannelsRequest{team, users[0], \"\", nil, true}\n\tresult, _ := s.serviceGroup.ChannelService.GetChannels(request)\n\tc.Assert(len(result.Channels), Equals, 1)\n\tc.Assert(len(result.Members), Equals, 1)\n\t// ensure all users have the same creator\n\tc.Assert(result.Channels[0].Creator.Id, Equals, users[0].Id)\n\tc.Assert(len(result.Members[0]), Equals, 5)\n\n\t// Test participants\n\trequest = &msgcore.GetChannelsRequest{team, nil, \"\", []*msgcore.User{users[1], users[2]}, true}\n\tresult, _ = s.serviceGroup.ChannelService.GetChannels(request)\n\tc.Assert(len(result.Channels), Equals, 4)\n\tfor i := 0; i < 4; i++ {\n\t\tc.Assert(len(result.Members[i]), Equals, 5)\n\t}\n}", "func (m *MockChoriaProvider) PublishRaw(arg0 string, arg1 []byte) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"PublishRaw\", arg0, arg1)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockWebsocketClientStore) CountChannels(clientID wspubsub.UUID) (int, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"CountChannels\", clientID)\n\tret0, _ := ret[0].(int)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockAMQPChan) Consume(arg0, arg1 string, arg2, arg3, arg4, arg5 bool, arg6 amqp.Table) (<-chan amqp.Delivery, error) {\n\tret := m.ctrl.Call(m, \"Consume\", arg0, arg1, arg2, arg3, arg4, arg5, arg6)\n\tret0, _ := ret[0].(<-chan amqp.Delivery)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}" ]
[ "0.72489923", "0.6751296", "0.6729731", "0.6153569", "0.61135983", "0.6057166", "0.6054517", "0.5930565", "0.5925086", "0.59205496", "0.59125435", "0.5870955", "0.5845958", "0.5832964", "0.5823897", "0.58165205", "0.5808184", "0.57830024", "0.57754666", "0.57749516", "0.57468253", "0.57318926", "0.5721575", "0.5714591", "0.56840426", "0.56641996", "0.5653062", "0.56499577", "0.56364167", "0.5619127", "0.56025493", "0.55980915", "0.55738676", "0.55490685", "0.55266345", "0.5525505", "0.55210894", "0.55088264", "0.55066943", "0.54867184", "0.5479955", "0.54778075", "0.54713947", "0.54634446", "0.5462797", "0.54361594", "0.54206336", "0.5418061", "0.54170215", "0.54168415", "0.5416697", "0.54051226", "0.54006726", "0.53968203", "0.53892386", "0.53817624", "0.53779006", "0.53725594", "0.536024", "0.53566", "0.5346966", "0.5340234", "0.5328267", "0.5322905", "0.5322579", "0.53096706", "0.53016514", "0.52993655", "0.52804565", "0.5274022", "0.5272792", "0.527115", "0.5268956", "0.526725", "0.5266349", "0.5265111", "0.52625924", "0.52579296", "0.52540165", "0.52473897", "0.5245937", "0.5243764", "0.52350324", "0.5233514", "0.5219781", "0.5219683", "0.5217055", "0.5204583", "0.5202766", "0.519056", "0.5186911", "0.51867205", "0.51827526", "0.5182705", "0.51773465", "0.51739657", "0.5172467", "0.51712507", "0.5169238", "0.5166768" ]
0.74381363
0
ChannelProvider indicates an expected call of ChannelProvider
func (mr *MockClientMockRecorder) ChannelProvider() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ChannelProvider", reflect.TypeOf((*MockClient)(nil).ChannelProvider)) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (mr *MockProvidersMockRecorder) ChannelProvider() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"ChannelProvider\", reflect.TypeOf((*MockProviders)(nil).ChannelProvider))\n}", "func (m *MockClient) ChannelProvider() fab.ChannelProvider {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ChannelProvider\")\n\tret0, _ := ret[0].(fab.ChannelProvider)\n\treturn ret0\n}", "func (c *Provider) ChannelProvider() fab.ChannelProvider {\n\treturn c.channelProvider\n}", "func (m *MockProviders) ChannelProvider() fab.ChannelProvider {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ChannelProvider\")\n\tret0, _ := ret[0].(fab.ChannelProvider)\n\treturn ret0\n}", "func TestConsumerChannel(t *testing.T) {\n\tconsumerTestWithCommits(t, \"Channel Consumer\", 0, true, eventTestChannelConsumer, nil)\n}", "func (a *AbstractSSHConnectionHandler) OnUnsupportedChannel(_ uint64, _ string, _ []byte) {}", "func Test_ChannelFlow_Failed_FlowOkSend(t *testing.T) {\n\tsc, _ := getNewSC(getDefaultTestConfig())\n\tdefer sc.clean()\n\tch, _ := sc.client.Channel()\n\n\tflowChan := make(chan bool)\n\tcloseChan := make(chan *amqpclient.Error, 1)\n\tch.NotifyFlow(flowChan)\n\tch.NotifyClose(closeChan)\n\n\tchannel := getServerChannel(sc, 1)\n\tchannel.SendMethod(&amqp.ChannelFlow{Active: false})\n\n\tselect {\n\tcase <-flowChan:\n\tcase <-time.After(100 * time.Millisecond):\n\t}\n\n\tfor notify := range flowChan {\n\t\tfmt.Println(notify)\n\t}\n\n\tvar closeErr *amqpclient.Error\n\n\tselect {\n\tcase closeErr = <-closeChan:\n\tcase <-time.After(100 * time.Millisecond):\n\t}\n\n\tif closeErr == nil {\n\t\tt.Error(\"Expected NOT_IMPLEMENTED error\")\n\t}\n}", "func (s *RingpopOptionsTestSuite) TestChannelRequired() {\n\trp, err := New(\"test\")\n\ts.Nil(rp)\n\ts.Error(err)\n}", "func TestChannelAttachNotMember(t *testing.T) {\n\th := newHelper(t)\n\n\tch := h.repoMakePrivateCh()\n\n\th.apiChAttach(ch, []byte(\"NOPE\")).\n\t\tAssert(helpers.AssertError(\"not allowed to attach files this channel\")).\n\t\tEnd()\n}", "func (p *peer) hasChannel(chID byte) bool {\r\n\tfor _, ch := range p.channels {\r\n\t\tif ch == chID {\r\n\t\t\treturn true\r\n\t\t}\r\n\t}\r\n\t// NOTE: probably will want to remove this\r\n\t// but could be helpful while the feature is new\r\n\tp.Logger.Debug(\r\n\t\t\"Unknown channel for peer\",\r\n\t\t\"channel\",\r\n\t\tchID,\r\n\t\t\"channels\",\r\n\t\tp.channels,\r\n\t)\r\n\treturn false\r\n}", "func (*ProtocolHeader) Channel() uint16 {\n\tpanic(\"Should never be called\")\n}", "func TestProducerChannel(t *testing.T) {\n\tproducerTest(t, \"Channel producer (without DR)\",\n\t\tnil, producerCtrl{},\n\t\tfunc(p *Producer, m *Message, drChan chan Event) {\n\t\t\tp.ProduceChannel() <- m\n\t\t})\n}", "func (mr *MockRConnectionInterfaceMockRecorder) Channel() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Channel\", reflect.TypeOf((*MockRConnectionInterface)(nil).Channel))\n}", "func TestConjur_Provider(t *testing.T) {\n\tvar err error\n\tvar provider plugin_v1.Provider\n\tname := \"conjur\"\n\n\toptions := plugin_v1.ProviderOptions{\n\t\tName: name,\n\t}\n\n\tt.Run(\"Can create the Conjur provider\", func(t *testing.T) {\n\t\tprovider, err = providers.ProviderFactories[name](options)\n\t\tassert.NoError(t, err)\n\t})\n\n\tt.Run(\"Has the expected provider name\", func(t *testing.T) {\n\t\tassert.Equal(t, \"conjur\", provider.GetName())\n\t})\n\n\tt.Run(\"Can provide an access token\", func(t *testing.T) {\n\t\tid := \"accessToken\"\n\t\tvalues, err := provider.GetValues(id)\n\n\t\tassert.NoError(t, err)\n\t\tassert.NotNil(t, values[id])\n\t\tassert.NoError(t, values[id].Error)\n\t\tassert.NotNil(t, values[id].Value)\n\n\t\ttoken := make(map[string]string)\n\t\terr = json.Unmarshal(values[id].Value, &token)\n\t\tassert.NoError(t, err)\n\t\tassert.NotNil(t, token[\"protected\"])\n\t\tassert.NotNil(t, token[\"payload\"])\n\t})\n\n\tt.Run(\"Reports an unknown value\",\n\t\ttestutils.Reports(\n\t\t\tprovider,\n\t\t\t\"foobar\",\n\t\t\t\"404 Not Found. CONJ00076E Variable dev:variable:foobar is empty or not found..\",\n\t\t),\n\t)\n\n\tt.Run(\"Provides\", func(t *testing.T) {\n\t\tfor _, testCase := range canProvideTestCases {\n\t\t\tt.Run(testCase.Description, testutils.CanProvide(provider, testCase.ID, testCase.ExpectedValue))\n\t\t}\n\t})\n}", "func (a *AbstractSessionChannelHandler) OnUnsupportedChannelRequest(\n\t_ uint64,\n\t_ string,\n\t_ []byte,\n) {\n}", "func TestChannelStore(t *testing.T) {\n\t// mock Insert function\n\tfn := func(_ context.Context, v are_hub.Archetype) error {\n\t\treturn nil\n\t}\n\n\t// create mock repo and controller\n\trepo := &mock.ChannelRepo{InsertFunc: fn}\n\tcontroller := NewChannel(repo)\n\n\t// create and embed a new channel\n\tmsport := are_hub.Channel{Name: \"Bentley Team M-Sport\", Password: \"abc123\"}\n\n\t// create a mock request\n\treq, e := http.NewRequest(http.MethodPost, \"/channel\", nil)\n\n\tif e != nil {\n\t\tt.Fatal(e)\n\t}\n\n\t// update the request's context with the channel\n\treq = req.WithContext(msport.ToCtx(req.Context()))\n\n\t// create a response recorder and run the controller method\n\tw := httptest.NewRecorder()\n\te = controller.Store(w, req)\n\n\tif e != nil {\n\t\tt.Fatal(e)\n\t}\n\n\t// check if the repo was hit\n\tif !repo.InsertCalled {\n\t\tt.Error(\"Did not call repo.Insert\")\n\t}\n\n\t// get the response\n\tres := w.Result()\n\n\t// ensure the content type is application/json\n\tcheckCT(res, t)\n\n\t// extract the returned channel\n\tdefer res.Body.Close()\n\tresBody, e := io.ReadAll(res.Body)\n\n\tif e != nil {\n\t\tt.Fatal(e)\n\t}\n\n\t// unmarshal the response body\n\treceived := are_hub.Channel{}\n\te = json.Unmarshal(resBody, &received)\n\n\tif e != nil {\n\t\tt.Fatal(e)\n\t}\n\n\t// compare the sent and received channels\n\tif msport.Name != received.Name {\n\t\tt.Fatalf(\"Expected: %+v. Actual: %+v\", msport, received)\n\t}\n}", "func New(fabricProvider api.FabricProvider) (*ChannelProvider, error) {\n\tcp := ChannelProvider{fabricProvider: fabricProvider}\n\treturn &cp, nil\n}", "func Test_Provider(t *testing.T) {\n\t// SetLogLevel(\"TRACE\")\n\t// CheckVersion()\n\n\t// Start provider API in the background\n\tgo InitProvider()\n\t// err := InitProvider()\n\t// if err != nil {\n\t// \tlog.Fatalf(\"Error initializing Provider %+v\", err)\n\t// }\n\n\tverifier := HTTPVerifier{}\n\t// Authorization middleware\n\t// This is your chance to modify the request before it hits your provider\n\t// NOTE: this should be used very carefully, as it has the potential to\n\t// _change_ the contract\n\t// f := func(next http.Handler) http.Handler {\n\t// \treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t// \t\tlog.Println(\"[DEBUG] HOOK request filter\")\n\t// \t\t// r.Header.Add(\"Authorization\", \"Bearer 1234-dynamic-value\")\n\t// \t\tnext.ServeHTTP(w, r)\n\t// \t})\n\t// }\n\n\t// Verify the Provider with local Pact Files\n\terr := verifier.VerifyProvider(t, VerifyRequest{\n\t\tProviderBaseURL: \"http://localhost:9000\",\n\t\tBrokerURL: \"http://localhost:9292\",\n\t\tProvider: \"GreetingAPI\",\n\t\tProviderVersion: \"1.0.0\",\n\t\tPublishVerificationResults: true,\n\t\t// PactFiles: []string{\n\t\t// \tfilepath.ToSlash(fmt.Sprintf(\"%s/GreetingAPIConsumer-GreetingAPI.json\", pactDir)),\n\t\t// },\n\t\t// RequestFilter: f,\n\t\t// BeforeEach: func() error {\n\t\t// \tlog.Println(\"[DEBUG] HOOK before each\")\n\t\t// \treturn nil\n\t\t// },\n\t\t// AfterEach: func() error {\n\t\t// \tlog.Println(\"[DEBUG] HOOK after each\")\n\t\t// \treturn nil\n\t\t// },\n\t\t// StateHandlers: StateHandlers{\n\t\t// \t\"User foo exists\": func(setup bool, s ProviderStateV3) (ProviderStateV3Response, error) {\n\n\t\t// \t\tif setup {\n\t\t// \t\t\tlog.Println(\"[DEBUG] HOOK calling user foo exists state handler\", s)\n\t\t// \t\t} else {\n\t\t// \t\t\tlog.Println(\"[DEBUG] HOOK teardown the 'User foo exists' state\")\n\t\t// \t\t}\n\n\t\t// \t\t// ... do something, such as create \"foo\" in the database\n\n\t\t// \t\t// Optionally (if there are generators in the pact) return provider state values to be used in the verification\n\t\t// \t\treturn ProviderStateV3Response{\"uuid\": \"1234\"}, nil\n\t\t// \t},\n\t\t// },\n\t})\n\n\tassert.NoError(t, err)\n}", "func testChannel(t *testing.T, src, dst *Chain) {\n\tchans, err := src.QueryChannels(1, 1000)\n\trequire.NoError(t, err)\n\trequire.Equal(t, 1, len(chans))\n\trequire.Equal(t, chans[0].GetOrdering().String(), \"ORDERED\")\n\trequire.Equal(t, chans[0].GetState().String(), \"OPEN\")\n\trequire.Equal(t, chans[0].GetCounterparty().GetChannelID(), dst.PathEnd.ChannelID)\n\trequire.Equal(t, chans[0].GetCounterparty().GetPortID(), dst.PathEnd.PortID)\n\n\th, err := src.Client.Status()\n\trequire.NoError(t, err)\n\n\tch, err := src.QueryChannel(h.SyncInfo.LatestBlockHeight)\n\trequire.NoError(t, err)\n\trequire.Equal(t, ch.Channel.GetOrdering().String(), \"ORDERED\")\n\trequire.Equal(t, ch.Channel.GetState().String(), \"OPEN\")\n\trequire.Equal(t, ch.Channel.GetCounterparty().GetChannelID(), dst.PathEnd.ChannelID)\n\trequire.Equal(t, ch.Channel.GetCounterparty().GetPortID(), dst.PathEnd.PortID)\n}", "func (_m *KenContext) Channel() (*discordgo.Channel, error) {\n\tret := _m.Called()\n\n\tvar r0 *discordgo.Channel\n\tvar r1 error\n\tif rf, ok := ret.Get(0).(func() (*discordgo.Channel, error)); ok {\n\t\treturn rf()\n\t}\n\tif rf, ok := ret.Get(0).(func() *discordgo.Channel); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*discordgo.Channel)\n\t\t}\n\t}\n\n\tif rf, ok := ret.Get(1).(func() error); ok {\n\t\tr1 = rf()\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func NewMockChannelProvider(ctx fab.Context) (*MockChannelProvider, error) {\n\tchannels := make(map[string]fab.Channel)\n\n\t// Create a mock client with the mock channel\n\tcp := MockChannelProvider{\n\t\tctx,\n\t\tchannels,\n\t}\n\treturn &cp, nil\n}", "func (suite *KeeperTestSuite) TestChanCloseInit() {\n\tvar (\n\t\tpath *ibctesting.Path\n\t\tchannelCap *capabilitytypes.Capability\n\t)\n\n\ttestCases := []testCase{\n\t\t{\"success\", func() {\n\t\t\tsuite.coordinator.Setup(path)\n\t\t\tchannelCap = suite.chainA.GetChannelCapability(path.EndpointA.ChannelConfig.PortID, path.EndpointA.ChannelID)\n\t\t}, true},\n\t\t{\"channel doesn't exist\", func() {\n\t\t\t// any non-nil values work for connections\n\t\t\tpath.EndpointA.ConnectionID = ibctesting.FirstConnectionID\n\t\t\tpath.EndpointB.ConnectionID = ibctesting.FirstConnectionID\n\n\t\t\tpath.EndpointA.ChannelID = ibctesting.FirstChannelID\n\t\t\tpath.EndpointB.ChannelID = ibctesting.FirstChannelID\n\n\t\t\t// ensure channel capability check passes\n\t\t\tsuite.chainA.CreateChannelCapability(suite.chainA.GetSimApp().ScopedIBCMockKeeper, path.EndpointA.ChannelConfig.PortID, path.EndpointA.ChannelID)\n\t\t\tchannelCap = suite.chainA.GetChannelCapability(path.EndpointA.ChannelConfig.PortID, path.EndpointA.ChannelID)\n\t\t}, false},\n\t\t{\"channel state is CLOSED\", func() {\n\t\t\tsuite.coordinator.Setup(path)\n\t\t\tchannelCap = suite.chainA.GetChannelCapability(path.EndpointA.ChannelConfig.PortID, path.EndpointA.ChannelID)\n\n\t\t\t// close channel\n\t\t\terr := path.EndpointA.SetChannelClosed()\n\t\t\tsuite.Require().NoError(err)\n\t\t}, false},\n\t\t{\"connection not found\", func() {\n\t\t\tsuite.coordinator.Setup(path)\n\t\t\tchannelCap = suite.chainA.GetChannelCapability(path.EndpointA.ChannelConfig.PortID, path.EndpointA.ChannelID)\n\n\t\t\t// set the channel's connection hops to wrong connection ID\n\t\t\tchannel := path.EndpointA.GetChannel()\n\t\t\tchannel.ConnectionHops[0] = \"doesnotexist\"\n\t\t\tsuite.chainA.App.GetIBCKeeper().ChannelKeeper.SetChannel(suite.chainA.GetContext(), path.EndpointA.ChannelConfig.PortID, path.EndpointA.ChannelID, channel)\n\t\t}, false},\n\t\t{\"connection is not OPEN\", func() {\n\t\t\tsuite.coordinator.SetupClients(path)\n\n\t\t\terr := path.EndpointA.ConnOpenInit()\n\t\t\tsuite.Require().NoError(err)\n\n\t\t\t// create channel in init\n\t\t\tpath.SetChannelOrdered()\n\t\t\terr = path.EndpointA.ChanOpenInit()\n\n\t\t\t// ensure channel capability check passes\n\t\t\tsuite.chainA.CreateChannelCapability(suite.chainA.GetSimApp().ScopedIBCMockKeeper, path.EndpointA.ChannelConfig.PortID, path.EndpointA.ChannelID)\n\t\t\tchannelCap = suite.chainA.GetChannelCapability(path.EndpointA.ChannelConfig.PortID, path.EndpointA.ChannelID)\n\t\t}, false},\n\t\t{\"channel capability not found\", func() {\n\t\t\tsuite.coordinator.Setup(path)\n\t\t\tchannelCap = capabilitytypes.NewCapability(3)\n\t\t}, false},\n\t}\n\n\tfor _, tc := range testCases {\n\t\ttc := tc\n\t\tsuite.Run(fmt.Sprintf(\"Case %s\", tc.msg), func() {\n\t\t\tsuite.SetupTest() // reset\n\t\t\tpath = ibctesting.NewPath(suite.chainA, suite.chainB)\n\n\t\t\ttc.malleate()\n\n\t\t\terr := suite.chainA.App.GetIBCKeeper().ChannelKeeper.ChanCloseInit(\n\t\t\t\tsuite.chainA.GetContext(), path.EndpointA.ChannelConfig.PortID, ibctesting.FirstChannelID, channelCap,\n\t\t\t)\n\n\t\t\tif tc.expPass {\n\t\t\t\tsuite.Require().NoError(err)\n\t\t\t} else {\n\t\t\t\tsuite.Require().Error(err)\n\t\t\t}\n\t\t})\n\t}\n}", "func (p *Provider) Provide(configurationChan chan<- dynamic.Message, pool *safe.Pool) error {\n\tctx := log.With(context.Background(), log.Str(log.ProviderName, p.name))\n\tlogger := log.FromContext(ctx)\n\n\toperation := func() error {\n\t\tif _, err := p.kvClient.Exists(path.Join(p.RootKey, \"qmslkjdfmqlskdjfmqlksjazçueznbvbwzlkajzebvkwjdcqmlsfj\"), nil); err != nil {\n\t\t\treturn fmt.Errorf(\"KV store connection error: %w\", err)\n\t\t}\n\t\treturn nil\n\t}\n\n\tnotify := func(err error, time time.Duration) {\n\t\tlogger.Errorf(\"KV connection error: %+v, retrying in %s\", err, time)\n\t}\n\terr := backoff.RetryNotify(safe.OperationWithRecover(operation), job.NewBackOff(backoff.NewExponentialBackOff()), notify)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"cannot connect to KV server: %w\", err)\n\t}\n\n\tconfiguration, err := p.buildConfiguration()\n\tif err != nil {\n\t\tlogger.Errorf(\"Cannot build the configuration: %v\", err)\n\t} else {\n\t\tconfigurationChan <- dynamic.Message{\n\t\t\tProviderName: p.name,\n\t\t\tConfiguration: configuration,\n\t\t}\n\t}\n\n\tpool.GoCtx(func(ctxPool context.Context) {\n\t\tctxLog := log.With(ctxPool, log.Str(log.ProviderName, p.name))\n\n\t\terr := p.watchKv(ctxLog, configurationChan)\n\t\tif err != nil {\n\t\t\tlogger.Errorf(\"Cannot watch KV store: %v\", err)\n\t\t}\n\t})\n\n\treturn nil\n}", "func (m *MockRConnectionInterface) Channel() (*amqp.Channel, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Channel\")\n\tret0, _ := ret[0].(*amqp.Channel)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func TestKnativeEventingKafkaChannelAcceptance(t *testing.T) {\n\t// test meta for the Kafka channel\n\tname := \"test-kafka-channel\"\n\tnamespace := \"knative-eventing\"\n\n\t// load cluster config\n\tconfig := loadConfigOrDie(t)\n\n\t// prepare a Kafka client\n\tkafkaClient := kafkaclientset.NewForConfigOrDie(config).KafkaChannels(namespace)\n\n\t// cleanup test resources gracefully when an interrupt signal is received\n\tinterrupted := cleanupOnInterrupt(t, interruptSignals, func() { deleteChannel(t, kafkaClient, name) })\n\tdefer close(interrupted)\n\n\t// cleanup the Kafka channel when the test is finished\n\tdefer deleteChannel(t, kafkaClient, name)\n\n\t// delete the Kafka channel if existed before to make sure that\n\t// the new channel to be created has the correct structure and data\n\tif err := deleteChannelIfExistsAndWaitUntilDeleted(t, interrupted, kafkaClient, name, 5*time.Second, 10, retry.FixedDelay); err != nil {\n\t\tt.Fatalf(\"test failed with error: %s\", err)\n\t}\n\n\t// create a Kafka channel\n\tif _, err := kafkaClient.Create(newKafkaChannel(name, namespace)); err != nil {\n\t\tt.Fatalf(\"cannot create a Kafka channel: %s: error: %v\", name, err)\n\t} else {\n\t\tt.Logf(\"created Kafka channel: %s\", name)\n\t}\n\n\t// assert the Kafka channel status to be ready\n\tif err := checkChannelReadyWithRetry(t, interrupted, kafkaClient, name, 5*time.Second, 10, retry.FixedDelay); err != nil {\n\t\tt.Fatalf(\"test failed with error: %s\", err)\n\t} else {\n\t\tt.Logf(\"test finished successfully\")\n\t}\n\n\t// TODO(marcobebway) extend the test to assert event delivery also works using the Kafka channel https://github.com/kyma-project/kyma/issues/7015.\n}", "func InvalidChannel(plat int8, srcCh, cfgCh string) bool {\n\treturn plat == PlatAndroid && cfgCh != \"*\" && cfgCh != srcCh\n}", "func (suite *KeeperTestSuite) TestChanCloseConfirm() {\n\tvar (\n\t\tpath *ibctesting.Path\n\t\tchannelCap *capabilitytypes.Capability\n\t\theightDiff uint64\n\t)\n\n\ttestCases := []testCase{\n\t\t{\"success\", func() {\n\t\t\tsuite.coordinator.Setup(path)\n\t\t\tchannelCap = suite.chainB.GetChannelCapability(path.EndpointB.ChannelConfig.PortID, path.EndpointB.ChannelID)\n\n\t\t\terr := path.EndpointA.SetChannelClosed()\n\t\t\tsuite.Require().NoError(err)\n\t\t}, true},\n\t\t{\"channel doesn't exist\", func() {\n\t\t\t// any non-nil values work for connections\n\t\t\tpath.EndpointA.ChannelID = ibctesting.FirstChannelID\n\t\t\tpath.EndpointB.ChannelID = ibctesting.FirstChannelID\n\n\t\t\t// ensure channel capability check passes\n\t\t\tsuite.chainB.CreateChannelCapability(suite.chainB.GetSimApp().ScopedIBCMockKeeper, path.EndpointB.ChannelConfig.PortID, ibctesting.FirstChannelID)\n\t\t\tchannelCap = suite.chainB.GetChannelCapability(path.EndpointB.ChannelConfig.PortID, ibctesting.FirstChannelID)\n\t\t}, false},\n\t\t{\"channel state is CLOSED\", func() {\n\t\t\tsuite.coordinator.Setup(path)\n\t\t\tchannelCap = suite.chainB.GetChannelCapability(path.EndpointB.ChannelConfig.PortID, path.EndpointB.ChannelID)\n\n\t\t\terr := path.EndpointB.SetChannelClosed()\n\t\t\tsuite.Require().NoError(err)\n\t\t}, false},\n\t\t{\"connection not found\", func() {\n\t\t\tsuite.coordinator.Setup(path)\n\t\t\tchannelCap = suite.chainB.GetChannelCapability(path.EndpointB.ChannelConfig.PortID, path.EndpointB.ChannelID)\n\n\t\t\t// set the channel's connection hops to wrong connection ID\n\t\t\tchannel := path.EndpointB.GetChannel()\n\t\t\tchannel.ConnectionHops[0] = \"doesnotexist\"\n\t\t\tsuite.chainB.App.GetIBCKeeper().ChannelKeeper.SetChannel(suite.chainB.GetContext(), path.EndpointB.ChannelConfig.PortID, path.EndpointB.ChannelID, channel)\n\t\t}, false},\n\t\t{\"connection is not OPEN\", func() {\n\t\t\tsuite.coordinator.SetupClients(path)\n\n\t\t\terr := path.EndpointB.ConnOpenInit()\n\t\t\tsuite.Require().NoError(err)\n\n\t\t\t// create channel in init\n\t\t\tpath.SetChannelOrdered()\n\t\t\terr = path.EndpointB.ChanOpenInit()\n\t\t\tsuite.Require().NoError(err)\n\n\t\t\t// ensure channel capability check passes\n\t\t\tsuite.chainB.CreateChannelCapability(suite.chainB.GetSimApp().ScopedIBCMockKeeper, path.EndpointB.ChannelConfig.PortID, path.EndpointB.ChannelID)\n\t\t\tchannelCap = suite.chainB.GetChannelCapability(path.EndpointB.ChannelConfig.PortID, path.EndpointB.ChannelID)\n\t\t}, false},\n\t\t{\"consensus state not found\", func() {\n\t\t\tsuite.coordinator.Setup(path)\n\t\t\tchannelCap = suite.chainB.GetChannelCapability(path.EndpointB.ChannelConfig.PortID, path.EndpointB.ChannelID)\n\n\t\t\terr := path.EndpointA.SetChannelClosed()\n\t\t\tsuite.Require().NoError(err)\n\n\t\t\theightDiff = 3\n\t\t}, false},\n\t\t{\"channel verification failed\", func() {\n\t\t\t// channel not closed\n\t\t\tsuite.coordinator.Setup(path)\n\t\t\tchannelCap = suite.chainB.GetChannelCapability(path.EndpointB.ChannelConfig.PortID, path.EndpointB.ChannelID)\n\t\t}, false},\n\t\t{\"channel capability not found\", func() {\n\t\t\tsuite.coordinator.Setup(path)\n\t\t\tchannelCap = suite.chainB.GetChannelCapability(path.EndpointB.ChannelConfig.PortID, path.EndpointB.ChannelID)\n\n\t\t\terr := path.EndpointA.SetChannelClosed()\n\t\t\tsuite.Require().NoError(err)\n\n\t\t\tchannelCap = capabilitytypes.NewCapability(3)\n\t\t}, false},\n\t}\n\n\tfor _, tc := range testCases {\n\t\ttc := tc\n\t\tsuite.Run(fmt.Sprintf(\"Case %s\", tc.msg), func() {\n\t\t\tsuite.SetupTest() // reset\n\t\t\theightDiff = 0 // must explicitly be changed\n\t\t\tpath = ibctesting.NewPath(suite.chainA, suite.chainB)\n\n\t\t\ttc.malleate()\n\n\t\t\tchannelKey := host.ChannelKey(path.EndpointA.ChannelConfig.PortID, ibctesting.FirstChannelID)\n\t\t\tproof, proofHeight := suite.chainA.QueryProof(channelKey)\n\n\t\t\terr := suite.chainB.App.GetIBCKeeper().ChannelKeeper.ChanCloseConfirm(\n\t\t\t\tsuite.chainB.GetContext(), path.EndpointB.ChannelConfig.PortID, ibctesting.FirstChannelID, channelCap,\n\t\t\t\tproof, malleateHeight(proofHeight, heightDiff),\n\t\t\t)\n\n\t\t\tif tc.expPass {\n\t\t\t\tsuite.Require().NoError(err)\n\t\t\t} else {\n\t\t\t\tsuite.Require().Error(err)\n\t\t\t}\n\t\t})\n\t}\n}", "func (suite *KeeperTestSuite) TestChanOpenConfirm() {\n\tvar (\n\t\tpath *ibctesting.Path\n\t\tchannelCap *capabilitytypes.Capability\n\t\theightDiff uint64\n\t)\n\ttestCases := []testCase{\n\t\t{\"success\", func() {\n\t\t\tsuite.coordinator.SetupConnections(path)\n\t\t\tpath.SetChannelOrdered()\n\n\t\t\terr := path.EndpointA.ChanOpenInit()\n\t\t\tsuite.Require().NoError(err)\n\n\t\t\terr = path.EndpointB.ChanOpenTry()\n\t\t\tsuite.Require().NoError(err)\n\n\t\t\terr = path.EndpointA.ChanOpenAck()\n\t\t\tsuite.Require().NoError(err)\n\n\t\t\tchannelCap = suite.chainB.GetChannelCapability(path.EndpointB.ChannelConfig.PortID, path.EndpointB.ChannelID)\n\t\t}, true},\n\t\t{\"channel doesn't exist\", func() {}, false},\n\t\t{\"channel state is not TRYOPEN\", func() {\n\t\t\t// create fully open channels on both cahins\n\t\t\tsuite.coordinator.Setup(path)\n\t\t\tchannelCap = suite.chainB.GetChannelCapability(path.EndpointB.ChannelConfig.PortID, path.EndpointB.ChannelID)\n\t\t}, false},\n\t\t{\"connection not found\", func() {\n\t\t\tsuite.coordinator.SetupConnections(path)\n\t\t\tpath.SetChannelOrdered()\n\n\t\t\terr := path.EndpointA.ChanOpenInit()\n\t\t\tsuite.Require().NoError(err)\n\n\t\t\terr = path.EndpointB.ChanOpenTry()\n\t\t\tsuite.Require().NoError(err)\n\n\t\t\terr = path.EndpointA.ChanOpenAck()\n\t\t\tsuite.Require().NoError(err)\n\n\t\t\tchannelCap = suite.chainB.GetChannelCapability(path.EndpointB.ChannelConfig.PortID, path.EndpointB.ChannelID)\n\n\t\t\t// set the channel's connection hops to wrong connection ID\n\t\t\tchannel := path.EndpointB.GetChannel()\n\t\t\tchannel.ConnectionHops[0] = \"doesnotexist\"\n\t\t\tsuite.chainB.App.GetIBCKeeper().ChannelKeeper.SetChannel(suite.chainB.GetContext(), path.EndpointB.ChannelConfig.PortID, path.EndpointB.ChannelID, channel)\n\t\t}, false},\n\t\t{\"connection is not OPEN\", func() {\n\t\t\tsuite.coordinator.SetupClients(path)\n\n\t\t\terr := path.EndpointB.ConnOpenInit()\n\t\t\tsuite.Require().NoError(err)\n\n\t\t\tsuite.chainB.CreateChannelCapability(suite.chainB.GetSimApp().ScopedIBCMockKeeper, path.EndpointB.ChannelConfig.PortID, ibctesting.FirstChannelID)\n\t\t\tchannelCap = suite.chainB.GetChannelCapability(path.EndpointB.ChannelConfig.PortID, ibctesting.FirstChannelID)\n\t\t}, false},\n\t\t{\"consensus state not found\", func() {\n\t\t\tsuite.coordinator.SetupConnections(path)\n\t\t\tpath.SetChannelOrdered()\n\n\t\t\terr := path.EndpointA.ChanOpenInit()\n\t\t\tsuite.Require().NoError(err)\n\n\t\t\terr = path.EndpointB.ChanOpenTry()\n\t\t\tsuite.Require().NoError(err)\n\n\t\t\terr = path.EndpointA.ChanOpenAck()\n\t\t\tsuite.Require().NoError(err)\n\n\t\t\tchannelCap = suite.chainB.GetChannelCapability(path.EndpointB.ChannelConfig.PortID, path.EndpointB.ChannelID)\n\n\t\t\theightDiff = 3\n\t\t}, false},\n\t\t{\"channel verification failed\", func() {\n\t\t\t// chainA is INIT, chainB in TRYOPEN\n\t\t\tsuite.coordinator.SetupConnections(path)\n\t\t\tpath.SetChannelOrdered()\n\n\t\t\terr := path.EndpointA.ChanOpenInit()\n\t\t\tsuite.Require().NoError(err)\n\n\t\t\terr = path.EndpointB.ChanOpenTry()\n\t\t\tsuite.Require().NoError(err)\n\n\t\t\tchannelCap = suite.chainB.GetChannelCapability(path.EndpointB.ChannelConfig.PortID, path.EndpointB.ChannelID)\n\t\t}, false},\n\t\t{\"channel capability not found\", func() {\n\t\t\tsuite.coordinator.SetupConnections(path)\n\t\t\tpath.SetChannelOrdered()\n\n\t\t\terr := path.EndpointA.ChanOpenInit()\n\t\t\tsuite.Require().NoError(err)\n\n\t\t\terr = path.EndpointB.ChanOpenTry()\n\t\t\tsuite.Require().NoError(err)\n\n\t\t\terr = path.EndpointA.ChanOpenAck()\n\t\t\tsuite.Require().NoError(err)\n\n\t\t\tchannelCap = capabilitytypes.NewCapability(6)\n\t\t}, false},\n\t}\n\n\tfor _, tc := range testCases {\n\t\ttc := tc\n\t\tsuite.Run(fmt.Sprintf(\"Case %s\", tc.msg), func() {\n\t\t\tsuite.SetupTest() // reset\n\t\t\theightDiff = 0 // must be explicitly changed\n\t\t\tpath = ibctesting.NewPath(suite.chainA, suite.chainB)\n\n\t\t\ttc.malleate()\n\n\t\t\tif path.EndpointB.ClientID != \"\" {\n\t\t\t\t// ensure client is up to date\n\t\t\t\terr := path.EndpointB.UpdateClient()\n\t\t\t\tsuite.Require().NoError(err)\n\n\t\t\t}\n\n\t\t\tchannelKey := host.ChannelKey(path.EndpointA.ChannelConfig.PortID, ibctesting.FirstChannelID)\n\t\t\tproof, proofHeight := suite.chainA.QueryProof(channelKey)\n\n\t\t\terr := suite.chainB.App.GetIBCKeeper().ChannelKeeper.ChanOpenConfirm(\n\t\t\t\tsuite.chainB.GetContext(), path.EndpointB.ChannelConfig.PortID, ibctesting.FirstChannelID,\n\t\t\t\tchannelCap, proof, malleateHeight(proofHeight, heightDiff),\n\t\t\t)\n\n\t\t\tif tc.expPass {\n\t\t\t\tsuite.Require().NoError(err)\n\t\t\t} else {\n\t\t\t\tsuite.Require().Error(err)\n\t\t\t}\n\t\t})\n\t}\n}", "func TestChannelShow(t *testing.T) {\n\t// expecting this channel\n\twrt := channels[0]\n\n\t// create the mock repo and controller\n\trepo := &mock.ChannelRepo{FindIDFunc: findChannelID}\n\tcontroller := NewChannel(repo)\n\n\t// create a mock request\n\tp := httprouter.Param{Key: \"id\", Value: \"1\"}\n\treq, e := http.NewRequest(http.MethodGet, \"/channel/\"+p.Value, nil)\n\n\tif e != nil {\n\t\tt.Fatal(e)\n\t}\n\n\t// embed the channel ID in the request's\n\t// context (necessary for controller.Show to function)\n\tuf.EmbedParams(req, httprouter.Param{Key: \"id\", Value: \"1\"})\n\n\t// create a response recorder and call the show method\n\tw := httptest.NewRecorder()\n\te = controller.Show(w, req)\n\n\tif e != nil {\n\t\tt.Fatal(e)\n\t}\n\n\t// check the repo was hit\n\tif !repo.FindIDCalled {\n\t\tt.Error(\"Did not call repo.FindID\")\n\t}\n\n\tres := w.Result()\n\n\t// ensure the content type is application/json\n\tcheckCT(res, t)\n\n\t// read and unmarshal the body\n\tdefer res.Body.Close()\n\tbody, e := io.ReadAll(res.Body)\n\n\tif e != nil {\n\t\tt.Fatal(e)\n\t}\n\n\treceived := are_hub.Channel{}\n\te = json.Unmarshal(body, &received)\n\n\tif e != nil {\n\t\tt.Fatal(e)\n\t}\n\n\t// compare the expected and received channels\n\tif received.Name != wrt.Name {\n\t\tt.Fatalf(\"Expected: %+v. Actual: %+v.\", wrt, received)\n\t}\n\n\t// check show returns 404 for an invalid ID\n\tp = httprouter.Param{Key: \"id\", Value: \"-1\"}\n\ttest404(t, http.MethodGet, \"/channel/\"+p.Value, nil, controller.Show, p)\n}", "func TestChannelFactoryPattern(t *testing.T) {\n\tsuck(pump(5))\n\ttime.Sleep(1e9)\n}", "func (suite *KeeperTestSuite) TestChanOpenAck() {\n\tvar (\n\t\tpath *ibctesting.Path\n\t\tcounterpartyChannelID string\n\t\tchannelCap *capabilitytypes.Capability\n\t\theightDiff uint64\n\t)\n\n\ttestCases := []testCase{\n\t\t{\"success\", func() {\n\t\t\tsuite.coordinator.SetupConnections(path)\n\t\t\tpath.SetChannelOrdered()\n\t\t\terr := path.EndpointA.ChanOpenInit()\n\t\t\tsuite.Require().NoError(err)\n\n\t\t\terr = path.EndpointB.ChanOpenTry()\n\t\t\tsuite.Require().NoError(err)\n\n\t\t\tchannelCap = suite.chainA.GetChannelCapability(path.EndpointA.ChannelConfig.PortID, path.EndpointA.ChannelID)\n\t\t}, true},\n\t\t{\"success with empty stored counterparty channel ID\", func() {\n\t\t\tsuite.coordinator.SetupConnections(path)\n\t\t\tpath.SetChannelOrdered()\n\n\t\t\terr := path.EndpointA.ChanOpenInit()\n\t\t\tsuite.Require().NoError(err)\n\n\t\t\terr = path.EndpointB.ChanOpenTry()\n\t\t\tsuite.Require().NoError(err)\n\n\t\t\t// set the channel's counterparty channel identifier to empty string\n\t\t\tchannel := path.EndpointA.GetChannel()\n\t\t\tchannel.Counterparty.ChannelId = \"\"\n\n\t\t\t// use a different channel identifier\n\t\t\tcounterpartyChannelID = path.EndpointB.ChannelID\n\n\t\t\tsuite.chainA.App.GetIBCKeeper().ChannelKeeper.SetChannel(suite.chainA.GetContext(), path.EndpointA.ChannelConfig.PortID, path.EndpointA.ChannelID, channel)\n\n\t\t\tchannelCap = suite.chainA.GetChannelCapability(path.EndpointA.ChannelConfig.PortID, path.EndpointA.ChannelID)\n\t\t}, true},\n\t\t{\"channel doesn't exist\", func() {}, false},\n\t\t{\"channel state is not INIT or TRYOPEN\", func() {\n\t\t\t// create fully open channels on both chains\n\t\t\tsuite.coordinator.Setup(path)\n\t\t\tchannelCap = suite.chainA.GetChannelCapability(path.EndpointA.ChannelConfig.PortID, path.EndpointA.ChannelID)\n\t\t}, false},\n\t\t{\"connection not found\", func() {\n\t\t\tsuite.coordinator.SetupConnections(path)\n\t\t\tpath.SetChannelOrdered()\n\t\t\terr := path.EndpointA.ChanOpenInit()\n\t\t\tsuite.Require().NoError(err)\n\n\t\t\terr = path.EndpointB.ChanOpenTry()\n\t\t\tsuite.Require().NoError(err)\n\n\t\t\tchannelCap = suite.chainA.GetChannelCapability(path.EndpointA.ChannelConfig.PortID, path.EndpointA.ChannelID)\n\n\t\t\t// set the channel's connection hops to wrong connection ID\n\t\t\tchannel := path.EndpointA.GetChannel()\n\t\t\tchannel.ConnectionHops[0] = \"doesnotexist\"\n\t\t\tsuite.chainA.App.GetIBCKeeper().ChannelKeeper.SetChannel(suite.chainA.GetContext(), path.EndpointA.ChannelConfig.PortID, path.EndpointA.ChannelID, channel)\n\t\t}, false},\n\t\t{\"connection is not OPEN\", func() {\n\t\t\tsuite.coordinator.SetupClients(path)\n\n\t\t\terr := path.EndpointA.ConnOpenInit()\n\t\t\tsuite.Require().NoError(err)\n\n\t\t\t// create channel in init\n\t\t\tpath.SetChannelOrdered()\n\n\t\t\terr = path.EndpointA.ChanOpenInit()\n\t\t\tsuite.Require().NoError(err)\n\n\t\t\tsuite.chainA.CreateChannelCapability(suite.chainA.GetSimApp().ScopedIBCMockKeeper, path.EndpointA.ChannelConfig.PortID, path.EndpointA.ChannelID)\n\t\t\tchannelCap = suite.chainA.GetChannelCapability(path.EndpointA.ChannelConfig.PortID, path.EndpointA.ChannelID)\n\t\t}, false},\n\t\t{\"consensus state not found\", func() {\n\t\t\tsuite.coordinator.SetupConnections(path)\n\t\t\tpath.SetChannelOrdered()\n\n\t\t\terr := path.EndpointA.ChanOpenInit()\n\t\t\tsuite.Require().NoError(err)\n\n\t\t\terr = path.EndpointB.ChanOpenTry()\n\t\t\tsuite.Require().NoError(err)\n\n\t\t\tchannelCap = suite.chainA.GetChannelCapability(path.EndpointA.ChannelConfig.PortID, path.EndpointA.ChannelID)\n\n\t\t\theightDiff = 3 // consensus state doesn't exist at this height\n\t\t}, false},\n\t\t{\"invalid counterparty channel identifier\", func() {\n\t\t\tsuite.coordinator.SetupConnections(path)\n\t\t\tpath.SetChannelOrdered()\n\n\t\t\terr := path.EndpointA.ChanOpenInit()\n\t\t\tsuite.Require().NoError(err)\n\n\t\t\terr = path.EndpointB.ChanOpenTry()\n\t\t\tsuite.Require().NoError(err)\n\n\t\t\tcounterpartyChannelID = \"otheridentifier\"\n\n\t\t\tchannelCap = suite.chainA.GetChannelCapability(path.EndpointA.ChannelConfig.PortID, path.EndpointA.ChannelID)\n\t\t}, false},\n\t\t{\"channel verification failed\", func() {\n\t\t\t// chainB is INIT, chainA in TRYOPEN\n\t\t\tsuite.coordinator.SetupConnections(path)\n\t\t\tpath.SetChannelOrdered()\n\n\t\t\terr := path.EndpointB.ChanOpenInit()\n\t\t\tsuite.Require().NoError(err)\n\n\t\t\terr = path.EndpointA.ChanOpenTry()\n\t\t\tsuite.Require().NoError(err)\n\n\t\t\tchannelCap = suite.chainA.GetChannelCapability(path.EndpointA.ChannelConfig.PortID, path.EndpointA.ChannelID)\n\t\t}, false},\n\t\t{\"channel capability not found\", func() {\n\t\t\tsuite.coordinator.SetupConnections(path)\n\t\t\tpath.SetChannelOrdered()\n\t\t\terr := path.EndpointA.ChanOpenInit()\n\t\t\tsuite.Require().NoError(err)\n\n\t\t\tpath.EndpointB.ChanOpenTry()\n\n\t\t\tchannelCap = capabilitytypes.NewCapability(6)\n\t\t}, false},\n\t}\n\n\tfor _, tc := range testCases {\n\t\ttc := tc\n\t\tsuite.Run(fmt.Sprintf(\"Case %s\", tc.msg), func() {\n\t\t\tsuite.SetupTest() // reset\n\t\t\tcounterpartyChannelID = \"\" // must be explicitly changed in malleate\n\t\t\theightDiff = 0 // must be explicitly changed\n\t\t\tpath = ibctesting.NewPath(suite.chainA, suite.chainB)\n\n\t\t\ttc.malleate()\n\n\t\t\tif counterpartyChannelID == \"\" {\n\t\t\t\tcounterpartyChannelID = ibctesting.FirstChannelID\n\t\t\t}\n\n\t\t\tif path.EndpointA.ClientID != \"\" {\n\t\t\t\t// ensure client is up to date\n\t\t\t\terr := path.EndpointA.UpdateClient()\n\t\t\t\tsuite.Require().NoError(err)\n\t\t\t}\n\n\t\t\tchannelKey := host.ChannelKey(path.EndpointB.ChannelConfig.PortID, ibctesting.FirstChannelID)\n\t\t\tproof, proofHeight := suite.chainB.QueryProof(channelKey)\n\n\t\t\terr := suite.chainA.App.GetIBCKeeper().ChannelKeeper.ChanOpenAck(\n\t\t\t\tsuite.chainA.GetContext(), path.EndpointA.ChannelConfig.PortID, path.EndpointA.ChannelID, channelCap, path.EndpointB.ChannelConfig.Version, counterpartyChannelID,\n\t\t\t\tproof, malleateHeight(proofHeight, heightDiff),\n\t\t\t)\n\n\t\t\tif tc.expPass {\n\t\t\t\tsuite.Require().NoError(err)\n\t\t\t} else {\n\t\t\t\tsuite.Require().Error(err)\n\t\t\t}\n\t\t})\n\t}\n}", "func (m *MockCallResult) Channel() <-chan *Result {\n\targs := m.MethodCalled(\"Channel\")\n\n\tif resultChan := args.Get(0); resultChan != nil {\n\t\treturn resultChan.(<-chan *Result)\n\t}\n\n\treturn nil\n}", "func (scnb *SupplyChainNodeBuilder) requireProvider() bool {\n\tif scnb.currentProvider == nil {\n\t\treturn false\n\t}\n\treturn true\n}", "func (amqpSuite *AmqpSuite) ChannelConsumeTester() *amqp.ChannelTesting {\n\treturn amqpSuite.ChannelConsume().Test(amqpSuite.T())\n}", "func (p *Provider) Provide(configurationChan chan<- types.ConfigMessage, pool *safe.Pool, constraints types.Constraints) error {\n\tif p.Metadata == nil {\n\t\treturn p.apiProvide(configurationChan, pool, constraints)\n\t}\n\treturn p.metadataProvide(configurationChan, pool, constraints)\n}", "func (suite *KeeperTestSuite) TestChanOpenTry() {\n\tvar (\n\t\tpath *ibctesting.Path\n\t\tpreviousChannelID string\n\t\tportCap *capabilitytypes.Capability\n\t\theightDiff uint64\n\t)\n\n\ttestCases := []testCase{\n\t\t{\"success\", func() {\n\t\t\tsuite.coordinator.SetupConnections(path)\n\t\t\tpath.SetChannelOrdered()\n\t\t\tpath.EndpointA.ChanOpenInit()\n\n\t\t\tsuite.chainB.CreatePortCapability(suite.chainB.GetSimApp().ScopedIBCMockKeeper, ibctesting.MockPort)\n\t\t\tportCap = suite.chainB.GetPortCapability(ibctesting.MockPort)\n\t\t}, true},\n\t\t{\"success with crossing hello\", func() {\n\t\t\tsuite.coordinator.SetupConnections(path)\n\t\t\tpath.SetChannelOrdered()\n\t\t\terr := suite.coordinator.ChanOpenInitOnBothChains(path)\n\t\t\tsuite.Require().NoError(err)\n\n\t\t\tpreviousChannelID = path.EndpointB.ChannelID\n\t\t\tportCap = suite.chainB.GetPortCapability(ibctesting.MockPort)\n\t\t}, true},\n\t\t{\"previous channel with invalid state\", func() {\n\t\t\tsuite.coordinator.SetupConnections(path)\n\n\t\t\t// make previous channel have wrong ordering\n\t\t\tpath.EndpointA.ChanOpenInit()\n\t\t}, false},\n\t\t{\"connection doesn't exist\", func() {\n\t\t\tpath.EndpointA.ConnectionID = ibctesting.FirstConnectionID\n\t\t\tpath.EndpointB.ConnectionID = ibctesting.FirstConnectionID\n\n\t\t\t// pass capability check\n\t\t\tsuite.chainB.CreatePortCapability(suite.chainB.GetSimApp().ScopedIBCMockKeeper, ibctesting.MockPort)\n\t\t\tportCap = suite.chainB.GetPortCapability(ibctesting.MockPort)\n\t\t}, false},\n\t\t{\"connection is not OPEN\", func() {\n\t\t\tsuite.coordinator.SetupClients(path)\n\t\t\t// pass capability check\n\t\t\tsuite.chainB.CreatePortCapability(suite.chainB.GetSimApp().ScopedIBCMockKeeper, ibctesting.MockPort)\n\t\t\tportCap = suite.chainB.GetPortCapability(ibctesting.MockPort)\n\n\t\t\terr := path.EndpointB.ConnOpenInit()\n\t\t\tsuite.Require().NoError(err)\n\t\t}, false},\n\t\t{\"consensus state not found\", func() {\n\t\t\tsuite.coordinator.SetupConnections(path)\n\t\t\tpath.SetChannelOrdered()\n\t\t\tpath.EndpointA.ChanOpenInit()\n\n\t\t\tsuite.chainB.CreatePortCapability(suite.chainB.GetSimApp().ScopedIBCMockKeeper, ibctesting.MockPort)\n\t\t\tportCap = suite.chainB.GetPortCapability(ibctesting.MockPort)\n\n\t\t\theightDiff = 3 // consensus state doesn't exist at this height\n\t\t}, false},\n\t\t{\"channel verification failed\", func() {\n\t\t\t// not creating a channel on chainA will result in an invalid proof of existence\n\t\t\tsuite.coordinator.SetupConnections(path)\n\t\t\tportCap = suite.chainB.GetPortCapability(ibctesting.MockPort)\n\t\t}, false},\n\t\t{\"port capability not found\", func() {\n\t\t\tsuite.coordinator.SetupConnections(path)\n\t\t\tpath.SetChannelOrdered()\n\t\t\tpath.EndpointA.ChanOpenInit()\n\n\t\t\tportCap = capabilitytypes.NewCapability(3)\n\t\t}, false},\n\t\t{\"connection version not negotiated\", func() {\n\t\t\tsuite.coordinator.SetupConnections(path)\n\t\t\tpath.SetChannelOrdered()\n\t\t\tpath.EndpointA.ChanOpenInit()\n\n\t\t\t// modify connB versions\n\t\t\tconn := path.EndpointB.GetConnection()\n\n\t\t\tversion := connectiontypes.NewVersion(\"2\", []string{\"ORDER_ORDERED\", \"ORDER_UNORDERED\"})\n\t\t\tconn.Versions = append(conn.Versions, version)\n\n\t\t\tsuite.chainB.App.GetIBCKeeper().ConnectionKeeper.SetConnection(\n\t\t\t\tsuite.chainB.GetContext(),\n\t\t\t\tpath.EndpointB.ConnectionID, conn,\n\t\t\t)\n\t\t\tsuite.chainB.CreatePortCapability(suite.chainB.GetSimApp().ScopedIBCMockKeeper, ibctesting.MockPort)\n\t\t\tportCap = suite.chainB.GetPortCapability(ibctesting.MockPort)\n\t\t}, false},\n\t\t{\"connection does not support ORDERED channels\", func() {\n\t\t\tsuite.coordinator.SetupConnections(path)\n\t\t\tpath.SetChannelOrdered()\n\t\t\tpath.EndpointA.ChanOpenInit()\n\n\t\t\t// modify connA versions to only support UNORDERED channels\n\t\t\tconn := path.EndpointA.GetConnection()\n\n\t\t\tversion := connectiontypes.NewVersion(\"1\", []string{\"ORDER_UNORDERED\"})\n\t\t\tconn.Versions = []*connectiontypes.Version{version}\n\n\t\t\tsuite.chainA.App.GetIBCKeeper().ConnectionKeeper.SetConnection(\n\t\t\t\tsuite.chainA.GetContext(),\n\t\t\t\tpath.EndpointA.ConnectionID, conn,\n\t\t\t)\n\t\t\tsuite.chainA.CreatePortCapability(suite.chainA.GetSimApp().ScopedIBCMockKeeper, ibctesting.MockPort)\n\t\t\tportCap = suite.chainA.GetPortCapability(ibctesting.MockPort)\n\t\t}, false},\n\t}\n\n\tfor _, tc := range testCases {\n\t\ttc := tc\n\t\tsuite.Run(fmt.Sprintf(\"Case %s\", tc.msg), func() {\n\t\t\tsuite.SetupTest() // reset\n\t\t\theightDiff = 0 // must be explicitly changed in malleate\n\t\t\tpreviousChannelID = \"\"\n\t\t\tpath = ibctesting.NewPath(suite.chainA, suite.chainB)\n\n\t\t\ttc.malleate()\n\n\t\t\tif path.EndpointB.ClientID != \"\" {\n\t\t\t\t// ensure client is up to date\n\t\t\t\terr := path.EndpointB.UpdateClient()\n\t\t\t\tsuite.Require().NoError(err)\n\t\t\t}\n\n\t\t\tcounterparty := types.NewCounterparty(path.EndpointB.ChannelConfig.PortID, ibctesting.FirstChannelID)\n\n\t\t\tchannelKey := host.ChannelKey(counterparty.PortId, counterparty.ChannelId)\n\t\t\tproof, proofHeight := suite.chainA.QueryProof(channelKey)\n\n\t\t\tchannelID, cap, err := suite.chainB.App.GetIBCKeeper().ChannelKeeper.ChanOpenTry(\n\t\t\t\tsuite.chainB.GetContext(), types.ORDERED, []string{path.EndpointB.ConnectionID},\n\t\t\t\tpath.EndpointB.ChannelConfig.PortID, previousChannelID, portCap, counterparty, path.EndpointB.ChannelConfig.Version, path.EndpointA.ChannelConfig.Version,\n\t\t\t\tproof, malleateHeight(proofHeight, heightDiff),\n\t\t\t)\n\n\t\t\tif tc.expPass {\n\t\t\t\tsuite.Require().NoError(err)\n\t\t\t\tsuite.Require().NotNil(cap)\n\n\t\t\t\tchanCap, ok := suite.chainB.App.GetScopedIBCKeeper().GetCapability(\n\t\t\t\t\tsuite.chainB.GetContext(),\n\t\t\t\t\thost.ChannelCapabilityPath(path.EndpointB.ChannelConfig.PortID, channelID),\n\t\t\t\t)\n\t\t\t\tsuite.Require().True(ok, \"could not retrieve channel capapbility after successful ChanOpenTry\")\n\t\t\t\tsuite.Require().Equal(chanCap.String(), cap.String(), \"channel capability is not correct\")\n\t\t\t} else {\n\t\t\t\tsuite.Require().Error(err)\n\t\t\t}\n\t\t})\n\t}\n}", "func getAPIChannel(c api.ChannelProvider) (api.Channel, error) {\n\tch, err := c.NewAPIChannel()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif err := ch.CheckCompatiblity(vpe.AllMessages()...); err != nil {\n\t\treturn nil, fmt.Errorf(\"compatibility check failed: %w\", err)\n\t}\n\tif err := ch.CheckCompatiblity(interfaces.AllMessages()...); err != nil {\n\t\tlogInfo(\"compatibility check failed: %v\", err)\n\t}\n\treturn ch, nil\n}", "func (suite *KeeperTestSuite) TestSetChannel() {\n\t// create client and connections on both chains\n\tpath := ibctesting.NewPath(suite.chainA, suite.chainB)\n\tsuite.coordinator.SetupConnections(path)\n\n\t// check for channel to be created on chainA\n\t_, found := suite.chainA.App.GetIBCKeeper().ChannelKeeper.GetChannel(suite.chainA.GetContext(), path.EndpointA.ChannelConfig.PortID, path.EndpointA.ChannelID)\n\tsuite.False(found)\n\n\tpath.SetChannelOrdered()\n\n\t// init channel\n\terr := path.EndpointA.ChanOpenInit()\n\tsuite.NoError(err)\n\n\tstoredChannel, found := suite.chainA.App.GetIBCKeeper().ChannelKeeper.GetChannel(suite.chainA.GetContext(), path.EndpointA.ChannelConfig.PortID, path.EndpointA.ChannelID)\n\t// counterparty channel id is empty after open init\n\texpectedCounterparty := types.NewCounterparty(path.EndpointB.ChannelConfig.PortID, \"\")\n\n\tsuite.True(found)\n\tsuite.Equal(types.INIT, storedChannel.State)\n\tsuite.Equal(types.ORDERED, storedChannel.Ordering)\n\tsuite.Equal(expectedCounterparty, storedChannel.Counterparty)\n}", "func (am AppModule) OnChanOpenTry(\n\tctx sdk.Context,\n\torder channeltypes.Order,\n\tconnectionHops []string,\n\tportID,\n\tchannelID string,\n\tchanCap *capabilitytypes.Capability,\n\tcounterparty channeltypes.Counterparty,\n\tversion,\n\tcounterpartyVersion string,\n) error {\n\t// TODO: Enforce ordering, currently relayers use ORDERED channels\n\n\tif counterparty.GetPortID() != commontypes.PortID {\n\t\treturn sdkerrors.Wrapf(porttypes.ErrInvalidPort, \"counterparty has invalid portid. expected: %s, got %s\", commontypes.PortID, counterparty.GetPortID())\n\t}\n\n\tif version != commontypes.Version {\n\t\treturn sdkerrors.Wrapf(porttypes.ErrInvalidPort, \"invalid version: %s, expected %s\", version, commontypes.Version)\n\t}\n\n\tif counterpartyVersion != commontypes.Version {\n\t\treturn sdkerrors.Wrapf(porttypes.ErrInvalidPort, \"invalid counterparty version: %s, expected %s\", counterpartyVersion, commontypes.Version)\n\t}\n\n\t// Claim channel capability passed back by IBC module\n\tif err := am.keeper.ClaimCapability(ctx, chanCap, host.ChannelCapabilityPath(portID, channelID)); err != nil {\n\t\treturn sdkerrors.Wrap(channeltypes.ErrChannelCapabilityNotFound, err.Error()+\"by cross chanOpenTry\")\n\t}\n\n\t// TODO: escrow\n\treturn nil\n}", "func TestChannelOpenOnAClosedConnectionFails_ReleasesAllocatedChannel(t *testing.T) {\n\tconn := integrationConnection(t, \"releases channel allocation\")\n\tconn.Close()\n\n\tbefore := len(conn.channels)\n\n\tif _, err := conn.Channel(); err != ErrClosed {\n\t\tt.Fatalf(\"channel.open on a closed connection %#v is expected to fail\", conn)\n\t}\n\n\tif len(conn.channels) != before {\n\t\tt.Fatalf(\"channel.open failed, but the allocated channel was not released\")\n\t}\n}", "func eventTestChannelConsumer(c *Consumer, mt *msgtracker, expCnt int) {\n\tfor ev := range c.Events() {\n\t\tif !handleTestEvent(c, mt, expCnt, ev) {\n\t\t\tbreak\n\t\t}\n\t}\n}", "func (mdhth *MockDHTHandler) Provider(string, bool) error {\n\treturn nil\n}", "func (suite *KeeperTestSuite) TestChanOpenInit() {\n\tvar (\n\t\tpath *ibctesting.Path\n\t\tfeatures []string\n\t\tportCap *capabilitytypes.Capability\n\t)\n\n\ttestCases := []testCase{\n\t\t{\"success\", func() {\n\t\t\tsuite.coordinator.SetupConnections(path)\n\t\t\tfeatures = []string{\"ORDER_ORDERED\", \"ORDER_UNORDERED\"}\n\t\t\tsuite.chainA.CreatePortCapability(suite.chainA.GetSimApp().ScopedIBCMockKeeper, ibctesting.MockPort)\n\t\t\tportCap = suite.chainA.GetPortCapability(ibctesting.MockPort)\n\t\t}, true},\n\t\t{\"channel already exists\", func() {\n\t\t\tsuite.coordinator.Setup(path)\n\t\t}, false},\n\t\t{\"connection doesn't exist\", func() {\n\t\t\t// any non-empty values\n\t\t\tpath.EndpointA.ConnectionID = \"connection-0\"\n\t\t\tpath.EndpointB.ConnectionID = \"connection-0\"\n\t\t}, false},\n\t\t{\"capability is incorrect\", func() {\n\t\t\tsuite.coordinator.SetupConnections(path)\n\t\t\tfeatures = []string{\"ORDER_ORDERED\", \"ORDER_UNORDERED\"}\n\t\t\tportCap = capabilitytypes.NewCapability(3)\n\t\t}, false},\n\t\t{\"connection version not negotiated\", func() {\n\t\t\tsuite.coordinator.SetupConnections(path)\n\n\t\t\t// modify connA versions\n\t\t\tconn := path.EndpointA.GetConnection()\n\n\t\t\tversion := connectiontypes.NewVersion(\"2\", []string{\"ORDER_ORDERED\", \"ORDER_UNORDERED\"})\n\t\t\tconn.Versions = append(conn.Versions, version)\n\n\t\t\tsuite.chainA.App.GetIBCKeeper().ConnectionKeeper.SetConnection(\n\t\t\t\tsuite.chainA.GetContext(),\n\t\t\t\tpath.EndpointA.ConnectionID, conn,\n\t\t\t)\n\t\t\tfeatures = []string{\"ORDER_ORDERED\", \"ORDER_UNORDERED\"}\n\t\t\tsuite.chainA.CreatePortCapability(suite.chainA.GetSimApp().ScopedIBCMockKeeper, ibctesting.MockPort)\n\t\t\tportCap = suite.chainA.GetPortCapability(ibctesting.MockPort)\n\t\t}, false},\n\t\t{\"connection does not support ORDERED channels\", func() {\n\t\t\tsuite.coordinator.SetupConnections(path)\n\n\t\t\t// modify connA versions to only support UNORDERED channels\n\t\t\tconn := path.EndpointA.GetConnection()\n\n\t\t\tversion := connectiontypes.NewVersion(\"1\", []string{\"ORDER_UNORDERED\"})\n\t\t\tconn.Versions = []*connectiontypes.Version{version}\n\n\t\t\tsuite.chainA.App.GetIBCKeeper().ConnectionKeeper.SetConnection(\n\t\t\t\tsuite.chainA.GetContext(),\n\t\t\t\tpath.EndpointA.ConnectionID, conn,\n\t\t\t)\n\t\t\t// NOTE: Opening UNORDERED channels is still expected to pass but ORDERED channels should fail\n\t\t\tfeatures = []string{\"ORDER_UNORDERED\"}\n\t\t\tsuite.chainA.CreatePortCapability(suite.chainA.GetSimApp().ScopedIBCMockKeeper, ibctesting.MockPort)\n\t\t\tportCap = suite.chainA.GetPortCapability(ibctesting.MockPort)\n\t\t}, true},\n\t}\n\n\tfor _, tc := range testCases {\n\t\ttc := tc\n\t\tsuite.Run(fmt.Sprintf(\"Case %s\", tc.msg), func() {\n\t\t\t// run test for all types of ordering\n\t\t\tfor _, order := range []types.Order{types.UNORDERED, types.ORDERED} {\n\t\t\t\tsuite.SetupTest() // reset\n\t\t\t\tpath = ibctesting.NewPath(suite.chainA, suite.chainB)\n\t\t\t\tpath.EndpointA.ChannelConfig.Order = order\n\t\t\t\tpath.EndpointB.ChannelConfig.Order = order\n\n\t\t\t\ttc.malleate()\n\n\t\t\t\tcounterparty := types.NewCounterparty(ibctesting.MockPort, ibctesting.FirstChannelID)\n\n\t\t\t\tchannelID, cap, err := suite.chainA.App.GetIBCKeeper().ChannelKeeper.ChanOpenInit(\n\t\t\t\t\tsuite.chainA.GetContext(), path.EndpointA.ChannelConfig.Order, []string{path.EndpointA.ConnectionID},\n\t\t\t\t\tpath.EndpointA.ChannelConfig.PortID, portCap, counterparty, path.EndpointA.ChannelConfig.Version,\n\t\t\t\t)\n\n\t\t\t\t// check if order is supported by channel to determine expected behaviour\n\t\t\t\torderSupported := false\n\t\t\t\tfor _, f := range features {\n\t\t\t\t\tif f == order.String() {\n\t\t\t\t\t\torderSupported = true\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// Testcase must have expectedPass = true AND channel order supported before\n\t\t\t\t// asserting the channel handshake initiation succeeded\n\t\t\t\tif tc.expPass && orderSupported {\n\t\t\t\t\tsuite.Require().NoError(err)\n\t\t\t\t\tsuite.Require().NotNil(cap)\n\t\t\t\t\tsuite.Require().Equal(types.FormatChannelIdentifier(0), channelID)\n\n\t\t\t\t\tchanCap, ok := suite.chainA.App.GetScopedIBCKeeper().GetCapability(\n\t\t\t\t\t\tsuite.chainA.GetContext(),\n\t\t\t\t\t\thost.ChannelCapabilityPath(path.EndpointA.ChannelConfig.PortID, channelID),\n\t\t\t\t\t)\n\t\t\t\t\tsuite.Require().True(ok, \"could not retrieve channel capability after successful ChanOpenInit\")\n\t\t\t\t\tsuite.Require().Equal(chanCap.String(), cap.String(), \"channel capability is not correct\")\n\t\t\t\t} else {\n\t\t\t\t\tsuite.Require().Error(err)\n\t\t\t\t\tsuite.Require().Nil(cap)\n\t\t\t\t\tsuite.Require().Equal(\"\", channelID)\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n}", "func AssertSent(t *testing.T, ch <-chan bool) {\n\ttimeout := time.After(10 * time.Second)\n\tselect {\n\tcase <-ch:\n\t\t// This case is ok\n\tcase <-timeout:\n\t\trequire.FailNow(t, \"Nothing sent on channel\")\n\t}\n}", "func (p *Provider) Provide(configurationChan chan<- dynamic.Message, pool *safe.Pool) error {\n\tpool.GoCtx(func(routineCtx context.Context) {\n\t\tlogger := log.Ctx(routineCtx).With().Str(logs.ProviderName, dockerName).Logger()\n\t\tctxLog := logger.WithContext(routineCtx)\n\n\t\toperation := func() error {\n\t\t\tvar err error\n\t\t\tctx, cancel := context.WithCancel(ctxLog)\n\t\t\tdefer cancel()\n\n\t\t\tctx = log.Ctx(ctx).With().Str(logs.ProviderName, dockerName).Logger().WithContext(ctx)\n\n\t\t\tdockerClient, err := p.createClient(ctxLog)\n\t\t\tif err != nil {\n\t\t\t\tlogger.Error().Err(err).Msg(\"Failed to create Docker API client\")\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tdefer func() { _ = dockerClient.Close() }()\n\n\t\t\tbuilder := NewDynConfBuilder(p.Shared, dockerClient)\n\n\t\t\tserverVersion, err := dockerClient.ServerVersion(ctx)\n\t\t\tif err != nil {\n\t\t\t\tlogger.Error().Err(err).Msg(\"Failed to retrieve information of the docker client and server host\")\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tlogger.Debug().Msgf(\"Provider connection established with docker %s (API %s)\", serverVersion.Version, serverVersion.APIVersion)\n\n\t\t\tdockerDataList, err := p.listContainers(ctx, dockerClient)\n\t\t\tif err != nil {\n\t\t\t\tlogger.Error().Err(err).Msg(\"Failed to list containers for docker\")\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tconfiguration := builder.build(ctxLog, dockerDataList)\n\t\t\tconfigurationChan <- dynamic.Message{\n\t\t\t\tProviderName: dockerName,\n\t\t\t\tConfiguration: configuration,\n\t\t\t}\n\n\t\t\tif p.Watch {\n\t\t\t\tf := filters.NewArgs()\n\t\t\t\tf.Add(\"type\", \"container\")\n\t\t\t\toptions := dockertypes.EventsOptions{\n\t\t\t\t\tFilters: f,\n\t\t\t\t}\n\n\t\t\t\tstartStopHandle := func(m eventtypes.Message) {\n\t\t\t\t\tlogger.Debug().Msgf(\"Provider event received %+v\", m)\n\t\t\t\t\tcontainers, err := p.listContainers(ctx, dockerClient)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlogger.Error().Err(err).Msg(\"Failed to list containers for docker\")\n\t\t\t\t\t\t// Call cancel to get out of the monitor\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\n\t\t\t\t\tconfiguration := builder.build(ctx, containers)\n\t\t\t\t\tif configuration != nil {\n\t\t\t\t\t\tmessage := dynamic.Message{\n\t\t\t\t\t\t\tProviderName: dockerName,\n\t\t\t\t\t\t\tConfiguration: configuration,\n\t\t\t\t\t\t}\n\t\t\t\t\t\tselect {\n\t\t\t\t\t\tcase configurationChan <- message:\n\t\t\t\t\t\tcase <-ctx.Done():\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\teventsc, errc := dockerClient.Events(ctx, options)\n\t\t\t\tfor {\n\t\t\t\t\tselect {\n\t\t\t\t\tcase event := <-eventsc:\n\t\t\t\t\t\tif event.Action == \"start\" ||\n\t\t\t\t\t\t\tevent.Action == \"die\" ||\n\t\t\t\t\t\t\tstrings.HasPrefix(event.Action, \"health_status\") {\n\t\t\t\t\t\t\tstartStopHandle(event)\n\t\t\t\t\t\t}\n\t\t\t\t\tcase err := <-errc:\n\t\t\t\t\t\tif errors.Is(err, io.EOF) {\n\t\t\t\t\t\t\tlogger.Debug().Msg(\"Provider event stream closed\")\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn err\n\t\t\t\t\tcase <-ctx.Done():\n\t\t\t\t\t\treturn nil\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn nil\n\t\t}\n\n\t\tnotify := func(err error, time time.Duration) {\n\t\t\tlogger.Error().Err(err).Msgf(\"Provider error, retrying in %s\", time)\n\t\t}\n\t\terr := backoff.RetryNotify(safe.OperationWithRecover(operation), backoff.WithContext(job.NewBackOff(backoff.NewExponentialBackOff()), ctxLog), notify)\n\t\tif err != nil {\n\t\t\tlogger.Error().Err(err).Msg(\"Cannot retrieve data\")\n\t\t}\n\t})\n\n\treturn nil\n}", "func TestGetNonExistentChannel(t *testing.T) {\n\tclearTable()\n\t// Generate JWT for authorization.\n\tvalidToken, err := auth.GenerateJWT()\n\tif err != nil {\n\t\tt.Error(\"Failed to generate token\")\n\t}\n\treq, _ := http.NewRequest(\"GET\", \"/api/channel/\"+channelTestID.String(), nil)\n\t// Add \"Token\" header to request with generated token.\n\treq.Header.Add(\"Token\", validToken)\n\tresponse := executeRequest(req)\n\n\tcheckResponseCode(t, http.StatusNotFound, response.Code)\n\n\tvar m map[string]string\n\tjson.Unmarshal(response.Body.Bytes(), &m)\n\tif m[\"error\"] != \"Channel not found\" {\n\t\tt.Errorf(\"Expected the 'error' key of the response to be set to 'Channel not found'. Got '%s'\", m[\"error\"])\n\t}\n}", "func TestChannelClientBasic(t *testing.T) {\n\tc := make(chan *http.Response, 10)\n\tclient := cloudtest.NewChannelClient(c)\n\n\tresp := &http.Response{}\n\tresp.StatusCode = http.StatusOK\n\tresp.Status = \"OK\"\n\tc <- resp\n\tresp, err := client.Get(\"http://foobar\")\n\tlog.Printf(\"%v\\n\", resp)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tif resp.StatusCode != http.StatusOK {\n\t\tt.Error(\"Response should be OK: \", resp.Status)\n\t}\n}", "func (mr *MockClientMockRecorder) InfraProvider() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"InfraProvider\", reflect.TypeOf((*MockClient)(nil).InfraProvider))\n}", "func (amqpSuite *AmqpSuite) ChannelPublishTester() *amqp.ChannelTesting {\n\treturn amqpSuite.channelPublish.Test(amqpSuite.T())\n}", "func (mr *MockProviderMockRecorder) Provide(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Provide\", reflect.TypeOf((*MockProvider)(nil).Provide), arg0)\n}", "func (_m *AuthServer) mustEmbedUnimplementedAuthServer() {\n\t_m.Called()\n}", "func allowedChan(f *fact, m slack.Msg) bool {\n\tif len(f.RestrictToChannelsID) > 0 {\n\t\tfor _, rc := range f.RestrictToChannelsID {\n\t\t\tif rc == m.Channel {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t} else {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (c *SwitchTicker) Channel() <-chan time.Time {\n\tfailCount := atomic.LoadInt64(&c.failCount)\n\tif failCount > c.threshold {\n\t\treturn c.fastTicker.C\n\t}\n\treturn c.slowTicker.C\n}", "func isValidChannel(f corev1.ObjectReference) *apis.FieldError {\n\treturn IsValidObjectReference(f)\n}", "func (t *Transport) ChannelConnectivityStateForTesting() connectivity.State {\n\treturn t.cc.GetState()\n}", "func IsChannel(data interface{}) bool {\n\treturn typeIs(data, reflect.Chan)\n}", "func ChannelValidator(c Channel) error {\n\tswitch c {\n\tcase ChannelShopee, ChannelDirect:\n\t\treturn nil\n\tdefault:\n\t\treturn fmt.Errorf(\"outboundtransaction: invalid enum value for channel field: %q\", c)\n\t}\n}", "func (o *Invoice) GetChannelOk() (*string, bool) {\n\tif o == nil || o.Channel == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Channel, true\n}", "func (_m *Socket) WriteChannel() chan<- *packet.Packet {\n\tret := _m.Called()\n\n\tvar r0 chan<- *packet.Packet\n\tif rf, ok := ret.Get(0).(func() chan<- *packet.Packet); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(chan<- *packet.Packet)\n\t\t}\n\t}\n\n\treturn r0\n}", "func TestChannelIndex(t *testing.T) {\n\t// mock All function\n\tfn := func(_ context.Context) ([]are_hub.Channel, error) {\n\t\treturn channels, nil\n\t}\n\n\t// create the mock repo and controller\n\trepo := &mock.ChannelRepo{AllFunc: fn}\n\tcontroller := NewChannel(repo)\n\n\t// create a mock request\n\treq, e := http.NewRequest(http.MethodGet, \"/channel\", nil)\n\n\tif e != nil {\n\t\tt.Fatal(e)\n\t}\n\n\t// create a response recorder and run the controller method\n\tw := httptest.NewRecorder()\n\te = controller.Index(w, req)\n\n\tif e != nil {\n\t\tt.Fatal(e)\n\t}\n\n\t// get the response\n\tres := w.Result()\n\n\t// check if the repo was hit\n\tif !repo.AllCalled {\n\t\tt.Error(\"Did not call repo.All\")\n\t}\n\n\t// ensure the content type is application/json\n\tcheckCT(res, t)\n\n\t// extract the body and confirm all data was returned\n\tdefer res.Body.Close()\n\tbody, e := io.ReadAll(res.Body)\n\n\tif e != nil {\n\t\tt.Fatal(e)\n\t}\n\n\tvar received []are_hub.Channel\n\te = json.Unmarshal(body, &received)\n\n\tif e != nil {\n\t\tt.Fatal(e)\n\t}\n\n\tlr := len(received)\n\tlc := len(channels)\n\n\t// check that all channels were returned\n\tif lr != lc {\n\t\tt.Fatalf(\"Expected: %d channels. Actual: %d.\", lc, lr)\n\t}\n\n\t// loop and ensure the data is correct\n\tfor i := 0; i < lr; i++ {\n\t\tif received[i].Name != channels[i].Name {\n\t\t\tt.Fatalf(\"Expected: %s. Actual: %s.\", channels[i].Name, received[i].Name)\n\t\t}\n\t}\n}", "func HasPrimaryPeerJoinedChannel(client fab.FabricClient, orgUser ca.User, channel fab.Channel) (bool, error) {\n\tfoundChannel := false\n\tprimaryPeer := channel.PrimaryPeer()\n\n\tcurrentUser := client.UserContext()\n\tdefer client.SetUserContext(currentUser)\n\n\tclient.SetUserContext(orgUser)\n\tresponse, err := client.QueryChannels(primaryPeer)\n\tif err != nil {\n\t\treturn false, fmt.Errorf(\"Error querying channel for primary peer: %s\", err)\n\t}\n\tlog.Println(\"channel num: \",len(response.Channels))\n\tfor _, responseChannel := range response.Channels {\n\t\tlog.Println(\"channel ----------> : \",responseChannel.ChannelId)\n\t\tif responseChannel.ChannelId == channel.Name() {\n\t\t\tfoundChannel = true\n\t\t}\n\t}\n\treturn foundChannel, nil\n}", "func TestChannelFull(t *testing.T) {\n\ticmpPackets := make(chan gopacket.Packet, 100)\n\tvar data []byte\n\tdata = nil\n\tpacket := gopacket.NewPacket(data, layers.LayerTypeEthernet, gopacket.Default)\n\n\tvar err error\n\terr = nil\n\ti := 0\n\tfor err == nil {\n\t\ti++\n\t\terr = putChannel(packet, icmpPackets)\n\t\tif i > 200 {\n\t\t\tt.Error(\"Channel should be full and there should be an error but there isn't.\")\n\t\t}\n\t}\n}", "func (p *Provider) Provide(configurationChan chan<- types.ConfigMessage, pool *safe.Pool, constraints types.Constraints) error {\n\tif p.APIVersion == \"\" {\n\t\tp.APIVersion = sf.DefaultAPIVersion\n\t}\n\n\ttlsConfig, err := p.TLS.CreateTLSConfig()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsfClient, err := sf.NewClient(http.DefaultClient, p.ClusterManagementURL, p.APIVersion, tlsConfig)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif p.RefreshSeconds <= 0 {\n\t\tp.RefreshSeconds = 10\n\t}\n\n\treturn p.updateConfig(configurationChan, pool, sfClient, time.Duration(p.RefreshSeconds)*time.Second)\n}", "func (mr *MockBootstrapperProviderMockRecorder) Provide() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Provide\", reflect.TypeOf((*MockBootstrapperProvider)(nil).Provide))\n}", "func (o *NotificationConfig) GetChannelOk() (*string, bool) {\n\tif o == nil || o.Channel == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Channel, true\n}", "func (res channelBase) Invoker() auth.Identifiable {\n\treturn res.invoker\n}", "func (a *MockAction) ChannelClient() (*channel.Client, error) {\n\tpanic(\"not implemented\")\n}", "func (cm *ConnectionManager) WantsMoreChannels() bool {\n\t_, ok := cm.raiden.MessageHandler.blockedTokens[cm.tokenAddress]\n\tif ok {\n\t\treturn false\n\t}\n\treturn cm.fundsRemaining().Cmp(utils.BigInt0) > 0 && len(cm.openChannels()) < int(cm.initChannelTarget)\n}", "func (_m *Knapsack) UpdateChannel() string {\n\tret := _m.Called()\n\n\tvar r0 string\n\tif rf, ok := ret.Get(0).(func() string); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tr0 = ret.Get(0).(string)\n\t}\n\n\treturn r0\n}", "func set_channel(c spi.Conn, channel uint8) {\n\tif (channel > 125) {\n\t\tchannel = 125\n\t}\n\twrite_register(c, RfCh, channel)\n}", "func (mr *MockCandidatePropertyGetterMockRecorder) Cloudprovider() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Cloudprovider\", reflect.TypeOf((*MockCandidatePropertyGetter)(nil).Cloudprovider))\n}", "func TestDontWaitForOtherProvidersIfWeGotError(t *testing.T) {\n\tstart := time.Now()\n\n\tappCustom := App{\n\t\tContentProvider: NewContentProviderService(\n\t\t\tmap[Provider]Client{\n\t\t\t\tProvider1: &ClientMock{\n\t\t\t\t\tGetContentFn: func(userIP string, count int) ([]*ContentItem, error) {\n\t\t\t\t\t\treturn []*ContentItem{}, errors.New(\"some error from provider 1\")\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tProvider2: &ClientMock{\n\t\t\t\t\tGetContentFn: func(userIP string, count int) ([]*ContentItem, error) {\n\t\t\t\t\t\treturn []*ContentItem{}, errors.New(\"some error from provider 2\")\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tProvider3: &ClientMock{\n\t\t\t\t\tGetContentFn: func(userIP string, count int) ([]*ContentItem, error) {\n\t\t\t\t\t\t// let's imitate some pending request to provider\n\t\t\t\t\t\ttime.Sleep(5 * time.Second)\n\t\t\t\t\t\treturn []*ContentItem{{\n\t\t\t\t\t\t\tSource: \"3\",\n\t\t\t\t\t\t}}, nil\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tDefaultConfig,\n\t\t\tWithTimeOut(500*time.Millisecond),\n\t\t),\n\t}\n\n\tcontent := runRequest(t, appCustom, SimpleContentRequest)\n\n\tif len(content) != 0 {\n\t\tt.Fatalf(\"Got %d items back, want 0\", len(content))\n\t}\n\n\texecTime := time.Since(start)\n\tif execTime > time.Second {\n\t\tt.Fatalf(\"test time should be less then 1 second, got: %s\", execTime)\n\t}\n}", "func verified(srvChan chan string, channel, nick, hostname string, args []string) {\n\tmessage := \"NOTICE \" + channel + \" :\"\n\tif len(args) != 1 {\n\t\tmessage += \":ERROR: Invalid number of arguments\"\n\t} else {\n\t\tuname := args[0]\n\t\tif checkVerified(uname, hostname) {\n\t\t\tmessage += \"You are \" + uname + \" at \" + hostname\n\t\t} else {\n\t\t\tmessage += \"You are not \" + uname\n\t\t}\n\t}\n\tlog.Println(message)\n\tsrvChan <- message\n}", "func TestChannelEvents(t *testing.T) {\n\ttc := testutil.SystemTest(t)\n\tbuf := &bytes.Buffer{}\n\n\t// Test setup\n\n\t// Stop and delete the default channel if it exists\n\tif err := getChannel(buf, tc.ProjectID, location, channelID); err == nil {\n\t\ttestutil.Retry(t, 3, 2*time.Second, func(r *testutil.R) {\n\t\t\tif err := stopChannel(buf, tc.ProjectID, location, channelID); err != nil {\n\t\t\t\t// Ignore the error when the channel is already stopped.\n\t\t\t}\n\t\t})\n\n\t\ttestutil.Retry(t, 3, 2*time.Second, func(r *testutil.R) {\n\t\t\tif err := deleteChannel(buf, tc.ProjectID, location, channelID); err != nil {\n\t\t\t\tr.Errorf(\"deleteChannel got err: %v\", err)\n\t\t\t}\n\t\t})\n\t}\n\n\t// Delete the default input if it exists\n\tif err := getInput(buf, tc.ProjectID, location, inputID); err == nil {\n\t\ttestutil.Retry(t, 3, 2*time.Second, func(r *testutil.R) {\n\t\t\tif err := deleteInput(buf, tc.ProjectID, location, inputID); err != nil {\n\t\t\t\tr.Errorf(\"deleteInput got err: %v\", err)\n\t\t\t}\n\t\t})\n\t}\n\n\t// Create a new input.\n\ttestutil.Retry(t, 3, 2*time.Second, func(r *testutil.R) {\n\t\tinputName := fmt.Sprintf(\"projects/%s/locations/%s/inputs/%s\", tc.ProjectID, location, inputID)\n\t\tif err := createInput(buf, tc.ProjectID, location, inputID); err != nil {\n\t\t\tr.Errorf(\"createInput got err: %v\", err)\n\t\t}\n\t\tif got := buf.String(); !strings.Contains(got, inputName) {\n\t\t\tr.Errorf(\"createInput got\\n----\\n%v\\n----\\nWant to contain:\\n----\\n%v\\n----\\n\", got, inputName)\n\t\t}\n\t})\n\n\t// Create a new channel.\n\ttestutil.Retry(t, 3, 2*time.Second, func(r *testutil.R) {\n\t\tchannelName := fmt.Sprintf(\"projects/%s/locations/%s/channels/%s\", tc.ProjectID, location, channelID)\n\t\tif err := createChannel(buf, tc.ProjectID, location, channelID, inputID, outputURI); err != nil {\n\t\t\tr.Errorf(\"createChannel got err: %v\", err)\n\t\t}\n\t\tif got := buf.String(); !strings.Contains(got, channelName) {\n\t\t\tr.Errorf(\"createChannel got\\n----\\n%v\\n----\\nWant to contain:\\n----\\n%v\\n----\\n\", got, channelName)\n\t\t}\n\t})\n\n\t// Start the channel.\n\ttestutil.Retry(t, 3, 2*time.Second, func(r *testutil.R) {\n\t\tif err := startChannel(buf, tc.ProjectID, location, channelID); err != nil {\n\t\t\tr.Errorf(\"startChannel got err: %v\", err)\n\t\t}\n\t\tif got := buf.String(); !strings.Contains(got, startChannelResponse) {\n\t\t\tr.Errorf(\"startChannel got\\n----\\n%v\\n----\\nWant to contain:\\n----\\n%v\\n----\\n\", got, startChannelResponse)\n\t\t}\n\t})\n\n\tbuf.Reset()\n\n\t// Tests\n\n\t// Create a new channel event.\n\ttestutil.Retry(t, 3, 2*time.Second, func(r *testutil.R) {\n\t\teventName := fmt.Sprintf(\"projects/%s/locations/%s/channels/%s/events/%s\", tc.ProjectID, location, channelID, eventID)\n\t\tif err := createChannelEvent(buf, tc.ProjectID, location, channelID, eventID); err != nil {\n\t\t\tr.Errorf(\"createChannelEvent got err: %v\", err)\n\t\t}\n\t\tif got := buf.String(); !strings.Contains(got, eventName) {\n\t\t\tr.Errorf(\"createChannelEvent got\\n----\\n%v\\n----\\nWant to contain:\\n----\\n%v\\n----\\n\", got, eventName)\n\t\t}\n\t})\n\tbuf.Reset()\n\n\t// List the channel events for a given channel.\n\ttestutil.Retry(t, 3, 2*time.Second, func(r *testutil.R) {\n\t\teventName := fmt.Sprintf(\"projects/%s/locations/%s/channels/%s/events/%s\", tc.ProjectID, location, channelID, eventID)\n\t\tif err := listChannelEvents(buf, tc.ProjectID, location, channelID); err != nil {\n\t\t\tr.Errorf(\"listChannelEvents got err: %v\", err)\n\t\t}\n\t\tif got := buf.String(); !strings.Contains(got, eventName) {\n\t\t\tr.Errorf(\"listChannelEvents got\\n----\\n%v\\n----\\nWant to contain:\\n----\\n%v\\n----\\n\", got, eventName)\n\t\t}\n\t})\n\tbuf.Reset()\n\n\t// Get the channel event.\n\ttestutil.Retry(t, 3, 2*time.Second, func(r *testutil.R) {\n\t\teventName := fmt.Sprintf(\"projects/%s/locations/%s/channels/%s/events/%s\", tc.ProjectID, location, channelID, eventID)\n\t\tif err := getChannelEvent(buf, tc.ProjectID, location, channelID, eventID); err != nil {\n\t\t\tr.Errorf(\"getChannelEvent got err: %v\", err)\n\t\t}\n\t\tif got := buf.String(); !strings.Contains(got, eventName) {\n\t\t\tr.Errorf(\"getChannelEvent got\\n----\\n%v\\n----\\nWant to contain:\\n----\\n%v\\n----\\n\", got, eventName)\n\t\t}\n\t})\n\tbuf.Reset()\n\n\t// Delete the channel event.\n\ttestutil.Retry(t, 3, 2*time.Second, func(r *testutil.R) {\n\t\tif err := deleteChannelEvent(buf, tc.ProjectID, location, channelID, eventID); err != nil {\n\t\t\tr.Errorf(\"deleteChannelEvent got err: %v\", err)\n\t\t}\n\t\tif got := buf.String(); !strings.Contains(got, deleteChannelEventResponse) {\n\t\t\tr.Errorf(\"deleteChannelEvent got\\n----\\n%v\\n----\\nWant to contain:\\n----\\n%v\\n----\\n\", got, deleteChannelEventResponse)\n\t\t}\n\t})\n\n\t// Clean up\n\n\t// Stop the channel.\n\ttestutil.Retry(t, 3, 2*time.Second, func(r *testutil.R) {\n\t\tif err := stopChannel(buf, tc.ProjectID, location, channelID); err != nil {\n\t\t\tr.Errorf(\"stopChannel got err: %v\", err)\n\t\t}\n\t\tif got := buf.String(); !strings.Contains(got, stopChannelResponse) {\n\t\t\tr.Errorf(\"stopChannel got\\n----\\n%v\\n----\\nWant to contain:\\n----\\n%v\\n----\\n\", got, stopChannelResponse)\n\t\t}\n\t})\n\n\t// Delete the channel.\n\ttestutil.Retry(t, 3, 2*time.Second, func(r *testutil.R) {\n\t\tif err := deleteChannel(buf, tc.ProjectID, location, channelID); err != nil {\n\t\t\tr.Errorf(\"deleteChannel got err: %v\", err)\n\t\t}\n\t\tif got := buf.String(); !strings.Contains(got, deleteChannelResponse) {\n\t\t\tr.Errorf(\"deleteChannel got\\n----\\n%v\\n----\\nWant to contain:\\n----\\n%v\\n----\\n\", got, deleteChannelResponse)\n\t\t}\n\t})\n\n\t// Delete the input.\n\ttestutil.Retry(t, 3, 2*time.Second, func(r *testutil.R) {\n\t\tif err := deleteInput(buf, tc.ProjectID, location, inputID); err != nil {\n\t\t\tr.Errorf(\"deleteInput got err: %v\", err)\n\t\t}\n\t\tif got := buf.String(); !strings.Contains(got, deleteInputResponse) {\n\t\t\tr.Errorf(\"deleteInput got\\n----\\n%v\\n----\\nWant to contain:\\n----\\n%v\\n----\\n\", got, deleteInputResponse)\n\t\t}\n\t})\n\tt.Logf(\"\\nTestChannelEvents() completed\\n\")\n}", "func (amqpSuite *AmqpSuite) ChannelConsume() *amqp.Channel {\n\tif amqpSuite.channelConsume != nil {\n\t\treturn amqpSuite.channelConsume\n\t}\n\tamqpSuite.channelConsume = amqpSuite.getChannel(amqpSuite.ConnConsume())\n\treturn amqpSuite.channelConsume\n}", "func TestProducerChannelDR(t *testing.T) {\n\tproducerTest(t, \"Channel producer (with DR)\",\n\t\tnil, producerCtrl{withDr: true},\n\t\tfunc(p *Producer, m *Message, drChan chan Event) {\n\t\t\tp.ProduceChannel() <- m\n\t\t})\n\n}", "func (p *Provider) Provide(configurationChan chan<- types.ConfigMessage, pool *safe.Pool, constraints types.Constraints) error {\n\tlog.Debugf(\"Providing Provider...\")\n\tp.Constraints = append(p.Constraints, constraints...)\n\thandleCanceled := func(ctx context.Context, err error) error {\n\t\tif ctx.Err() == context.Canceled || err == context.Canceled {\n\t\t\treturn nil\n\t\t}\n\t\treturn err\n\t}\n\n\tpool.Go(func(stop chan bool) {\n\t\tctx, cancel := context.WithCancel(context.Background())\n\t\tgo func() {\n\t\t\tselect {\n\t\t\tcase <-stop:\n\t\t\t\tcancel()\n\t\t\t}\n\t\t}()\n\n\t\toperation := func() error {\n\t\t\taws, err := p.createClient()\n\t\t\tif err != nil {\n\t\t\t\treturn handleCanceled(ctx, err)\n\t\t\t}\n\n\t\t\tconfiguration, err := p.loadPostgresConfig(aws)\n\t\t\tif err != nil {\n\t\t\t\treturn handleCanceled(ctx, err)\n\t\t\t}\n\n\t\t\tconfigurationChan <- types.ConfigMessage{\n\t\t\t\tProviderName: \"postgres\",\n\t\t\t\tConfiguration: configuration,\n\t\t\t}\n\n\t\t\tif p.Watch {\n\t\t\t\treload := time.NewTicker(time.Second * time.Duration(p.RefreshSeconds))\n\t\t\t\tdefer reload.Stop()\n\t\t\t\tfor {\n\t\t\t\t\tlog.Debug(\"Watching Provider...\")\n\t\t\t\t\tselect {\n\t\t\t\t\tcase <-reload.C:\n\t\t\t\t\t\tconfiguration, err := p.loadPostgresConfig(aws)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\treturn handleCanceled(ctx, err)\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconfigurationChan <- types.ConfigMessage{\n\t\t\t\t\t\t\tProviderName: \"postgres\",\n\t\t\t\t\t\t\tConfiguration: configuration,\n\t\t\t\t\t\t}\n\t\t\t\t\tcase <-ctx.Done():\n\t\t\t\t\t\treturn handleCanceled(ctx, ctx.Err())\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\t\tnotify := func(err error, time time.Duration) {\n\t\t\tlog.Errorf(\"Provider error: %s time: %v\", err.Error(), time)\n\t\t}\n\n\t\terr := backoff.RetryNotify(safe.OperationWithRecover(operation), job.NewBackOff(backoff.NewExponentialBackOff()), notify)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"Failed to connect to Provider. %s\", err.Error())\n\t\t}\n\t})\n\treturn nil\n}", "func TestGetChannel(t *testing.T) {\n\tclearTable()\n\taddChannel(1)\n\t// Generate JWT for authorization.\n\tvalidToken, err := auth.GenerateJWT()\n\tif err != nil {\n\t\tt.Error(\"Failed to generate token\")\n\t}\n\n\treq, _ := http.NewRequest(\"GET\", \"/api/channel/\"+channelTestID.String(), nil)\n\t// Add \"Token\" header to request with generated token.\n\treq.Header.Add(\"Token\", validToken)\n\tresponse := executeRequest(req)\n\n\tcheckResponseCode(t, http.StatusOK, response.Code)\n}", "func NewChannel() Channel {\n\t// dependency injection? never heard of it...\n\treturn Channel{request{validator.New()}}\n}", "func (_m *MockMessageProducer) ProduceChannel() chan *kafka.Message {\n\tret := _m.Called()\n\n\tvar r0 chan *kafka.Message\n\tif rf, ok := ret.Get(0).(func() chan *kafka.Message); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(chan *kafka.Message)\n\t\t}\n\t}\n\n\treturn r0\n}", "func (r AuthenticationMethodsReferences) ChannelBrowser() bool {\n\treturn r.UsernameAndPassword || r.TOTP || r.WebAuthn\n}", "func (p *Provider) Provide(configurationChan chan<- types.ConfigMessage, pool *safe.Pool) error {\n\toperation := func() error {\n\t\tconfig := marathon.NewDefaultConfig()\n\t\tconfig.URL = p.Endpoint\n\t\tconfig.EventsTransport = marathon.EventsTransportSSE\n\t\tif p.Trace {\n\t\t\tconfig.LogOutput = log.CustomWriterLevel(logrus.DebugLevel, traceMaxScanTokenSize)\n\t\t}\n\t\tif p.Basic != nil {\n\t\t\tconfig.HTTPBasicAuthUser = p.Basic.HTTPBasicAuthUser\n\t\t\tconfig.HTTPBasicPassword = p.Basic.HTTPBasicPassword\n\t\t}\n\t\tvar rc *readinessChecker\n\t\tif p.RespectReadinessChecks {\n\t\t\tlog.Debug(\"Enabling Marathon readiness checker\")\n\t\t\trc = defaultReadinessChecker(p.Trace)\n\t\t}\n\t\tp.readyChecker = rc\n\n\t\tif len(p.DCOSToken) > 0 {\n\t\t\tconfig.DCOSToken = p.DCOSToken\n\t\t}\n\t\tTLSConfig, err := p.TLS.CreateTLSConfig()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tconfig.HTTPClient = &http.Client{\n\t\t\tTransport: &http.Transport{\n\t\t\t\tDialContext: (&net.Dialer{\n\t\t\t\t\tKeepAlive: time.Duration(p.KeepAlive),\n\t\t\t\t\tTimeout: time.Duration(p.DialerTimeout),\n\t\t\t\t}).DialContext,\n\t\t\t\tResponseHeaderTimeout: time.Duration(p.ResponseHeaderTimeout),\n\t\t\t\tTLSHandshakeTimeout: time.Duration(p.TLSHandshakeTimeout),\n\t\t\t\tTLSClientConfig: TLSConfig,\n\t\t\t},\n\t\t}\n\t\tclient, err := marathon.NewClient(config)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"Failed to create a client for marathon, error: %s\", err)\n\t\t\treturn err\n\t\t}\n\t\tp.marathonClient = client\n\n\t\tif p.Watch {\n\t\t\tupdate, err := client.AddEventsListener(marathonEventIDs)\n\t\t\tif err != nil {\n\t\t\t\tlog.Errorf(\"Failed to register for events, %s\", err)\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tpool.Go(func(stop chan bool) {\n\t\t\t\tdefer close(update)\n\t\t\t\tfor {\n\t\t\t\t\tselect {\n\t\t\t\t\tcase <-stop:\n\t\t\t\t\t\treturn\n\t\t\t\t\tcase event := <-update:\n\t\t\t\t\t\tlog.Debugf(\"Received provider event %s\", event)\n\n\t\t\t\t\t\tconfiguration := p.getConfiguration()\n\t\t\t\t\t\tif configuration != nil {\n\t\t\t\t\t\t\tconfigurationChan <- types.ConfigMessage{\n\t\t\t\t\t\t\t\tProviderName: \"marathon\",\n\t\t\t\t\t\t\t\tConfiguration: configuration,\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t})\n\t\t}\n\n\t\tconfiguration := p.getConfiguration()\n\t\tconfigurationChan <- types.ConfigMessage{\n\t\t\tProviderName: \"marathon\",\n\t\t\tConfiguration: configuration,\n\t\t}\n\t\treturn nil\n\t}\n\n\tnotify := func(err error, time time.Duration) {\n\t\tlog.Errorf(\"Provider connection error %+v, retrying in %s\", err, time)\n\t}\n\terr := backoff.RetryNotify(safe.OperationWithRecover(operation), job.NewBackOff(backoff.NewExponentialBackOff()), notify)\n\tif err != nil {\n\t\tlog.Errorf(\"Cannot connect to Provider server %+v\", err)\n\t}\n\treturn nil\n}", "func (p *Provider) Provide(configurationChan chan<- types.ConfigMessage, pool *safe.Pool, constraints types.Constraints) error {\n\tp.Constraints = append(p.Constraints, constraints...)\n\toperation := func() error {\n\t\tconfig := marathon.NewDefaultConfig()\n\t\tconfig.URL = p.Endpoint\n\t\tconfig.EventsTransport = marathon.EventsTransportSSE\n\t\tif p.Trace {\n\t\t\tconfig.LogOutput = log.CustomWriterLevel(logrus.DebugLevel, traceMaxScanTokenSize)\n\t\t}\n\t\tif p.Basic != nil {\n\t\t\tconfig.HTTPBasicAuthUser = p.Basic.HTTPBasicAuthUser\n\t\t\tconfig.HTTPBasicPassword = p.Basic.HTTPBasicPassword\n\t\t}\n\t\tvar rc *readinessChecker\n\t\tif p.RespectReadinessChecks {\n\t\t\tlog.Debug(\"Enabling Marathon readiness checker\")\n\t\t\trc = defaultReadinessChecker(p.Trace)\n\t\t}\n\t\tp.readyChecker = rc\n\n\t\tif len(p.DCOSToken) > 0 {\n\t\t\tconfig.DCOSToken = p.DCOSToken\n\t\t}\n\t\tTLSConfig, err := p.TLS.CreateTLSConfig()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tconfig.HTTPClient = &http.Client{\n\t\t\tTransport: &http.Transport{\n\t\t\t\tDialContext: (&net.Dialer{\n\t\t\t\t\tKeepAlive: time.Duration(p.KeepAlive),\n\t\t\t\t\tTimeout: time.Duration(p.DialerTimeout),\n\t\t\t\t}).DialContext,\n\t\t\t\tTLSClientConfig: TLSConfig,\n\t\t\t},\n\t\t}\n\t\tclient, err := marathon.NewClient(config)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"Failed to create a client for marathon, error: %s\", err)\n\t\t\treturn err\n\t\t}\n\t\tp.marathonClient = client\n\n\t\tif p.Watch {\n\t\t\tupdate, err := client.AddEventsListener(marathonEventIDs)\n\t\t\tif err != nil {\n\t\t\t\tlog.Errorf(\"Failed to register for events, %s\", err)\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tpool.Go(func(stop chan bool) {\n\t\t\t\tdefer close(update)\n\t\t\t\tfor {\n\t\t\t\t\tselect {\n\t\t\t\t\tcase <-stop:\n\t\t\t\t\t\treturn\n\t\t\t\t\tcase event := <-update:\n\t\t\t\t\t\tlog.Debugf(\"Received provider event %s\", event)\n\t\t\t\t\t\tconfiguration := p.loadMarathonConfig()\n\t\t\t\t\t\tif configuration != nil {\n\t\t\t\t\t\t\tconfigurationChan <- types.ConfigMessage{\n\t\t\t\t\t\t\t\tProviderName: \"marathon\",\n\t\t\t\t\t\t\t\tConfiguration: configuration,\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t})\n\t\t}\n\t\tconfiguration := p.loadMarathonConfig()\n\t\tconfigurationChan <- types.ConfigMessage{\n\t\t\tProviderName: \"marathon\",\n\t\t\tConfiguration: configuration,\n\t\t}\n\t\treturn nil\n\t}\n\n\tnotify := func(err error, time time.Duration) {\n\t\tlog.Errorf(\"Provider connection error %+v, retrying in %s\", err, time)\n\t}\n\terr := backoff.RetryNotify(safe.OperationWithRecover(operation), job.NewBackOff(backoff.NewExponentialBackOff()), notify)\n\tif err != nil {\n\t\tlog.Errorf(\"Cannot connect to Provider server %+v\", err)\n\t}\n\treturn nil\n}", "func deleteChannel(t *testing.T, kafkaClient kafkaclientset.KafkaChannelInterface, name string) {\n\tt.Helper()\n\n\terr := kafkaClient.Delete(name, &v1.DeleteOptions{})\n\tswitch {\n\tcase errors.IsGone(err):\n\tcase errors.IsNotFound(err):\n\t\tt.Logf(\"tried to delete Kafka channel: %s but it was already deleted\", name)\n\tcase err != nil:\n\t\tt.Fatalf(\"cannot delete Kafka channel %v, Error: %v\", name, err)\n\tdefault:\n\t\tt.Logf(\"deleted Kafka channel: %s\", name)\n\t}\n}", "func TestDefaultProviderIsWarnOnceProvider(t *testing.T) {\n\t// create logger that writes to buffer using the default logger provider\n\tbuf := &bytes.Buffer{}\n\tlogger := svc1log.New(buf, wlog.DebugLevel) // uses default provider\n\n\t// verify that output provides warning that no logger provider was specified\n\tlogger.Info(\"Test output 1\")\n\tconst wantOutput = `[WARNING] Logging operation that uses the default logger provider was performed without specifying a logger provider implementation. To see logger output, set the global logger provider implementation using wlog.SetDefaultLoggerProvider or by importing an implementation. This warning can be disabled by setting the global logger provider to be the noop logger provider using wlog.SetDefaultLoggerProvider(wlog.NewNoopLoggerProvider()).` + \"\\n\"\n\tgot := buf.String()\n\tassert.Equal(t, wantOutput, got)\n\n\t// verify that warning is only written on first call to logger\n\tlogger.Info(\"Test output 2\")\n\tbuf.Reset()\n\tgot = buf.String()\n\tassert.Equal(t, \"\", got)\n}", "func (_m *ISession) Channel(channelID string, options ...discordgo.RequestOption) (*discordgo.Channel, error) {\n\t_va := make([]interface{}, len(options))\n\tfor _i := range options {\n\t\t_va[_i] = options[_i]\n\t}\n\tvar _ca []interface{}\n\t_ca = append(_ca, channelID)\n\t_ca = append(_ca, _va...)\n\tret := _m.Called(_ca...)\n\n\tvar r0 *discordgo.Channel\n\tvar r1 error\n\tif rf, ok := ret.Get(0).(func(string, ...discordgo.RequestOption) (*discordgo.Channel, error)); ok {\n\t\treturn rf(channelID, options...)\n\t}\n\tif rf, ok := ret.Get(0).(func(string, ...discordgo.RequestOption) *discordgo.Channel); ok {\n\t\tr0 = rf(channelID, options...)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*discordgo.Channel)\n\t\t}\n\t}\n\n\tif rf, ok := ret.Get(1).(func(string, ...discordgo.RequestOption) error); ok {\n\t\tr1 = rf(channelID, options...)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func BotHasChannelPermission(session *discordgo.Session, channel *discordgo.Channel) error {\n\tpermissions, err := session.UserChannelPermissions(session.State.User.ID, channel.ID)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to determine channel permissions: %w\", err)\n\t}\n\n\tif permissions&discordgo.PermissionViewChannel != discordgo.PermissionViewChannel {\n\t\treturn fmt.Errorf(\"insufficient channel permissions: channel: %s\", channel.Name)\n\t}\n\n\treturn nil\n}", "func TestClock_AfterApplyInterval(t *testing.T) {\n\tc := raft.NewClock()\n\tc.ApplyInterval = 10 * time.Millisecond\n\tt0 := time.Now()\n\t<-c.AfterApplyInterval()\n\tif d := time.Since(t0); d < c.ApplyInterval {\n\t\tt.Fatalf(\"channel fired too soon: %v\", d)\n\t}\n}", "func TestRawCanChannelMultiplexWorks(t *testing.T) {\n\tmessage := RawCanFrame{ID: 555}\n\tres1 := RawCanFrame{}\n\tres2 := RawCanFrame{}\n\tcanIn := make(chan RawCanFrame)\n\tout1 := make(chan RawCanFrame)\n\tout2 := make(chan RawCanFrame)\n\n\tgo RawCanChannelMultiplex(canIn, out1, out2)\n\tcanIn <- message\n\tres1 = <-out1\n\tres2 = <-out2\n\tclose(canIn)\n\n\tif !CompareRawFrames(res1, message) {\n\t\tt.Error(\"The CAN frames did not match\")\n\t}\n\tif !CompareRawFrames(res2, message) {\n\t\tt.Error(\"The CAN frames did not match\")\n\t}\n}", "func (e EEPROM) ChannelDriver(c Channel) bool {\n\treturn e.channelValue(channelDriver, c) != 0\n}", "func handleNewChannel(newChannel ssh.NewChannel, sshRuntime *sshConnectionRuntime, app *applicationItemData) {\n\tchType := newChannel.ChannelType()\n\n\tswitch chType {\n\tcase comm_app.ProvideSSHChannelType:\n\t\t// this commands is not for Intent application type\n\t\tif !app.appIntentType {\n\t\t\terr := app.provideApplication(newChannel, sshRuntime)\n\t\t\tif err != nil {\n\t\t\t\t// create transport container\n\t\t\t\treplyData, errLocal := comm_app.ErrorViaCommunicationContainer(err.Error())\n\t\t\t\tif errLocal != nil {\n\t\t\t\t\tapp.logger.Errorf(\"Can't create communication error object for received provide channel creation request from %s due to: %v\", BrokerInfo(sshRuntime), errLocal)\n\t\t\t\t\tnewChannel.Reject(ssh.ConnectionFailed, \"\")\n\t\t\t\t} else {\n\t\t\t\t\tnewChannel.Reject(ssh.ConnectionFailed, string(replyData))\n\t\t\t\t}\n\t\t\t\t// because something goes wrong, we doesn't reset provide negiate status until connection closed\n\t\t\t}\n\t\t} else {\n\t\t\t// create transport container\n\t\t\treplyData, errLocal := comm_app.ErrorViaCommunicationContainer(\"Internally unsupported payload struct type\")\n\t\t\tif errLocal != nil {\n\t\t\t\tapp.logger.Errorf(\"Can't create communication error object for received unsupported channel creation request from %s due to: %v\", BrokerInfo(sshRuntime), errLocal)\n\t\t\t\tnewChannel.Reject(ssh.ConnectionFailed, \"\")\n\t\t\t} else {\n\t\t\t\tnewChannel.Reject(ssh.ConnectionFailed, string(replyData))\n\t\t\t}\n\t\t}\n\tdefault:\n\t\tapp.logger.Warnf(\"Unsupported channel type %s detected in connection from %s\", chType, BrokerInfo(sshRuntime))\n\n\t\t// create transport container\n\t\treplyData, errLocal := comm_app.ErrorViaCommunicationContainer(fmt.Sprintf(\"Unsupported channel type: %s detected\", chType))\n\t\tif errLocal != nil {\n\t\t\tapp.logger.Errorf(\"Can't create communication error object for received unsupported channel creation request from %s due to: %v\", BrokerInfo(sshRuntime), errLocal)\n\t\t\tnewChannel.Reject(ssh.ConnectionFailed, \"\")\n\t\t} else {\n\t\t\tnewChannel.Reject(ssh.ConnectionFailed, string(replyData))\n\t\t}\n\t}\n}", "func (mr *MockProvidersMockRecorder) InfraProvider() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"InfraProvider\", reflect.TypeOf((*MockProviders)(nil).InfraProvider))\n}", "func TestBasicMethodChannelStringCodecSend(t *testing.T) {\n\tcodec := StringCodec{}\n\tmessenger := NewTestingBinaryMessenger()\n\tmessenger.MockSetChannelHandler(\"ch\", func(encodedMessage []byte, r ResponseSender) error {\n\t\tmessage, err := codec.DecodeMessage(encodedMessage)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"failed to decode message\")\n\t\t}\n\t\tmessageString, ok := message.(string)\n\t\tif !ok {\n\t\t\treturn errors.New(\"message is invalid type, expected string\")\n\t\t}\n\t\treply := messageString + \" world\"\n\t\tencodedReply, err := codec.EncodeMessage(reply)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"failed to encode message\")\n\t\t}\n\t\tr.Send(encodedReply)\n\t\treturn nil\n\t})\n\tchannel := NewBasicMessageChannel(messenger, \"ch\", codec)\n\treply, err := channel.SendWithReply(\"hello\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tt.Log(spew.Sdump(reply))\n\treplyString, ok := reply.(string)\n\tif !ok {\n\t\tt.Fatal(\"reply is invalid type, expected string\")\n\t}\n\tEqual(t, \"hello world\", replyString)\n}", "func (cp *MockChannelProvider) SetChannel(id string, channel fab.Channel) {\n\tcp.channels[id] = channel\n}", "func (s *Server) ExposeChannel() (string, chan interface{}, chan error, error) {\n\t// TODO(adamb) Fire off error handlers on callbacks if server shuts down without\n\t// response.\n\n\tisRunningMutex := s.isRunningMutex\n\tisRunningMutex.Lock()\n\tdefer isRunningMutex.Unlock()\n\tif s.isRunning {\n\t\t// Make new token\n\t\ttoken := randomToken(16)\n\t\tch := make(chan interface{}, 1)\n\t\terrChan := make(chan error, 1)\n\t\ts.registerChannelChan <- registerChannelEntry{token, ch, errChan}\n\t\taddress := fmt.Sprintf(\"%s@%s\", token, s.listener.Addr().String())\n\t\treturn address, ch, errChan, nil\n\t} else {\n\t\treturn \"\", nil, nil, fmt.Errorf(\"Server is not running; can't expose a channel\")\n\t}\n}", "func (_m *Socket) ReadChannel() <-chan *packet.Packet {\n\tret := _m.Called()\n\n\tvar r0 <-chan *packet.Packet\n\tif rf, ok := ret.Get(0).(func() <-chan *packet.Packet); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(<-chan *packet.Packet)\n\t\t}\n\t}\n\n\treturn r0\n}", "func TestBasicMethodChannelStringCodecHandle(t *testing.T) {\n\tcodec := StringCodec{}\n\tmessenger := NewTestingBinaryMessenger()\n\tchannel := NewBasicMessageChannel(messenger, \"ch\", codec)\n\tchannel.HandleFunc(func(message interface{}) (reply interface{}, err error) {\n\t\tmessageString, ok := message.(string)\n\t\tif !ok {\n\t\t\treturn nil, errors.New(\"message is invalid type, expected string\")\n\t\t}\n\t\treply = messageString + \" world\"\n\t\treturn reply, nil\n\t})\n\tencodedMessage, err := codec.EncodeMessage(\"hello\")\n\tif err != nil {\n\t\tt.Fatalf(\"failed to encode message: %v\", err)\n\t}\n\tencodedReply, err := messenger.MockSend(\"ch\", encodedMessage)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\treply, err := codec.DecodeMessage(encodedReply)\n\tif err != nil {\n\t\tt.Fatalf(\"failed to decode reply: %v\", err)\n\t}\n\tt.Log(spew.Sdump(reply))\n\treplyString, ok := reply.(string)\n\tif !ok {\n\t\tt.Fatal(\"reply is invalid type, expected string\")\n\t}\n\tEqual(t, \"hello world\", replyString)\n}", "func (r AuthenticationMethodsReferences) ChannelService() bool {\n\treturn r.Duo\n}", "func (mr *MockProcessProviderMockRecorder) BootstrapperProvider() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"BootstrapperProvider\", reflect.TypeOf((*MockProcessProvider)(nil).BootstrapperProvider))\n}", "func (_m *MockDispatchServer) mustEmbedUnimplementedDispatchServer() {\n\t_m.Called()\n}" ]
[ "0.69362783", "0.6633123", "0.65392905", "0.6514544", "0.6098021", "0.5991934", "0.59471476", "0.5913013", "0.572652", "0.5656788", "0.5588901", "0.5575467", "0.5548425", "0.5537879", "0.5521586", "0.5423457", "0.5391196", "0.53427863", "0.53340673", "0.5321305", "0.5308125", "0.5303947", "0.5300517", "0.5270052", "0.5267565", "0.526693", "0.5262409", "0.52534217", "0.52392757", "0.5233666", "0.52013975", "0.51918477", "0.51780343", "0.51687306", "0.51618314", "0.5155654", "0.5139567", "0.51183313", "0.5087577", "0.5073967", "0.50513947", "0.50499415", "0.5044505", "0.503758", "0.50311553", "0.5016614", "0.50072765", "0.50063723", "0.49968004", "0.4988122", "0.4971558", "0.49641082", "0.49583882", "0.49570382", "0.49562493", "0.49523887", "0.4935094", "0.49311274", "0.49184078", "0.4915564", "0.4909103", "0.4907837", "0.49026647", "0.48997852", "0.4895201", "0.48888347", "0.48863807", "0.48766947", "0.48684275", "0.4867919", "0.48632613", "0.4859963", "0.4858294", "0.48451382", "0.48429745", "0.48354596", "0.48293674", "0.48267165", "0.48253173", "0.4808149", "0.4798575", "0.47963405", "0.47834817", "0.4783296", "0.4771699", "0.47692564", "0.4763381", "0.47596222", "0.47560376", "0.4751985", "0.47504637", "0.47416276", "0.47377354", "0.47340566", "0.47223848", "0.47191173", "0.47169316", "0.47148925", "0.47147024", "0.47119135" ]
0.70414907
0
CryptoSuite mocks base method
func (m *MockClient) CryptoSuite() core.CryptoSuite { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "CryptoSuite") ret0, _ := ret[0].(core.CryptoSuite) return ret0 }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func TestEncrypt() {\n\n}", "func (m *MockisCryptoApiRequest_CryptoApiReq) isCryptoApiRequest_CryptoApiReq() {\n\tm.ctrl.Call(m, \"isCryptoApiRequest_CryptoApiReq\")\n}", "func (m *MockProviders) CryptoSuite() core.CryptoSuite {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"CryptoSuite\")\n\tret0, _ := ret[0].(core.CryptoSuite)\n\treturn ret0\n}", "func (m *MockisCryptoAsymApiReqSetupPrivateKeyEx_Key) isCryptoAsymApiReqSetupPrivateKeyEx_Key() {\n\tm.ctrl.Call(m, \"isCryptoAsymApiReqSetupPrivateKeyEx_Key\")\n}", "func (pc *MockProviderContext) CryptoSuite() apicryptosuite.CryptoSuite {\n\treturn pc.cryptoSuite\n}", "func TestMain(m *testing.M) {\n\tconfigImp = mocks.NewMockConfig(caServerURL)\n\tcryptoSuiteProvider, _ = cryptosuiteimpl.GetSuiteByConfig(configImp)\n\tif cryptoSuiteProvider == nil {\n\t\tpanic(\"Failed initialize cryptoSuiteProvider\")\n\t}\n\t// Start Http Server\n\tgo mocks.StartFabricCAMockServer(strings.TrimPrefix(caServerURL, \"http://\"))\n\t// Allow HTTP server to start\n\ttime.Sleep(1 * time.Second)\n\tos.Exit(m.Run())\n}", "func (m *MockisCryptoAsymApiRespSetupPrivateKey_KeyInfo) isCryptoAsymApiRespSetupPrivateKey_KeyInfo() {\n\tm.ctrl.Call(m, \"isCryptoAsymApiRespSetupPrivateKey_KeyInfo\")\n}", "func (m *MockisCryptoApiResponse_CryptoApiResp) isCryptoApiResponse_CryptoApiResp() {\n\tm.ctrl.Call(m, \"isCryptoApiResponse_CryptoApiResp\")\n}", "func mockChildPackages() {\n\n\t// Fake an AWS credentials file so that the mfile package will nehave as if it is happy\n\tsetFakeCredentials()\n\n\t// Fake out the creds package into using an apparently credentials response from AWS\n\tcreds.SetGetSessionTokenFunc(func(awsService *sts.STS, input *sts.GetSessionTokenInput) (*sts.GetSessionTokenOutput, error) {\n\t\treturn getSessionTokenOutput, nil\n\t})\n\n}", "func (s *SignSuite) SetUpTest(c *C) {\n}", "func TestCryptoSignerInterfaceBehavior(t *testing.T) {\n\tcs := NewCryptoService(trustmanager.NewKeyMemoryStore(passphraseRetriever))\n\tinterfaces.EmptyCryptoServiceInterfaceBehaviorTests(t, cs)\n\tinterfaces.CreateGetKeyCryptoServiceInterfaceBehaviorTests(t, cs, data.ECDSAKey)\n\n\tcs = NewCryptoService(trustmanager.NewKeyMemoryStore(passphraseRetriever))\n\tinterfaces.CreateListKeyCryptoServiceInterfaceBehaviorTests(t, cs, data.ECDSAKey)\n\n\tcs = NewCryptoService(trustmanager.NewKeyMemoryStore(passphraseRetriever))\n\tinterfaces.AddGetKeyCryptoServiceInterfaceBehaviorTests(t, cs, data.ECDSAKey)\n\n\tcs = NewCryptoService(trustmanager.NewKeyMemoryStore(passphraseRetriever))\n\tinterfaces.AddListKeyCryptoServiceInterfaceBehaviorTests(t, cs, data.ECDSAKey)\n}", "func (m *MockInternalServer) CryptoAsymKeyWrite(arg0 context.Context, arg1 *CryptoAsymKeyWriteRequestMsg) (*CryptoAsymKeyWriteResponseMsg, error) {\n\tret := m.ctrl.Call(m, \"CryptoAsymKeyWrite\", arg0, arg1)\n\tret0, _ := ret[0].(*CryptoAsymKeyWriteResponseMsg)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func TestCorePkg_CreateCryptoSuiteProvider(t *testing.T) {\n\tpkg := newCorePkg()\n\trequire.NotNil(t, pkg)\n\n\tp, err := pkg.CreateCryptoSuiteProvider(nil)\n\trequire.NoError(t, err)\n\trequire.NotNil(t, p)\n}", "func (m *MockInternalServer) CryptoKeyUpdate(arg0 context.Context, arg1 *CryptoKeyUpdateRequestMsg) (*CryptoKeyUpdateResponseMsg, error) {\n\tret := m.ctrl.Call(m, \"CryptoKeyUpdate\", arg0, arg1)\n\tret0, _ := ret[0].(*CryptoKeyUpdateResponseMsg)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockPacketHandler) getCryptoStream() cryptoStreamI {\n\tret := m.ctrl.Call(m, \"getCryptoStream\")\n\tret0, _ := ret[0].(cryptoStreamI)\n\treturn ret0\n}", "func TestHandshakeCoreData(t *testing.T) {\n\n\t// node 1\n\tport := crypto.GetRandomUserPort()\n\taddress := fmt.Sprintf(\"0.0.0.0:%d\", port)\n\n\tnode1Local, err := NewNodeIdentity(address, nodeconfig.ConfigValues, false)\n\n\tif err != nil {\n\t\tt.Error(\"failed to create local node1\", err)\n\t}\n\n\t// this will be node 2 view of node 1\n\tnode1Remote, _ := NewRemoteNode(node1Local.String(), address)\n\n\t// node 2\n\tport1 := crypto.GetRandomUserPort()\n\taddress1 := fmt.Sprintf(\"0.0.0.0:%d\", port1)\n\n\tnode2Local, err := NewNodeIdentity(address1, nodeconfig.ConfigValues, false)\n\n\tif err != nil {\n\t\tt.Error(\"failed to create local node2\", err)\n\t}\n\n\t// this will be node1 view of node 2\n\tnode2Remote, _ := NewRemoteNode(node2Local.String(), address1)\n\n\t// STEP 1: Node1 generates handshake data and sends it to node2 ....\n\tdata, session, err := generateHandshakeRequestData(node1Local, node2Remote)\n\n\tassert.NoErr(t, err, \"expected no error\")\n\tassert.NotNil(t, session, \"expected session\")\n\tassert.NotNil(t, data, \"expected session\")\n\n\tlog.Info(\"Node 1 session data: Id:%s, AES-KEY:%s\", hex.EncodeToString(session.ID()), hex.EncodeToString(session.KeyE()))\n\n\tassert.False(t, session.IsAuthenticated(), \"Expected session to be not authenticated yet\")\n\n\t// STEP 2: Node2 gets handshake data from node 1 and processes it to establish a session with a shared AES key\n\n\tresp, session1, err := processHandshakeRequest(node2Local, node1Remote, data)\n\n\tassert.NoErr(t, err, \"expected no error\")\n\tassert.NotNil(t, session1, \"expected session\")\n\tassert.NotNil(t, resp, \"expected resp data\")\n\n\tlog.Info(\"Node 2 session data: Id:%s, AES-KEY:%s\", hex.EncodeToString(session1.ID()), hex.EncodeToString(session1.KeyE()))\n\n\tassert.Equal(t, string(session.ID()), string(session1.ID()), \"expected agreed Id\")\n\tassert.Equal(t, string(session.KeyE()), string(session1.KeyE()), \"expected same shared AES enc key\")\n\tassert.Equal(t, string(session.KeyM()), string(session1.KeyM()), \"expected same shared AES mac key\")\n\tassert.Equal(t, string(session.PubKey()), string(session1.PubKey()), \"expected same shared secret\")\n\n\tassert.True(t, session1.IsAuthenticated(), \"expected session1 to be authenticated\")\n\n\t// STEP 3: Node2 sends data1 back to node1.... Node 1 validates the data and sets its network session to authenticated\n\terr = processHandshakeResponse(node1Local, node2Remote, session, resp)\n\n\tassert.True(t, session.IsAuthenticated(), \"expected session to be authenticated\")\n\tassert.NoErr(t, err, \"failed to authenticate or process response\")\n\n\t// test session sym enc / dec\n\n\tconst msg = \"hello spacemesh - hello spacemesh - hello spacemesh :-)\"\n\tcipherText, err := session.Encrypt([]byte(msg))\n\tassert.NoErr(t, err, \"expected no error\")\n\n\tclearText, err := session1.Decrypt(cipherText)\n\tassert.NoErr(t, err, \"expected no error\")\n\tassert.True(t, bytes.Equal(clearText, []byte(msg)), \"Expected enc/dec to work\")\n\n\tnode1Local.Shutdown()\n\tnode2Local.Shutdown()\n}", "func (m *MockisKey_KeyInfo) isKey_KeyInfo() {\n\tm.ctrl.Call(m, \"isKey_KeyInfo\")\n}", "func (m *MockInternalServer) CryptoApiInvoke(arg0 context.Context, arg1 *CryptoApiRequestMsg) (*CryptoApiResponseMsg, error) {\n\tret := m.ctrl.Call(m, \"CryptoApiInvoke\", arg0, arg1)\n\tret0, _ := ret[0].(*CryptoApiResponseMsg)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func TestContext(t *testing.T) {\n\tnsCfg := config.Namespace{\n\t\tNamespace: didTrustblocNamespace,\n\t\tBasePath: didTrustblocBasePath,\n\t}\n\n\ttxnProvider := &peermocks.TxnServiceProvider{}\n\tdcasProvider := &peermocks.DCASClientProvider{}\n\topQueueProvider := &mocks.OperationQueueProvider{}\n\n\tt.Run(\"Success\", func(t *testing.T) {\n\t\tprotocolVersions := map[string]protocolApi.Protocol{\n\t\t\t\"0.5\": {\n\t\t\t\tStartingBlockChainTime: 100,\n\t\t\t\tHashAlgorithmInMultiHashCode: 18,\n\t\t\t\tMaxOperationsPerBatch: 100,\n\t\t\t\tMaxOperationByteSize: 1000,\n\t\t\t},\n\t\t}\n\n\t\tstConfigService := &peermocks.SidetreeConfigService{}\n\t\tstConfigService.LoadProtocolsReturns(protocolVersions, nil)\n\n\t\tctx, err := newContext(channel1, nsCfg, stConfigService, txnProvider, dcasProvider, opQueueProvider)\n\t\trequire.NoError(t, err)\n\t\trequire.NotNil(t, ctx)\n\n\t\trequire.NotNil(t, ctx.BatchWriter())\n\n\t\trequire.NoError(t, ctx.Start())\n\n\t\ttime.Sleep(20 * time.Millisecond)\n\n\t\tctx.Stop()\n\t})\n\n\tt.Run(\"No protocols -> error\", func(t *testing.T) {\n\t\tstConfigService := &peermocks.SidetreeConfigService{}\n\n\t\tctx, err := newContext(channel1, nsCfg, stConfigService, txnProvider, dcasProvider, opQueueProvider)\n\t\trequire.Error(t, err)\n\t\trequire.Contains(t, err.Error(), \"no protocols defined\")\n\t\trequire.Nil(t, ctx)\n\t})\n\n\tt.Run(\"Initialize protocols -> error\", func(t *testing.T) {\n\t\terrExpected := errors.New(\"injected sidetreeCfgService error\")\n\t\tstConfigService := &peermocks.SidetreeConfigService{}\n\t\tstConfigService.LoadProtocolsReturns(nil, errExpected)\n\n\t\tctx, err := newContext(channel1, nsCfg, stConfigService, txnProvider, dcasProvider, opQueueProvider)\n\t\trequire.EqualError(t, err, errExpected.Error())\n\t\trequire.Nil(t, ctx)\n\t})\n}", "func Test_Crypto(t *testing.T) {\n\trequire := require.New(t)\n\n\tc := &sm2.Driver{}\n\n\tpriv, err := c.GenKey()\n\trequire.Nil(err)\n\tt.Logf(\"priv:%X, len:%d\", priv.Bytes(), len(priv.Bytes()))\n\n\tpub := priv.PubKey()\n\trequire.NotNil(pub)\n\tt.Logf(\"pub:%X, len:%d\", pub.Bytes(), len(pub.Bytes()))\n\n\tmsg := []byte(\"hello world\")\n\tsignature := priv.Sign(msg)\n\tt.Logf(\"sign:%X, len:%d\", signature.Bytes(), len(signature.Bytes()))\n\n\tok := pub.VerifyBytes(msg, signature)\n\trequire.Equal(true, ok)\n}", "func (tradingSuite *KyberTradingTestSuite) SetupSuite() {\n\tfmt.Println(\"Setting up the suite...\")\n\t// Kovan env\n\ttradingSuite.EtherAddressStrKyber = \"0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee\"\n\n\ttradingSuite.IncKBNTokenIDStr = \"0000000000000000000000000000000000000000000000000000000000000082\"\n\ttradingSuite.IncSALTTokenIDStr = \"0000000000000000000000000000000000000000000000000000000000000081\"\n\ttradingSuite.IncOMGTokenIDStr = \"0000000000000000000000000000000000000000000000000000000000000072\"\n\ttradingSuite.IncSNTTokenIDStr = \"0000000000000000000000000000000000000000000000000000000000000071\"\n\ttradingSuite.KBNAddressStr = \"0xad67cB4d63C9da94AcA37fDF2761AaDF780ff4a2\" // kovan\n\ttradingSuite.SALTAddressStr = \"0x6fEE5727EE4CdCBD91f3A873ef2966dF31713A04\" // kovan\n\ttradingSuite.OMGAddressStr = \"0xdB7ec4E4784118D9733710e46F7C83fE7889596a\" // kovan\n\ttradingSuite.SNTAddressStr = \"0x4c99B04682fbF9020Fcb31677F8D8d66832d3322\" // kovan\n\ttradingSuite.KyberTradeDeployedAddr = common.HexToAddress(\"0x38A3cE5d944ff3de96401ddBFA9971D656222F89\") //kovan\n\ttradingSuite.KyberMultiTradeDeployedAddr = common.HexToAddress(\"0x8E7050E23A42052C75cdCE2d919f5e4F89afaD0a\") //kovan\n\ttradingSuite.DepositingEther = float64(0.05)\n\ttradingSuite.KyberContractAddr = common.HexToAddress(\"0x692f391bCc85cefCe8C237C01e1f636BbD70EA4D\") // kovan\n}", "func mockBatchCTXHeader() *BatchHeader {\n\tbh := NewBatchHeader()\n\tbh.ServiceClassCode = CreditsOnly\n\tbh.StandardEntryClassCode = CTX\n\tbh.CompanyName = \"Payee Name\"\n\tbh.CompanyIdentification = \"121042882\"\n\tbh.CompanyEntryDescription = \"ACH CTX\"\n\tbh.ODFIIdentification = \"12104288\"\n\treturn bh\n}", "func (m *MockInternalServer) CryptoKeyRead(arg0 context.Context, arg1 *CryptoKeyReadRequestMsg) (*CryptoKeyReadResponseMsg, error) {\n\tret := m.ctrl.Call(m, \"CryptoKeyRead\", arg0, arg1)\n\tret0, _ := ret[0].(*CryptoKeyReadResponseMsg)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (suite *SmsTests) SetUpSuite(c *C) {\n}", "func (m *MockInternalClient) CryptoAsymKeyWrite(ctx context.Context, in *CryptoAsymKeyWriteRequestMsg, opts ...grpc.CallOption) (*CryptoAsymKeyWriteResponseMsg, error) {\n\tvarargs := []interface{}{ctx, in}\n\tfor _, a := range opts {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"CryptoAsymKeyWrite\", varargs...)\n\tret0, _ := ret[0].(*CryptoAsymKeyWriteResponseMsg)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockSystemContract) Init(arg0 core.Keepers, arg1 types1.BaseTx, arg2 uint64) core.SystemContract {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Init\", arg0, arg1, arg2)\n\tret0, _ := ret[0].(core.SystemContract)\n\treturn ret0\n}", "func (m *MockProvider) KMSDecryptEnv(arg0, arg1 string) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"KMSDecryptEnv\", arg0, arg1)\n}", "func (m *MockInternalServer) CryptoAsymKeyCreate(arg0 context.Context, arg1 *CryptoAsymKeyCreateRequestMsg) (*CryptoAsymKeyCreateResponseMsg, error) {\n\tret := m.ctrl.Call(m, \"CryptoAsymKeyCreate\", arg0, arg1)\n\tret0, _ := ret[0].(*CryptoAsymKeyCreateResponseMsg)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func TestEncryptionEncryptByPassPhrase(t *testing.T) {\n\tpassPhrase := \"123\"\n\tplaintext := []byte{1, 2, 3, 4}\n\n\tciphertextStr, err := encryptByPassPhrase(passPhrase, plaintext)\n\tfmt.Println(\"ciphertextStr : \", ciphertextStr)\n\n\tassert.Equal(t, nil, err)\n\tassert.Greater(t, len(ciphertextStr), 0)\n\n\tplaintext2, err := decryptByPassPhrase(passPhrase, ciphertextStr)\n\tassert.Equal(t, plaintext, plaintext2)\n}", "func (m *MockInternalClient) CryptoApiInvoke(ctx context.Context, in *CryptoApiRequestMsg, opts ...grpc.CallOption) (*CryptoApiResponseMsg, error) {\n\tvarargs := []interface{}{ctx, in}\n\tfor _, a := range opts {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"CryptoApiInvoke\", varargs...)\n\tret0, _ := ret[0].(*CryptoApiResponseMsg)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockServicer) CalculateHashAndDuration(startTime time.Time, fiveSecTimer *time.Timer, password string) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"CalculateHashAndDuration\", startTime, fiveSecTimer, password)\n}", "func TestCommitMultipleKeys4A(t *testing.T) {\n}", "func Test_Redis(t *testing.T) {\n\n}", "func (s *TestSuite) setup() {\n\t// The first few keys from the following well-known mnemonic used by 0x:\n\t//\tconcert load couple harbor equip island argue ramp clarify fence smart topic\n\tkeys := []string{\n\t\t\"f2f48ee19680706196e2e339e5da3491186e0c4c5030670656b0e0164837257d\",\n\t\t\"5d862464fe9303452126c8bc94274b8c5f9874cbd219789b3eb2128075a76f72\",\n\t\t\"df02719c4df8b9b8ac7f551fcb5d9ef48fa27eef7a66453879f4d8fdc6e78fb1\",\n\t\t\"ff12e391b79415e941a94de3bf3a9aee577aed0731e297d5cfa0b8a1e02fa1d0\",\n\t\t\"752dd9cf65e68cfaba7d60225cbdbc1f4729dd5e5507def72815ed0d8abc6249\",\n\t\t\"efb595a0178eb79a8df953f87c5148402a224cdf725e88c0146727c6aceadccd\",\n\t}\n\ts.account = make([]account, len(keys))\n\tfor i, key := range keys {\n\t\tb, err := hex.DecodeString(key)\n\t\ts.Require().NoError(err)\n\t\ts.account[i].key, err = crypto.ToECDSA(b)\n\t\ts.Require().NoError(err)\n\t}\n\ts.signer = signer(s.account[0])\n}", "func TestDelegation(t *testing.T) {\n\tcsp, cleanup := newProvider(t, defaultOptions())\n\tdefer cleanup()\n\n\tk, err := csp.KeyGen(&bccsp.AES256KeyGenOpts{})\n\trequire.NoError(t, err)\n\n\tt.Run(\"KeyGen\", func(t *testing.T) {\n\t\tk, err := csp.KeyGen(&bccsp.AES256KeyGenOpts{})\n\t\trequire.NoError(t, err)\n\t\trequire.True(t, k.Private())\n\t\trequire.True(t, k.Symmetric())\n\t})\n\n\tt.Run(\"KeyDeriv\", func(t *testing.T) {\n\t\tk, err := csp.KeyDeriv(k, &bccsp.HMACDeriveKeyOpts{Arg: []byte{1}})\n\t\trequire.NoError(t, err)\n\t\trequire.True(t, k.Private())\n\t})\n\n\tt.Run(\"KeyImport\", func(t *testing.T) {\n\t\traw := make([]byte, 32)\n\t\t_, err := rand.Read(raw)\n\t\trequire.NoError(t, err)\n\n\t\tk, err := csp.KeyImport(raw, &bccsp.AES256ImportKeyOpts{})\n\t\trequire.NoError(t, err)\n\t\trequire.True(t, k.Private())\n\t})\n\n\tt.Run(\"GetKey\", func(t *testing.T) {\n\t\tk, err := csp.GetKey(k.SKI())\n\t\trequire.NoError(t, err)\n\t\trequire.True(t, k.Private())\n\t})\n\n\tt.Run(\"Hash\", func(t *testing.T) {\n\t\tdigest, err := csp.Hash([]byte(\"message\"), &bccsp.SHA3_384Opts{})\n\t\trequire.NoError(t, err)\n\t\trequire.NotEmpty(t, digest)\n\t})\n\n\tt.Run(\"GetHash\", func(t *testing.T) {\n\t\th, err := csp.GetHash(&bccsp.SHA256Opts{})\n\t\trequire.NoError(t, err)\n\t\trequire.Equal(t, sha256.New(), h)\n\t})\n\n\tt.Run(\"Sign\", func(t *testing.T) {\n\t\t_, err := csp.Sign(k, []byte(\"message\"), nil)\n\t\trequire.EqualError(t, err, \"Unsupported 'SignKey' provided [*sw.aesPrivateKey]\")\n\t})\n\n\tt.Run(\"Verify\", func(t *testing.T) {\n\t\t_, err := csp.Verify(k, []byte(\"signature\"), []byte(\"digest\"), nil)\n\t\trequire.Error(t, err)\n\t\trequire.Contains(t, err.Error(), \"Unsupported 'VerifyKey' provided\")\n\t})\n\n\tt.Run(\"EncryptDecrypt\", func(t *testing.T) {\n\t\tmsg := []byte(\"message\")\n\t\tct, err := csp.Encrypt(k, msg, &bccsp.AESCBCPKCS7ModeOpts{})\n\t\trequire.NoError(t, err)\n\n\t\tpt, err := csp.Decrypt(k, ct, &bccsp.AESCBCPKCS7ModeOpts{})\n\t\trequire.NoError(t, err)\n\t\trequire.Equal(t, msg, pt)\n\t})\n}", "func (suite *EmailTests) SetUpSuite(c *C) {\n}", "func (m *MockInternalClient) CryptoKeyUpdate(ctx context.Context, in *CryptoKeyUpdateRequestMsg, opts ...grpc.CallOption) (*CryptoKeyUpdateResponseMsg, error) {\n\tvarargs := []interface{}{ctx, in}\n\tfor _, a := range opts {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"CryptoKeyUpdate\", varargs...)\n\tret0, _ := ret[0].(*CryptoKeyUpdateResponseMsg)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func TestPagarmeEncryptCard(t *testing.T) {\n\t\n\tCard := new(pagarme.Card)\n\tPagarme := pagarme.NewPagarme(\"pt-BR\", ApiKey, CryptoKey)\n Pagarme.SetDebug()\n\n\tpagarmeFillCard(Card)\n\n\tresult, err := Pagarme.EncryptCard(Card)\n\n if err != nil {\n \tt.Errorf(\"Erro ao encrypt card: %v\", err)\n return\n }\n\n if len(result.Hash) == 0 {\n t.Errorf(\"card hash is expected\")\n return\n }\n}", "func (m *MockisCryptoAsymApiReqSetupPrivateKeyEx_Key) Size() int {\n\tret := m.ctrl.Call(m, \"Size\")\n\tret0, _ := ret[0].(int)\n\treturn ret0\n}", "func TestDelegatorProxyValidatorShares7Steps(t *testing.T) {\n\n}", "func TestSingleCommit4A(t *testing.T) {\n}", "func TestNewIdentityManager(t *testing.T) {\n\tt.Run(\"success\", func(t *testing.T) {\n\t\tepCfg := &mocks.EndpointConfig{}\n\t\tepCfg.NetworkConfigReturns(&fab.NetworkConfig{\n\t\t\tOrganizations: map[string]fab.OrganizationConfig{\"org1msp\": {}},\n\t\t})\n\n\t\tm, err := newIdentityManager(\"org1MSP\", &mocks.CryptoSuite{}, epCfg, \"./msp\")\n\t\trequire.NoError(t, err)\n\t\trequire.NotNil(t, m)\n\t})\n\n\tt.Run(\"No endpoint config -> error\", func(t *testing.T) {\n\t\tm, err := newIdentityManager(\"org1MSP\", &mocks.CryptoSuite{}, nil, \"./msp\")\n\t\trequire.EqualError(t, err, \"endpoint config is required\")\n\t\trequire.Nil(t, m)\n\t})\n\n\tt.Run(\"No org name -> error\", func(t *testing.T) {\n\t\tm, err := newIdentityManager(\"\", nil, &mocks.EndpointConfig{}, \"./msp\")\n\t\trequire.EqualError(t, err, \"orgName is required\")\n\t\trequire.Nil(t, m)\n\t})\n\n\tt.Run(\"No crypto suite -> error\", func(t *testing.T) {\n\t\tm, err := newIdentityManager(\"org1MSP\", nil, &mocks.EndpointConfig{}, \"./msp\")\n\t\trequire.EqualError(t, err, \"cryptoProvider is required\")\n\t\trequire.Nil(t, m)\n\t})\n\n\tt.Run(\"Org not found -> error\", func(t *testing.T) {\n\t\tepCfg := &mocks.EndpointConfig{}\n\t\tepCfg.NetworkConfigReturns(&fab.NetworkConfig{})\n\n\t\tm, err := newIdentityManager(\"org1MSP\", &mocks.CryptoSuite{}, epCfg, \"./msp\")\n\t\trequire.EqualError(t, err, \"org config retrieval failed\")\n\t\trequire.Nil(t, m)\n\t})\n\n\tt.Run(\"MSP config path not provided -> error\", func(t *testing.T) {\n\t\tepCfg := &mocks.EndpointConfig{}\n\t\tepCfg.NetworkConfigReturns(&fab.NetworkConfig{\n\t\t\tOrganizations: map[string]fab.OrganizationConfig{\"org1msp\": {}},\n\t\t})\n\n\t\tm, err := newIdentityManager(\"org1MSP\", &mocks.CryptoSuite{}, epCfg, \"\")\n\t\trequire.EqualError(t, err, \"either mspConfigPath or an embedded list of users is required\")\n\t\trequire.Nil(t, m)\n\t})\n}", "func (m *MockInternalClient) CryptoKeyRead(ctx context.Context, in *CryptoKeyReadRequestMsg, opts ...grpc.CallOption) (*CryptoKeyReadResponseMsg, error) {\n\tvarargs := []interface{}{ctx, in}\n\tfor _, a := range opts {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"CryptoKeyRead\", varargs...)\n\tret0, _ := ret[0].(*CryptoKeyReadResponseMsg)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func TestCipheringBasic(t *testing.T) {\n\tprivkey, err := NewPrivateKey(S256())\n\tif err != nil {\n\t\tt.Fatal(\"failed to generate private key\")\n\t}\n\n\tin := []byte(\"Hey there dude. How are you doing? This is a test.\")\n\n\tout, err := Encrypt(privkey.PubKey(), in)\n\tif err != nil {\n\t\tt.Fatal(\"failed to encrypt:\", err)\n\t}\n\n\tdec, err := Decrypt(privkey, out)\n\tif err != nil {\n\t\tt.Fatal(\"failed to decrypt:\", err)\n\t}\n\n\tif !bytes.Equal(in, dec) {\n\t\tt.Error(\"decrypted data doesn't match original\")\n\t}\n}", "func (v2 *UniswapTestSuite) SetupSuite() {\n\tfmt.Println(\"Setting up the suite...\")\n\tvar err error\n\tv2.WETH = common.HexToAddress(\"0xd0a1e359811322d97991e03f863a0c30c2cf029c\")\n\tv2.EtherAddress = common.HexToAddress(\"0x0000000000000000000000000000000000000000\")\n\tv2.ETHUniswapRouterAddress = common.HexToAddress(\"0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D\")\n\tv2.DAIAddress = common.HexToAddress(\"0x4f96fe3b7a6cf9725f59d353f723c1bdb64ca6aa\")\n\tv2.MRKAddressStr = common.HexToAddress(\"0xef13c0c8abcaf5767160018d268f9697ae4f5375\")\n\tv2.EthPrivateKey = \"B8DB29A7A43FB88AD520F762C5FDF6F1B0155637FA1E5CB2C796AFE9E5C04E31\"\n\tv2.VaultAddress = common.HexToAddress(\"0xF92c6bb5206BEFD3c8305ddd64d554322cC22aFc\")\n\tv2.EthHost = \"https://kovan.infura.io/v3/93fe721349134964aa71071a713c5cef\"\n\tv2.UniswapProxy = common.HexToAddress(\"0xc7724A86ced6D95573d36fc4B98f9C0414B907a1\")\n\tv2.IncAddr = common.HexToAddress(\"0xf295681641c170359E04Bbe2EA3985BaA4CF0baf\")\n\tv2.connectToETH()\n\tv2.c = getFixedCommittee()\n\tv2.auth = bind.NewKeyedTransactor(v2.ETHPrivKey)\n\tv2.v, err = vault.NewVault(v2.VaultAddress, v2.ETHClient)\n\trequire.Equal(v2.T(), nil, err)\n\n\t// uncomment to deploy new one on kovan\n\t// incAddr, tx, _, err := incognito_proxy.DeployIncognitoProxy(v2.auth, v2.ETHClient, v2.auth.From, v2.c.beacons, v2.c.bridges)\n\t// require.Equal(v2.T(), nil, err)\n\t// // Wait until tx is confirmed\n\t// err = wait(v2.ETHClient, tx.Hash())\n\t// require.Equal(v2.T(), nil, err)\n\t// v2.IncAddr = incAddr\n\t// fmt.Printf(\"Proxy address: %s\\n\", v2.IncAddr.Hex())\n\n\t// delegatorAddr, tx, _, err := vault.DeployVault(v2.auth, v2.ETHClient)\n\t// require.Equal(v2.T(), nil, err)\n\t// err = wait(v2.ETHClient, tx.Hash())\n\t// require.Equal(v2.T(), nil, err)\n\t// fmt.Printf(\"delegatorAddr address: %s\\n\", delegatorAddr.Hex())\n\n\t// vaultAbi, _ := abi.JSON(strings.NewReader(vault.VaultABI))\n\t// input, _ := vaultAbi.Pack(\"initialize\", common.Address{})\t\n\n\t// v2.VaultAddress, tx, _, err = vaultproxy.DeployVaultproxy(v2.auth, v2.ETHClient, delegatorAddr, common.HexToAddress(\"0x0000000000000000000000000000000000000001\"), v2.IncAddr, input)\n\t// require.Equal(v2.T(), nil, err)\n\t// err = wait(v2.ETHClient, tx.Hash())\n\t// require.Equal(v2.T(), nil, err)\n\t// fmt.Printf(\"vault proxy address: %s\\n\", v2.VaultAddress.Hex())\n\n\t// v2.UniswapProxy, tx, _, err = uniswap.DeployUniswapV2Trade(v2.auth, v2.ETHClient, v2.ETHUniswapRouterAddress)\n\t// require.Equal(v2.T(), nil, err)\n\t// err = wait(v2.ETHClient, tx.Hash())\n\t// require.Equal(v2.T(), nil, err)\n\t// fmt.Printf(\"Uniswap proxy address: %s\\n\", v2.UniswapProxy.Hex())\n}", "func TestEncryption(t *testing.T) {\n password := \"timisadork\"\n bPass := []byte(password)\n hash := Encrypt(password)\n\n if err := bcrypt.CompareHashAndPassword(hash, bPass); err != nil {\n t.Error(err)\n }\n}", "func (m *MockGQUICAEAD) Open(arg0, arg1 []byte, arg2 protocol.PacketNumber, arg3 []byte) ([]byte, protocol.EncryptionLevel, error) {\n\tret := m.ctrl.Call(m, \"Open\", arg0, arg1, arg2, arg3)\n\tret0, _ := ret[0].([]byte)\n\tret1, _ := ret[1].(protocol.EncryptionLevel)\n\tret2, _ := ret[2].(error)\n\treturn ret0, ret1, ret2\n}", "func init() {\n\ttesting.AddTest(&testing.Test{\n\t\tFunc: KeysetTiedToTPM1,\n\t\tDesc: \"Verifies that, for TPMv1.2 devices, the keyset is tied to TPM regardless of when it's created and if a reboot happens\",\n\t\tContacts: []string{\n\t\t\t\"cros-hwsec@chromium.org\",\n\t\t\t\"zuan@chromium.org\",\n\t\t},\n\t\tSoftwareDeps: []string{\"tpm1\"},\n\t\tAttr: []string{\"group:hwsec_destructive_func\"},\n\t})\n}", "func (pg *PortalIntegrationTestSuite) SetupSuite() {\n\tfmt.Println(\"Setting up the suite...\")\n\t// Kovan env\n\tpg.IncKBNTokenIDStr = \"0000000000000000000000000000000000000000000000000000000000000082\"\n\tpg.IncSALTTokenIDStr = \"0000000000000000000000000000000000000000000000000000000000000081\"\n\tpg.IncOMGTokenIDStr = \"0000000000000000000000000000000000000000000000000000000000000072\"\n\tpg.IncSNTTokenIDStr = \"0000000000000000000000000000000000000000000000000000000000000071\"\n\tpg.OMGAddressStr = \"0xdB7ec4E4784118D9733710e46F7C83fE7889596a\" // kovan\n\tpg.SNTAddressStr = \"0x4c99B04682fbF9020Fcb31677F8D8d66832d3322\" // kovan\n\tpg.DepositingEther = float64(5)\n\tpg.ETHPrivKeyStr = \"1ABA488300A9D7297A315D127837BE4219107C62C61966ECDF7A75431D75CC61\"\n\tpg.PortalAdminKey = \"B8DB29A7A43FB88AD520F762C5FDF6F1B0155637FA1E5CB2C796AFE9E5C04E31\"\n\tpg.ETHHost = \"http://localhost:8545\"\n\n\tvar err error\n\tfmt.Println(\"Pulling image if not exist, please wait...\")\n\t// remove container if already running\n\texec.Command(\"/bin/sh\", \"-c\", \"docker rm -f portalv3\").Output()\n\texec.Command(\"/bin/sh\", \"-c\", \"docker rm -f incognito\").Output()\n\t_, err = exec.Command(\"/bin/sh\", \"-c\", \"docker run -d -p 8545:8545 --name portalv3 trufflesuite/ganache-cli --account=\\\"0x1ABA488300A9D7297A315D127837BE4219107C62C61966ECDF7A75431D75CC61,10000000000000000000000000000000000,0xB8DB29A7A43FB88AD520F762C5FDF6F1B0155637FA1E5CB2C796AFE9E5C04E31,10000000000000000000000000000000000\\\"\").Output()\n\trequire.Equal(pg.T(), nil, err)\n\ttime.Sleep(10 * time.Second)\n\n\tETHPrivKey, ETHClient, err := ethInstance(pg.ETHPrivKeyStr, pg.ETHHost)\n\trequire.Equal(pg.T(), nil, err)\n\tpg.ETHClient = ETHClient\n\tpg.ETHPrivKey = ETHPrivKey\n\tpg.auth = bind.NewKeyedTransactor(ETHPrivKey)\n\n\t// admin key\n\tprivKey, err := crypto.HexToECDSA(pg.PortalAdminKey)\n\trequire.Equal(pg.T(), nil, err)\n\tadmin := bind.NewKeyedTransactor(privKey)\n\n\t//pg.Portalv3 = common.HexToAddress(\"0x8c13AFB7815f10A8333955854E6ec7503eD841B7\")\n\t//pg.portalV3Inst, err = portalv3.NewPortalv3(pg.Portalv3, pg.ETHClient)\n\t//require.Equal(pg.T(), nil, err)\n\t//incAddr := common.HexToAddress(\"0x2fe0423B148739CD9D0E49e07b5ca00d388A15ac\")\n\t//pg.incProxy, err = incognitoproxy.NewIncognitoproxy(incAddr, pg.ETHClient)\n\t//require.Equal(pg.T(), nil, err)\n\n\tc := getFixedCommittee()\n\tincAddr, _, _, err := incognitoproxy.DeployIncognitoproxy(pg.auth, pg.ETHClient, admin.From, c.beacons)\n\trequire.Equal(pg.T(), nil, err)\n\tfmt.Printf(\"Proxy address: %s\\n\", incAddr.Hex())\n\tportalv3Logic, _, _, err := portalv3.DeployPortalv3(pg.auth, pg.ETHClient)\n\trequire.Equal(pg.T(), nil, err)\n\tfmt.Printf(\"portalv3 address: %s\\n\", portalv3Logic.Hex())\n\n\tportalv3ABI, _ := abi.JSON(strings.NewReader(portalv3.Portalv3ABI))\n\tinput, _ := portalv3ABI.Pack(\"initialize\")\n\n\t//PortalV3\n\tpg.Portalv3, _, _, err = delegator.DeployDelegator(pg.auth, pg.ETHClient, portalv3Logic, admin.From, incAddr, input)\n\trequire.Equal(pg.T(), nil, err)\n\tfmt.Printf(\"delegator address: %s\\n\", pg.Portalv3.Hex())\n\tpg.portalV3Inst, err = portalv3.NewPortalv3(pg.Portalv3, pg.ETHClient)\n\trequire.Equal(pg.T(), nil, err)\n\tpg.incProxy, err = incognitoproxy.NewIncognitoproxy(incAddr, pg.ETHClient)\n\trequire.Equal(pg.T(), nil, err)\n\n\t// 0x54d28562271De782B261807a01d1D2fb97417912\n\tpg.USDTAddress, _, _, err = usdt.DeployUsdt(pg.auth, pg.ETHClient, big.NewInt(100000000000), \"Tether\", \"USDT\", big.NewInt(6))\n\trequire.Equal(pg.T(), nil, err)\n\tfmt.Printf(\"usdt address: %s\\n\", pg.USDTAddress.Hex())\n\n\t//get portalv3 ip\n\tipAddress, err := exec.Command(\"/bin/sh\", \"-c\", \"docker inspect -f \\\"{{ .NetworkSettings.IPAddress }}\\\" portalv3\").Output()\n\trequire.Equal(pg.T(), nil, err)\n\n\t// run incognito chaind\n\tincogitoWithArgument := fmt.Sprintf(\"docker run -d -p 9334:9334 -p 9338:9338 --name incognito -e GETH_NAME=%v -e PORTAL_CONTRACT=%v incognito\", string(ipAddress), pg.Portalv3.Hex())\n\tincogitoWithArgument = strings.Replace(incogitoWithArgument, \"\\n\", \"\", -1)\n\t_, err = exec.Command(\"/bin/sh\", \"-c\", incogitoWithArgument).Output()\n\trequire.Equal(pg.T(), nil, err)\n\n\tfor {\n\t\ttime.Sleep(5 * time.Second)\n\t\tif checkRepsonse(pg.IncBridgeHost) {\n\t\t\tbreak\n\t\t}\n\t}\n\ttime.Sleep(40 * time.Second)\n}", "func (c CryptoServiceTester) TestAddKey(t *testing.T) {\n\tcryptoService := c.cryptoServiceFactory()\n\tcryptoService.keyStores = append(cryptoService.keyStores,\n\t\ttrustmanager.NewKeyMemoryStore(passphraseRetriever))\n\n\tprivKey, err := utils.GenerateECDSAKey(rand.Reader)\n\trequire.NoError(t, err)\n\n\t// Add the key to the targets role\n\trequire.NoError(t, cryptoService.AddKey(data.CanonicalTargetsRole, c.gun, privKey))\n\n\t// Check that we added the key and its info to only the first keystore\n\tretrievedKey, retrievedRole, err := cryptoService.keyStores[0].GetKey(privKey.ID())\n\trequire.NoError(t, err)\n\trequire.Equal(t, privKey.Private(), retrievedKey.Private())\n\trequire.Equal(t, data.CanonicalTargetsRole, retrievedRole)\n\n\tretrievedKeyInfo, err := cryptoService.keyStores[0].GetKeyInfo(privKey.ID())\n\trequire.NoError(t, err)\n\trequire.Equal(t, data.CanonicalTargetsRole, retrievedKeyInfo.Role)\n\trequire.Equal(t, c.gun, retrievedKeyInfo.Gun)\n\n\t// The key should not exist in the second keystore\n\t_, _, err = cryptoService.keyStores[1].GetKey(privKey.ID())\n\trequire.Error(t, err)\n\t_, err = cryptoService.keyStores[1].GetKeyInfo(privKey.ID())\n\trequire.Error(t, err)\n\n\t// We should be able to successfully get the key from the cryptoservice level\n\tretrievedKey, retrievedRole, err = cryptoService.GetPrivateKey(privKey.ID())\n\trequire.NoError(t, err)\n\trequire.Equal(t, privKey.Private(), retrievedKey.Private())\n\trequire.Equal(t, data.CanonicalTargetsRole, retrievedRole)\n\tretrievedKeyInfo, err = cryptoService.GetKeyInfo(privKey.ID())\n\trequire.NoError(t, err)\n\trequire.Equal(t, data.CanonicalTargetsRole, retrievedKeyInfo.Role)\n\trequire.Equal(t, c.gun, retrievedKeyInfo.Gun)\n\n\t// Add the same key to the targets role, since the info is the same we should have no error\n\trequire.NoError(t, cryptoService.AddKey(data.CanonicalTargetsRole, c.gun, privKey))\n\n\t// Try to add the same key to the snapshot role, which should error due to the role mismatch\n\trequire.Error(t, cryptoService.AddKey(data.CanonicalSnapshotRole, c.gun, privKey))\n}", "func (m *MockisTlsProxyFlowConfig_Keys) isTlsProxyFlowConfig_Keys() {\n\tm.ctrl.Call(m, \"isTlsProxyFlowConfig_Keys\")\n}", "func (_m *MockEncoderPool) Init(alloc EncoderAllocate) {\n\t_m.ctrl.Call(_m, \"Init\", alloc)\n}", "func TestAssetSysCC_InvalidateToken(t *testing.T) {\n\n\tfmt.Println(\"-----------------------------------\")\n\tfmt.Println(\"Test3: invalidateToken\")\n\n\t//fmt.Println(\"******test string to big.newInt\")\n\t//str := \"12321\"\n\t//strInt := big.NewInt(0)\n\t//strInt.SetString(str,10)\n\t//fmt.Println(strInt.String())\n\t//fmt.Println(\"*******************************\")\n\n\tascc := new(AssetSysCC)\n\tstub := shim.NewMockStub(\"ascc\", ascc)\n\tcheckInit(t, stub, [][]byte{[]byte(\"\")})\n\n\tres_test3 := stub.MockInvoke(\"1\", [][]byte{[]byte(\"issueToken\"), []byte(\"SSToken\"), []byte(\"250\"), []byte(\"18\"), []byte(MAddress[:])})\n\n\tif res_test3.Status != shim.OK {\n\t\tfmt.Println(\"Register token failed\", string(res_test3.Message))\n\t\tt.FailNow()\n\t}\n\n\t////query token quantity\n\t//res1 := stub.MockInvoke(\"2\", [][]byte{[]byte(\"getBalance\"), []byte(MAddress[:]), []byte(\"SSToken\")});\n\t//if res1.Status != shim.OK {\n\t//\tfmt.Println(\"Query failed\", string(res1.Message))\n\t//\tt.FailNow()\n\t//}\n\t//amount,_ := strconv.Atoi(string(res1.Payload))\n\t//if amount != 250 {\n\t//\tfmt.Printf(\"Query result error! %v\", amount )\n\t//\tt.FailNow()\n\t//}\n\n\t//beging to invalidate this token\n\tcheckQueryInfo(t, stub, [][]byte{[]byte(\"getTokenInfo\"), []byte(\"SSToken\")})\n\n\ttestInvalidate := stub.MockInvoke(\"4\", [][]byte{[]byte(\"invalidateToken\"), []byte(\"SSToken\")});\n\tif testInvalidate.Status != shim.OK {\n\t\tfmt.Println(\"Query failed\", string(testInvalidate.Message))\n\t\tt.FailNow()\n\t}\n\n\tcheckQueryInfo(t, stub, [][]byte{[]byte(\"getTokenInfo\"), []byte(\"SSToken\")})\n}", "func TestRecommitKey4A(t *testing.T) {\n}", "func (m *MockInternalClient) CryptoAsymKeyCreate(ctx context.Context, in *CryptoAsymKeyCreateRequestMsg, opts ...grpc.CallOption) (*CryptoAsymKeyCreateResponseMsg, error) {\n\tvarargs := []interface{}{ctx, in}\n\tfor _, a := range opts {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"CryptoAsymKeyCreate\", varargs...)\n\tret0, _ := ret[0].(*CryptoAsymKeyCreateResponseMsg)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func TestSqlSMSStorage_GetSMSs(t *testing.T) {\n\n}", "func TestGetCaptcha(t *testing.T) {}", "func (m *MockisCryptoAsymApiRespSetupPrivateKey_KeyInfo) Size() int {\n\tret := m.ctrl.Call(m, \"Size\")\n\tret0, _ := ret[0].(int)\n\treturn ret0\n}", "func (m *MockClusterScoper) HashKey() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"HashKey\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func (m *MockProposalContract) Init(arg0 core.Keepers, arg1 types1.BaseTx, arg2 uint64) core.SystemContract {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Init\", arg0, arg1, arg2)\n\tret0, _ := ret[0].(core.SystemContract)\n\treturn ret0\n}", "func setupSuite(t *testing.T) (*os.File, *os.File, *os.File, func(t *testing.T)) {\n\ttempCertFile, err := ioutil.TempFile(\"\", \"\")\n\tif err != nil {\n\t\tt.Error(err.Error())\n\t}\n\n\ttempCertFile.Write([]byte(`-----BEGIN CERTIFICATE-----\nMIIFRDCCAyygAwIBAgIEYiZSQDANBgkqhkiG9w0BAQsFADA7MTkwNwYDVQQDEzBB\nbnNpYmxlIEF1dG9tYXRpb24gQ29udHJvbGxlciBOb2RlcyBNZXNoIFJPT1QgQ0Ew\nHhcNMjIwMzA3MTg0MzEyWhcNMzExMjI4MDUwMzUxWjARMQ8wDQYDVQQDEwZmb29i\nYXIwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQCnXsRTTIoV2Oqh5zvN\nJzQBYOZPpxmnKzwLvgeop44Csk++zARvg5XIpmPbSEU2PY3pNGvLTH6nD54/ZfOI\nRzSN0ipvfcrpJtkrJ7OYo1gX7ROXM30x3bj2KcJ/cMgMiZMQLqPegKhtMHLGz0TX\n+0MfJ5jqTlowVjSAyUhK6pMtf2ISpHqOA6uvmLhUhkruUrUkHMnbwWMTzrO8QDMa\ndLvV+hiWZNZFaf6Xt3lNBRY+yrXuSG7ZOc/6UsWDb4NVALL1mJ0IjfSeiK58Sf8V\nHUY4MEjy8VW2lfARU/mcNkxrUY1DBNp5zcHMhwoLkLId90PyFyzXMDCvZxHrGEwt\nZ23UAYY/wAvw1XWm5XJBiLzaL12dStuHeZgtAUOucQHvEOglvPilU6vKf5PFdxqo\nKEOwXtgLUTlw4otm2bWx5p2LPlxkPApbAv7UaxiTbcpuIMh8WTTSk/EUgpyEUjph\niN0uqnp2fH9Mmyn8hgSB/Kf6FhIZFl3VMNN6x8VTkqLkzVG8Ud48gFHfraVQXvaL\ncDDCLxTeda6Th6uTw2zCifBzXbWxZKjlinx8MEM/kIA1we/wlwsYwpQNhkbOorR3\neJ6Exdl1Ar8l3jHp293hCvxUNuzG5Z9oPDMQ6MSm8xxrBN2pYZNL3DCWaJ0njuNj\nYeNR7l7s+9ibX5RD+uASiC6hOwIDAQABo3oweDAOBgNVHQ8BAf8EBAMCB4AwHQYD\nVR0lBBYwFAYIKwYBBQUHAwIGCCsGAQUFBwMBMB8GA1UdIwQYMBaAFFAlC81rH211\nfPJoWglERKb/7/NfMCYGA1UdEQQfMB2HBH8AAAGgFQYJKwYBBAGSCBMBoAgMBmZv\nb2JhcjANBgkqhkiG9w0BAQsFAAOCAgEAbzKRqx2i8S0Kuu0bIX094EoGiGSTWW4l\nYNHwn9mC/5KgzjSvxTkD0pInt31d5O27rK7/wMVezeqBIG92uwwZr7ndS6Fe0FT1\n7tMZ1VH5VetIiicbu3AYssqMs/JYEocqOngLh/pGHmlwcnmPpCltipcE50bv9YWn\nO8Yc5O7v16SxHzGsDUDO5eQAe2qvBaE5F5SBCVkjSoajmh3fdx/4eSzoF2wrug3/\nO+WAb70UXX6r8dmRpr4RezQ6XPWAG57BgU3g0NUkczFo5gFndBUJngLhR6wr14xB\nst21haZ65XIA46PB8jY04l/H2INwCzo++PlKJ3ROKwLXYDSZlgQ3X9XxsSzCX3Hs\nviK9Ybzp2W8sl1Pvtb/jodcNTpD2IB8IrWnvuOgnwVmewqAqlxM7Ers9kC83lBpt\nEhAXh0QyJ5BpHOkpm4jpVhOx1swHTBDoibysvpdr5KuuOm1JTr7cYRYhIe65rVz3\naL0PryzHdvQB97LhYAaUPtFnxNxUIeXKZO3Ndg/KSrSe4IqGz51uKjxJy+MnH9//\nnnG0JqlerSVvSPSiZ2kdn4OwzV2eA3Gj3uyTSGsjjoj82bhhRwKaSWmUh+AJByQ9\nkE6r/6za1Hvm+i/mz8f1cTUxFjF5pKzrprNRz5NMzs6NkQ0pg+mq5CNzav1ATSyv\nBdt96MbGrC0=\n-----END CERTIFICATE-----\n`))\n\n\ttempCertKey, err := ioutil.TempFile(\"\", \"\")\n\tif err != nil {\n\t\tt.Error(err.Error())\n\t}\n\n\ttempCertKey.Write([]byte(`-----BEGIN RSA PRIVATE KEY-----\nMIIJKAIBAAKCAgEAp17EU0yKFdjqoec7zSc0AWDmT6cZpys8C74HqKeOArJPvswE\nb4OVyKZj20hFNj2N6TRry0x+pw+eP2XziEc0jdIqb33K6SbZKyezmKNYF+0TlzN9\nMd249inCf3DIDImTEC6j3oCobTByxs9E1/tDHyeY6k5aMFY0gMlISuqTLX9iEqR6\njgOrr5i4VIZK7lK1JBzJ28FjE86zvEAzGnS71foYlmTWRWn+l7d5TQUWPsq17khu\n2TnP+lLFg2+DVQCy9ZidCI30noiufEn/FR1GODBI8vFVtpXwEVP5nDZMa1GNQwTa\nec3BzIcKC5CyHfdD8hcs1zAwr2cR6xhMLWdt1AGGP8AL8NV1puVyQYi82i9dnUrb\nh3mYLQFDrnEB7xDoJbz4pVOryn+TxXcaqChDsF7YC1E5cOKLZtm1seadiz5cZDwK\nWwL+1GsYk23KbiDIfFk00pPxFIKchFI6YYjdLqp6dnx/TJsp/IYEgfyn+hYSGRZd\n1TDTesfFU5Ki5M1RvFHePIBR362lUF72i3Awwi8U3nWuk4erk8Nswonwc121sWSo\n5Yp8fDBDP5CANcHv8JcLGMKUDYZGzqK0d3iehMXZdQK/Jd4x6dvd4Qr8VDbsxuWf\naDwzEOjEpvMcawTdqWGTS9wwlmidJ47jY2HjUe5e7PvYm1+UQ/rgEoguoTsCAwEA\nAQKCAgApCj3Nxyjc7pGqHY82YPSJmf8fbPQHX7ybjH9IRb22v456VICJ75Qc3WAC\n9xexkypnEqmT8i/kOxospY0vz3X9iJlLOWc2AIaj5FpPhU4mn8V7/+4k+h9OjTLa\nGQeUu29KOoWIG7gw/f5G7bAN3di5nPYMDiZjT+AT7EdDx31LXL7pn1dF13ST3Djm\n0P8yrSkpr713m1X2F2tPL9bYF+OvNmItDpDT+IerIBwoXKT1xLMTuMMllN2Anic8\ncW2cvE0ll8R5woVHEnDmnSZlQQZk5MIegDrqSJ3TQeok+dOHRToEQv5ne6KXyk0W\nRObIHkeU50XhhjmJ6RYltZGIWKI/QohWBECINhjmBxqGKBz5ultIOmeLPd5IlC+Y\now+zQk8WuYaUIX2PAzhFnhRfxUsv2Zoljt2J4YC3oKsB9cynrhonozvwEJy9MJJF\na48+meJ6Wkm6LtcREPgbjFtfhrPKQlD+/kfHR6mxhjR977lgZAvrGhlBTZPKx/MF\nr0ZOP34+Cw2ZDrHO1L7GQVEjY0JM2B6lCEYtI8Mxy04gqa+kRIjL+04WhjT1w2Lk\n71tOBNNB2AqxK+aptqxLG2By4mlW7WliGZI0j/6caXkg02olL/WqeBWTKSoUXLd6\nLD523A02VHQgBDhTdIjezKI1FpAVKCXdHuwgqSWPQiQx6FkdAQKCAQEA1YinOp0U\n1/9nq5f9Oet5uOLLGNG5lpzvCY9tPk9gWjTlAes5aQ8Pftg+P6dGgAsVqGxT2NvS\nuNSqYIBdm7Uy7jUG9m6PjQeQ7+oQ1vJqbryqr4QDwnAtHdWFfXak17YZs9YuhesP\nl5h4Oxi43Q2tZalMUY/rAmn+URqI5jlSWYiH6D9p2j9mEzvFrPQLvsbDb6zbxlAv\n8oaqOiOrQa+q3T+loeRX0ErN9qf84Vw7tc7Qp5a4siWyWIHKGHHVveB+ITcHJ2+7\nKJf7saRAjcRyHxX3tsPyRVSfg37nIMoPHilnN8bbhgBs0eMq1zcQgEYVceWx4pcZ\nGonabS85TBsqwQKCAQEAyKfZoot+oOOfWXMVBD761o4msd3fxRJlyS9RsPzRx7VO\nrQNTw9fCmurcFnF444fCfnEVJ/bCh/rWETyt1wVQhuy+th16hq4NEwGOD87WBXCn\nb3K8ZNbFDB9WL30q7bLe9UBw4j1ciHGKqpkjEACBrrdBF3HxVjBCQiHUKci3KK7E\nj6rtmR97UJj3XtTU0XiFm2FNKRa+aw0OQ3rr5Bw9ZURd9aXoDCXUMoXgfFnUxLWd\ny8Mdh5/PWmf8/o7/WqWpwejRJqfcGR1576QJXZjbduXG5zviDjwe5VKjgH5XRe8x\nytCa5Z6APGWA4hhuZYfERcCsirEPO4ruew+iE0c2+wKCAQAA7o28Rb83ihfLuegS\n/qITWnoEa7XhoGGyqvuREAudmSl+rqYbfUNWDF+JK5O1L1cy2vYqthrfT55GuYiv\nC0VjoLudC7J4rRXG1kCoj3pDbXNZPLw/dvnbbXkdqQzjHBpUnJSrZPE2eiXcLCly\nXYLqNKjumjAuXIQNmo4KYymm1l+xdcVifHBXmSUtsgrzFC76J8j1vpfW+Rt5EXrH\n2JpoSMTSRgrUD9+COg1ydlKUYoiqko/PxzZWCIr3PFfwcjBauMDBPU2VycQBbHQT\nqk3NMO1Z0NUX1Fy12DHuBLO4L/oRVj7TAOF4sQMY2VarGKMzUgtKr9oeMYfQfipD\n2MKBAoIBAQCyCFuNYP+FePDVyMoI7mhZHd8vSZFVpbEyBA4TXv4yl6eq0pzr0vAT\ny/Zi42NDXh0vWt5Oix6mz+RHfvMvKMP+MugzZYxlGuD20BZf6ED0qrOkqsSFJBnJ\nW7R4hjIknOQ97mM6GP+VAEjsfNsjQ4/MmUPjrXFX65GeY61/NVtteUNlxV7y0X/0\nTwSM24HIKYtCBd8Uad2h1f+l19acmoHO7A4B+qYcwSO5gBdhvcKOliXfuMrmnuC3\ncjSDGBVxNDOenReVmLIshn6+JWk55noy0ETevb8gqi8vgVcYlwCQSF6BeP02Zp+Y\n9uaXtN2esAtxaDavB9JgHjDid0hymmkpAoIBABmtcLim8rEIo82NERAUvVHR7MxR\nhXKx9g3bm1O0w7kJ16jyf5uyJ85JNi1XF2/AomSNWH6ikHuX5Xj6vOdL4Ki9jPDq\nTOlmvys2LtCAMOM3e3NvzIfTnrQEurGusCQKxCbnlRk2W13j3uc2gVFgB3T1+w2H\nlSEhzuFpDrxKrsE9QcCf7/Cju+2ir9h3FsPDRKoxfRJ2/onsgQ/Q7NODRRQGjwxw\nP/Hli/j17jC7TdgC26JhtVHH7K5xC6iNL03Pf3GTSvwN1vK1BY2reoz1FtQrGZvM\nrydzkVNNVeMVX2TER9yc8AdFqkRlaBWHmO61rYmV+N1quLM0uMVsu55ZNCY=\n-----END RSA PRIVATE KEY-----\n`))\n\n\ttempCA, err := ioutil.TempFile(\"\", \"\")\n\tif err != nil {\n\t\tt.Error(err.Error())\n\t}\n\n\ttempCA.Write([]byte(`-----BEGIN CERTIFICATE-----\nMIIFVTCCAz2gAwIBAgIEYdeDaTANBgkqhkiG9w0BAQsFADA7MTkwNwYDVQQDEzBB\nbnNpYmxlIEF1dG9tYXRpb24gQ29udHJvbGxlciBOb2RlcyBNZXNoIFJPT1QgQ0Ew\nHhcNMjIwMTA3MDAwMzUxWhcNMzIwMTA3MDAwMzUxWjA7MTkwNwYDVQQDEzBBbnNp\nYmxlIEF1dG9tYXRpb24gQ29udHJvbGxlciBOb2RlcyBNZXNoIFJPT1QgQ0EwggIi\nMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQCxAErOWvVDU8mfZgtE6BSygTWU\nMkPxxIEQSYs/UesRAHaB+QXa7/0Foa0VUJKcWwUE+2yYkNRrg8MmE8VWMSewcaNI\nAs407stFXP+A2anPEglwemTskpO72sigiYDKShC5n5ciyPsHckwVlOCTtac5TwFe\neTmGnHWRcd4uBGvaEXx98fw/wLgYtr9vmKTdnOQjriX9EaAWrjlrlzm54Bs3uVUj\nGSL7zY381EuUVV4AjbqQyThbY9cVfsK0nmzLUqpiHG2IhGZDZA9+jxtz2wJWFkNQ\nnWA3afCUjcWV+4FpP3p1U1myCeh2yR2uCHs9pkUK3ts9uD/Wd5j9M1oBMlymbN/C\n5Fahd+cTXrPAjsoRqCso9TBP4mIlNl1Jq8MRUWTL5HOuwn+KnufBtuQ1hIb71Eso\nkj90eWeo/P+temYAEquUVWiej7lnHyZVW647lE+o+xJEOmW+tY5H4jgA/twP4s7U\nBgR545usWF9/utvnhsGSkg1EYcdzaM01pkrWrw1GvHT++HshsrG6Tse8gY7JrTds\nLDtU8LPhPUEnSfVBcgcMg2Dg8lEbaODtdp2xtCJwZHy9CiAx3CKcogVEfecrKSSr\n2iSocft9/l8J+mhVG2CI6ekG6Cy9hDct/3SV01Dfd4FG7xXJIE3mTDLILpi1AVIW\nMHxYD3skuQMyLhJDAwIDAQABo2EwXzAOBgNVHQ8BAf8EBAMCAoQwHQYDVR0lBBYw\nFAYIKwYBBQUHAwIGCCsGAQUFBwMBMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYE\nFFAlC81rH211fPJoWglERKb/7/NfMA0GCSqGSIb3DQEBCwUAA4ICAQCWCP/O6YQ9\njhae2/BeUeeKsnoxf90prg3o6/QHbelF6yL+MvGg5ZbPSlt+ywLDNR2CYvXk/4SD\n5To7CPKhSPBwwUJpafvQfAOZijU30fvXvp5yZEFoOzOyvBP58NfzL5qH6Pf5A6i3\nrHvtR1v7DgS7u2qWWcSimIM0UPoV3JubLTEORjOR6FIyNkIxdjhrP3SxyZ54xxde\nG3bchKaRcGVNoFYSDN4bAA22JAjlD8kXNYKzIS/0cOR/9SnHd1wMIQ2trx0+TfyG\nFAA1mW1mjzQd+h5SGBVeCz2W2XttNSIfQDndJCsyACxmIaOK99AQxdhZsWfHtGO1\n3TjnyoiHjf8rozJbAVYqrIdB6GDf6fUlxwhUXT0qkgOvvAzjNnLoOBUkE4TWqXHl\n38a+ITDNVzaUlrTd63eexS69V6kHe7mrqjywNQ9EXF9kaVeoNTzRf/ztT/DEVAl+\nrKshMt4IOKQf1ScE+EJe1njpREHV+fa+kYvQB6cRuxW9a8sOSeQNaSL73Zv54elZ\nxffYhMv6yXvVxVnJHEsG3kM/CsvsU364BBd9kDcZbHpjNcDHMu+XxECJjD2atVtu\nFdaOLykGKfMCYVBP+xs97IJO8En/5N9QQwc+N4cfCg9/BWoZKHPbRx/V+57VEj0m\n69EpJXbL15ZQLCPsaIcqJqpK23VyJKc8fA==\n-----END CERTIFICATE-----\n`))\n\n\treturn tempCertFile, tempCertKey, tempCA, func(t *testing.T) {\n\t\tdefer os.Remove(tempCertFile.Name())\n\t\tdefer os.Remove(tempCertKey.Name())\n\t\tdefer os.Remove(tempCA.Name())\n\t}\n}", "func (m *MockManagedClusterScoper) HashKey() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"HashKey\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func (m *MockCall) Key() []byte {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Key\")\n\tret0, _ := ret[0].([]byte)\n\treturn ret0\n}", "func (m *MockIpsecServer) IpsecSAEncryptGet(arg0 context.Context, arg1 *IpsecSAEncryptGetRequestMsg) (*IpsecSAEncryptGetResponseMsg, error) {\n\tret := m.ctrl.Call(m, \"IpsecSAEncryptGet\", arg0, arg1)\n\tret0, _ := ret[0].(*IpsecSAEncryptGetResponseMsg)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func TestPrivateData(t *testing.T) {\n\tsdk := mainSDK\n\n\torgsContext := setupMultiOrgContext(t, sdk)\n\terr := integration.EnsureChannelCreatedAndPeersJoined(t, sdk, orgChannelID, \"orgchannel.tx\", orgsContext)\n\trequire.NoError(t, err)\n\n\tcoll1 := \"collection1\"\n\tccID := integration.GenerateExamplePvtID(true)\n\tcollConfig, err := newCollectionConfig(coll1, \"OR('Org2MSP.member')\", 0, 2, 1000)\n\trequire.NoError(t, err)\n\n\terr = integration.InstallExamplePvtChaincode(orgsContext, ccID)\n\trequire.NoError(t, err)\n\terr = integration.InstantiateExamplePvtChaincode(orgsContext, orgChannelID, ccID, \"OR('Org1MSP.member','Org2MSP.member')\", collConfig)\n\trequire.NoError(t, err)\n\n\tctxProvider := sdk.ChannelContext(orgChannelID, fabsdk.WithUser(org1User), fabsdk.WithOrg(org1Name))\n\n\tchClient, err := channel.New(ctxProvider)\n\trequire.NoError(t, err)\n\n\tt.Run(\"Specified Invocation Chain\", func(t *testing.T) {\n\t\tresponse, err := chClient.Execute(\n\t\t\tchannel.Request{\n\t\t\t\tChaincodeID: ccID,\n\t\t\t\tFcn: \"putprivate\",\n\t\t\t\tArgs: [][]byte{[]byte(coll1), []byte(\"key\"), []byte(\"value\")},\n\t\t\t\tInvocationChain: []*fab.ChaincodeCall{\n\t\t\t\t\t{ID: ccID, Collections: []string{coll1}},\n\t\t\t\t},\n\t\t\t},\n\t\t\tchannel.WithRetry(retry.TestRetryOpts),\n\t\t)\n\t\trequire.NoError(t, err)\n\t\tt.Logf(\"Got %d response(s)\", len(response.Responses))\n\t\trequire.NotEmptyf(t, response.Responses, \"expecting at least one response\")\n\t})\n\n\tt.Run(\"Auto-detect Invocation Chain\", func(t *testing.T) {\n\t\tresponse, err := chClient.Execute(\n\t\t\tchannel.Request{\n\t\t\t\tChaincodeID: ccID,\n\t\t\t\tFcn: \"putprivate\",\n\t\t\t\tArgs: [][]byte{[]byte(coll1), []byte(\"key\"), []byte(\"value\")},\n\t\t\t},\n\t\t\tchannel.WithRetry(retry.TestRetryOpts),\n\t\t)\n\t\trequire.NoError(t, err)\n\t\tt.Logf(\"Got %d response(s)\", len(response.Responses))\n\t\trequire.NotEmptyf(t, response.Responses, \"expecting at least one response\")\n\t})\n}", "func (m *MockCipher) Encrypt(arg0 []byte) ([]byte, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Encrypt\", arg0)\n\tret0, _ := ret[0].([]byte)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func StandardCrypto() {\n\n}", "func NewCryptographyServiceMock(t minimock.Tester) *CryptographyServiceMock {\n\tm := &CryptographyServiceMock{t: t}\n\n\tif controller, ok := t.(minimock.MockController); ok {\n\t\tcontroller.RegisterMocker(m)\n\t}\n\n\tm.GetPublicKeyMock = mCryptographyServiceMockGetPublicKey{mock: m}\n\tm.SignMock = mCryptographyServiceMockSign{mock: m}\n\tm.VerifyMock = mCryptographyServiceMockVerify{mock: m}\n\n\treturn m\n}", "func (m *MockInternalServer) CryptoAsymKeyDelete(arg0 context.Context, arg1 *CryptoAsymKeyDeleteRequestMsg) (*CryptoAsymKeyDeleteResponseMsg, error) {\n\tret := m.ctrl.Call(m, \"CryptoAsymKeyDelete\", arg0, arg1)\n\tret0, _ := ret[0].(*CryptoAsymKeyDeleteResponseMsg)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockC2Client) GetCryptoMode(arg0 context.Context, arg1 *pb.GetCryptoModeRequest, arg2 ...grpc.CallOption) (*pb.GetCryptoModeResponse, error) {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{arg0, arg1}\n\tfor _, a := range arg2 {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"GetCryptoMode\", varargs...)\n\tret0, _ := ret[0].(*pb.GetCryptoModeResponse)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockInternalServer) CryptoKeyCreate(arg0 context.Context, arg1 *CryptoKeyCreateRequestMsg) (*CryptoKeyCreateResponseMsg, error) {\n\tret := m.ctrl.Call(m, \"CryptoKeyCreate\", arg0, arg1)\n\tret0, _ := ret[0].(*CryptoKeyCreateResponseMsg)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockChoriaProvider) MainCollective() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"MainCollective\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func TestOAuth2ClientCredentialsCache(t *testing.T) {\n\t// Setup\n\tmockCtrl := gomock.NewController(t)\n\tdefer mockCtrl.Finish()\n\n\t// Mock mockTokenProvider\n\tmockTokenProvider := mock.NewMockTokenProviderInterface(mockCtrl)\n\n\tgomock.InOrder(\n\t\t// First call returning abc and Bearer, expires within 1 second\n\t\tmockTokenProvider.\n\t\t\tEXPECT().\n\t\t\tGetToken(gomock.Any()).\n\t\t\tReturn(&oauth2.Token{\n\t\t\t\tAccessToken: \"abc\",\n\t\t\t\tTokenType: \"Bearer\",\n\t\t\t\tExpiry: time.Now().In(time.UTC).Add(1 * time.Second),\n\t\t\t}, nil).\n\t\t\tTimes(1),\n\t\t// Second call returning def and MAC, expires within 1 second\n\t\tmockTokenProvider.\n\t\t\tEXPECT().\n\t\t\tGetToken(gomock.Any()).\n\t\t\tReturn(&oauth2.Token{\n\t\t\t\tAccessToken: \"def\",\n\t\t\t\tTokenType: \"MAC\",\n\t\t\t\tExpiry: time.Now().In(time.UTC).Add(1 * time.Second),\n\t\t\t}, nil).\n\t\t\tTimes(1),\n\t)\n\n\t// Specify components metadata\n\tvar metadata middleware.Metadata\n\tmetadata.Properties = map[string]string{\n\t\t\"clientID\": \"testId\",\n\t\t\"clientSecret\": \"testSecret\",\n\t\t\"scopes\": \"ascope\",\n\t\t\"tokenURL\": \"https://localhost:9999\",\n\t\t\"headerName\": \"someHeader\",\n\t\t\"authStyle\": \"1\",\n\t}\n\n\t// Initialize middleware component and inject mocked TokenProvider\n\tlog := logger.NewLogger(\"oauth2clientcredentials.test\")\n\toauth2clientcredentialsMiddleware, _ := NewOAuth2ClientCredentialsMiddleware(log).(*Middleware)\n\toauth2clientcredentialsMiddleware.SetTokenProvider(mockTokenProvider)\n\thandler, err := oauth2clientcredentialsMiddleware.GetHandler(context.Background(), metadata)\n\trequire.NoError(t, err)\n\n\t// First handler call should return abc Token\n\tr := httptest.NewRequest(http.MethodGet, \"http://dapr.io\", nil)\n\tw := httptest.NewRecorder()\n\thandler(http.HandlerFunc(mockedRequestHandler)).ServeHTTP(w, r)\n\n\t// Assertion\n\tassert.Equal(t, \"Bearer abc\", r.Header.Get(\"someHeader\"))\n\n\t// Second handler call should still return 'cached' abc Token\n\tr = httptest.NewRequest(http.MethodGet, \"http://dapr.io\", nil)\n\tw = httptest.NewRecorder()\n\thandler(http.HandlerFunc(mockedRequestHandler)).ServeHTTP(w, r)\n\n\t// Assertion\n\tassert.Equal(t, \"Bearer abc\", r.Header.Get(\"someHeader\"))\n\n\t// Wait at a second to invalidate cache entry for abc\n\ttime.Sleep(1 * time.Second)\n\n\t// Third call should return def Token\n\tr = httptest.NewRequest(http.MethodGet, \"http://dapr.io\", nil)\n\tw = httptest.NewRecorder()\n\thandler(http.HandlerFunc(mockedRequestHandler)).ServeHTTP(w, r)\n\n\t// Assertion\n\tassert.Equal(t, \"MAC def\", r.Header.Get(\"someHeader\"))\n}", "func (suite *BaseSuite) SetupSuite() {\n\tif err := godotenv.Load(); err != nil {\n\t\tsuite.T().Log(err)\n\t}\n\n\tsetFromEnv := func(key string, target *string) {\n\t\tv := os.Getenv(key)\n\t\tif v == \"\" {\n\t\t\tsuite.FailNowf(\"missing environment variable\", \"%q required for integration tests.\", key)\n\t\t}\n\n\t\t*target = v\n\t}\n\n\tsetFromEnv(\"AZURE_TENANT_ID\", &suite.TenantID)\n\tsetFromEnv(\"AZURE_SUBSCRIPTION_ID\", &suite.SubscriptionID)\n\tsetFromEnv(\"AZURE_CLIENT_ID\", &suite.ClientID)\n\tsetFromEnv(\"AZURE_CLIENT_SECRET\", &suite.ClientSecret)\n\tsetFromEnv(\"SERVICEBUS_CONNECTION_STRING\", &suite.ConnStr)\n\tsetFromEnv(\"TEST_SERVICEBUS_RESOURCE_GROUP\", &suite.ResourceGroup)\n\n\t// TODO: automatically infer the location from the resource group, if it's not specified.\n\t// https://github.com/Azure/azure-service-bus-go/issues/40\n\tsetFromEnv(\"TEST_SERVICEBUS_LOCATION\", &suite.Location)\n\n\tparsed, err := conn.ParsedConnectionFromStr(suite.ConnStr)\n\tif !suite.NoError(err) {\n\t\tsuite.FailNowf(\"connection string could not be parsed\", \"Connection String: %q\", suite.ConnStr)\n\t}\n\tsuite.Namespace = parsed.Namespace\n\tsuite.Token = suite.servicePrincipalToken()\n\tsuite.Environment = azure.PublicCloud\n\tsuite.TagID = randomString(\"tag\", 10)\n\n\tif !suite.NoError(suite.ensureProvisioned(sbmgmt.SkuTierStandard)) {\n\t\tsuite.FailNow(\"failed to ensure provisioned\")\n\t}\n}", "func (m *MockIInterConnector) Key() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Key\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func (c *Provider) CryptoSuite() core.CryptoSuite {\n\treturn c.cryptoSuite\n}", "func TestAssetSysCC_IssueToken(t *testing.T) {\n\n\tfmt.Println(\"-----------------------------------\")\n\tfmt.Println(\"Test2: issueToken\")\n\n\tascc := new(AssetSysCC)\n\tstub := shim.NewMockStub(\"ascc\", ascc)\n\tcheckInit(t, stub, [][]byte{[]byte(\"\")})\n\n\n\tres_test2 := stub.MockInvoke(\"1\", [][]byte{[]byte(\"registerToken\"), []byte(\"SSToken\"), []byte(\"250\"), []byte(\"18\"), []byte(MAddress[:])})\n\n\tif res_test2.Status != shim.OK {\n\t\tfmt.Println(\"Register token failed\", string(res_test2.Message))\n\t\tt.FailNow()\n\t}\n\n\tres_test3 := stub.MockInvoke(\"1\", [][]byte{[]byte(\"issueToken\"), []byte(\"SSToken\"), []byte(\"250\"), []byte(\"18\"), []byte(MAddress[:])})\n\n\tif res_test3.Status != shim.OK {\n\t\tfmt.Println(\"Register token failed\", string(res_test3.Message))\n\t\tt.FailNow()\n\t}\n\tcheckQueryInfo(t, stub, [][]byte{[]byte(\"getTokenInfo\"), []byte(\"SSToken\")})\n\n\t////query token quantity\n\t//\tres1 := stub.MockInvoke(\"2\", [][]byte{[]byte(\"getBalance\"), []byte(MAddress[:]), []byte(\"SSToken\")});\n\t//\tif res1.Status != shim.OK {\n\t//\t\tfmt.Println(\"Query failed\", string(res1.Message))\n\t//\t\tt.FailNow()\n\t//\t}\n\t//\tamount,_ := strconv.Atoi(string(res1.Payload))\n\t//\tif amount != 250 {\n\t//\t\tfmt.Printf(\"Query result error! %v\", amount )\n\t//\t\tt.FailNow()\n\t//\t}\n\n\tfmt.Println(\"Test issueToken for a registered one Success!\")\n\n\tres_test4 := stub.MockInvoke(\"2\", [][]byte{[]byte(\"issueToken\"), []byte(\"MToken\"), []byte(\"888\"), []byte(\"20\"), []byte(testAddress[:])})\n\tif res_test4.Status != shim.OK {\n\t\tfmt.Println(\"Register token failed\", string(res_test3.Message))\n\t\tt.FailNow()\n\t}\n\tcheckQueryInfo(t, stub, [][]byte{[]byte(\"getTokenInfo\"), []byte(\"MToken\")})\n\n\t////query token quantity\n\t//res2 := stub.MockInvoke(\"2\", [][]byte{[]byte(\"getBalance\"), []byte(testAddress[:]), []byte(\"CMBToken\")});\n\t//if res1.Status != shim.OK {\n\t//\tfmt.Println(\"Query failed\", string(res2.Message))\n\t//\tt.FailNow()\n\t//}\n\t//amount2,_ := strconv.Atoi(string(res2.Payload))\n\t//if amount2 != 888 {\n\t//\tfmt.Printf(\"Query result error! %v\", amount2 )\n\t//\tt.FailNow()\n\t//}\n\n\tfmt.Println(\"Test issueToken for an un registered one Success!\")\n}", "func (m *MockisCryptoApiRequest_CryptoApiReq) Size() int {\n\tret := m.ctrl.Call(m, \"Size\")\n\tret0, _ := ret[0].(int)\n\treturn ret0\n}", "func (m *MockSystemContract) Exec() error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Exec\")\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func testTLSCertsAllocate(t *testing.T) {\n\tvar (\n\t\terr error\n\t)\n\n\ttestTLSCerts = &testTLSCertsStruct{}\n\n\ttestTLSCerts.caCertPEMBlock, testTLSCerts.caKeyPEMBlock, err = icertpkg.GenCACert(\n\t\ticertpkg.GenerateKeyAlgorithmEd25519,\n\t\tpkix.Name{\n\t\t\tOrganization: []string{\"Test Organization CA\"},\n\t\t\tCountry: []string{},\n\t\t\tProvince: []string{},\n\t\t\tLocality: []string{},\n\t\t\tStreetAddress: []string{},\n\t\t\tPostalCode: []string{},\n\t\t},\n\t\ttime.Hour,\n\t\t\"\",\n\t\t\"\")\n\tif nil != err {\n\t\tt.Fatalf(\"icertpkg.GenCACert() failed: %v\", err)\n\t}\n\n\ttestTLSCerts.endpointCertPEMBlock, testTLSCerts.endpointKeyPEMBlock, err = icertpkg.GenEndpointCert(\n\t\ticertpkg.GenerateKeyAlgorithmEd25519,\n\t\tpkix.Name{\n\t\t\tOrganization: []string{\"Test Organization Endpoint\"},\n\t\t\tCountry: []string{},\n\t\t\tProvince: []string{},\n\t\t\tLocality: []string{},\n\t\t\tStreetAddress: []string{},\n\t\t\tPostalCode: []string{},\n\t\t},\n\t\t[]string{},\n\t\t[]net.IP{net.ParseIP(\"127.0.0.1\")},\n\t\ttime.Hour,\n\t\ttestTLSCerts.caCertPEMBlock,\n\t\ttestTLSCerts.caKeyPEMBlock,\n\t\t\"\",\n\t\t\"\")\n\n\tif nil != err {\n\t\tt.Fatalf(\"icertpkg.genEndpointCert() failed: %v\", err)\n\t}\n\n\ttestTLSCerts.endpointTLSCert, err = tls.X509KeyPair(testTLSCerts.endpointCertPEMBlock, testTLSCerts.endpointKeyPEMBlock)\n\tif nil != err {\n\t\tt.Fatalf(\"tls.LoadX509KeyPair() failed: %v\", err)\n\t}\n}", "func TestPrivateData(t *testing.T) {\n\tsdk := mainSDK\n\n\torgsContext := setupMultiOrgContext(t, sdk)\n\terr := integration.EnsureChannelCreatedAndPeersJoined(t, sdk, orgChannelID, \"orgchannel.tx\", orgsContext)\n\trequire.NoError(t, err)\n\n\tcoll1 := \"collection1\"\n\tccID := integration.GenerateExamplePvtID(true)\n\tcollConfig, err := newCollectionConfig(coll1, \"OR('Org2MSP.member')\", 0, 2, 1000)\n\trequire.NoError(t, err)\n\n\tif metadata.CCMode == \"lscc\" {\n\t\terr = integration.InstallExamplePvtChaincode(orgsContext, ccID)\n\t\trequire.NoError(t, err)\n\t\terr = integration.InstantiateExamplePvtChaincode(orgsContext, orgChannelID, ccID, \"OR('Org1MSP.member','Org2MSP.member')\", collConfig)\n\t\trequire.NoError(t, err)\n\t} else {\n\t\terr := integration.InstantiatePvtExampleChaincodeLc(sdk, orgsContext, orgChannelID, ccID, \"OR('Org1MSP.member','Org2MSP.member')\", collConfig)\n\t\trequire.NoError(t, err)\n\t}\n\n\tctxProvider := sdk.ChannelContext(orgChannelID, fabsdk.WithUser(org1User), fabsdk.WithOrg(org1Name))\n\n\tchClient, err := channel.New(ctxProvider)\n\trequire.NoError(t, err)\n\n\tt.Run(\"Specified Invocation Chain\", func(t *testing.T) {\n\t\tresponse, err := chClient.Execute(\n\t\t\tchannel.Request{\n\t\t\t\tChaincodeID: ccID,\n\t\t\t\tFcn: \"putprivate\",\n\t\t\t\tArgs: [][]byte{[]byte(coll1), []byte(\"key\"), []byte(\"value\")},\n\t\t\t\tInvocationChain: []*fab.ChaincodeCall{\n\t\t\t\t\t{ID: ccID, Collections: []string{coll1}},\n\t\t\t\t},\n\t\t\t},\n\t\t\tchannel.WithRetry(retry.TestRetryOpts),\n\t\t)\n\t\trequire.NoError(t, err)\n\t\tt.Logf(\"Got %d response(s)\", len(response.Responses))\n\t\trequire.NotEmptyf(t, response.Responses, \"expecting at least one response\")\n\t})\n\n\tt.Run(\"Auto-detect Invocation Chain\", func(t *testing.T) {\n\t\tresponse, err := chClient.Execute(\n\t\t\tchannel.Request{\n\t\t\t\tChaincodeID: ccID,\n\t\t\t\tFcn: \"putprivate\",\n\t\t\t\tArgs: [][]byte{[]byte(coll1), []byte(\"key\"), []byte(\"value\")},\n\t\t\t},\n\t\t\tchannel.WithRetry(retry.TestRetryOpts),\n\t\t)\n\t\trequire.NoError(t, err)\n\t\tt.Logf(\"Got %d response(s)\", len(response.Responses))\n\t\trequire.NotEmptyf(t, response.Responses, \"expecting at least one response\")\n\t})\n}", "func newMockKvCapabilityVerifier(t mockConstructorTestingTnewMockKvCapabilityVerifier) *mockKvCapabilityVerifier {\n\tmock := &mockKvCapabilityVerifier{}\n\tmock.Mock.Test(t)\n\n\tt.Cleanup(func() { mock.AssertExpectations(t) })\n\n\treturn mock\n}", "func newTestContext() (tc *testContext, err error) {\n\ttc = new(testContext)\n\n\tconst genesisHash = \"0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e2206\"\n\tif tc.netParams, err = tc.createNetParams(genesisHash); err != nil {\n\t\treturn\n\t}\n\n\tconst block1Hex = \"0000002006226e46111a0b59caaf126043eb5bbf28c34f3a5e332a1fc7b2b73cf188910fadbb20ea41a8423ea937e76e8151636bf6093b70eaff942930d20576600521fdc30f9858ffff7f20000000000101000000010000000000000000000000000000000000000000000000000000000000000000ffffffff03510101ffffffff0100f2052a010000001976a9143ca33c2e4446f4a305f23c80df8ad1afdcf652f988ac00000000\"\n\tif tc.block1, err = blockFromHex(block1Hex); err != nil {\n\t\terr = fmt.Errorf(\"Failed to parse serialized block: %v\", err)\n\t\treturn\n\t}\n\n\tconst fundingInputPrivKeyHex = \"6bd078650fcee8444e4e09825227b801a1ca928debb750eb36e6d56124bb20e8\"\n\ttc.fundingInputPrivKey, err = privkeyFromHex(fundingInputPrivKeyHex)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Failed to parse serialized privkey: %v\", err)\n\t\treturn\n\t}\n\n\tconst localFundingPrivKeyHex = \"30ff4956bbdd3222d44cc5e8a1261dab1e07957bdac5ae88fe3261ef321f3749\"\n\ttc.localFundingPrivKey, err = privkeyFromHex(localFundingPrivKeyHex)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Failed to parse serialized privkey: %v\", err)\n\t\treturn\n\t}\n\n\tconst localPaymentPrivKeyHex = \"bb13b121cdc357cd2e608b0aea294afca36e2b34cf958e2e6451a2f274694491\"\n\ttc.localPaymentPrivKey, err = privkeyFromHex(localPaymentPrivKeyHex)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Failed to parse serialized privkey: %v\", err)\n\t\treturn\n\t}\n\n\tconst localFundingPubKeyHex = \"023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb\"\n\ttc.localFundingPubKey, err = pubkeyFromHex(localFundingPubKeyHex)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Failed to parse serialized pubkey: %v\", err)\n\t\treturn\n\t}\n\n\tconst remoteFundingPubKeyHex = \"030e9f7b623d2ccc7c9bd44d66d5ce21ce504c0acf6385a132cec6d3c39fa711c1\"\n\ttc.remoteFundingPubKey, err = pubkeyFromHex(remoteFundingPubKeyHex)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Failed to parse serialized pubkey: %v\", err)\n\t\treturn\n\t}\n\n\tconst localRevocationPubKeyHex = \"0212a140cd0c6539d07cd08dfe09984dec3251ea808b892efeac3ede9402bf2b19\"\n\ttc.localRevocationPubKey, err = pubkeyFromHex(localRevocationPubKeyHex)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Failed to parse serialized pubkey: %v\", err)\n\t\treturn\n\t}\n\n\tconst localPaymentPubKeyHex = \"030d417a46946384f88d5f3337267c5e579765875dc4daca813e21734b140639e7\"\n\ttc.localPaymentPubKey, err = pubkeyFromHex(localPaymentPubKeyHex)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Failed to parse serialized pubkey: %v\", err)\n\t\treturn\n\t}\n\n\tconst remotePaymentPubKeyHex = \"0394854aa6eab5b2a8122cc726e9dded053a2184d88256816826d6231c068d4a5b\"\n\ttc.remotePaymentPubKey, err = pubkeyFromHex(remotePaymentPubKeyHex)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Failed to parse serialized pubkey: %v\", err)\n\t\treturn\n\t}\n\n\tconst localDelayPubKeyHex = \"03fd5960528dc152014952efdb702a88f71e3c1653b2314431701ec77e57fde83c\"\n\ttc.localDelayPubKey, err = pubkeyFromHex(localDelayPubKeyHex)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Failed to parse serialized pubkey: %v\", err)\n\t\treturn\n\t}\n\n\tconst commitmentPointHex = \"025f7117a78150fe2ef97db7cfc83bd57b2e2c0d0dd25eaf467a4a1c2a45ce1486\"\n\ttc.commitmentPoint, err = pubkeyFromHex(commitmentPointHex)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Failed to parse serialized pubkey: %v\", err)\n\t\treturn\n\t}\n\n\tconst localPaymentBasePointHex = \"034f355bdcb7cc0af728ef3cceb9615d90684bb5b2ca5f859ab0f0b704075871aa\"\n\ttc.localPaymentBasePoint, err = pubkeyFromHex(localPaymentBasePointHex)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Failed to parse serialized pubkey: %v\", err)\n\t\treturn\n\t}\n\n\tconst remotePaymentBasePointHex = \"032c0b7cf95324a07d05398b240174dc0c2be444d96b159aa6c7f7b1e668680991\"\n\ttc.remotePaymentBasePoint, err = pubkeyFromHex(remotePaymentBasePointHex)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Failed to parse serialized pubkey: %v\", err)\n\t\treturn\n\t}\n\n\tconst fundingChangeAddressStr = \"bcrt1qgyeqfmptyh780dsk32qawsvdffc2g5q5sxamg0\"\n\ttc.fundingChangeAddress, err = btcutil.DecodeAddress(\n\t\tfundingChangeAddressStr, tc.netParams)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Failed to parse address: %v\", err)\n\t\treturn\n\t}\n\n\ttc.fundingInputUtxo, tc.fundingInputTxOut, err = tc.extractFundingInput()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tconst fundingTxHex = \"0200000001adbb20ea41a8423ea937e76e8151636bf6093b70eaff942930d20576600521fd000000006b48304502210090587b6201e166ad6af0227d3036a9454223d49a1f11839c1a362184340ef0240220577f7cd5cca78719405cbf1de7414ac027f0239ef6e214c90fcaab0454d84b3b012103535b32d5eb0a6ed0982a0479bbadc9868d9836f6ba94dd5a63be16d875069184ffffffff028096980000000000220020c015c4a6be010e21657068fc2e6a9d02b27ebe4d490a25846f7237f104d1a3cd20256d29010000001600143ca33c2e4446f4a305f23c80df8ad1afdcf652f900000000\"\n\tif tc.fundingTx, err = txFromHex(fundingTxHex); err != nil {\n\t\terr = fmt.Errorf(\"Failed to parse serialized tx: %v\", err)\n\t\treturn\n\t}\n\n\ttc.fundingOutpoint = wire.OutPoint{\n\t\tHash: *tc.fundingTx.Hash(),\n\t\tIndex: 0,\n\t}\n\n\ttc.shortChanID = lnwire.ShortChannelID{\n\t\tBlockHeight: 1,\n\t\tTxIndex: 0,\n\t\tTxPosition: 0,\n\t}\n\n\thtlcData := []struct {\n\t\tincoming bool\n\t\tamount lnwire.MilliSatoshi\n\t\texpiry uint32\n\t\tpreimage string\n\t}{\n\t\t{\n\t\t\tincoming: true,\n\t\t\tamount: 1000000,\n\t\t\texpiry: 500,\n\t\t\tpreimage: \"0000000000000000000000000000000000000000000000000000000000000000\",\n\t\t},\n\t\t{\n\t\t\tincoming: true,\n\t\t\tamount: 2000000,\n\t\t\texpiry: 501,\n\t\t\tpreimage: \"0101010101010101010101010101010101010101010101010101010101010101\",\n\t\t},\n\t\t{\n\t\t\tincoming: false,\n\t\t\tamount: 2000000,\n\t\t\texpiry: 502,\n\t\t\tpreimage: \"0202020202020202020202020202020202020202020202020202020202020202\",\n\t\t},\n\t\t{\n\t\t\tincoming: false,\n\t\t\tamount: 3000000,\n\t\t\texpiry: 503,\n\t\t\tpreimage: \"0303030303030303030303030303030303030303030303030303030303030303\",\n\t\t},\n\t\t{\n\t\t\tincoming: true,\n\t\t\tamount: 4000000,\n\t\t\texpiry: 504,\n\t\t\tpreimage: \"0404040404040404040404040404040404040404040404040404040404040404\",\n\t\t},\n\t}\n\n\ttc.htlcs = make([]channeldb.HTLC, len(htlcData))\n\tfor i, htlc := range htlcData {\n\t\tpreimage, decodeErr := hex.DecodeString(htlc.preimage)\n\t\tif decodeErr != nil {\n\t\t\terr = fmt.Errorf(\"Failed to decode HTLC preimage: %v\", decodeErr)\n\t\t\treturn\n\t\t}\n\n\t\ttc.htlcs[i].RHash = sha256.Sum256(preimage)\n\t\ttc.htlcs[i].Amt = htlc.amount\n\t\ttc.htlcs[i].RefundTimeout = htlc.expiry\n\t\ttc.htlcs[i].Incoming = htlc.incoming\n\t}\n\n\ttc.localCsvDelay = 144\n\ttc.fundingAmount = 10000000\n\ttc.dustLimit = 546\n\ttc.feePerKW = 15000\n\n\treturn\n}", "func mockPasswordHasher(x string) *crypto.PasswordHasher {\n\treturn &crypto.PasswordHasher{\n\t\tSwapper: passwap.NewSwapper(plainHasher{x: x}),\n\t\tPrefixes: []string{\"$plain$\"},\n\t}\n}", "func (m *MockSessionProvider) Exec(arg0 ...string) ([]byte, []byte, error) {\n\tvarargs := []interface{}{}\n\tfor _, a := range arg0 {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"Exec\", varargs...)\n\tret0, _ := ret[0].([]byte)\n\tret1, _ := ret[1].([]byte)\n\tret2, _ := ret[2].(error)\n\treturn ret0, ret1, ret2\n}", "func TestGetOrder(t *testing.T) {\n\n // ...\n\n}", "func (m *MockAuthorizer) HashKey() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"HashKey\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func TestSIFTLib2(t *testing.T) { TestingT(t) }", "func (m *MockSessionRunner) Add(arg0 protocol.ConnectionID, arg1 packetHandler) [16]byte {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Add\", arg0, arg1)\n\tret0, _ := ret[0].([16]byte)\n\treturn ret0\n}", "func useUtilsSetupSuite(t *testing.T, name string) (string, string, string, func(t *testing.T)) {\n\t_, ca, err := utils.GenerateCA(name, name)\n\tif err != nil {\n\t\tt.Error(err.Error())\n\t}\n\tcertKey, cert, err := utils.GenerateCert(name, name, []string{name}, []string{name})\n\tif err != nil {\n\t\tt.Error(err.Error())\n\t}\n\n\treturn ca, certKey, cert, func(t *testing.T) {\n\t\tdefer os.Remove(ca)\n\t\tdefer os.Remove(certKey)\n\t\tdefer os.Remove(cert)\n\t}\n}", "func TestService_Handle_Invitee(t *testing.T) {\n\tprotocolStateStore := mockstorage.NewMockStoreProvider()\n\tstore := mockstorage.NewMockStoreProvider()\n\tk := newKMS(t, store)\n\tprov := &protocol.MockProvider{\n\t\tStoreProvider: store,\n\t\tProtocolStateStoreProvider: protocolStateStore,\n\t\tServiceMap: map[string]interface{}{\n\t\t\tmediator.Coordination: &mockroute.MockMediatorSvc{},\n\t\t},\n\t\tCustomKMS: k,\n\t\tKeyTypeValue: kms.ED25519Type,\n\t\tKeyAgreementTypeValue: kms.X25519ECDHKWType,\n\t}\n\n\tctx := &context{\n\t\toutboundDispatcher: prov.OutboundDispatcher(),\n\t\tcrypto: &tinkcrypto.Crypto{},\n\t\tkms: k,\n\t\tkeyType: kms.ED25519Type,\n\t\tkeyAgreementType: kms.X25519ECDHKWType,\n\t}\n\n\tverPubKey, encPubKey := newSigningAndEncryptionDIDKeys(t, ctx)\n\n\tctx.vdRegistry = &mockvdr.MockVDRegistry{CreateValue: createDIDDocWithKey(verPubKey, encPubKey)}\n\n\tconnRec, err := connection.NewRecorder(prov)\n\trequire.NoError(t, err)\n\trequire.NotNil(t, connRec)\n\n\tctx.connectionRecorder = connRec\n\n\tdoc, err := ctx.vdRegistry.Create(testMethod, nil)\n\trequire.NoError(t, err)\n\n\ts, err := New(prov)\n\trequire.NoError(t, err)\n\n\ts.ctx.vdRegistry = &mockvdr.MockVDRegistry{ResolveValue: doc.DIDDocument}\n\tactionCh := make(chan service.DIDCommAction, 10)\n\terr = s.RegisterActionEvent(actionCh)\n\trequire.NoError(t, err)\n\n\tstatusCh := make(chan service.StateMsg, 10)\n\terr = s.RegisterMsgEvent(statusCh)\n\trequire.NoError(t, err)\n\n\trequestedCh := make(chan string)\n\tcompletedCh := make(chan struct{})\n\n\tgo handleMessagesInvitee(statusCh, requestedCh, completedCh)\n\n\tgo func() { service.AutoExecuteActionEvent(actionCh) }()\n\n\tinvitation := &Invitation{\n\t\tType: InvitationMsgType,\n\t\tID: randomString(),\n\t\tLabel: \"Bob\",\n\t\tRecipientKeys: []string{verPubKey},\n\t\tServiceEndpoint: \"http://alice.agent.example.com:8081\",\n\t}\n\n\terr = ctx.connectionRecorder.SaveInvitation(invitation.ID, invitation)\n\trequire.NoError(t, err)\n\t// Alice receives an invitation from Bob\n\tpayloadBytes, err := json.Marshal(invitation)\n\trequire.NoError(t, err)\n\n\tdidMsg, err := service.ParseDIDCommMsgMap(payloadBytes)\n\trequire.NoError(t, err)\n\n\t_, err = s.HandleInbound(didMsg, service.EmptyDIDCommContext())\n\trequire.NoError(t, err)\n\n\tvar connID string\n\tselect {\n\tcase connID = <-requestedCh:\n\tcase <-time.After(2 * time.Second):\n\t\trequire.Fail(t, \"didn't receive post event requested\")\n\t}\n\n\t// Alice automatically sends a Request to Bob and is now in REQUESTED state.\n\tconnRecord, err := s.connectionRecorder.GetConnectionRecord(connID)\n\trequire.NoError(t, err)\n\trequire.Equal(t, (&requested{}).Name(), connRecord.State)\n\trequire.Equal(t, invitation.ID, connRecord.InvitationID)\n\trequire.Equal(t, invitation.RecipientKeys, connRecord.RecipientKeys)\n\trequire.Equal(t, invitation.ServiceEndpoint, connRecord.ServiceEndPoint)\n\n\tdidKey, err := ctx.getVerKey(invitation.ID)\n\trequire.NoError(t, err)\n\n\tdocAttach, err := ctx.didDocAttachment(doc.DIDDocument, didKey)\n\trequire.NoError(t, err)\n\n\t// Bob replies with a Response\n\tpayloadBytes, err = json.Marshal(\n\t\t&Response{\n\t\t\tType: ResponseMsgType,\n\t\t\tID: randomString(),\n\t\t\tDID: doc.DIDDocument.ID,\n\t\t\tDocAttach: docAttach,\n\t\t\tThread: &decorator.Thread{\n\t\t\t\tID: connRecord.ThreadID,\n\t\t\t},\n\t\t},\n\t)\n\trequire.NoError(t, err)\n\n\tdidMsg, err = service.ParseDIDCommMsgMap(payloadBytes)\n\trequire.NoError(t, err)\n\n\t_, err = s.HandleInbound(didMsg, service.EmptyDIDCommContext())\n\trequire.NoError(t, err)\n\n\t// Alice automatically sends an ACK to Bob\n\t// Alice must now be in COMPLETED state\n\tselect {\n\tcase <-completedCh:\n\tcase <-time.After(2 * time.Second):\n\t\trequire.Fail(t, \"didn't receive post event complete\")\n\t}\n\n\tvalidateState(t, s, connRecord.ThreadID, findNamespace(ResponseMsgType), (&completed{}).Name())\n}", "func testInMemoryDataStore() IDataStore {\n return NewInMemoryDataStore();\n}", "func TestGetAllOrders(t *testing.T) {\n\n // ...\n\n}", "func (m *MockisKey_KeyInfo) Size() int {\n\tret := m.ctrl.Call(m, \"Size\")\n\tret0, _ := ret[0].(int)\n\treturn ret0\n}", "func TestAesEnDecrytion(t *testing.T) {\n\t//需要16的倍数\n\tpriKey := randStr(32)\n\toriStr := randStr(32)\n\tfmt.Println(\"original: \", oriStr)\n\tencrypted, err := AesEncrypt([]byte(oriStr), []byte(priKey))\n\tif err != nil {\n\t\tt.Errorf(\"encrypt err: %s\\n\", err.Error())\n\t}\n\tfmt.Println(\"encryptd: \", encrypted)\n\n\toriginal, err := AesDecrypt(encrypted, []byte(priKey))\n\tif err != nil {\n\t\tt.Errorf(\"decrypt err: %s\\n\", err.Error())\n\t}\n\tfmt.Println(\"decryptd: \", original)\n\tif original != oriStr {\n\t\tt.Errorf(\"Decryption Error, old: %s, new: %s\", oriStr, original)\n\t}\n}", "func (m *MockisIpsecCbKeyHandle_KeyOrHandle) Size() int {\n\tret := m.ctrl.Call(m, \"Size\")\n\tret0, _ := ret[0].(int)\n\treturn ret0\n}", "func TestEmptyCommit4A(t *testing.T) {\n}", "func TestCiphering(t *testing.T) {\n\tpb, _ := hex.DecodeString(\"fe38240982f313ae5afb3e904fb8215fb11af1200592b\" +\n\t\t\"fca26c96c4738e4bf8f\")\n\tprivkey, _ := PrivKeyFromBytes(S256(), pb)\n\n\tin := []byte(\"This is just a test.\")\n\tout, _ := hex.DecodeString(\"b0d66e5adaa5ed4e2f0ca68e17b8f2fc02ca002009e3\" +\n\t\t\"3487e7fa4ab505cf34d98f131be7bd258391588ca7804acb30251e71a04e0020ecf\" +\n\t\t\"df0f84608f8add82d7353af780fbb28868c713b7813eb4d4e61f7b75d7534dd9856\" +\n\t\t\"9b0ba77cf14348fcff80fee10e11981f1b4be372d93923e9178972f69937ec850ed\" +\n\t\t\"6c3f11ff572ddd5b2bedf9f9c0b327c54da02a28fcdce1f8369ffec\")\n\n\tdec, err := Decrypt(privkey, out)\n\tif err != nil {\n\t\tt.Fatal(\"failed to decrypt:\", err)\n\t}\n\n\tif !bytes.Equal(in, dec) {\n\t\tt.Error(\"decrypted data doesn't match original\")\n\t}\n}", "func TestKyberTradingTestSuite(t *testing.T) {\n\tfmt.Println(\"Starting entry point for Kyber test suite...\")\n\n\ttradingSuite := new(TradingTestSuite)\n\tsuite.Run(t, tradingSuite)\n\n\tkyberTradingSuite := NewKyberTradingTestSuite(tradingSuite)\n\tsuite.Run(t, kyberTradingSuite)\n\n\tfmt.Println(\"Finishing entry point for 0x test suite...\")\n}", "func (m *MockisTlsCbKeyHandle_KeyOrHandle) Size() int {\n\tret := m.ctrl.Call(m, \"Size\")\n\tret0, _ := ret[0].(int)\n\treturn ret0\n}" ]
[ "0.6349443", "0.6250889", "0.61201334", "0.61085963", "0.61015576", "0.5863399", "0.5833078", "0.5814647", "0.5803716", "0.57591796", "0.57540137", "0.57426", "0.57124424", "0.56994677", "0.56921124", "0.56864023", "0.56789786", "0.5662635", "0.5635828", "0.5629587", "0.5623318", "0.5584721", "0.5577739", "0.5574427", "0.55540407", "0.55523044", "0.55254585", "0.5515649", "0.55040234", "0.5493469", "0.5479536", "0.54750586", "0.5463222", "0.5454088", "0.5421137", "0.5418974", "0.5416784", "0.5407748", "0.5406221", "0.5395352", "0.53897595", "0.5369998", "0.53658", "0.5357557", "0.5345857", "0.5343158", "0.53374296", "0.533544", "0.5332733", "0.53317606", "0.53283614", "0.532031", "0.5311461", "0.5305934", "0.5283849", "0.5282254", "0.5281123", "0.5280674", "0.5262361", "0.5255106", "0.5240867", "0.52387685", "0.5234365", "0.5234103", "0.5228845", "0.5228581", "0.52209884", "0.5220208", "0.52201873", "0.5210762", "0.52090526", "0.52047503", "0.5202487", "0.5199722", "0.5197068", "0.5187813", "0.51866055", "0.51864123", "0.5176831", "0.5172813", "0.5166115", "0.51649743", "0.516155", "0.5159019", "0.51552755", "0.51531726", "0.5146844", "0.5146327", "0.51453596", "0.51434356", "0.51394904", "0.5138214", "0.5135526", "0.5134479", "0.5132012", "0.51314443", "0.51242816", "0.51215434", "0.51164895", "0.5115589" ]
0.609855
5
CryptoSuite indicates an expected call of CryptoSuite
func (mr *MockClientMockRecorder) CryptoSuite() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CryptoSuite", reflect.TypeOf((*MockClient)(nil).CryptoSuite)) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (mr *MockProvidersMockRecorder) CryptoSuite() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"CryptoSuite\", reflect.TypeOf((*MockProviders)(nil).CryptoSuite))\n}", "func (pc *MockProviderContext) CryptoSuite() apicryptosuite.CryptoSuite {\n\treturn pc.cryptoSuite\n}", "func TestCorePkg_CreateCryptoSuiteProvider(t *testing.T) {\n\tpkg := newCorePkg()\n\trequire.NotNil(t, pkg)\n\n\tp, err := pkg.CreateCryptoSuiteProvider(nil)\n\trequire.NoError(t, err)\n\trequire.NotNil(t, p)\n}", "func (c *Provider) CryptoSuite() core.CryptoSuite {\n\treturn c.cryptoSuite\n}", "func Test_Crypto(t *testing.T) {\n\trequire := require.New(t)\n\n\tc := &sm2.Driver{}\n\n\tpriv, err := c.GenKey()\n\trequire.Nil(err)\n\tt.Logf(\"priv:%X, len:%d\", priv.Bytes(), len(priv.Bytes()))\n\n\tpub := priv.PubKey()\n\trequire.NotNil(pub)\n\tt.Logf(\"pub:%X, len:%d\", pub.Bytes(), len(pub.Bytes()))\n\n\tmsg := []byte(\"hello world\")\n\tsignature := priv.Sign(msg)\n\tt.Logf(\"sign:%X, len:%d\", signature.Bytes(), len(signature.Bytes()))\n\n\tok := pub.VerifyBytes(msg, signature)\n\trequire.Equal(true, ok)\n}", "func CipherSuiteName(suite uint16) string {\n\tswitch suite {\n\tcase tls.TLS_RSA_WITH_RC4_128_SHA:\n\t\treturn \"TLS_RSA_WITH_RC4_128_SHA\"\n\tcase tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA:\n\t\treturn \"TLS_RSA_WITH_3DES_EDE_CBC_SHA\"\n\tcase tls.TLS_RSA_WITH_AES_128_CBC_SHA:\n\t\treturn \"TLS_RSA_WITH_AES_128_CBC_SHA\"\n\tcase tls.TLS_RSA_WITH_AES_256_CBC_SHA:\n\t\treturn \"TLS_RSA_WITH_AES_256_CBC_SHA\"\n\tcase tls.TLS_RSA_WITH_AES_128_CBC_SHA256:\n\t\treturn \"TLS_RSA_WITH_AES_128_CBC_SHA256\"\n\tcase tls.TLS_RSA_WITH_AES_128_GCM_SHA256:\n\t\treturn \"TLS_RSA_WITH_AES_128_GCM_SHA256\"\n\tcase tls.TLS_RSA_WITH_AES_256_GCM_SHA384:\n\t\treturn \"TLS_RSA_WITH_AES_256_GCM_SHA384\"\n\tcase tls.TLS_ECDHE_ECDSA_WITH_RC4_128_SHA:\n\t\treturn \"TLS_ECDHE_ECDSA_WITH_RC4_128_SHA\"\n\tcase tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA:\n\t\treturn \"TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA\"\n\tcase tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA:\n\t\treturn \"TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA\"\n\tcase tls.TLS_ECDHE_RSA_WITH_RC4_128_SHA:\n\t\treturn \"TLS_ECDHE_RSA_WITH_RC4_128_SHA\"\n\tcase tls.TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA:\n\t\treturn \"TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA\"\n\tcase tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA:\n\t\treturn \"TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA\"\n\tcase tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA:\n\t\treturn \"TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA\"\n\tcase tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256:\n\t\treturn \"TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256\"\n\tcase tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256:\n\t\treturn \"TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256\"\n\tcase tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:\n\t\treturn \"TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256\"\n\tcase tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:\n\t\treturn \"TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256\"\n\tcase tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384:\n\t\treturn \"TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384\"\n\tcase tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384:\n\t\treturn \"TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384\"\n\tcase tls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256:\n\t\treturn \"TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256\"\n\tcase tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256:\n\t\treturn \"TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256\"\n\tcase tls.TLS_AES_128_GCM_SHA256:\n\t\treturn \"TLS_AES_128_GCM_SHA256\"\n\tcase tls.TLS_AES_256_GCM_SHA384:\n\t\treturn \"TLS_AES_256_GCM_SHA384\"\n\tcase tls.TLS_CHACHA20_POLY1305_SHA256:\n\t\treturn \"TLS_CHACHA20_POLY1305_SHA256\"\n\tcase tls.TLS_FALLBACK_SCSV:\n\t\treturn \"TLS_FALLBACK_SCSV\"\n\t}\n\n\treturn \"Unknown\"\n}", "func (tradingSuite *KyberTradingTestSuite) SetupSuite() {\n\tfmt.Println(\"Setting up the suite...\")\n\t// Kovan env\n\ttradingSuite.EtherAddressStrKyber = \"0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee\"\n\n\ttradingSuite.IncKBNTokenIDStr = \"0000000000000000000000000000000000000000000000000000000000000082\"\n\ttradingSuite.IncSALTTokenIDStr = \"0000000000000000000000000000000000000000000000000000000000000081\"\n\ttradingSuite.IncOMGTokenIDStr = \"0000000000000000000000000000000000000000000000000000000000000072\"\n\ttradingSuite.IncSNTTokenIDStr = \"0000000000000000000000000000000000000000000000000000000000000071\"\n\ttradingSuite.KBNAddressStr = \"0xad67cB4d63C9da94AcA37fDF2761AaDF780ff4a2\" // kovan\n\ttradingSuite.SALTAddressStr = \"0x6fEE5727EE4CdCBD91f3A873ef2966dF31713A04\" // kovan\n\ttradingSuite.OMGAddressStr = \"0xdB7ec4E4784118D9733710e46F7C83fE7889596a\" // kovan\n\ttradingSuite.SNTAddressStr = \"0x4c99B04682fbF9020Fcb31677F8D8d66832d3322\" // kovan\n\ttradingSuite.KyberTradeDeployedAddr = common.HexToAddress(\"0x38A3cE5d944ff3de96401ddBFA9971D656222F89\") //kovan\n\ttradingSuite.KyberMultiTradeDeployedAddr = common.HexToAddress(\"0x8E7050E23A42052C75cdCE2d919f5e4F89afaD0a\") //kovan\n\ttradingSuite.DepositingEther = float64(0.05)\n\ttradingSuite.KyberContractAddr = common.HexToAddress(\"0x692f391bCc85cefCe8C237C01e1f636BbD70EA4D\") // kovan\n}", "func TestEncrypt() {\n\n}", "func TestPionE2ELossy(t *testing.T) {\n\t// Check for leaking routines\n\treport := transportTest.CheckRoutines(t)\n\tdefer report()\n\n\ttype runResult struct {\n\t\tdtlsConn *dtls.Conn\n\t\terr error\n\t}\n\n\tserverCert, err := selfsign.GenerateSelfSigned()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tclientCert, err := selfsign.GenerateSelfSigned()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tfor _, test := range []struct {\n\t\tLossChanceRange int\n\t\tDoClientAuth bool\n\t\tCipherSuites []dtls.CipherSuiteID\n\t\tMTU int\n\t}{\n\t\t{\n\t\t\tLossChanceRange: 0,\n\t\t},\n\t\t{\n\t\t\tLossChanceRange: 10,\n\t\t},\n\t\t{\n\t\t\tLossChanceRange: 20,\n\t\t},\n\t\t{\n\t\t\tLossChanceRange: 50,\n\t\t},\n\t\t{\n\t\t\tLossChanceRange: 0,\n\t\t\tDoClientAuth: true,\n\t\t},\n\t\t{\n\t\t\tLossChanceRange: 10,\n\t\t\tDoClientAuth: true,\n\t\t},\n\t\t{\n\t\t\tLossChanceRange: 20,\n\t\t\tDoClientAuth: true,\n\t\t},\n\t\t{\n\t\t\tLossChanceRange: 50,\n\t\t\tDoClientAuth: true,\n\t\t},\n\t\t{\n\t\t\tLossChanceRange: 0,\n\t\t\tCipherSuites: []dtls.CipherSuiteID{dtls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA},\n\t\t},\n\t\t{\n\t\t\tLossChanceRange: 10,\n\t\t\tCipherSuites: []dtls.CipherSuiteID{dtls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA},\n\t\t},\n\t\t{\n\t\t\tLossChanceRange: 20,\n\t\t\tCipherSuites: []dtls.CipherSuiteID{dtls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA},\n\t\t},\n\t\t{\n\t\t\tLossChanceRange: 50,\n\t\t\tCipherSuites: []dtls.CipherSuiteID{dtls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA},\n\t\t},\n\t\t{\n\t\t\tLossChanceRange: 10,\n\t\t\tMTU: 100,\n\t\t\tDoClientAuth: true,\n\t\t},\n\t\t{\n\t\t\tLossChanceRange: 20,\n\t\t\tMTU: 100,\n\t\t\tDoClientAuth: true,\n\t\t},\n\t\t{\n\t\t\tLossChanceRange: 50,\n\t\t\tMTU: 100,\n\t\t\tDoClientAuth: true,\n\t\t},\n\t} {\n\t\tname := fmt.Sprintf(\"Loss%d_MTU%d\", test.LossChanceRange, test.MTU)\n\t\tif test.DoClientAuth {\n\t\t\tname += \"_WithCliAuth\"\n\t\t}\n\t\tfor _, ciph := range test.CipherSuites {\n\t\t\tname += \"_With\" + ciph.String()\n\t\t}\n\t\ttest := test\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\t// Limit runtime in case of deadlocks\n\t\t\tlim := transportTest.TimeOut(lossyTestTimeout + time.Second)\n\t\t\tdefer lim.Stop()\n\n\t\t\trand.Seed(time.Now().UTC().UnixNano())\n\t\t\tchosenLoss := rand.Intn(9) + test.LossChanceRange //nolint:gosec\n\t\t\tserverDone := make(chan runResult)\n\t\t\tclientDone := make(chan runResult)\n\t\t\tbr := transportTest.NewBridge()\n\n\t\t\tif err = br.SetLossChance(chosenLoss); err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\n\t\t\tgo func() {\n\t\t\t\tcfg := &dtls.Config{\n\t\t\t\t\tFlightInterval: flightInterval,\n\t\t\t\t\tCipherSuites: test.CipherSuites,\n\t\t\t\t\tInsecureSkipVerify: true,\n\t\t\t\t\tMTU: test.MTU,\n\t\t\t\t}\n\n\t\t\t\tif test.DoClientAuth {\n\t\t\t\t\tcfg.Certificates = []tls.Certificate{clientCert}\n\t\t\t\t}\n\n\t\t\t\tclient, startupErr := dtls.Client(dtlsnet.PacketConnFromConn(br.GetConn0()), br.GetConn0().RemoteAddr(), cfg)\n\t\t\t\tclientDone <- runResult{client, startupErr}\n\t\t\t}()\n\n\t\t\tgo func() {\n\t\t\t\tcfg := &dtls.Config{\n\t\t\t\t\tCertificates: []tls.Certificate{serverCert},\n\t\t\t\t\tFlightInterval: flightInterval,\n\t\t\t\t\tMTU: test.MTU,\n\t\t\t\t}\n\n\t\t\t\tif test.DoClientAuth {\n\t\t\t\t\tcfg.ClientAuth = dtls.RequireAnyClientCert\n\t\t\t\t}\n\n\t\t\t\tserver, startupErr := dtls.Server(dtlsnet.PacketConnFromConn(br.GetConn1()), br.GetConn1().RemoteAddr(), cfg)\n\t\t\t\tserverDone <- runResult{server, startupErr}\n\t\t\t}()\n\n\t\t\ttestTimer := time.NewTimer(lossyTestTimeout)\n\t\t\tvar serverConn, clientConn *dtls.Conn\n\t\t\tdefer func() {\n\t\t\t\tif serverConn != nil {\n\t\t\t\t\tif err = serverConn.Close(); err != nil {\n\t\t\t\t\t\tt.Error(err)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif clientConn != nil {\n\t\t\t\t\tif err = clientConn.Close(); err != nil {\n\t\t\t\t\t\tt.Error(err)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}()\n\n\t\t\tfor {\n\t\t\t\tif serverConn != nil && clientConn != nil {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\tbr.Tick()\n\t\t\t\tselect {\n\t\t\t\tcase serverResult := <-serverDone:\n\t\t\t\t\tif serverResult.err != nil {\n\t\t\t\t\t\tt.Errorf(\"Fail, serverError: clientComplete(%t) serverComplete(%t) LossChance(%d) error(%v)\", clientConn != nil, serverConn != nil, chosenLoss, serverResult.err)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\n\t\t\t\t\tserverConn = serverResult.dtlsConn\n\t\t\t\tcase clientResult := <-clientDone:\n\t\t\t\t\tif clientResult.err != nil {\n\t\t\t\t\t\tt.Errorf(\"Fail, clientError: clientComplete(%t) serverComplete(%t) LossChance(%d) error(%v)\", clientConn != nil, serverConn != nil, chosenLoss, clientResult.err)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\n\t\t\t\t\tclientConn = clientResult.dtlsConn\n\t\t\t\tcase <-testTimer.C:\n\t\t\t\t\tt.Errorf(\"Test expired: clientComplete(%t) serverComplete(%t) LossChance(%d)\", clientConn != nil, serverConn != nil, chosenLoss)\n\t\t\t\t\treturn\n\t\t\t\tcase <-time.After(10 * time.Millisecond):\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n}", "func cipherSuiteName(id uint16) string {\n\tswitch id {\n\tcase 0x0005:\n\t\treturn \"TLS_RSA_WITH_RC4_128_SHA\"\n\tcase 0x000a:\n\t\treturn \"TLS_RSA_WITH_3DES_EDE_CBC_SHA\"\n\tcase 0x002f:\n\t\treturn \"TLS_RSA_WITH_AES_128_CBC_SHA\"\n\tcase 0x0035:\n\t\treturn \"TLS_RSA_WITH_AES_256_CBC_SHA\"\n\tcase 0x003c:\n\t\treturn \"TLS_RSA_WITH_AES_128_CBC_SHA256\"\n\tcase 0x009c:\n\t\treturn \"TLS_RSA_WITH_AES_128_GCM_SHA256\"\n\tcase 0x009d:\n\t\treturn \"TLS_RSA_WITH_AES_256_GCM_SHA384\"\n\tcase 0xc007:\n\t\treturn \"TLS_ECDHE_ECDSA_WITH_RC4_128_SHA\"\n\tcase 0xc009:\n\t\treturn \"TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA\"\n\tcase 0xc00a:\n\t\treturn \"TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA\"\n\tcase 0xc011:\n\t\treturn \"TLS_ECDHE_RSA_WITH_RC4_128_SHA\"\n\tcase 0xc012:\n\t\treturn \"TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA\"\n\tcase 0xc013:\n\t\treturn \"TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA\"\n\tcase 0xc014:\n\t\treturn \"TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA\"\n\tcase 0xc023:\n\t\treturn \"TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256\"\n\tcase 0xc027:\n\t\treturn \"TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256\"\n\tcase 0xc02f:\n\t\treturn \"TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256\"\n\tcase 0xc02b:\n\t\treturn \"TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256\"\n\tcase 0xc030:\n\t\treturn \"TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384\"\n\tcase 0xc02c:\n\t\treturn \"TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384\"\n\tcase 0xcca8:\n\t\treturn \"TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256\"\n\tcase 0xcca9:\n\t\treturn \"TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256\"\n\tcase 0x1301:\n\t\treturn \"TLS_AES_128_GCM_SHA256\"\n\tcase 0x1302:\n\t\treturn \"TLS_AES_256_GCM_SHA384\"\n\tcase 0x1303:\n\t\treturn \"TLS_CHACHA20_POLY1305_SHA256\"\n\tcase 0x5600:\n\t\treturn \"TLS_FALLBACK_SCSV\"\n\t}\n\treturn fmt.Sprintf(\"0x%04X\", id)\n}", "func ProviderTestKOSeal() (configstore.ItemList, error) {\n\tret := configstore.ItemList{\n\t\tItems: []configstore.Item{\n\t\t\tconfigstore.NewItem(\n\t\t\t\tkeyloader.EncryptionKeyConfigName,\n\t\t\t\t`{\"key\":\"5fdb8af280b007a46553dfddb3f42bc10619dcabca8d4fdf5239b09445ab1a41\",\"identifier\":\"test\",\"sealed\":false,\"timestamp\":10,\"cipher\":\"aes-gcm\"}`,\n\t\t\t\t1,\n\t\t\t),\n\t\t\tconfigstore.NewItem(\n\t\t\t\tkeyloader.EncryptionKeyConfigName,\n\t\t\t\t`{\"key\":\"QXdDW4N/jmJzpMu7i1zu4YF1opTn7H+eOk9CLFGBSFg=\",\"identifier\":\"test\",\"sealed\":true,\"timestamp\":1,\"cipher\":\"xchacha20-poly1305\"}`,\n\t\t\t\t1,\n\t\t\t),\n\t\t},\n\t}\n\treturn ret, nil\n}", "func TestPagarmeEncryptCard(t *testing.T) {\n\t\n\tCard := new(pagarme.Card)\n\tPagarme := pagarme.NewPagarme(\"pt-BR\", ApiKey, CryptoKey)\n Pagarme.SetDebug()\n\n\tpagarmeFillCard(Card)\n\n\tresult, err := Pagarme.EncryptCard(Card)\n\n if err != nil {\n \tt.Errorf(\"Erro ao encrypt card: %v\", err)\n return\n }\n\n if len(result.Hash) == 0 {\n t.Errorf(\"card hash is expected\")\n return\n }\n}", "func TestSignContractFailure(t *testing.T) {\n\tsignatureHelper(t, true)\n}", "func TestInitAessiv(t *testing.T) {\n\tdir := test_helpers.InitFS(t, \"-aessiv\")\n\t_, c, err := configfile.LoadAndDecrypt(dir+\"/\"+configfile.ConfDefaultName, testPw)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif !c.IsFeatureFlagSet(configfile.FlagAESSIV) {\n\t\tt.Error(\"AESSIV flag should be set but is not\")\n\t}\n}", "func (s *SignSuite) TearDownSuite(c *C) {\n}", "func CipherSuiteString(value uint16) string {\n\tif str, found := tlsCipherSuiteString[value]; found {\n\t\treturn str\n\t}\n\treturn fmt.Sprintf(\"TLS_CIPHER_SUITE_UNKNOWN_%d\", value)\n}", "func CipherSuiteName(id uint16) string", "func TestCompliancetestDemo(t *testing.T) {\n\t// Register new Vendor account\n\tvendor := utils.CreateNewAccount(auth.AccountRoles{auth.Vendor}, testconstants.VID)\n\n\t// Register new TestHouse account\n\ttestHouse := utils.CreateNewAccount(auth.AccountRoles{auth.TestHouse}, 0)\n\n\t// Register new TestHouse account\n\tsecondTestHouse := utils.CreateNewAccount(auth.AccountRoles{auth.TestHouse}, 0)\n\n\t// Publish model info\n\tmodel := utils.NewMsgAddModel(vendor.Address, testconstants.VID)\n\t_, _ = utils.AddModel(model, vendor)\n\t// Publish modelVersion\n\tmodelVersion := utils.NewMsgAddModelVersion(model.VID, model.PID,\n\t\ttestconstants.SoftwareVersion, testconstants.SoftwareVersionString, vendor.Address)\n\t_, _ = utils.AddModelVersion(modelVersion, vendor)\n\n\t// Publish first testing result using Sign and Broadcast AddTestingResult message\n\tfirstTestingResult := utils.NewMsgAddTestingResult(model.VID, model.PID,\n\t\tmodelVersion.SoftwareVersion, modelVersion.SoftwareVersionString, testHouse.Address)\n\tutils.SignAndBroadcastMessage(testHouse, firstTestingResult)\n\n\t// Check testing result is created\n\treceivedTestingResult, _ := utils.GetTestingResult(firstTestingResult.VID,\n\t\tfirstTestingResult.PID, firstTestingResult.SoftwareVersion)\n\trequire.Equal(t, receivedTestingResult.VID, firstTestingResult.VID)\n\trequire.Equal(t, receivedTestingResult.PID, firstTestingResult.PID)\n\trequire.Equal(t, receivedTestingResult.SoftwareVersion, firstTestingResult.SoftwareVersion)\n\trequire.Equal(t, 1, len(receivedTestingResult.Results))\n\trequire.Equal(t, receivedTestingResult.Results[0].TestResult, firstTestingResult.TestResult)\n\trequire.Equal(t, receivedTestingResult.Results[0].TestDate, firstTestingResult.TestDate)\n\trequire.Equal(t, receivedTestingResult.Results[0].Owner, firstTestingResult.Signer)\n\n\t// Publish second model info\n\tsecondModel := utils.NewMsgAddModel(vendor.Address, testconstants.VID)\n\t_, _ = utils.AddModel(secondModel, vendor)\n\t// Publish second modelVersion\n\tsecondModelVersion := utils.NewMsgAddModelVersion(secondModel.VID, secondModel.PID,\n\t\ttestconstants.SoftwareVersion, testconstants.SoftwareVersionString, vendor.Address)\n\t_, _ = utils.AddModelVersion(secondModelVersion, vendor)\n\n\t// Publish second testing result using POST\n\tsecondTestingResult := utils.NewMsgAddTestingResult(secondModel.VID, secondModel.PID,\n\t\tsecondModelVersion.SoftwareVersion, secondModelVersion.SoftwareVersionString, testHouse.Address)\n\t_, _ = utils.PublishTestingResult(secondTestingResult, testHouse)\n\n\t// Check testing result is created\n\treceivedTestingResult, _ = utils.GetTestingResult(secondTestingResult.VID,\n\t\tsecondTestingResult.PID, secondTestingResult.SoftwareVersion)\n\trequire.Equal(t, receivedTestingResult.VID, secondTestingResult.VID)\n\trequire.Equal(t, receivedTestingResult.PID, secondTestingResult.PID)\n\trequire.Equal(t, receivedTestingResult.SoftwareVersion, secondTestingResult.SoftwareVersion)\n\trequire.Equal(t, 1, len(receivedTestingResult.Results))\n\trequire.Equal(t, receivedTestingResult.Results[0].TestResult, secondTestingResult.TestResult)\n\trequire.Equal(t, receivedTestingResult.Results[0].TestDate, secondTestingResult.TestDate)\n\trequire.Equal(t, receivedTestingResult.Results[0].Owner, secondTestingResult.Signer)\n\n\t// Publish new testing result for second model\n\tthirdTestingResult := utils.NewMsgAddTestingResult(secondModel.VID, secondModel.PID,\n\t\tsecondModelVersion.SoftwareVersion, secondModelVersion.SoftwareVersionString, secondTestHouse.Address)\n\t_, _ = utils.PublishTestingResult(thirdTestingResult, secondTestHouse)\n\n\t// Check testing result is created\n\treceivedTestingResult, _ = utils.GetTestingResult(secondTestingResult.VID,\n\t\tsecondTestingResult.PID, secondTestingResult.SoftwareVersion)\n\trequire.Equal(t, 2, len(receivedTestingResult.Results))\n\trequire.Equal(t, receivedTestingResult.Results[0].Owner, secondTestingResult.Signer)\n\trequire.Equal(t, receivedTestingResult.Results[0].TestResult, secondTestingResult.TestResult)\n\trequire.Equal(t, receivedTestingResult.Results[1].Owner, thirdTestingResult.Signer)\n\trequire.Equal(t, receivedTestingResult.Results[1].TestResult, thirdTestingResult.TestResult)\n}", "func TestChallenge11Cbc(test *testing.T) {\n\tmode, err := unsafeaes.DetectMode(cbcOracle{})\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tif mode != \"CBC\" {\n\t\ttest.Errorf(\"expected AES mode CBC to be detected but instead detected %s\", mode)\n\t}\n}", "func cipherSuiteScan(addr, hostname string) (grade Grade, output Output, err error) {\n\tvar cvList cipherVersionList\n\tallCiphers := allCiphersIDs()\n\n\tvar vers uint16\n\tfor vers = tls.VersionTLS12; vers >= tls.VersionSSL30; vers-- {\n\t\tciphers := make([]uint16, len(allCiphers))\n\t\tcopy(ciphers, allCiphers)\n\t\tfor len(ciphers) > 0 {\n\t\t\tvar cipherIndex int\n\t\t\tcipherIndex, _, _, err = sayHello(addr, hostname, ciphers, nil, vers, nil)\n\t\t\tif err != nil {\n\t\t\t\tif err == errHelloFailed {\n\t\t\t\t\terr = nil\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif vers == tls.VersionSSL30 {\n\t\t\t\tgrade = Warning\n\t\t\t}\n\t\t\tcipherID := ciphers[cipherIndex]\n\n\t\t\t// If this is an EC cipher suite, do a second scan for curve support\n\t\t\tvar supportedCurves []tls.CurveID\n\t\t\tif tls.CipherSuites[cipherID].EllipticCurve {\n\t\t\t\tsupportedCurves, err = doCurveScan(addr, hostname, vers, cipherID, ciphers)\n\t\t\t\tif len(supportedCurves) == 0 {\n\t\t\t\t\terr = errors.New(\"couldn't negotiate any curves\")\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor i, c := range cvList {\n\t\t\t\tif cipherID == c.cipherID {\n\t\t\t\t\tcvList[i].data = append(c.data, cipherDatum{vers, supportedCurves})\n\t\t\t\t\tgoto exists\n\t\t\t\t}\n\t\t\t}\n\t\t\tcvList = append(cvList, cipherVersions{cipherID, []cipherDatum{{vers, supportedCurves}}})\n\t\texists:\n\t\t\tciphers = append(ciphers[:cipherIndex], ciphers[cipherIndex+1:]...)\n\t\t}\n\t}\n\n\tif len(cvList) == 0 {\n\t\terr = errors.New(\"couldn't negotiate any cipher suites\")\n\t\treturn\n\t}\n\n\tif grade != Warning {\n\t\tgrade = Good\n\t}\n\n\toutput = cvList\n\treturn\n}", "func TestVigenereCipher(t *testing.T) {\n\tvar vigenere Vigenere\n\n\tcases := []struct {\n\t\tcaseString string\n\t\tcaseKey string\n\t\texpected string\n\t\t// Tells if a case is of success or fail\n\t\tsuccess bool\n\t}{\n\t\t{\n\t\t\tcaseString: \"Deus e bom, o tempo todo\",\n\t\t\tcaseKey: \"UnB\",\n\t\t\texpected: \"Xrvm r ciz, p nrnjb uiqp\",\n\t\t\tsuccess: true,\n\t\t},\n\n\t\t{\n\t\t\tcaseString: \"Fim de semestre eh assim\",\n\t\t\tcaseKey: \"hard\",\n\t\t\texpected: \"Mid gl svplskul ey dzszp\",\n\t\t\tsuccess: true,\n\t\t},\n\n\t\t{\n\t\t\tcaseString: \"this year was a tragic year\",\n\t\t\tcaseKey: \"corona\",\n\t\t\texpected: \"vvzg lecf nof a vfruvc asrf\",\n\t\t\tsuccess: true,\n\t\t},\n\n\t\t{\n\t\t\tcaseString: \"die Kunst des Rechnens\",\n\t\t\tcaseKey: \"GOLANG\",\n\t\t\texpected: \"jwp Khtyh oef Xkqsnrty\",\n\t\t\tsuccess: true,\n\t\t},\n\n\t\t{\n\t\t\tcaseString: \"a chave de codificacao eh restrita\",\n\t\t\tcaseKey: \"%\",\n\t\t\texpected: \"? a,?:) () a3(-*-a?a?3 ), 6)786-8?\",\n\t\t\tsuccess: false,\n\t\t},\n\n\t\t{\n\t\t\tcaseString: \"somente caracteres alfabeticos da ascii podem ser utilizados\",\n\t\t\tcaseKey: \"123\",\n\t\t\texpected: \"c@?5?f5 43b25d6d5d 3<7326f94ac 53 1d59: b?57= d7b ff9=;j26?d\",\n\t\t\tsuccess: false,\n\t\t},\n\n\t\t{\n\t\t\tcaseString: \"Porem, tanto faz Usar MaIUsCUlo ou MINUSculo\",\n\t\t\tcaseKey: \"GOisNice\",\n\t\t\texpected: \"Vczwz, bcrzc nsm Cuex AiAHaEYrc wm ZQPYYqcdb\",\n\t\t\tsuccess: true,\n\t\t},\n\t}\n\tfor _, c := range cases {\n\t\tif c.success {\n\t\t\t// Success cases\n\t\t\tt.Logf(\"Vigenere testing: %s <key: %s> -> %s\", c.caseString, c.caseKey, c.expected)\n\t\t\tresult, err := vigenere.Cipher(c.caseString, c.caseKey)\n\n\t\t\tif err != nil {\n\t\t\t\tt.Errorf(\"Vigenere FAILED: %s <key: %s> -> expected: %s; got ERROR: %s\", c.caseString, c.caseKey, c.expected, err)\n\t\t\t}\n\n\t\t\tif result != c.expected {\n\t\t\t\tt.Errorf(\"Vigenere FAILED: %s <key: %s> -> expected: %s; got: %s\", c.caseString, c.caseKey, c.expected, result)\n\t\t\t}\n\t\t} else {\n\t\t\t// Fail cases\n\t\t\tt.Logf(\"Vigenere testing: %s <key: %s> -> expected err\", c.caseString, c.caseKey)\n\t\t\tresult, err := vigenere.Cipher(c.caseString, c.caseKey)\n\n\t\t\tif err == nil {\n\t\t\t\tt.Errorf(\"Vigenere FAILED: %s <key: %s> -> expected error, but got: %s\", c.caseString, c.caseKey, result)\n\t\t\t}\n\t\t}\n\t}\n}", "func TestCipheringBasic(t *testing.T) {\n\tprivkey, err := NewPrivateKey(S256())\n\tif err != nil {\n\t\tt.Fatal(\"failed to generate private key\")\n\t}\n\n\tin := []byte(\"Hey there dude. How are you doing? This is a test.\")\n\n\tout, err := Encrypt(privkey.PubKey(), in)\n\tif err != nil {\n\t\tt.Fatal(\"failed to encrypt:\", err)\n\t}\n\n\tdec, err := Decrypt(privkey, out)\n\tif err != nil {\n\t\tt.Fatal(\"failed to decrypt:\", err)\n\t}\n\n\tif !bytes.Equal(in, dec) {\n\t\tt.Error(\"decrypted data doesn't match original\")\n\t}\n}", "func (mr *MockisCryptoApiRequest_CryptoApiReqMockRecorder) isCryptoApiRequest_CryptoApiReq() *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"isCryptoApiRequest_CryptoApiReq\", reflect.TypeOf((*MockisCryptoApiRequest_CryptoApiReq)(nil).isCryptoApiRequest_CryptoApiReq))\n}", "func InsecureCipherSuites() []*tls.CipherSuite", "func TestPionE2ELossy(t *testing.T) {\n\tserverCert, serverKey, err := dtls.GenerateSelfSigned()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tclientCert, clientKey, err := dtls.GenerateSelfSigned()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tfor _, test := range []struct {\n\t\tLossChanceRange int\n\t\tDoClientAuth bool\n\t\tCipherSuites []dtls.CipherSuiteID\n\t}{\n\t\t{\n\t\t\tLossChanceRange: 0,\n\t\t},\n\t\t{\n\t\t\tLossChanceRange: 10,\n\t\t},\n\t\t{\n\t\t\tLossChanceRange: 20,\n\t\t},\n\t\t{\n\t\t\tLossChanceRange: 50,\n\t\t},\n\t\t{\n\t\t\tLossChanceRange: 0,\n\t\t\tDoClientAuth: true,\n\t\t},\n\t\t{\n\t\t\tLossChanceRange: 10,\n\t\t\tDoClientAuth: true,\n\t\t},\n\t\t{\n\t\t\tLossChanceRange: 20,\n\t\t\tDoClientAuth: true,\n\t\t},\n\t\t{\n\t\t\tLossChanceRange: 50,\n\t\t\tDoClientAuth: true,\n\t\t},\n\t\t{\n\t\t\tLossChanceRange: 0,\n\t\t\tCipherSuites: []dtls.CipherSuiteID{dtls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA},\n\t\t},\n\t\t{\n\t\t\tLossChanceRange: 10,\n\t\t\tCipherSuites: []dtls.CipherSuiteID{dtls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA},\n\t\t},\n\t\t{\n\t\t\tLossChanceRange: 20,\n\t\t\tCipherSuites: []dtls.CipherSuiteID{dtls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA},\n\t\t},\n\t\t{\n\t\t\tLossChanceRange: 50,\n\t\t\tCipherSuites: []dtls.CipherSuiteID{dtls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA},\n\t\t},\n\t} {\n\t\trand.Seed(time.Now().UTC().UnixNano())\n\t\tchosenLoss := rand.Intn(9) + test.LossChanceRange\n\t\tserverDone := make(chan error)\n\t\tclientDone := make(chan error)\n\t\tbr := transportTest.NewBridge()\n\t\tif err := br.SetLossChance(chosenLoss); err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\n\t\tgo func() {\n\t\t\tcfg := &dtls.Config{\n\t\t\t\tFlightInterval: flightInterval,\n\t\t\t\tCipherSuites: test.CipherSuites,\n\t\t\t}\n\t\t\tif test.DoClientAuth {\n\t\t\t\tcfg.Certificate = clientCert\n\t\t\t\tcfg.PrivateKey = clientKey\n\t\t\t}\n\n\t\t\tif _, err := dtls.Client(br.GetConn0(), cfg); err != nil {\n\t\t\t\tclientDone <- err\n\t\t\t} else {\n\t\t\t\tclose(clientDone)\n\t\t\t}\n\t\t}()\n\n\t\tgo func() {\n\t\t\tcfg := &dtls.Config{\n\t\t\t\tCertificate: serverCert,\n\t\t\t\tPrivateKey: serverKey,\n\t\t\t\tFlightInterval: flightInterval,\n\t\t\t}\n\t\t\tif test.DoClientAuth {\n\t\t\t\tcfg.ClientAuth = dtls.RequireAnyClientCert\n\n\t\t\t}\n\n\t\t\tif _, err := dtls.Server(br.GetConn1(), cfg); err != nil {\n\t\t\t\tserverDone <- err\n\t\t\t} else {\n\t\t\t\tclose(serverDone)\n\t\t\t}\n\t\t}()\n\n\t\ttestTimer := time.NewTimer(lossyTestTimeout)\n\t\tvar serverComplete, clientComplete bool\n\t\tfor {\n\t\t\tif serverComplete && clientComplete {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tbr.Tick()\n\t\t\tselect {\n\t\t\tcase err, ok := <-serverDone:\n\t\t\t\tif ok {\n\t\t\t\t\tt.Fatalf(\"Fail, serverError: clientComplete(%t) serverComplete(%t) LossChance(%d) error(%v)\", clientComplete, serverComplete, chosenLoss, err)\n\t\t\t\t}\n\n\t\t\t\tserverComplete = true\n\t\t\tcase err, ok := <-clientDone:\n\t\t\t\tif ok {\n\t\t\t\t\tt.Fatalf(\"Fail, clientError: clientComplete(%t) serverComplete(%t) LossChance(%d) error(%v)\", clientComplete, serverComplete, chosenLoss, err)\n\t\t\t\t}\n\n\t\t\t\tclientComplete = true\n\t\t\tcase <-testTimer.C:\n\t\t\t\tt.Fatalf(\"Test expired: clientComplete(%t) serverComplete(%t) LossChance(%d)\", clientComplete, serverComplete, chosenLoss)\n\t\t\tdefault:\n\t\t\t}\n\t\t}\n\t}\n\n}", "func TestRequestAttestationReport(t *testing.T) {\n\n\tias := NewIAS()\n\tverifier := VerifierImpl{}\n\n\tquoteAsBytes, err := base64.StdEncoding.DecodeString(quote)\n\tif err != nil {\n\t\tjsonResp := \"{\\\"Error\\\":\\\" Can not parse quoteBase64 string: \" + err.Error() + \" \\\"}\"\n\t\tt.Errorf(jsonResp)\n\t}\n\n\t// send quote to intel for verification\n\tattestationReport, err := ias.RequestAttestationReport(apiKey, quoteAsBytes)\n\tif err != nil {\n\t\tjsonResp := \"{\\\"Error\\\":\\\" Error while retrieving attestation report: \" + err.Error() + \"\\\"}\"\n\t\tt.Errorf(jsonResp)\n\t}\n\n\tverificationPK, err := ias.GetIntelVerificationKey()\n\tif err != nil {\n\t\tt.Errorf(\"Can not parse verifiaction key: %s\", err)\n\t}\n\n\t// verify attestation report\n\tisValid, err := verifier.VerifyAttestionReport(verificationPK, attestationReport)\n\tif err != nil {\n\t\tjsonResp := \"{\\\"Error\\\":\\\" Error while attestation report verification: \" + err.Error() + \"\\\"}\"\n\t\tt.Errorf(jsonResp)\n\t}\n\tif !isValid {\n\t\tjsonResp := \"{\\\"Error\\\":\\\" Attestation report is not valid \\\"}\"\n\t\tt.Errorf(jsonResp)\n\t}\n\n}", "func AssertCertificateHasClientAuthUsage(t *testing.T, cert *x509.Certificate) {\n\tfor i := range cert.ExtKeyUsage {\n\t\tif cert.ExtKeyUsage[i] == x509.ExtKeyUsageClientAuth {\n\t\t\treturn\n\t\t}\n\t}\n\tt.Error(\"cert has not ClientAuth usage as expected\")\n}", "func (s *SignSuite) SetUpTest(c *C) {\n}", "func (suite *EmailTests) SetUpSuite(c *C) {\n}", "func TestSecretsShouldBeEnveloped(t *testing.T) {\n\tvar testCases = []struct {\n\t\ttransformerConfigContent string\n\t\ttransformerPrefix string\n\t\tunSealFunc unSealSecret\n\t}{\n\t\t{aesGCMConfigYAML, aesGCMPrefix, unSealWithGCMTransformer},\n\t\t{aesCBCConfigYAML, aesCBCPrefix, unSealWithCBCTransformer},\n\t\t// TODO: add secretbox\n\t}\n\tfor _, tt := range testCases {\n\t\trunEnvelopeTest(t, tt.unSealFunc, tt.transformerConfigContent, tt.transformerPrefix)\n\t}\n}", "func TestAckInstalledApplicationListDuplicateRegression(t *testing.T) {\n\n}", "func (mr *MockisCryptoAsymApiReqSetupPrivateKeyEx_KeyMockRecorder) isCryptoAsymApiReqSetupPrivateKeyEx_Key() *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"isCryptoAsymApiReqSetupPrivateKeyEx_Key\", reflect.TypeOf((*MockisCryptoAsymApiReqSetupPrivateKeyEx_Key)(nil).isCryptoAsymApiReqSetupPrivateKeyEx_Key))\n}", "func TestAuthorise(t *testing.T) {\n\tt.Parallel()\n\n\tinstance := getTestInstance()\n\n\tauthRequest := &Authorise{\n\t\tCard: &Card{\n\t\t\tNumber: \"4111111111111111\",\n\t\t\tExpireMonth: \"08\",\n\t\t\tExpireYear: \"2018\",\n\t\t\tCvc: \"737\",\n\t\t\tHolderName: \"John Smith\",\n\t\t},\n\t\tAmount: &Amount{\n\t\t\tValue: 1000,\n\t\t\tCurrency: \"EUR\",\n\t\t},\n\t\tReference: \"DE-TEST-1\" + randomString(10),\n\t\tMerchantAccount: os.Getenv(\"ADYEN_ACCOUNT\"),\n\t}\n\n\tresponse, err := instance.Payment().Authorise(authRequest)\n\n\tknownError, ok := err.(APIError)\n\tif ok {\n\t\tt.Errorf(\"Response should be succesfull. Known API Error: Code - %s, Message - %s, Type - %s\", knownError.ErrorCode, knownError.Message, knownError.ErrorType)\n\t}\n\n\tif err != nil {\n\t\tt.Errorf(\"Response should be succesfull, error - %s\", err.Error())\n\t}\n\n\tresponseBytes, err := json.Marshal(response)\n\n\tif err != nil {\n\t\tt.Error(\"Response can't be converted to JSON\")\n\t}\n\n\tif response.PspReference == \"\" {\n\t\tt.Errorf(\"Response should contain PSP Reference. Response - %s\", string(responseBytes))\n\t}\n\n\tif response.ResultCode != \"Authorised\" {\n\t\tt.Errorf(\"Response resultCode should be Authorised, Response - %s\", string(responseBytes))\n\t}\n}", "func TestMain(m *testing.M) {\n\tconfigImp = mocks.NewMockConfig(caServerURL)\n\tcryptoSuiteProvider, _ = cryptosuiteimpl.GetSuiteByConfig(configImp)\n\tif cryptoSuiteProvider == nil {\n\t\tpanic(\"Failed initialize cryptoSuiteProvider\")\n\t}\n\t// Start Http Server\n\tgo mocks.StartFabricCAMockServer(strings.TrimPrefix(caServerURL, \"http://\"))\n\t// Allow HTTP server to start\n\ttime.Sleep(1 * time.Second)\n\tos.Exit(m.Run())\n}", "func (s *TestSuite) setup() {\n\t// The first few keys from the following well-known mnemonic used by 0x:\n\t//\tconcert load couple harbor equip island argue ramp clarify fence smart topic\n\tkeys := []string{\n\t\t\"f2f48ee19680706196e2e339e5da3491186e0c4c5030670656b0e0164837257d\",\n\t\t\"5d862464fe9303452126c8bc94274b8c5f9874cbd219789b3eb2128075a76f72\",\n\t\t\"df02719c4df8b9b8ac7f551fcb5d9ef48fa27eef7a66453879f4d8fdc6e78fb1\",\n\t\t\"ff12e391b79415e941a94de3bf3a9aee577aed0731e297d5cfa0b8a1e02fa1d0\",\n\t\t\"752dd9cf65e68cfaba7d60225cbdbc1f4729dd5e5507def72815ed0d8abc6249\",\n\t\t\"efb595a0178eb79a8df953f87c5148402a224cdf725e88c0146727c6aceadccd\",\n\t}\n\ts.account = make([]account, len(keys))\n\tfor i, key := range keys {\n\t\tb, err := hex.DecodeString(key)\n\t\ts.Require().NoError(err)\n\t\ts.account[i].key, err = crypto.ToECDSA(b)\n\t\ts.Require().NoError(err)\n\t}\n\ts.signer = signer(s.account[0])\n}", "func testBatchCTXServiceClassCodeEquality(t testing.TB) {\n\tmockBatch := mockBatchCTX(t)\n\tmockBatch.GetControl().ServiceClassCode = MixedDebitsAndCredits\n\terr := mockBatch.Validate()\n\tif !base.Match(err, NewErrBatchHeaderControlEquality(220, MixedDebitsAndCredits)) {\n\t\tt.Errorf(\"%T: %s\", err, err)\n\t}\n}", "func (suite *SmsTests) SetUpSuite(c *C) {\n}", "func (suite *AWSSecurityGroupManagerTestSuite) SetupSuite() {\n\tsuite.Prov = GetProvider()\n}", "func StandardCrypto() {\n\n}", "func TestEmptyCommit4A(t *testing.T) {\n}", "func CipherSuites() []*tls.CipherSuite", "func (mr *MockisCryptoAsymApiRespSetupPrivateKey_KeyInfoMockRecorder) isCryptoAsymApiRespSetupPrivateKey_KeyInfo() *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"isCryptoAsymApiRespSetupPrivateKey_KeyInfo\", reflect.TypeOf((*MockisCryptoAsymApiRespSetupPrivateKey_KeyInfo)(nil).isCryptoAsymApiRespSetupPrivateKey_KeyInfo))\n}", "func defaultCipherSuite() []uint16 {\n\treturn []uint16{\n\t\ttls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,\n\t\ttls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,\n\t\ttls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,\n\t\ttls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,\n\t\ttls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,\n\t\ttls.TLS_RSA_WITH_AES_128_GCM_SHA256,\n\t\ttls.TLS_RSA_WITH_AES_256_GCM_SHA384,\n\t\ttls.TLS_RSA_WITH_AES_128_CBC_SHA,\n\t\ttls.TLS_RSA_WITH_AES_256_CBC_SHA,\n\t}\n}", "func BoringCrypto() {\n\n}", "func (suite *iamTestSuite) SetupSuite() {\n\tvar err error\n\terr = ioutil.WriteFile(testKeyFile, []byte(testKeyPemRaw), 0600)\n\tsuite.Require().NoErrorf(err, \"cannot create private key file %s: %v\", testKeyFile, err)\n\terr = generateBadPrivateKeyPEM(testBadKeyFile)\n\tsuite.Require().NoErrorf(err, \"cannot create private key file %s: %v\", testBadKeyFile, err)\n}", "func TestCiphering(t *testing.T) {\n\tpb, _ := hex.DecodeString(\"fe38240982f313ae5afb3e904fb8215fb11af1200592b\" +\n\t\t\"fca26c96c4738e4bf8f\")\n\tprivkey, _ := PrivKeyFromBytes(S256(), pb)\n\n\tin := []byte(\"This is just a test.\")\n\tout, _ := hex.DecodeString(\"b0d66e5adaa5ed4e2f0ca68e17b8f2fc02ca002009e3\" +\n\t\t\"3487e7fa4ab505cf34d98f131be7bd258391588ca7804acb30251e71a04e0020ecf\" +\n\t\t\"df0f84608f8add82d7353af780fbb28868c713b7813eb4d4e61f7b75d7534dd9856\" +\n\t\t\"9b0ba77cf14348fcff80fee10e11981f1b4be372d93923e9178972f69937ec850ed\" +\n\t\t\"6c3f11ff572ddd5b2bedf9f9c0b327c54da02a28fcdce1f8369ffec\")\n\n\tdec, err := Decrypt(privkey, out)\n\tif err != nil {\n\t\tt.Fatal(\"failed to decrypt:\", err)\n\t}\n\n\tif !bytes.Equal(in, dec) {\n\t\tt.Error(\"decrypted data doesn't match original\")\n\t}\n}", "func TestAESCMAC2(t *testing.T) {\n\ttests := []struct {\n\t\tkey, plain, mac string\n\t}{\n\t\t// 0\n\t\t{\n\t\t\tkey: \"2b7e151628aed2a6abf7158809cf4f3c\",\n\t\t\tplain: \"\",\n\t\t\tmac: \"bb1d6929e95937287fa37d129b756746\",\n\t\t},\n\t\t{\n\t\t\tkey: \"2b7e151628aed2a6abf7158809cf4f3c\",\n\t\t\tplain: \"6bc1bee22e409f96e93d7e117393172a\",\n\t\t\tmac: \"070a16b46b4d4144f79bdd9dd04a287c\",\n\t\t},\n\t\t{\n\t\t\tkey: \"2b7e151628aed2a6abf7158809cf4f3c\",\n\t\t\tplain: \"6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e5130c81c46a35ce411\",\n\t\t\tmac: \"dfa66747de9ae63030ca32611497c827\",\n\t\t},\n\t\t{\n\t\t\tkey: \"2b7e151628aed2a6abf7158809cf4f3c\",\n\t\t\tplain: \"6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e5130c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710\",\n\t\t\tmac: \"51f0bebf7e3b9d92fc49741779363cfe\",\n\t\t},\n\t\t{\n\t\t\tkey: \"8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b\",\n\t\t\tplain: \"\",\n\t\t\tmac: \"d17ddf46adaacde531cac483de7a9367\",\n\t\t},\n\t\t// 5\n\t\t{\n\t\t\tkey: \"8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b\",\n\t\t\tplain: \"6bc1bee22e409f96e93d7e117393172a\",\n\t\t\tmac: \"9e99a7bf31e710900662f65e617c5184\",\n\t\t},\n\t\t{\n\t\t\tkey: \"8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b\",\n\t\t\tplain: \"6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e5130c81c46a35ce411\",\n\t\t\tmac: \"8a1de5be2eb31aad089a82e6ee908b0e\",\n\t\t},\n\t\t{\n\t\t\tkey: \"8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b\",\n\t\t\tplain: \"6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e5130c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710\",\n\t\t\tmac: \"a1d5df0eed790f794d77589659f39a11\",\n\t\t},\n\t\t{\n\t\t\tkey: \"603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4\",\n\t\t\tplain: \"\",\n\t\t\tmac: \"028962f61b7bf89efc6b551f4667d983\",\n\t\t},\n\t\t{\n\t\t\tkey: \"603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4\",\n\t\t\tplain: \"6bc1bee22e409f96e93d7e117393172a\",\n\t\t\tmac: \"28a7023f452e8f82bd4bf28d8c37c35c\",\n\t\t},\n\t\t// 10\n\t\t{\n\t\t\tkey: \"603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4\",\n\t\t\tplain: \"6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e5130c81c46a35ce411\",\n\t\t\tmac: \"aaf3d8f1de5640c232f5b169b9c911e6\",\n\t\t},\n\t\t{\n\t\t\tkey: \"603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4\",\n\t\t\tplain: \"6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e5130c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710\",\n\t\t\tmac: \"e1992190549f6ed5696a2c056c315410\",\n\t\t},\n\t}\n\n\tfor i, test := range tests {\n\t\trefKey, _ := hex.DecodeString(test.key)\n\t\tplain, _ := hex.DecodeString(test.plain)\n\t\trefMac, _ := hex.DecodeString(test.mac)\n\t\tcm, err := New(aes.NewCipher, refKey)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tcm.Reset()\n\t\tn, err := cm.Write(plain)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"unexpected error: %s\", err)\n\t\t\tcontinue\n\t\t}\n\t\tif len(plain) != n {\n\t\t\tt.Errorf(\"got len %d, expected %d for test %d\", n, len(plain), i)\n\t\t\tcontinue\n\t\t}\n\t\tif !Equal(cm.Sum(nil), refMac) {\n\t\t\tt.Errorf(\"mac mismatch for test %d\", i)\n\t\t}\n\t}\n}", "func TestCirclHpkeKemAlgorithmMismatchError(t *testing.T) {\n\tkem := hpke.KEM_P256_HKDF_SHA256\n\tkdf := hpke.KDF_HKDF_SHA256\n\taead := hpke.AEAD_AES128GCM\n\tsuite := hpke.NewSuite(kem, kdf, aead)\n\t_, sk, err := kem.Scheme().GenerateKeyPair()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tincorrectKEM := hpke.KEM_X25519_HKDF_SHA256\n\tincorrectSuite := hpke.NewSuite(incorrectKEM, kdf, aead)\n\tincorrectPK, _, err := incorrectKEM.Scheme().GenerateKeyPair()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// Generate an encapsulated key share with the incorrect KEM algorithm.\n\tincorrectSender, err := incorrectSuite.NewSender(incorrectPK, []byte(\"some info string\"))\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tincorrectEnc, _, err := incorrectSender.Setup(rand.Reader)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// Attempt to parse an encapsulated key generated using the incorrect KEM\n\t// algorithm.\n\treceiver, err := suite.NewReceiver(sk, []byte(\"some info string\"))\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\texpectedErrorString := \"hpke: invalid KEM public key\"\n\tif _, err := receiver.Setup(incorrectEnc); err == nil {\n\t\tt.Errorf(\"expected error; got success\")\n\t} else if err.Error() != expectedErrorString {\n\t\tt.Errorf(\"incorrect error string: got '%s'; want '%s'\", err, expectedErrorString)\n\t}\n}", "func TestHandshakeCoreData(t *testing.T) {\n\n\t// node 1\n\tport := crypto.GetRandomUserPort()\n\taddress := fmt.Sprintf(\"0.0.0.0:%d\", port)\n\n\tnode1Local, err := NewNodeIdentity(address, nodeconfig.ConfigValues, false)\n\n\tif err != nil {\n\t\tt.Error(\"failed to create local node1\", err)\n\t}\n\n\t// this will be node 2 view of node 1\n\tnode1Remote, _ := NewRemoteNode(node1Local.String(), address)\n\n\t// node 2\n\tport1 := crypto.GetRandomUserPort()\n\taddress1 := fmt.Sprintf(\"0.0.0.0:%d\", port1)\n\n\tnode2Local, err := NewNodeIdentity(address1, nodeconfig.ConfigValues, false)\n\n\tif err != nil {\n\t\tt.Error(\"failed to create local node2\", err)\n\t}\n\n\t// this will be node1 view of node 2\n\tnode2Remote, _ := NewRemoteNode(node2Local.String(), address1)\n\n\t// STEP 1: Node1 generates handshake data and sends it to node2 ....\n\tdata, session, err := generateHandshakeRequestData(node1Local, node2Remote)\n\n\tassert.NoErr(t, err, \"expected no error\")\n\tassert.NotNil(t, session, \"expected session\")\n\tassert.NotNil(t, data, \"expected session\")\n\n\tlog.Info(\"Node 1 session data: Id:%s, AES-KEY:%s\", hex.EncodeToString(session.ID()), hex.EncodeToString(session.KeyE()))\n\n\tassert.False(t, session.IsAuthenticated(), \"Expected session to be not authenticated yet\")\n\n\t// STEP 2: Node2 gets handshake data from node 1 and processes it to establish a session with a shared AES key\n\n\tresp, session1, err := processHandshakeRequest(node2Local, node1Remote, data)\n\n\tassert.NoErr(t, err, \"expected no error\")\n\tassert.NotNil(t, session1, \"expected session\")\n\tassert.NotNil(t, resp, \"expected resp data\")\n\n\tlog.Info(\"Node 2 session data: Id:%s, AES-KEY:%s\", hex.EncodeToString(session1.ID()), hex.EncodeToString(session1.KeyE()))\n\n\tassert.Equal(t, string(session.ID()), string(session1.ID()), \"expected agreed Id\")\n\tassert.Equal(t, string(session.KeyE()), string(session1.KeyE()), \"expected same shared AES enc key\")\n\tassert.Equal(t, string(session.KeyM()), string(session1.KeyM()), \"expected same shared AES mac key\")\n\tassert.Equal(t, string(session.PubKey()), string(session1.PubKey()), \"expected same shared secret\")\n\n\tassert.True(t, session1.IsAuthenticated(), \"expected session1 to be authenticated\")\n\n\t// STEP 3: Node2 sends data1 back to node1.... Node 1 validates the data and sets its network session to authenticated\n\terr = processHandshakeResponse(node1Local, node2Remote, session, resp)\n\n\tassert.True(t, session.IsAuthenticated(), \"expected session to be authenticated\")\n\tassert.NoErr(t, err, \"failed to authenticate or process response\")\n\n\t// test session sym enc / dec\n\n\tconst msg = \"hello spacemesh - hello spacemesh - hello spacemesh :-)\"\n\tcipherText, err := session.Encrypt([]byte(msg))\n\tassert.NoErr(t, err, \"expected no error\")\n\n\tclearText, err := session1.Decrypt(cipherText)\n\tassert.NoErr(t, err, \"expected no error\")\n\tassert.True(t, bytes.Equal(clearText, []byte(msg)), \"Expected enc/dec to work\")\n\n\tnode1Local.Shutdown()\n\tnode2Local.Shutdown()\n}", "func TestBatchCTXValidTranCodeForServiceClassCode(t *testing.T) {\n\tmockBatch := mockBatchCTX(t)\n\tmockBatch.GetHeader().ServiceClassCode = DebitsOnly\n\terr := mockBatch.Create()\n\tif !base.Match(err, NewErrBatchServiceClassTranCode(DebitsOnly, 22)) {\n\t\tt.Errorf(\"%T: %s\", err, err)\n\t}\n}", "func TestCMPreIssuedCert(t *testing.T) {\n\tvar b64Chain = []string{\n\t\t\"MIID+jCCAuKgAwIBAgIHBWW7shJizTANBgkqhkiG9w0BAQsFADB1MQswCQYDVQQGEwJHQjEPMA0GA1UEBwwGTG9uZG9uMTowOAYDVQQKDDFHb29nbGUgQ2VydGlmaWNhdGUgVHJhbnNwYXJlbmN5IChQcmVjZXJ0IFNpZ25pbmcpMRkwFwYDVQQFExAxNTE5MjMxNzA0MTczNDg3MB4XDTE4MDIyMTE2NDgyNFoXDTE4MTIwMTIwMzMyN1owYzELMAkGA1UEBhMCR0IxDzANBgNVBAcMBkxvbmRvbjEoMCYGA1UECgwfR29vZ2xlIENlcnRpZmljYXRlIFRyYW5zcGFyZW5jeTEZMBcGA1UEBRMQMTUxOTIzMTcwNDM5MjM5NzCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAKnKP9TP6hkEuD+d1rPeA8mxo5xFYffhCcEitP8PtTl7G2RqFrndPeAkzgvOxPB3Jrhx7LtMtg0IvS8y7Sy1qDqDou1/OrJgwCeWMc1/KSneuGP8GTX0Rqy4z8+LsiBN/tMDbt94RuiyCeltIAaHGmsNeYXV34ayD3vSIAQbtLUOD39KqrJWO0tQ//nshBuFlebiUrDP7rirPusYYW0stJKiCKeORhHvL3/I8mCYGNO0XIWMpASH2S9LGMwg+AQM13whC1KL65EGuVs4Ta0rO+Tl8Yi0is0RwdUmgdSGtl0evPTzyUXbA1n1BpkLcSQ5E3RxY3O6Ge9Whvtmg9vAJiMCAwEAAaOBoDCBnTATBgNVHSUEDDAKBggrBgEFBQcDATAjBgNVHREEHDAaghhmbG93ZXJzLXRvLXRoZS13b3JsZC5jb20wDAYDVR0TAQH/BAIwADAfBgNVHSMEGDAWgBRKCM/Ajh0Fu6FFjJ9F4gVWK2oj/jAdBgNVHQ4EFgQUVjYl6wDey3DxvmTG2HL4vdiUt+MwEwYKKwYBBAHWeQIEAwEB/wQCBQAwDQYJKoZIhvcNAQELBQADggEBAAvyEFDIAWr0URsZzrJLZEL8p6FMTzVxY/MOvGP8QMXA6xNVElxYnDPF32JERAl+poR7syByhVFcEjrw7f2FTlMc04+hT/hsYzi8cMAmfX9KA36xUBVjyqvqwofxTwoWYdf+eGZW0EG8Yp1pM7iUy9bdlh3sgdOpmT9Z5XGCRwvdW1+mctv0JMKDdWzxBqYyNMnNjvjHBmkiuHeDDGFsV2zq+wV64RwJa2eVrnkMDMV1mscL6KzNRLPP2ZpNz/8H7SPock+fk4cZrdqj+0IzFt+6ixSoKyltyD+nkbWjRGY4iyboo/nPgTQ1IQCS2OPVHWw3NijFD8hqgAnYvz0Dn+k=\",\n\t\t\"MIIE4jCCAsqgAwIBAgIHBWW7sg8LrzANBgkqhkiG9w0BAQUFADB/MQswCQYDVQQGEwJHQjEPMA0GA1UECAwGTG9uZG9uMRcwFQYDVQQKDA5Hb29nbGUgVUsgTHRkLjEhMB8GA1UECwwYQ2VydGlmaWNhdGUgVHJhbnNwYXJlbmN5MSMwIQYDVQQDDBpNZXJnZSBEZWxheSBJbnRlcm1lZGlhdGUgMTAeFw0xODAyMjExNjQ4MjRaFw0xODEyMDEyMDM0MjdaMHUxCzAJBgNVBAYTAkdCMQ8wDQYDVQQHDAZMb25kb24xOjA4BgNVBAoMMUdvb2dsZSBDZXJ0aWZpY2F0ZSBUcmFuc3BhcmVuY3kgKFByZWNlcnQgU2lnbmluZykxGTAXBgNVBAUTEDE1MTkyMzE3MDQxNzM0ODcwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCKWlc3A43kJ9IzmkCPXcsGwTxlIvtl9sNYBWlx9qqHa1i6tU6rZuH9uXAb3wsn39fqY22HzF/yrx9pd05doFfRq6dvvm4eHNFfFm4cJur1kmPe8vLKpSI/P2DPx4/mRzrHnPAI8Jo9QgKcj91AyYeB689ZFzH30ay32beo6PxQvtoJkzl+dzf9Hs1ezavS7nDCuqDnu1V1Og7J5xTHZeNyTKgD5Kx28ukmIp2wGOvg3omuInABg/ew0VxnG/txKV+69zfV9dhclU3m16L81e3RkJ8Kg4RLb0mh9X3EMn90SpJ9yw0j8FF0Esk6wxuYeUGLShUji8BPnnbactY9B6ORAgMBAAGjbTBrMBgGA1UdJQEB/wQOMAwGCisGAQQB1nkCBAQwDwYDVR0TAQH/BAUwAwEB/zAfBgNVHSMEGDAWgBTpPAThgC/ChBMtJnCe8v0az6r+xjAdBgNVHQ4EFgQUSgjPwI4dBbuhRYyfReIFVitqI/4wDQYJKoZIhvcNAQEFBQADggIBAEep2uWAFsdq1nLtLWLGh7DfVPc/K+1lcqNx64ucjpVZbDnMnYKFagf2Z9rHEWqR7kwuLac5xW8woSlLa/NHmJmdg18HGUhlS+x8iMPv7dK6hfNsRFdjLZkZOFneuf9j1b0dV+rXoRvyY+Oq+lomC98bEr+g9zq+M7wJ4wS/KeaNHpPw1pBeTtCdw+1c4ZgRTOEa2OUUpkpueJ+9psD/hbp6HLF+WYijWQ0/iYSxJ4TbjTC+omKRsGhvxSLbP8cSMt3X1pJgrFK1BvH4lqqEXGDNEiVNoPCHraEa8JtMZIo47/Af13lDfp6sBdZ0lvLAVDduWgg/2RkWCbHefAe81h+cYdDS775TF2TCMTwsR6GsM9sVCbfPvHXI/pUzamRn0i0CrhyccBBdPrUhj+cXuc9kqSkLegun9D8EBDMM9va5wb1HM0ruSno+YuLtfhCdBRHr/RG2BKJi7uUDjJ8goHov/EUJmHjAIARKz74IPWRkxMrnOvGhnNa2Hz+da3hpusz0Mj4rsqv1EKTC2wbCs6Rk2MRPSxdRbywdWLSmGn249SMfXK4An+dqoRk1fwKqdXc4swoUvxnGUi5ajBaRtc6631zBTmvmSFQnvGmS42aF7q2PjfvWPIuO+d//m8KgN6o2YyjrdPDDslI2RZUE5ngOR+JynvhjYrrB7Bat1EY7\",\n\t\t\"MIIFyDCCA7CgAwIBAgICEAEwDQYJKoZIhvcNAQEFBQAwfTELMAkGA1UEBhMCR0IxDzANBgNVBAgMBkxvbmRvbjEXMBUGA1UECgwOR29vZ2xlIFVLIEx0ZC4xITAfBgNVBAsMGENlcnRpZmljYXRlIFRyYW5zcGFyZW5jeTEhMB8GA1UEAwwYTWVyZ2UgRGVsYXkgTW9uaXRvciBSb290MB4XDTE0MDcxNzEyMjYzMFoXDTE5MDcxNjEyMjYzMFowfzELMAkGA1UEBhMCR0IxDzANBgNVBAgMBkxvbmRvbjEXMBUGA1UECgwOR29vZ2xlIFVLIEx0ZC4xITAfBgNVBAsMGENlcnRpZmljYXRlIFRyYW5zcGFyZW5jeTEjMCEGA1UEAwwaTWVyZ2UgRGVsYXkgSW50ZXJtZWRpYXRlIDEwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQDB6HT+/5ru8wO7+mNFOIH6r43BwiwJZB2vQwOB8zvBV79sTIqNV7Grx5KFnSDyGRUJxZfEN7FGc96lr0vqFDlt1DbcYgVV15U+Dt4B9/+0Tz/3zeZO0kVjTg3wqvzpw6xetj2N4dlpysiFQZVAOp+dHUw9zu3xNR7dlFdDvFSrdFsgT7Uln+Pt9pXCz5C4hsSP9oC3RP7CaRtDRSQrMcNvMRi3J8XeXCXsGqMKTCRhxRGe9ruQ2Bbm5ExbmVW/ou00Fr9uSlPJL6+sDR8Li/PTW+DU9hygXSj8Zi36WI+6PuA4BHDAEt7Z5Ru/Hnol76dFeExJ0F6vjc7gUnNh7JExJgBelyz0uGORT4NhWC7SRWP/ngPFLoqcoyZMVsGGtOxSt+aVzkKuF+x64CVxMeHb9I8t3iQubpHqMEmIE1oVSCsF/AkTVTKLOeWG6N06SjoUy5fu9o+faXKMKR8hldLM5z1K6QhFsb/F+uBAuU/DWaKVEZgbmWautW06fF5I+OyoFeW+hrPTbmon4OLE3ubjDxKnyTa4yYytWSisojjfw5z58sUkbLu7KAy2+Z60m/0deAiVOQcsFkxwgzcXRt7bxN7By5Q5Bzrz8uYPjFBfBnlhqMU5RU/FNBFY7Mx4Uy8+OcMYfJQ5/A/4julXEx1HjfBj3VCyrT/noHDpBeOGiwIDAQABo1AwTjAdBgNVHQ4EFgQU6TwE4YAvwoQTLSZwnvL9Gs+q/sYwHwYDVR0jBBgwFoAU8197dUnjeEE5aiC2fGtMXMk9WEEwDAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQUFAAOCAgEACFjL1UXy6S4JkGrDnz1VwTYHplFDY4bG6Q8Sh3Og6z9HJdivNft/iAQ2tIHyz0eAGCXeVPE/j1kgvz2RbnUxQd5eWdLeu/w/wiZyHxWhbTt6RhjqBVFjnx0st7n6rRt+Bw8jpugZfD11SbumVT/V20Gc45lHf2oEgbkPUcnTB9gssFz5Z4KKGs5lIHz4a20WeSJF3PJLTBefkRhHNufi/LhjpLXImwrC82g5ChBZS5XIVuJZx3VkMWiYz4emgX0YWF/JdtaB2dUQ7yrTforQ5J9b1JnJ7H/o9DsX3/ubfQ39gwDBxTicnqC+Q3Dcv3i9PvwjCNJQuGa7ygMcDEn/d6elQg2qHxtqRE02ZlOXTC0XnDAJhx7myJFA/Knv3yO9S4jG6665KG9Y88/CHkh08YLR7NYFiRmwOxjbe3lb6csl/FFmqUXvjhEzzWAxKjI09GSd9hZkB8u17Mg46eEYwF3ufIlqmYdlWufjSc2BZuaNNN6jtK6JKp8jhQUycehgtUK+NlBQOXTzu28miDdasoSH2mdR0PLDo1547+MLGdV4COvqLERTmQrYHrliicD5nFCA+CCSvGEjo0DGOmF/O8StwSmNiKJ4ppPvk2iGEdO07e0LbQI+2fbC6og2SDGXUlsbG85wqQw0A7CU1fQSqhFBuZZauDFMUvdy3v/BAIw=\",\n\t\t\"MIIFzTCCA7WgAwIBAgIJAJ7TzLHRLKJyMA0GCSqGSIb3DQEBBQUAMH0xCzAJBgNVBAYTAkdCMQ8wDQYDVQQIDAZMb25kb24xFzAVBgNVBAoMDkdvb2dsZSBVSyBMdGQuMSEwHwYDVQQLDBhDZXJ0aWZpY2F0ZSBUcmFuc3BhcmVuY3kxITAfBgNVBAMMGE1lcmdlIERlbGF5IE1vbml0b3IgUm9vdDAeFw0xNDA3MTcxMjA1NDNaFw00MTEyMDIxMjA1NDNaMH0xCzAJBgNVBAYTAkdCMQ8wDQYDVQQIDAZMb25kb24xFzAVBgNVBAoMDkdvb2dsZSBVSyBMdGQuMSEwHwYDVQQLDBhDZXJ0aWZpY2F0ZSBUcmFuc3BhcmVuY3kxITAfBgNVBAMMGE1lcmdlIERlbGF5IE1vbml0b3IgUm9vdDCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAKoWHPIgXtgaxWVIPNpCaj2y5Yj9t1ixe5PqjWhJXVNKAbpPbNHA/AoSivecBm3FTD9DfgW6J17mHb+cvbKSgYNzgTk5e2GJrnOP7yubYJpt2OCw0OILJD25NsApzcIiCvLA4aXkqkGgBq9FiVfisReNJxVu8MtxfhbVQCXZf0PpkW+yQPuF99V5Ri+grHbHYlaEN1C/HM3+t2yMR4hkd2RNXsMjViit9qCchIi/pQNt5xeQgVGmtYXyc92ftTMrmvduj7+pHq9DEYFt3ifFxE8v0GzCIE1xR/d7prFqKl/KRwAjYUcpU4vuazywcmRxODKuwWFVDrUBkGgCIVIjrMJWStH5i7WTSSTrVtOD/HWYvkXInZlSgcDvsNIG0pptJaEKSP4jUzI3nFymnoNZn6pnfdIII/XISpYSVeyl1IcdVMod8HdKoRew9CzW6f2n6KSKU5I8X5QEM1NUTmRLWmVi5c75/CvS/PzOMyMzXPf+fE2Dwbf4OcR5AZLTupqp8yCTqo7ny+cIBZ1TjcZjzKG4JTMaqDZ1Sg0T3mO/ZbbiBE3N8EHxoMWpw8OP50z1dtRRwj6qUZ2zLvngOb2EihlMO15BpVZC3Cg929c9Hdl65pUd4YrYnQBQB/rn6IvHo8zot8zElgOg22fHbViijUt3qnRggB40N30MXkYGwuJbAgMBAAGjUDBOMB0GA1UdDgQWBBTzX3t1SeN4QTlqILZ8a0xcyT1YQTAfBgNVHSMEGDAWgBTzX3t1SeN4QTlqILZ8a0xcyT1YQTAMBgNVHRMEBTADAQH/MA0GCSqGSIb3DQEBBQUAA4ICAQB3HP6jRXmpdSDYwkI9aOzQeJH4x/HDi/PNMOqdNje/xdNzUy7HZWVYvvSVBkZ1DG/ghcUtn/wJ5m6/orBn3ncnyzgdKyXbWLnCGX/V61PgIPQpuGo7HzegenYaZqWz7NeXxGaVo3/y1HxUEmvmvSiioQM1cifGtz9/aJsJtIkn5umlImenKKEV1Ly7R3Uz3Cjz/Ffac1o+xU+8NpkLF/67fkazJCCMH6dCWgy6SL3AOB6oKFIVJhw8SD8vptHaDbpJSRBxifMtcop/85XUNDCvO4zkvlB1vPZ9ZmYZQdyL43NA+PkoKy0qrdaQZZMq1Jdp+Lx/yeX255/zkkILp43jFyd44rZ+TfGEQN1WHlp4RMjvoGwOX1uGlfoGkRSgBRj7TBn514VYMbXu687RS4WY2v+kny3PUFv/ZBfYSyjoNZnU4Dce9kstgv+gaKMQRPcyL+4vZU7DV8nBIfNFilCXKMN/VnNBKtDV52qmtOsVghgai+QE09w15x7dg+44gIfWFHxNhvHKys+s4BBN8fSxAMLOsb5NGFHE8x58RAkmIYWHjyPM6zB5AUPw1b2A0sDtQmCqoxJZfZUKrzyLz8gS2aVujRYN13KklHQ3EKfkeKBG2KXVBe5rjMN/7Anf1MtXxsTY6O8qIuHZ5QlXhSYzE41yIlPlG6d7AGnTiBIgeg==\",\n\t}\n\trawChain := make([][]byte, len(b64Chain))\n\tfor i, b64Data := range b64Chain {\n\t\tvar err error\n\t\trawChain[i], err = base64.StdEncoding.DecodeString(b64Data)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"failed to base64.Decode(chain[%d]): %v\", i, err)\n\t\t}\n\t}\n\n\troot, err := x509.ParseCertificate(rawChain[len(rawChain)-1])\n\tif err != nil {\n\t\tt.Fatalf(\"failed to parse root cert: %v\", err)\n\t}\n\tcmRoot := x509util.NewPEMCertPool()\n\tcmRoot.AddCert(root)\n\n\tfor _, tc := range []struct {\n\t\tdesc string\n\t\teku []x509.ExtKeyUsage\n\t}{\n\t\t{\n\t\t\tdesc: \"no EKU specified\",\n\t\t}, {\n\t\t\tdesc: \"EKU ServerAuth\",\n\t\t\teku: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},\n\t\t},\n\t} {\n\t\tt.Run(tc.desc, func(t *testing.T) {\n\t\t\topts := CertValidationOpts{\n\t\t\t\ttrustedRoots: cmRoot,\n\t\t\t\textKeyUsages: tc.eku,\n\t\t\t}\n\t\t\tchain, err := ValidateChain(rawChain, opts)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatalf(\"failed to ValidateChain: %v\", err)\n\t\t\t}\n\t\t\tfor i, c := range chain {\n\t\t\t\tt.Logf(\"chain[%d] = \\n%s\", i, x509util.CertificateToString(c))\n\t\t\t}\n\t\t})\n\t}\n}", "func TestVerifySignedMessage(t *testing.T) {\n\tfor _, tc := range []struct {\n\t\tdesc string\n\t\tsettings *crypt.PkiSettings\n\t\tsetup func(mdb *mocks.MockDepsBundle, setupDone *bool) error\n\t\tmessageToSign string\n\t\tbase64Signature string\n\t\tPEMPublicKey string\n\t\texpectedError *testtools.ErrorSpec\n\t\texpectedValidity bool\n\t}{\n\t\t{\n\t\t\tdesc: \"invalid base64 signature\",\n\t\t\tsettings: &crypt.PkiSettings{\n\t\t\t\tAlgorithm: x509.ECDSA,\n\t\t\t\tPrivateKeyPath: \".prog/ecdsa_priv.key\",\n\t\t\t\tPublicKeyPath: \".prog/ecdsa.pub\",\n\t\t\t},\n\t\t\tsetup: func(mdb *mocks.MockDepsBundle, setupDone *bool) error {\n\t\t\t\treturn nil\n\t\t\t},\n\t\t\tmessageToSign: \"some other message\",\n\t\t\tbase64Signature: \"@#$^&*()_\",\n\t\t\tPEMPublicKey: \"\",\n\t\t\texpectedError: &testtools.ErrorSpec{\n\t\t\t\tType: \"base64.CorruptInputError\",\n\t\t\t\tMessage: \"illegal base64 data at input byte 0\",\n\t\t\t},\n\t\t\texpectedValidity: false,\n\t\t},\n\t\t{\n\t\t\tdesc: \"empty PEM key\",\n\t\t\tsettings: &crypt.PkiSettings{\n\t\t\t\tAlgorithm: x509.ECDSA,\n\t\t\t\tPrivateKeyPath: \".prog/ecdsa_priv.key\",\n\t\t\t\tPublicKeyPath: \".prog/ecdsa.pub\",\n\t\t\t},\n\t\t\tsetup: func(mdb *mocks.MockDepsBundle, setupDone *bool) error {\n\t\t\t\treturn nil\n\t\t\t},\n\t\t\tmessageToSign: \"some other message\",\n\t\t\tbase64Signature: \"abcdefgh\",\n\t\t\tPEMPublicKey: \"\",\n\t\t\texpectedError: &testtools.ErrorSpec{\n\t\t\t\tType: \"*errors.errorString\",\n\t\t\t\tMessage: \"No PEM data was found\",\n\t\t\t},\n\t\t\texpectedValidity: false,\n\t\t},\n\t\t{\n\t\t\tdesc: \"bad key data\",\n\t\t\tsettings: &crypt.PkiSettings{\n\t\t\t\tAlgorithm: x509.ECDSA,\n\t\t\t\tPrivateKeyPath: \".prog/ecdsa_priv.key\",\n\t\t\t\tPublicKeyPath: \".prog/ecdsa.pub\",\n\t\t\t},\n\t\t\tsetup: func(mdb *mocks.MockDepsBundle, setupDone *bool) error {\n\t\t\t\treturn nil\n\t\t\t},\n\t\t\tmessageToSign: \"some other message\",\n\t\t\tbase64Signature: \"abcdefgh\",\n\t\t\tPEMPublicKey: \"-----BEGIN INVALID DATA-----\\n\" +\n\t\t\t\t\"MTIzNDU2Nzg5MGFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6\\n\" +\n\t\t\t\t\"-----END INVALID DATA-----\\n\",\n\t\t\texpectedError: &testtools.ErrorSpec{\n\t\t\t\tType: \"asn1.StructuralError\",\n\t\t\t\tMessage: \"asn1: structure \" +\n\t\t\t\t\t\"error: tags don't match (16 vs {class:0 \" +\n\t\t\t\t\t\"tag:17 \" +\n\t\t\t\t\t\"length:50 \" +\n\t\t\t\t\t\"isCompound:true}) {optional:false \" +\n\t\t\t\t\t\"explicit:false \" +\n\t\t\t\t\t\"application:false \" +\n\t\t\t\t\t\"defaultValue:<nil> \" +\n\t\t\t\t\t\"tag:<nil> \" +\n\t\t\t\t\t\"stringType:0 \" +\n\t\t\t\t\t\"timeType:0 \" +\n\t\t\t\t\t\"set:false \" +\n\t\t\t\t\t\"omitEmpty:false} publicKeyInfo @2\",\n\t\t\t},\n\t\t\texpectedValidity: false,\n\t\t},\n\t\t{\n\t\t\tdesc: \"invalid signature\",\n\t\t\tsettings: &crypt.PkiSettings{\n\t\t\t\tAlgorithm: x509.ECDSA,\n\t\t\t\tPrivateKeyPath: \".prog/ecdsa_priv.key\",\n\t\t\t\tPublicKeyPath: \".prog/ecdsa.pub\",\n\t\t\t},\n\t\t\tsetup: func(mdb *mocks.MockDepsBundle, setupDone *bool) error {\n\t\t\t\treturn nil\n\t\t\t},\n\t\t\tmessageToSign: \"some other message\",\n\t\t\tbase64Signature: \"abcdefgh\",\n\t\t\tPEMPublicKey: \"-----BEGIN ECDSA PUBLIC KEY-----\\n\" +\n\t\t\t\t\"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE7WzVjtn9Gk+WHr5xbv8XMvooqU25\\n\" +\n\t\t\t\t\"BhgNjZ/vHZLBdVtCOjk4KxjS1UBfQm0c3TRxWBl3hj2AmnJbCrnGofMHBQ==\\n\" +\n\t\t\t\t\"-----END ECDSA PUBLIC KEY-----\\n\",\n\t\t\texpectedError: &testtools.ErrorSpec{\n\t\t\t\tType: \"asn1.SyntaxError\",\n\t\t\t\tMessage: \"asn1: syntax error: truncated tag or length\",\n\t\t\t},\n\t\t\texpectedValidity: false,\n\t\t},\n\t\t{\n\t\t\tdesc: \"ecdsa key for rsa mode\",\n\t\t\tsettings: &crypt.PkiSettings{\n\t\t\t\tAlgorithm: x509.RSA,\n\t\t\t\tPrivateKeyPath: \".prog/ecdsa_priv.key\",\n\t\t\t\tPublicKeyPath: \".prog/ecdsa.pub\",\n\t\t\t},\n\t\t\tsetup: func(mdb *mocks.MockDepsBundle, setupDone *bool) error {\n\t\t\t\treturn nil\n\t\t\t},\n\t\t\tmessageToSign: \"some other message\",\n\t\t\tbase64Signature: \"N3SuIdWI7XlXDteTmcOZUd2OBacyUWY+/+A8SC4QUBz9rXnldBqXha6YyGwnTuizxuy6quQ2QDFdtW16dj7EQk3lozfngskyhc2r86q3AUbdFDvrQVphMQhzsgBhHVoMjCL/YRfvtzCTWhBxegjVMLraLDCBb8IZTIqcMYafYyeJTvAnjBuntlZ+14TDuTt14Uqz85T04CXxBEqlIXMMKpTc01ST4Jsxz5HLO+At1htXp5eHOUFtQSilm3G7iO8ynhgPcXHDWfMAWu6VySUoHWCG70pJaCq6ehF7223t0UFOCqAyDyyQyP9yeUHj8F75SPSxfJm8iKXGx2LND/qLYw==\",\n\t\t\tPEMPublicKey: \"-----BEGIN RSA PUBLIC KEY-----\\n\" +\n\t\t\t\t\"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE7WzVjtn9Gk+WHr5xbv8XMvooqU25\\n\" +\n\t\t\t\t\"BhgNjZ/vHZLBdVtCOjk4KxjS1UBfQm0c3TRxWBl3hj2AmnJbCrnGofMHBQ==\\n\" +\n\t\t\t\t\"-----END RSA PUBLIC KEY-----\\n\",\n\t\t\texpectedError: &testtools.ErrorSpec{\n\t\t\t\tType: \"*errors.errorString\",\n\t\t\t\tMessage: \"Expecting a *rsa.PublicKey, but encountered a *ecdsa.PublicKey instead\",\n\t\t\t},\n\t\t\texpectedValidity: false,\n\t\t},\n\t\t{\n\t\t\tdesc: \"rsa key for ecdsa mode\",\n\t\t\tsettings: &crypt.PkiSettings{\n\t\t\t\tAlgorithm: x509.ECDSA,\n\t\t\t\tPrivateKeyPath: \".prog/ecdsa_priv.key\",\n\t\t\t\tPublicKeyPath: \".prog/ecdsa.pub\",\n\t\t\t},\n\t\t\tsetup: func(mdb *mocks.MockDepsBundle, setupDone *bool) error {\n\t\t\t\treturn nil\n\t\t\t},\n\t\t\tmessageToSign: \"some other message\",\n\t\t\tbase64Signature: \"MEYCIQDPM0fc/PFauoZzpltH3RpWtlaqRnL0gFk5WFiLMrFqrwIhAIDvlBozU6Ky2UC9xOSq3YZ5iFuO356t9RnHOElaaXFJ\",\n\t\t\tPEMPublicKey: \"-----BEGIN RSA PUBLIC KEY-----\\n\" +\n\t\t\t\t\"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAzCTTFKQBHfTN8jW6q8PT\\n\" +\n\t\t\t\t\"HNZKWnRPxSt9kpgWmyqFaZnEUipgoKGAxSIsVrl2PJSm5OlgkVzx+MY+LWM64VKM\\n\" +\n\t\t\t\t\"bRpUUGJR3zdMNhwZQX0hjOpLpVJvUwD78utVs8vijrU7sH48usFiaZQYjy4m4hQh\\n\" +\n\t\t\t\t\"63/x4h3KVz7YqUnlRMzYJFT43+AwYzYuEpzWRxtW7IObJPtjtmYVoqva98fF6aj5\\n\" +\n\t\t\t\t\"uHAsvaAgZGBalHXmCiPzKiGU/halzXSPvyJ2Cqz2aUqMHgwi/2Ip4z/mrfX+mUTa\\n\" +\n\t\t\t\t\"S+LyBy7GgqJ5vbkGArMagJIc0eARF60r6Uf483xh17oniABdLJy4qlLf6PcEU+ut\\n\" +\n\t\t\t\t\"EwIDAQAB\\n\" +\n\t\t\t\t\"-----END RSA PUBLIC KEY-----\\n\",\n\t\t\texpectedError: &testtools.ErrorSpec{\n\t\t\t\tType: \"*errors.errorString\",\n\t\t\t\tMessage: \"Expecting a *ecdsa.PublicKey, but encountered a *rsa.PublicKey instead\",\n\t\t\t},\n\t\t\texpectedValidity: false,\n\t\t},\n\t} {\n\t\tt.Run(fmt.Sprintf(\"Subtest: %s\", tc.desc), func(tt *testing.T) {\n\t\t\tmockDepsBundle := mocks.NewDefaultMockDeps(\"\", []string{\"progname\"}, \"/home/user\", nil)\n\t\t\treturnedNormally := false\n\t\t\tvar tooling *crypt.CryptoTooling\n\t\t\tvar actualErr error\n\t\t\tvar actualValidity bool\n\t\t\terr := mockDepsBundle.InvokeCallInMockedEnv(func() error {\n\t\t\t\tsetupComplete := false\n\t\t\t\tinnerErr := tc.setup(mockDepsBundle, &setupComplete)\n\t\t\t\tif innerErr != nil {\n\t\t\t\t\treturn innerErr\n\t\t\t\t}\n\t\t\t\tvar toolingErr error\n\t\t\t\ttooling, toolingErr = crypt.GetCryptoTooling(mockDepsBundle.Deps, tc.settings)\n\t\t\t\tif toolingErr != nil {\n\t\t\t\t\treturn toolingErr\n\t\t\t\t}\n\t\t\t\tsetupComplete = true\n\t\t\t\tactualValidity, actualErr = tooling.VerifySignedMessage(tc.messageToSign, tc.base64Signature, tc.PEMPublicKey)\n\t\t\t\treturnedNormally = true\n\t\t\t\treturn nil\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\ttt.Errorf(\"Unexpected error calling mockDepsBundle.InvokeCallInMockedEnv(): %s\", err.Error())\n\t\t\t}\n\t\t\tif exitStatus := mockDepsBundle.GetExitStatus(); (exitStatus != 0) || !returnedNormally {\n\t\t\t\ttt.Error(\"EncodeAndSaveKey() should not have paniced or called os.Exit.\")\n\t\t\t}\n\t\t\tif (mockDepsBundle.OutBuf.String() != \"\") || (mockDepsBundle.ErrBuf.String() != \"\") {\n\t\t\t\ttt.Errorf(\"EncodeAndSaveKey() should not have output any data. Saw stdout:\\n%s\\nstderr:\\n%s\", mockDepsBundle.OutBuf.String(), mockDepsBundle.ErrBuf.String())\n\t\t\t}\n\t\t\tif err := tc.expectedError.EnsureMatches(actualErr); err != nil {\n\t\t\t\ttt.Error(err.Error())\n\t\t\t}\n\t\t\tif tc.expectedError == nil {\n\t\t\t\tif actualValidity != tc.expectedValidity {\n\t\t\t\t\ttt.Errorf(\"Signature is %#v when %#v expected\", actualValidity, tc.expectedValidity)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif tc.expectedValidity {\n\t\t\t\t\ttt.Error(\"TEST CASE INVALID. Should not expect \\\"valid\\\".\")\n\t\t\t\t}\n\t\t\t\tif actualValidity {\n\t\t\t\t\ttt.Error(\"Error was expected. Should not report \\\"valid\\\".\")\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n}", "func init() {\n\ttesting.AddTest(&testing.Test{\n\t\tFunc: KeysetTiedToTPM1,\n\t\tDesc: \"Verifies that, for TPMv1.2 devices, the keyset is tied to TPM regardless of when it's created and if a reboot happens\",\n\t\tContacts: []string{\n\t\t\t\"cros-hwsec@chromium.org\",\n\t\t\t\"zuan@chromium.org\",\n\t\t},\n\t\tSoftwareDeps: []string{\"tpm1\"},\n\t\tAttr: []string{\"group:hwsec_destructive_func\"},\n\t})\n}", "func TestAccountSupported(t *testing.T) {\n\t// From mnemonic: wisdom minute home employ west tail liquid mad deal catalog narrow mistake\n\trootKey := mustXKey(\"xprv9s21ZrQH143K3gie3VFLgx8JcmqZNsBcBc6vAdJrsf4bPRhx69U8qZe3EYAyvRWyQdEfz7ZpyYtL8jW2d2Lfkfh6g2zivq8JdZPQqxoxLwB\")\n\tkeystoreHelper := software.NewKeystore(rootKey)\n\n\tfingerprint := []byte{0x55, 0x055, 0x55, 0x55}\n\tbb02Multi := &keystoremock.KeystoreMock{\n\t\tRootFingerprintFunc: func() ([]byte, error) {\n\t\t\treturn fingerprint, nil\n\t\t},\n\t\tSupportsAccountFunc: func(coin coinpkg.Coin, meta interface{}) bool {\n\t\t\tswitch coin.(type) {\n\t\t\tcase *btc.Coin:\n\t\t\t\tscriptType := meta.(signing.ScriptType)\n\t\t\t\treturn scriptType != signing.ScriptTypeP2PKH\n\t\t\tdefault:\n\t\t\t\treturn true\n\t\t\t}\n\t\t},\n\t\tSupportsUnifiedAccountsFunc: func() bool {\n\t\t\treturn true\n\t\t},\n\t\tSupportsMultipleAccountsFunc: func() bool {\n\t\t\treturn true\n\t\t},\n\t\tExtendedPublicKeyFunc: keystoreHelper.ExtendedPublicKey,\n\t}\n\tbb02BtcOnly := &keystoremock.KeystoreMock{\n\t\tRootFingerprintFunc: func() ([]byte, error) {\n\t\t\treturn fingerprint, nil\n\t\t},\n\t\tSupportsAccountFunc: func(coin coinpkg.Coin, meta interface{}) bool {\n\t\t\tswitch coin.(type) {\n\t\t\tcase *btc.Coin:\n\t\t\t\tscriptType := meta.(signing.ScriptType)\n\t\t\t\treturn coin.Code() == coinpkg.CodeBTC && scriptType != signing.ScriptTypeP2PKH\n\t\t\tdefault:\n\t\t\t\treturn false\n\t\t\t}\n\t\t},\n\t\tSupportsUnifiedAccountsFunc: func() bool {\n\t\t\treturn true\n\t\t},\n\t\tSupportsMultipleAccountsFunc: func() bool {\n\t\t\treturn true\n\t\t},\n\t\tExtendedPublicKeyFunc: keystoreHelper.ExtendedPublicKey,\n\t}\n\n\tb := newBackend(t, testnetDisabled, regtestDisabled)\n\tdefer b.Close()\n\n\t// Registering a new keystore persists a set of initial default accounts.\n\tb.registerKeystore(bb02Multi)\n\trequire.Len(t, b.Accounts(), 3)\n\trequire.Len(t, b.Config().AccountsConfig().Accounts, 3)\n\n\tb.DeregisterKeystore()\n\t// Registering a Bitcoin-only like keystore loads only the Bitcoin account, even though altcoins\n\t// were persisted previously.\n\tb.registerKeystore(bb02BtcOnly)\n\trequire.Len(t, b.Accounts(), 1)\n\trequire.Len(t, b.Config().AccountsConfig().Accounts, 3)\n}", "func TestCMAC(t *testing.T) {\n\tkey := \"2b7e151628aed2a6abf7158809cf4f3c\"\n\tk1 := \"fbeed618357133667c85e08f7236a8de\"\n\tk2 := \"f7ddac306ae266ccf90bc11ee46d513b\"\n\n\tkeyBytes, _ := hex.DecodeString(key)\n\tk1Bytes, _ := hex.DecodeString(k1)\n\tk2Bytes, _ := hex.DecodeString(k2)\n\n\t_, err := New(aes.NewCipher, nil)\n\tif err == nil {\n\t\tt.Fatal(\"unexpeced nil error\")\n\t}\n\n\tcm, err := New(aes.NewCipher, keyBytes)\n\tif err != nil {\n\t\tt.Fatal(\"unexpected error: \", err)\n\t}\n\ttmp := cm.(*cmac)\n\tif !bytes.Equal(tmp.k1, k1Bytes) {\n\t\tt.Errorf(\"k1 mismatch, got \\n %+v\\nexpected\\n %+v\", tmp.k1, k1)\n\t}\n\tif !bytes.Equal(tmp.k2, k2Bytes) {\n\t\tt.Errorf(\"k2 mismatch, got \\n %+v\\nexpected\\n %+v\", tmp.k2, k2)\n\t}\n\n\tif !Equal(keyBytes, keyBytes) {\n\t\tt.Errorf(\"got equal false, expected true\")\n\t}\n\tif Equal(keyBytes, k1Bytes) {\n\t\tt.Errorf(\"got equal true, expected false\")\n\t}\n\tif Equal(keyBytes, k1Bytes[:5]) {\n\t\tt.Errorf(\"got equal true, expected false\")\n\t}\n\n\tif cm.Size() != len(keyBytes) {\n\t\tt.Fatalf(\"expected Size %d, got %d\", len(keyBytes), cm.Size())\n\t}\n\n\tif cm.Size() != cm.BlockSize() {\n\t\tt.Fatalf(\"expected same Size and BlockSize\")\n\t}\n\n\ttests := []struct {\n\t\tmsg, mac string\n\t}{\n\t\t{\n\t\t\tmsg: \"\",\n\t\t\tmac: \"bb1d6929e95937287fa37d129b756746\",\n\t\t},\n\t\t{\n\t\t\tmsg: \"6bc1bee22e409f96e93d7e117393172a\",\n\t\t\tmac: \"070a16b46b4d4144f79bdd9dd04a287c\",\n\t\t},\n\t\t{\n\t\t\tmsg: \"6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e5130c81c46a35ce411\",\n\t\t\tmac: \"dfa66747de9ae63030ca32611497c827\",\n\t\t},\n\t\t{\n\t\t\tmsg: \"6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e5130c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710\",\n\t\t\tmac: \"51f0bebf7e3b9d92fc49741779363cfe\",\n\t\t},\n\t}\n\tfor i, test := range tests {\n\t\tcm.Reset()\n\t\tmsgBytes, _ := hex.DecodeString(test.msg)\n\t\tn, err := cm.Write(msgBytes)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"%2d: unexpected error: %s\", i, err)\n\t\t\tcontinue\n\t\t}\n\t\tif len(msgBytes) != n {\n\t\t\tt.Errorf(\"%2d: expect len %d, got %d\", i, len(msgBytes), n)\n\t\t\tcontinue\n\t\t}\n\t\tmacBytes, _ := hex.DecodeString(test.mac)\n\t\tif !Equal(cm.Sum(nil), macBytes) {\n\t\t\tt.Errorf(\"%2d: mac mismatch\", i)\n\t\t}\n\t}\n}", "func testBatchCTXStandardEntryClassCode(t testing.TB) {\n\tmockBatch := mockBatchCTX(t)\n\tmockBatch.Header.StandardEntryClassCode = WEB\n\terr := mockBatch.Create()\n\tif !base.Match(err, ErrBatchSECType) {\n\t\tt.Errorf(\"%T: %s\", err, err)\n\t}\n}", "func (t Ticker) IsCrypto() bool {\r\n\treturn strings.Compare(t.Exchange, \"CURRENCY\") == 0\r\n}", "func TestCheck(t *testing.T) {\n\t// Valid OCSP Must Staple Extension.\n\tvalidExtension := pkix.Extension{\n\t\tId: extensionOid,\n\t\tValue: expectedExtensionValue,\n\t\tCritical: false,\n\t}\n\t// Invalid OCSP Must Staple Extension: Critical field set to `true`.\n\tcriticalExtension := pkix.Extension{\n\t\tId: extensionOid,\n\t\tValue: expectedExtensionValue,\n\t\tCritical: true,\n\t}\n\t// Invalid OCSP Must Staple Extension: Wrong value.\n\twrongValueExtension := pkix.Extension{\n\t\tId: extensionOid,\n\t\tValue: []uint8{0xC0, 0xFF, 0xEE},\n\t\tCritical: false,\n\t}\n\t// Invalid OCSP Must Staple Extension: Wrong value, Critical field set to\n\t// `true`\n\twrongValueExtensionCritical := pkix.Extension{\n\t\tId: extensionOid,\n\t\tValue: []uint8{0xC0, 0xFF, 0xEE},\n\t\tCritical: true,\n\t}\n\n\ttestCases := []struct {\n\t\tName string\n\t\tInputEx pkix.Extension\n\t\tCertType string\n\t\tExpectedErrors []string\n\t}{\n\t\t{\n\t\t\tName: \"Valid: DV cert type\",\n\t\t\tInputEx: validExtension,\n\t\t\tCertType: \"DV\",\n\t\t\tExpectedErrors: []string{},\n\t\t},\n\t\t{\n\t\t\tName: \"Valid: OV cert type\",\n\t\t\tInputEx: validExtension,\n\t\t\tCertType: \"DV\",\n\t\t\tExpectedErrors: []string{},\n\t\t},\n\t\t{\n\t\t\tName: \"Valid: EV cert type\",\n\t\t\tInputEx: validExtension,\n\t\t\tCertType: \"DV\",\n\t\t\tExpectedErrors: []string{},\n\t\t},\n\t\t{\n\t\t\tName: \"Valid: CA cert type\",\n\t\t\tInputEx: validExtension,\n\t\t\tCertType: \"CA\",\n\t\t\tExpectedErrors: []string{},\n\t\t},\n\t\t{\n\t\t\tName: \"Invalid: OCSP cert type\",\n\t\t\tInputEx: validExtension,\n\t\t\tCertType: \"OCSP\",\n\t\t\tExpectedErrors: []string{\n\t\t\t\tcertTypeErr,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName: \"Invalid: critical extension\",\n\t\t\tInputEx: criticalExtension,\n\t\t\tCertType: \"DV\",\n\t\t\tExpectedErrors: []string{critExtErr},\n\t\t},\n\t\t{\n\t\t\tName: \"Invalid: critical extension, OCSP cert type\",\n\t\t\tInputEx: criticalExtension,\n\t\t\tCertType: \"OCSP\",\n\t\t\tExpectedErrors: []string{\n\t\t\t\tcertTypeErr, critExtErr,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName: \"Invalid: wrong extension value\",\n\t\t\tInputEx: wrongValueExtension,\n\t\t\tCertType: \"DV\",\n\t\t\tExpectedErrors: []string{\n\t\t\t\textValueErr,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName: \"Invalid: wrong extension value, critical extension, OCSP cert type\",\n\t\t\tInputEx: wrongValueExtensionCritical,\n\t\t\tCertType: \"OCSP\",\n\t\t\tExpectedErrors: []string{\n\t\t\t\tcertTypeErr, critExtErr, extValueErr,\n\t\t\t},\n\t\t},\n\t}\n\n\tfor _, tc := range testCases {\n\t\tt.Run(tc.Name, func(t *testing.T) {\n\t\t\tcertData := &certdata.Data{\n\t\t\t\tType: tc.CertType,\n\t\t\t}\n\t\t\t// Run the OCSP Must Staple check on the test data\n\t\t\terrors := Check(tc.InputEx, certData)\n\t\t\t// Collect the returned errors into a list\n\t\t\terrList := errors.List()\n\t\t\t// Verify the expected number of errors are in the list\n\t\t\tif len(tc.ExpectedErrors) != len(errList) {\n\t\t\t\tt.Errorf(\"wrong number of Check errors: expected %d, got %d\\n\",\n\t\t\t\t\tlen(tc.ExpectedErrors), len(errList))\n\t\t\t} else {\n\t\t\t\t// Match the error list to the expected error list\n\t\t\t\tfor i, err := range errList {\n\t\t\t\t\tif errMsg := err.Error(); errMsg != tc.ExpectedErrors[i] {\n\t\t\t\t\t\tt.Errorf(\"expected error %q at index %d, got %q\",\n\t\t\t\t\t\t\ttc.ExpectedErrors[i], i, errMsg)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n}", "func TestCryptoSignerInterfaceBehavior(t *testing.T) {\n\tcs := NewCryptoService(trustmanager.NewKeyMemoryStore(passphraseRetriever))\n\tinterfaces.EmptyCryptoServiceInterfaceBehaviorTests(t, cs)\n\tinterfaces.CreateGetKeyCryptoServiceInterfaceBehaviorTests(t, cs, data.ECDSAKey)\n\n\tcs = NewCryptoService(trustmanager.NewKeyMemoryStore(passphraseRetriever))\n\tinterfaces.CreateListKeyCryptoServiceInterfaceBehaviorTests(t, cs, data.ECDSAKey)\n\n\tcs = NewCryptoService(trustmanager.NewKeyMemoryStore(passphraseRetriever))\n\tinterfaces.AddGetKeyCryptoServiceInterfaceBehaviorTests(t, cs, data.ECDSAKey)\n\n\tcs = NewCryptoService(trustmanager.NewKeyMemoryStore(passphraseRetriever))\n\tinterfaces.AddListKeyCryptoServiceInterfaceBehaviorTests(t, cs, data.ECDSAKey)\n}", "func weakCipherSuites(details scan.LabsEndpointDetails) string {\n\t//Will require update as more vulnerabilities discovered, display results for TLS v1.2\n\t//https://github.com/ssllabs/research/wiki/SSL-and-TLS-Deployment-Best-Practices#23-use-secure-cipher-suites\n\tvar vulnSuites string\n\tfor _, suite := range details.Suites {\n\t\tfor _, suiteList := range suite.List {\n\t\t\tif !strings.Contains(suiteList.Name, \"DHE_\") {\n\t\t\t\tif suite.Protocol == 771 {\n\t\t\t\t\tvulnSuites += suiteList.Name + \"\\n\"\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn (vulnSuites)\n}", "func TestLicensingLogic(privKey, pubKey string) error {\n\tfmt.Println(\"*** TestLicensingLogic ***\")\n\n\texpDate := time.Date(2017, 7, 16, 0, 0, 0, 0, time.UTC)\n\tlicInfo := LicenseInfo{Name: \"Chathura Colombage\", Expiration: expDate}\n\n\tjsonLicInfo, err := json.Marshal(licInfo)\n\tif err != nil {\n\t\tfmt.Println(\"Error marshalling json data:\", err)\n\t\treturn err\n\t}\n\n\trsaPrivKey, err := ReadPrivateKeyFromFile(privKey)\n\tif err != nil {\n\t\tfmt.Println(\"Error reading private key:\", err)\n\t\treturn err\n\t}\n\n\tsignedData, err := Sign(rsaPrivKey, jsonLicInfo)\n\tif err != nil {\n\t\tfmt.Println(\"Error signing data:\", err)\n\t\treturn err\n\t}\n\n\tsignedDataBase64 := encodeKey(signedData)\n\tfmt.Println(\"Signed data:\", signedDataBase64)\n\n\t// rsaPrivKey.Sign(rand io.Reader, msg []byte, opts crypto.SignerOpts)\n\n\t// we need to sign jsonLicInfo using private key\n\n\tlicData := LicenseData{Info: licInfo, Key: signedDataBase64}\n\n\tjsonLicData, err := json.MarshalIndent(licData, \"\", \" \")\n\tif err != nil {\n\t\tfmt.Println(\"Error marshalling json data:\", err)\n\t\treturn err\n\t}\n\n\tfmt.Printf(\"License: \\n%s\\n\", jsonLicData)\n\n\tbackFromBase64, err := decodeKey(signedDataBase64)\n\tif err != nil {\n\t\tfmt.Println(\"Error decoding base64\")\n\t\treturn err\n\t}\n\n\t// Now we need to check whether we can verify this data or not\n\tpublicKey, err := ReadPublicKeyFromFile(pubKey)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := Unsign(publicKey, backFromBase64, signedData); err != nil {\n\t\tfmt.Println(\"Couldn't Sign!\")\n\t}\n\n\treturn nil\n}", "func RunChallenge11() {\n\tutil.PrintChallengeHeader(2, 11)\n\n\tplaintext := \"DUPLICATEBLOCKS!DUPLICATEBLOCKS!DUPLICATEBLOCKS!\"\n\tfor i := 0; i < 10; i++ {\n\t\tciphertext, _ := aes.EncryptRandom([]byte(plaintext))\n\t\tfmt.Println(hex.EncodeToString(ciphertext))\n\t\taesMode := aes.DetectAesMode(ciphertext, 16)\n\t\tswitch aesMode {\n\t\tcase aes.ECB:\n\t\t\tprintln(\"Probably AES ECB\")\n\t\tcase aes.CBC:\n\t\t\tprintln(\"Probably AES CBC\")\n\t\t}\n\t}\n}", "func TestDelegation(t *testing.T) {\n\tcsp, cleanup := newProvider(t, defaultOptions())\n\tdefer cleanup()\n\n\tk, err := csp.KeyGen(&bccsp.AES256KeyGenOpts{})\n\trequire.NoError(t, err)\n\n\tt.Run(\"KeyGen\", func(t *testing.T) {\n\t\tk, err := csp.KeyGen(&bccsp.AES256KeyGenOpts{})\n\t\trequire.NoError(t, err)\n\t\trequire.True(t, k.Private())\n\t\trequire.True(t, k.Symmetric())\n\t})\n\n\tt.Run(\"KeyDeriv\", func(t *testing.T) {\n\t\tk, err := csp.KeyDeriv(k, &bccsp.HMACDeriveKeyOpts{Arg: []byte{1}})\n\t\trequire.NoError(t, err)\n\t\trequire.True(t, k.Private())\n\t})\n\n\tt.Run(\"KeyImport\", func(t *testing.T) {\n\t\traw := make([]byte, 32)\n\t\t_, err := rand.Read(raw)\n\t\trequire.NoError(t, err)\n\n\t\tk, err := csp.KeyImport(raw, &bccsp.AES256ImportKeyOpts{})\n\t\trequire.NoError(t, err)\n\t\trequire.True(t, k.Private())\n\t})\n\n\tt.Run(\"GetKey\", func(t *testing.T) {\n\t\tk, err := csp.GetKey(k.SKI())\n\t\trequire.NoError(t, err)\n\t\trequire.True(t, k.Private())\n\t})\n\n\tt.Run(\"Hash\", func(t *testing.T) {\n\t\tdigest, err := csp.Hash([]byte(\"message\"), &bccsp.SHA3_384Opts{})\n\t\trequire.NoError(t, err)\n\t\trequire.NotEmpty(t, digest)\n\t})\n\n\tt.Run(\"GetHash\", func(t *testing.T) {\n\t\th, err := csp.GetHash(&bccsp.SHA256Opts{})\n\t\trequire.NoError(t, err)\n\t\trequire.Equal(t, sha256.New(), h)\n\t})\n\n\tt.Run(\"Sign\", func(t *testing.T) {\n\t\t_, err := csp.Sign(k, []byte(\"message\"), nil)\n\t\trequire.EqualError(t, err, \"Unsupported 'SignKey' provided [*sw.aesPrivateKey]\")\n\t})\n\n\tt.Run(\"Verify\", func(t *testing.T) {\n\t\t_, err := csp.Verify(k, []byte(\"signature\"), []byte(\"digest\"), nil)\n\t\trequire.Error(t, err)\n\t\trequire.Contains(t, err.Error(), \"Unsupported 'VerifyKey' provided\")\n\t})\n\n\tt.Run(\"EncryptDecrypt\", func(t *testing.T) {\n\t\tmsg := []byte(\"message\")\n\t\tct, err := csp.Encrypt(k, msg, &bccsp.AESCBCPKCS7ModeOpts{})\n\t\trequire.NoError(t, err)\n\n\t\tpt, err := csp.Decrypt(k, ct, &bccsp.AESCBCPKCS7ModeOpts{})\n\t\trequire.NoError(t, err)\n\t\trequire.Equal(t, msg, pt)\n\t})\n}", "func TestCommitMultipleKeys4A(t *testing.T) {\n}", "func (v2 *UniswapTestSuite) SetupSuite() {\n\tfmt.Println(\"Setting up the suite...\")\n\tvar err error\n\tv2.WETH = common.HexToAddress(\"0xd0a1e359811322d97991e03f863a0c30c2cf029c\")\n\tv2.EtherAddress = common.HexToAddress(\"0x0000000000000000000000000000000000000000\")\n\tv2.ETHUniswapRouterAddress = common.HexToAddress(\"0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D\")\n\tv2.DAIAddress = common.HexToAddress(\"0x4f96fe3b7a6cf9725f59d353f723c1bdb64ca6aa\")\n\tv2.MRKAddressStr = common.HexToAddress(\"0xef13c0c8abcaf5767160018d268f9697ae4f5375\")\n\tv2.EthPrivateKey = \"B8DB29A7A43FB88AD520F762C5FDF6F1B0155637FA1E5CB2C796AFE9E5C04E31\"\n\tv2.VaultAddress = common.HexToAddress(\"0xF92c6bb5206BEFD3c8305ddd64d554322cC22aFc\")\n\tv2.EthHost = \"https://kovan.infura.io/v3/93fe721349134964aa71071a713c5cef\"\n\tv2.UniswapProxy = common.HexToAddress(\"0xc7724A86ced6D95573d36fc4B98f9C0414B907a1\")\n\tv2.IncAddr = common.HexToAddress(\"0xf295681641c170359E04Bbe2EA3985BaA4CF0baf\")\n\tv2.connectToETH()\n\tv2.c = getFixedCommittee()\n\tv2.auth = bind.NewKeyedTransactor(v2.ETHPrivKey)\n\tv2.v, err = vault.NewVault(v2.VaultAddress, v2.ETHClient)\n\trequire.Equal(v2.T(), nil, err)\n\n\t// uncomment to deploy new one on kovan\n\t// incAddr, tx, _, err := incognito_proxy.DeployIncognitoProxy(v2.auth, v2.ETHClient, v2.auth.From, v2.c.beacons, v2.c.bridges)\n\t// require.Equal(v2.T(), nil, err)\n\t// // Wait until tx is confirmed\n\t// err = wait(v2.ETHClient, tx.Hash())\n\t// require.Equal(v2.T(), nil, err)\n\t// v2.IncAddr = incAddr\n\t// fmt.Printf(\"Proxy address: %s\\n\", v2.IncAddr.Hex())\n\n\t// delegatorAddr, tx, _, err := vault.DeployVault(v2.auth, v2.ETHClient)\n\t// require.Equal(v2.T(), nil, err)\n\t// err = wait(v2.ETHClient, tx.Hash())\n\t// require.Equal(v2.T(), nil, err)\n\t// fmt.Printf(\"delegatorAddr address: %s\\n\", delegatorAddr.Hex())\n\n\t// vaultAbi, _ := abi.JSON(strings.NewReader(vault.VaultABI))\n\t// input, _ := vaultAbi.Pack(\"initialize\", common.Address{})\t\n\n\t// v2.VaultAddress, tx, _, err = vaultproxy.DeployVaultproxy(v2.auth, v2.ETHClient, delegatorAddr, common.HexToAddress(\"0x0000000000000000000000000000000000000001\"), v2.IncAddr, input)\n\t// require.Equal(v2.T(), nil, err)\n\t// err = wait(v2.ETHClient, tx.Hash())\n\t// require.Equal(v2.T(), nil, err)\n\t// fmt.Printf(\"vault proxy address: %s\\n\", v2.VaultAddress.Hex())\n\n\t// v2.UniswapProxy, tx, _, err = uniswap.DeployUniswapV2Trade(v2.auth, v2.ETHClient, v2.ETHUniswapRouterAddress)\n\t// require.Equal(v2.T(), nil, err)\n\t// err = wait(v2.ETHClient, tx.Hash())\n\t// require.Equal(v2.T(), nil, err)\n\t// fmt.Printf(\"Uniswap proxy address: %s\\n\", v2.UniswapProxy.Hex())\n}", "func TestAesEnDecrytion(t *testing.T) {\n\t//需要16的倍数\n\tpriKey := randStr(32)\n\toriStr := randStr(32)\n\tfmt.Println(\"original: \", oriStr)\n\tencrypted, err := AesEncrypt([]byte(oriStr), []byte(priKey))\n\tif err != nil {\n\t\tt.Errorf(\"encrypt err: %s\\n\", err.Error())\n\t}\n\tfmt.Println(\"encryptd: \", encrypted)\n\n\toriginal, err := AesDecrypt(encrypted, []byte(priKey))\n\tif err != nil {\n\t\tt.Errorf(\"decrypt err: %s\\n\", err.Error())\n\t}\n\tfmt.Println(\"decryptd: \", original)\n\tif original != oriStr {\n\t\tt.Errorf(\"Decryption Error, old: %s, new: %s\", oriStr, original)\n\t}\n}", "func (mr *MockInternalServerMockRecorder) CryptoApiInvoke(arg0, arg1 interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"CryptoApiInvoke\", reflect.TypeOf((*MockInternalServer)(nil).CryptoApiInvoke), arg0, arg1)\n}", "func TestCreateValidBCCSPOptsForNewFabricClient(t *testing.T) {\n\tmockCtrl := gomock.NewController(t)\n\tdefer mockCtrl.Finish()\n\tmockConfig := mock_apiconfig.NewMockConfig(mockCtrl)\n\tclientMockObject := &config.ClientConfig{Organization: \"org1\", Logging: config.LoggingType{Level: \"info\"}, CryptoConfig: config.CCType{Path: \"test/path\"}}\n\n\tmockConfig.EXPECT().CAConfig(org1).Return(&config.CAConfig{}, nil)\n\tmockConfig.EXPECT().CAServerCertPaths(org1).Return([]string{\"test\"}, nil)\n\tmockConfig.EXPECT().CAClientCertPath(org1).Return(\"\", nil)\n\tmockConfig.EXPECT().CAClientKeyPath(org1).Return(\"\", nil)\n\tmockConfig.EXPECT().CAKeyStorePath().Return(os.TempDir())\n\tmockConfig.EXPECT().Client().Return(clientMockObject, nil)\n\tmockConfig.EXPECT().SecurityProvider().Return(\"SW\")\n\tmockConfig.EXPECT().SecurityAlgorithm().Return(\"SHA2\")\n\tmockConfig.EXPECT().SecurityLevel().Return(256)\n\tmockConfig.EXPECT().KeyStorePath().Return(\"/tmp/msp\")\n\tmockConfig.EXPECT().Ephemeral().Return(false)\n\n\tnewCryptosuiteProvider, err := cryptosuiteimpl.GetSuiteByConfig(mockConfig)\n\n\tif err != nil {\n\t\tt.Fatalf(\"Expected fabric client ryptosuite to be created with SW BCCS provider, but got %v\", err.Error())\n\t}\n\n\t_, err = NewFabricCAClient(org1, mockConfig, newCryptosuiteProvider)\n\tif err != nil {\n\t\tt.Fatalf(\"Expected fabric client to be created with SW BCCS provider, but got %v\", err.Error())\n\t}\n}", "func AssertCertificateHasServerAuthUsage(t *testing.T, cert *x509.Certificate) {\n\tfor i := range cert.ExtKeyUsage {\n\t\tif cert.ExtKeyUsage[i] == x509.ExtKeyUsageServerAuth {\n\t\t\treturn\n\t\t}\n\t}\n\tt.Error(\"cert is not a ServerAuth\")\n}", "func TestEnvelope(t *testing.T) {\n\tprivateKey, err := rsa.GenerateKey(rand.Reader, 2048)\n\trequire.NoError(t, err)\n\tpublicKey := &privateKey.PublicKey\n\n\t// Create a new Envelope with a payload\n\tpayload := &protocol.Payload{\n\t\tIdentity: &anypb.Any{},\n\t}\n\tidentity := &ivms101.LegalPerson{\n\t\tName: &ivms101.LegalPersonName{\n\t\t\tNameIdentifiers: []*ivms101.LegalPersonNameId{\n\t\t\t\t{\n\t\t\t\t\tLegalPersonName: \"John Doe\",\n\t\t\t\t\tLegalPersonNameIdentifierType: ivms101.LegalPersonLegal,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\tanypb.MarshalFrom(payload.Identity, identity, proto.MarshalOptions{})\n\tenvelope := handler.New(\"\", payload, nil)\n\trequire.NotNil(t, envelope)\n\trequire.NotEmpty(t, envelope.ID)\n\trequire.NotNil(t, envelope.Payload)\n\trequire.NotNil(t, envelope.Cipher)\n\n\t// Fail to seal the envelope with an unsupported key type\n\t_, err = envelope.Seal(nil)\n\trequire.Error(t, err)\n\t_, err = envelope.Seal(privateKey)\n\trequire.Error(t, err)\n\n\t// Seal the envelope with an RSA key\n\tsecure, err := envelope.Seal(publicKey)\n\trequire.NoError(t, err)\n\trequire.NotNil(t, secure)\n\trequire.Equal(t, envelope.ID, secure.Id)\n\trequire.Equal(t, envelope.Cipher.EncryptionAlgorithm(), secure.EncryptionAlgorithm)\n\trequire.Equal(t, envelope.Cipher.SignatureAlgorithm(), secure.HmacAlgorithm)\n\trequire.NotEmpty(t, secure.Payload)\n\trequire.NotEmpty(t, secure.Hmac)\n\trequire.NotEmpty(t, secure.EncryptionKey)\n\trequire.NotEmpty(t, secure.HmacSecret)\n\n\t// Fail to open a nil envelope\n\t_, err = handler.Open(nil, privateKey)\n\trequire.Error(t, err)\n\n\t// Fail to open an envelope with an invalid encryption algorithm\n\tsecure.EncryptionAlgorithm = \"invalid\"\n\t_, err = handler.Open(secure, privateKey)\n\trequire.Error(t, err)\n\n\t// Fail to open an envelope with an invalid hmac algorithm\n\tsecure.EncryptionAlgorithm = envelope.Cipher.EncryptionAlgorithm()\n\tsecure.HmacAlgorithm = \"invalid\"\n\t_, err = handler.Open(secure, privateKey)\n\trequire.Error(t, err)\n\n\t// Fail to open an envelope with an unsupported key type\n\tsecure.EncryptionAlgorithm = envelope.Cipher.EncryptionAlgorithm()\n\tsecure.HmacAlgorithm = envelope.Cipher.SignatureAlgorithm()\n\t_, err = handler.Open(secure, nil)\n\trequire.Error(t, err)\n\t_, err = handler.Open(secure, publicKey)\n\trequire.Error(t, err)\n\n\t// Fail to open the envelope using the wrong key\n\twrongKey, err := rsa.GenerateKey(rand.Reader, 2048)\n\trequire.NoError(t, err)\n\t_, err = handler.Open(secure, wrongKey)\n\trequire.Error(t, err)\n\n\t// Successfully opening an envelope\n\topened, err := handler.Open(secure, privateKey)\n\trequire.NoError(t, err)\n\trequire.NotNil(t, opened)\n\trequire.Equal(t, envelope.ID, opened.ID)\n\trequire.Equal(t, envelope.Cipher, opened.Cipher)\n\trequire.True(t, proto.Equal(envelope.Payload, opened.Payload), \"unexpected payload in opened envelope\")\n}", "func testBatchXCKCreditsOnly(t testing.TB) {\n\tmockBatch := mockBatchXCK(t)\n\tmockBatch.Header.ServiceClassCode = CreditsOnly\n\terr := mockBatch.Validate()\n\tif !base.Match(err, NewErrBatchHeaderControlEquality(CreditsOnly, 225)) {\n\t\tt.Errorf(\"%T: %s\", err, err)\n\t}\n}", "func TestSSHAuditorE2E(t *testing.T) {\n\tif testing.Short() {\n\t\tt.Skip(\"skipping test in short mode.\")\n\t}\n\tfor _, tt := range authTestCases {\n\t\tt.Run(fmt.Sprintf(\"TestSSHAuditorE2E(%q, %q, %q) => %q\", tt.hostport, tt.user, tt.password, tt.expected), func(t *testing.T) {\n\t\t\tstore, err := NewSQLiteStore(\":memory:\")\n\t\t\tif err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\t\t\terr = store.Init()\n\t\t\tif err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\n\t\t\tcred := Credential{\n\t\t\t\tUser: tt.user,\n\t\t\t\tPassword: tt.password,\n\t\t\t\tScanInterval: 1,\n\t\t\t}\n\t\t\t_, err = store.AddCredential(cred)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\n\t\t\tauditor := New(store)\n\t\t\tsc, ipport, err := makeScanConfig(tt.hostport)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\t\t\terr = auditor.Discover(sc)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\t\t\tar, err := auditor.Scan(sc)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\t\t\tif ar.totalCount != 1 {\n\t\t\t\tt.Errorf(\"totalCount != 1: %#v\", ar.totalCount)\n\t\t\t}\n\t\t\tvulns, err := auditor.Vulnerabilities()\n\t\t\tif err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\n\t\t\tif tt.expected != \"\" {\n\t\t\t\tif ar.posCount != 1 {\n\t\t\t\t\tt.Errorf(\"posCount != 1: %#v\", ar.posCount)\n\t\t\t\t}\n\t\t\t\tif ar.negCount != 0 {\n\t\t\t\t\tt.Errorf(\"negCount != 0: %#v\", ar.negCount)\n\t\t\t\t}\n\t\t\t\tif len(vulns) != 1 {\n\t\t\t\t\tt.Fatalf(\"len(vulns) != 1: %#v\", vulns)\n\t\t\t\t}\n\t\t\t\tif vulns[0].Host.Hostport != ipport {\n\t\t\t\t\tt.Errorf(\"vuln[0].hostport != %#v: %#v\", ipport, vulns)\n\t\t\t\t}\n\t\t\t\tif vulns[0].HostCredential.Result != tt.expected {\n\t\t\t\t\tt.Errorf(\"vuln[0].HostCredential.Result != %#v: %#v\", tt.expected, vulns)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif ar.posCount != 0 {\n\t\t\t\t\tt.Errorf(\"posCount != 0: %#v\", ar.posCount)\n\t\t\t\t}\n\t\t\t\tif ar.negCount != 1 {\n\t\t\t\t\tt.Errorf(\"negCount != 1: %#v\", ar.negCount)\n\t\t\t\t}\n\t\t\t\tif len(vulns) != 0 {\n\t\t\t\t\tt.Errorf(\"len(vulns) != 0: %#v\", vulns)\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n}", "func testBatchXCKMixedCreditsAndDebits(t testing.TB) {\n\tmockBatch := mockBatchXCK(t)\n\tmockBatch.Header.ServiceClassCode = MixedDebitsAndCredits\n\terr := mockBatch.Validate()\n\tif !base.Match(err, NewErrBatchHeaderControlEquality(MixedDebitsAndCredits, 225)) {\n\t\tt.Errorf(\"%T: %s\", err, err)\n\t}\n}", "func (m *MockisCryptoAsymApiReqSetupPrivateKeyEx_Key) isCryptoAsymApiReqSetupPrivateKeyEx_Key() {\n\tm.ctrl.Call(m, \"isCryptoAsymApiReqSetupPrivateKeyEx_Key\")\n}", "func (me TxsdPaymentMechanism) IsCs() bool { return me.String() == \"CS\" }", "func TestCheckTicketExhaustion(t *testing.T) {\n\t// Hardcoded values expected by the tests so they remain valid if network\n\t// parameters change.\n\tconst (\n\t\tcoinbaseMaturity = 16\n\t\tticketMaturity = 16\n\t\tticketsPerBlock = 5\n\t\tstakeEnabledHeight = coinbaseMaturity + ticketMaturity\n\t\tstakeValidationHeight = 144\n\t)\n\n\t// Create chain params based on regnet params with the specific values\n\t// overridden.\n\tparams := chaincfg.RegNetParams()\n\tparams.CoinbaseMaturity = coinbaseMaturity\n\tparams.TicketMaturity = ticketMaturity\n\tparams.TicketsPerBlock = ticketsPerBlock\n\tparams.StakeEnabledHeight = stakeEnabledHeight\n\tparams.StakeValidationHeight = stakeValidationHeight\n\n\t// ticketInfo is used to control the tests by specifying the details about\n\t// how many fake blocks to create with the specified number of tickets.\n\ttype ticketInfo struct {\n\t\tnumNodes uint32 // number of fake blocks to create\n\t\ttickets uint8 // number of tickets to buy in each block\n\t}\n\n\ttests := []struct {\n\t\tname string // test description\n\t\tticketInfo []ticketInfo // num blocks and tickets to construct\n\t\tnewBlockTix uint8 // num tickets in new block for check call\n\t\terr error // expected error\n\t}{{\n\t\t// Reach inevitable ticket exhaustion by not including any ticket\n\t\t// purchases up to and including the final possible block prior to svh\n\t\t// that can prevent it.\n\t\tname: \"guaranteed exhaustion prior to svh\",\n\t\tticketInfo: []ticketInfo{\n\t\t\t{126, 0}, // height: 126, 0 live, 0 immature\n\t\t},\n\t\tnewBlockTix: 0, // extending height: 126, 0 live, 0 immature\n\t\terr: ErrTicketExhaustion,\n\t}, {\n\t\t// Reach inevitable ticket exhaustion by not including any ticket\n\t\t// purchases up to just before the final possible block prior to svh\n\t\t// that can prevent it and only include enough tickets in that final\n\t\t// block such that it is one short of the required amount.\n\t\tname: \"one ticket short in final possible block prior to svh\",\n\t\tticketInfo: []ticketInfo{\n\t\t\t{126, 0}, // height: 126, 0 live, 0 immature\n\t\t},\n\t\tnewBlockTix: 4, // extending height: 126, 0 live, 4 immature\n\t\terr: ErrTicketExhaustion,\n\t}, {\n\t\t// Construct chain such that there are no ticket purchases up to just\n\t\t// before the final possible block prior to svh that can prevent ticket\n\t\t// exhaustion and that final block contains the exact amount of ticket\n\t\t// purchases required to prevent it.\n\t\tname: \"just enough in final possible block prior to svh\",\n\t\tticketInfo: []ticketInfo{\n\t\t\t{126, 0}, // height: 126, 0 live, 0 immature\n\t\t},\n\t\tnewBlockTix: 5, // extending height: 126, 0 live, 5 immature\n\t\terr: nil,\n\t}, {\n\t\t// Reach inevitable ticket exhaustion with one live ticket less than\n\t\t// needed to prevent it at the first block which ticket exhaustion can\n\t\t// happen.\n\t\tname: \"one ticket short with live tickets at 1st possible exhaustion\",\n\t\tticketInfo: []ticketInfo{\n\t\t\t{16, 0}, // height: 16, 0 live, 0 immature\n\t\t\t{1, 4}, // height: 17, 0 live, 4 immature\n\t\t\t{109, 0}, // height: 126, 4 live, 0 immature\n\t\t},\n\t\tnewBlockTix: 0, // extending height: 126, 4 live, 0 immature\n\t\terr: ErrTicketExhaustion,\n\t}, {\n\t\tname: \"just enough live tickets at 1st possible exhaustion\",\n\t\tticketInfo: []ticketInfo{\n\t\t\t{16, 0}, // height: 16, 0 live, 0 immature\n\t\t\t{1, 5}, // height: 17, 0 live, 5 immature\n\t\t\t{109, 0}, // height: 126, 5 live, 0 immature\n\t\t},\n\t\tnewBlockTix: 0, // extending height: 126, 5 live, 0 immature\n\t\terr: nil,\n\t}, {\n\t\t// Reach inevitable ticket exhaustion in the second possible block that\n\t\t// it can happen. Notice this means it consumes the exact number of\n\t\t// live tickets in the first block that ticket exhaustion can happen.\n\t\tname: \"exhaustion at 2nd possible block, five tickets short\",\n\t\tticketInfo: []ticketInfo{\n\t\t\t{16, 0}, // height: 16, 0 live, 0 immature\n\t\t\t{1, 5}, // height: 17, 0 live, 5 immature\n\t\t\t{110, 0}, // height: 127, 5 live, 0 immature\n\t\t},\n\t\tnewBlockTix: 0, // extending height: 127, 5 live, 0 immature\n\t\terr: ErrTicketExhaustion,\n\t}, {\n\t\t// Reach inevitable ticket exhaustion in the second possible block that\n\t\t// it can happen with one live ticket less than needed to prevent it.\n\t\tname: \"exhaustion at 2nd possible block, one ticket short\",\n\t\tticketInfo: []ticketInfo{\n\t\t\t{16, 0}, // height: 16, 0 live, 0 immature\n\t\t\t{1, 9}, // height: 17, 0 live, 9 immature\n\t\t\t{110, 0}, // height: 127, 9 live, 0 immature\n\t\t},\n\t\tnewBlockTix: 0, // extending height: 127, 9 live, 0 immature\n\t\terr: ErrTicketExhaustion,\n\t}, {\n\t\t// Construct chain to one block before svh such that there are exactly\n\t\t// enough live tickets to prevent exhaustion.\n\t\tname: \"just enough to svh-1 with live tickets\",\n\t\tticketInfo: []ticketInfo{\n\t\t\t{36, 0}, // height: 36, 0 live, 0 immature\n\t\t\t{4, 20}, // height: 40, 0 live, 80 immature\n\t\t\t{1, 5}, // height: 41, 0 live, 85 immature\n\t\t\t{101, 0}, // height: 142, 85 live, 0 immature\n\t\t},\n\t\tnewBlockTix: 0, // extending height: 142, 85 live, 0 immature\n\t\terr: nil,\n\t}, {\n\t\t// Construct chain to one block before svh such that there is a mix of\n\t\t// live and immature tickets that sum to exactly enough prevent\n\t\t// exhaustion.\n\t\tname: \"just enough to svh-1 with mix of live and immature tickets\",\n\t\tticketInfo: []ticketInfo{\n\t\t\t{36, 0}, // height: 36, 0 live, 0 immature\n\t\t\t{3, 20}, // height: 39, 0 live, 60 immature\n\t\t\t{1, 15}, // height: 40, 0 live, 75 immature\n\t\t\t{101, 0}, // height: 141, 75 live, 0 immature\n\t\t\t{1, 5}, // height: 142, 75 live, 5 immature\n\t\t},\n\t\tnewBlockTix: 5, // extending height: 142, 75 live, 10 immature\n\t\terr: nil,\n\t}, {\n\t\t// Construct chain to svh such that there are exactly enough live\n\t\t// tickets to prevent exhaustion.\n\t\tname: \"just enough to svh with live tickets\",\n\t\tticketInfo: []ticketInfo{\n\t\t\t{32, 0}, // height: 32, 0 live, 0 immature\n\t\t\t{4, 20}, // height: 36, 0 live, 80 immature\n\t\t\t{1, 10}, // height: 37, 0 live, 90 immature\n\t\t\t{106, 0}, // height: 143, 90 live, 0 immature\n\t\t},\n\t\tnewBlockTix: 0, // extending height: 143, 90 live, 0 immature\n\t\terr: nil,\n\t}, {\n\t\t// Construct chain to svh such that there are exactly enough live\n\t\t// tickets just becoming mature to prevent exhaustion.\n\t\tname: \"just enough to svh with maturing\",\n\t\tticketInfo: []ticketInfo{\n\t\t\t{126, 0}, // height: 126, 0 live, 0 immature\n\t\t\t{16, 5}, // height: 142, 0 live, 80 immature\n\t\t\t{1, 5}, // height: 143, 5 live, 80 immature\n\t\t},\n\t\tnewBlockTix: 5, // extending height: 143, 5 live, 80 immature\n\t\terr: nil,\n\t}, {\n\t\t// Reach inevitable ticket exhaustion after creating a large pool of\n\t\t// live tickets and allowing the live ticket pool to dwindle due to\n\t\t// votes without buying more any more tickets.\n\t\tname: \"exhaustion due to dwindling live tickets w/o new purchases\",\n\t\tticketInfo: []ticketInfo{\n\t\t\t{126, 0}, // height: 126, 0 live, 0 immature\n\t\t\t{25, 20}, // height: 151, 140 live, 360 immature\n\t\t\t{75, 0}, // height: 226, 85 live, 0 immature\n\t\t},\n\t\tnewBlockTix: 0, // extending height: 226, 85 live, 0 immature\n\t\terr: ErrTicketExhaustion,\n\t}}\n\n\tfor _, test := range tests {\n\t\tbc := newFakeChain(params)\n\n\t\t// immatureTickets tracks which height the purchased tickets will mature\n\t\t// and thus be eligible for admission to the live ticket pool.\n\t\timmatureTickets := make(map[int64]uint8)\n\t\tvar poolSize uint32\n\t\tnode := bc.bestChain.Tip()\n\t\tblockTime := time.Unix(node.timestamp, 0)\n\t\tfor _, ticketInfo := range test.ticketInfo {\n\t\t\tfor i := uint32(0); i < ticketInfo.numNodes; i++ {\n\t\t\t\tblockTime = blockTime.Add(time.Second)\n\t\t\t\tnode = newFakeNode(node, 1, 1, 0, blockTime)\n\t\t\t\tnode.poolSize = poolSize\n\t\t\t\tnode.freshStake = ticketInfo.tickets\n\n\t\t\t\t// Update the pool size for the next header. Notice how tickets\n\t\t\t\t// that mature for this block do not show up in the pool size\n\t\t\t\t// until the next block. This is correct behavior.\n\t\t\t\tpoolSize += uint32(immatureTickets[node.height])\n\t\t\t\tdelete(immatureTickets, node.height)\n\t\t\t\tif node.height >= stakeValidationHeight {\n\t\t\t\t\tpoolSize -= ticketsPerBlock\n\t\t\t\t}\n\n\t\t\t\t// Track maturity height for new ticket purchases.\n\t\t\t\tmaturityHeight := node.height + ticketMaturity\n\t\t\t\timmatureTickets[maturityHeight] = ticketInfo.tickets\n\n\t\t\t\t// Add the new fake node to the block index and update the chain\n\t\t\t\t// to use it as the new best node.\n\t\t\t\tbc.index.AddNode(node)\n\t\t\t\tbc.bestChain.SetTip(node)\n\n\t\t\t\t// Ensure the test data does not have any invalid intermediate\n\t\t\t\t// states leading up to the final test condition.\n\t\t\t\tparentHash := &node.parent.hash\n\t\t\t\terr := bc.CheckTicketExhaustion(parentHash, ticketInfo.tickets)\n\t\t\t\tif err != nil {\n\t\t\t\t\tt.Errorf(\"%q: unexpected err: %v\", test.name, err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Ensure the expected result is returned from ticket exhaustion check.\n\t\terr := bc.CheckTicketExhaustion(&node.hash, test.newBlockTix)\n\t\tif !errors.Is(err, test.err) {\n\t\t\tt.Errorf(\"%q: mismatched err -- got %v, want %v\", test.name, err,\n\t\t\t\ttest.err)\n\t\t\tcontinue\n\t\t}\n\t}\n}", "func TestEncryptionEncryptByPassPhrase(t *testing.T) {\n\tpassPhrase := \"123\"\n\tplaintext := []byte{1, 2, 3, 4}\n\n\tciphertextStr, err := encryptByPassPhrase(passPhrase, plaintext)\n\tfmt.Println(\"ciphertextStr : \", ciphertextStr)\n\n\tassert.Equal(t, nil, err)\n\tassert.Greater(t, len(ciphertextStr), 0)\n\n\tplaintext2, err := decryptByPassPhrase(passPhrase, ciphertextStr)\n\tassert.Equal(t, plaintext, plaintext2)\n}", "func NewSuite(kemID KEM, kdfID KDF, aeadID AEAD) Suite {\n\ts := Suite{kemID, kdfID, aeadID}\n\tif !s.isValid() {\n\t\tpanic(ErrInvalidHPKESuite)\n\t}\n\treturn s\n}", "func TestSingleCommit4A(t *testing.T) {\n}", "func TestChallenge12(test *testing.T) {\n\t// Feed identical bytes of your-string to the function 1 at a time --- start with 1 byte (\"A\"),\n\t// then \"AA\", then \"AAA\" and so on. Discover the block size of the cipher. You know it, but do this step anyway.\n\toracle := challenge12Oracle{key(16)}\n\tblockSize, err := unsafeaes.DetectBlockSize(oracle)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tif blockSize != 16 {\n\t\ttest.Errorf(\"Expected block size to be 16 but was %d\", blockSize)\n\t}\n\n\t// Detect that the function is using ECB. You already know, but do this step anyways.\n\tmode, err := unsafeaes.DetectMode(oracle)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tif mode != \"ECB\" {\n\t\ttest.Errorf(\"Expected to detect AES mode ECB, but instead detected %s\", mode)\n\t}\n\n\t// Knowing the block size, craft an input block that is exactly 1 byte short (for instance, if the block size is\n\t// 8 bytes, make \"AAAAAAA\"). Think about what the oracle function is going to put in that last byte position.\n\tplaintextSize, err := findTextLength(oracle)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// round up to the nearest full block size, so we have enough capacity\n\t// in our chosen text to slurp up the target text char by char\n\tblocks := (plaintextSize / blockSize) + 1\n\tplaintext := make([]byte, 0, plaintextSize)\n\tattackSize := blocks * blockSize\n\n\tfor i := 1; i < plaintextSize; i++ {\n\t\tchosentext := make([]byte, attackSize-i)\n\t\t// Make a dictionary of every possible last byte by feeding different strings to the oracle; for instance, \"AAAAAAAA\",\n\t\t// \"AAAAAAAB\", \"AAAAAAAC\", remembering the first block of each invocation.\n\t\tlastbyte := make(map[string]byte)\n\n\t\tfor b := 0; b < 256; b++ {\n\t\t\tknowntext := append(chosentext, plaintext...)\n\t\t\ttesttext := append(knowntext, byte(b))\n\t\t\tciphertext, err := oracle.Encrypt(testtext)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\tattackBlocks := ciphertext[:attackSize]\n\t\t\tlastbyte[encodings.BytesToHex(attackBlocks)] = byte(b)\n\t\t}\n\n\t\tciphertext, err := oracle.Encrypt(chosentext)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\t// Match the output of the one-byte-short input to one of the entries in your dictionary.\n\t\t// You've now discovered the first byte of unknown-string.\n\t\tattackBlocks := ciphertext[:attackSize]\n\t\tdecodedByte := lastbyte[encodings.BytesToHex(attackBlocks)]\n\t\tplaintext = append(plaintext, decodedByte)\n\t}\n\n\texpected := \"Rollin' in my 5.0\\n\" +\n\t\t\"With my rag-top down so my hair can blow\\n\" +\n\t\t\"The girlies on standby waving just to say hi\\n\" +\n\t\t\"Did you stop? No, I just drove by\"\n\tif string(plaintext) != expected {\n\t\ttest.Errorf(\"Expected:\\n%s\\nActual:\\n%s\\n\", expected, string(plaintext))\n\t}\n}", "func (c CryptoServiceTester) TestSignNoMatchingKeys(t *testing.T) {\n\tcryptoService := c.cryptoServiceFactory()\n\n\tprivKey, err := utils.GenerateECDSAKey(rand.Reader)\n\trequire.NoError(t, err, c.errorMsg(\"error creating key\"))\n\n\t// Test Sign\n\t_, _, err = cryptoService.GetPrivateKey(privKey.ID())\n\trequire.Error(t, err, c.errorMsg(\"Should not have found private key\"))\n}", "func (s *SignSuite) TearDownTest(c *C) {\n}", "func (m *MockisCryptoApiRequest_CryptoApiReq) isCryptoApiRequest_CryptoApiReq() {\n\tm.ctrl.Call(m, \"isCryptoApiRequest_CryptoApiReq\")\n}", "func parseCipherSuite(ids []string) []uint16 {\n\tciphers := []uint16{}\n\n\tcorrespondenceMap := map[string]uint16{\n\t\t\"TLS_RSA_WITH_RC4_128_SHA\": tls.TLS_RSA_WITH_RC4_128_SHA,\n\t\t\"TLS_RSA_WITH_3DES_EDE_CBC_SHA\": tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA,\n\t\t\"TLS_RSA_WITH_AES_128_CBC_SHA\": tls.TLS_RSA_WITH_AES_128_CBC_SHA,\n\t\t\"TLS_RSA_WITH_AES_256_CBC_SHA\": tls.TLS_RSA_WITH_AES_256_CBC_SHA,\n\t\t\"TLS_RSA_WITH_AES_128_CBC_SHA256\": tls.TLS_RSA_WITH_AES_128_CBC_SHA256,\n\t\t\"TLS_RSA_WITH_AES_128_GCM_SHA256\": tls.TLS_RSA_WITH_AES_128_GCM_SHA256,\n\t\t\"TLS_RSA_WITH_AES_256_GCM_SHA384\": tls.TLS_RSA_WITH_AES_256_GCM_SHA384,\n\t\t\"TLS_ECDHE_ECDSA_WITH_RC4_128_SHA\": tls.TLS_ECDHE_ECDSA_WITH_RC4_128_SHA,\n\t\t\"TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA\": tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,\n\t\t\"TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA\": tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,\n\t\t\"TLS_ECDHE_RSA_WITH_RC4_128_SHA\": tls.TLS_ECDHE_RSA_WITH_RC4_128_SHA,\n\t\t\"TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA\": tls.TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA,\n\t\t\"TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA\": tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,\n\t\t\"TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA\": tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,\n\t\t\"TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256\": tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256,\n\t\t\"TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256\": tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256,\n\t\t\"TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256\": tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,\n\t\t\"TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256\": tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,\n\t\t\"TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384\": tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,\n\t\t\"TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384\": tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,\n\t\t\"TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305\": tls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,\n\t\t\"TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305\": tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,\n\t}\n\n\tfor _, id := range ids {\n\t\tid = strings.ToUpper(id)\n\t\tif cipher, ok := correspondenceMap[id]; ok {\n\t\t\tciphers = append(ciphers, cipher)\n\t\t} else {\n\t\t\tlogger.Fatalf(\"unknown '%s' cipher\", id)\n\t\t}\n\t}\n\n\treturn ciphers\n}", "func (m *MockProviders) CryptoSuite() core.CryptoSuite {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"CryptoSuite\")\n\tret0, _ := ret[0].(core.CryptoSuite)\n\treturn ret0\n}", "func TestEncapsulateSanity(t *testing.T) {\n\tpacket := Packet6(relayForwBytes)\n\tstartXid, err := packet.XID()\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to extract XId: %s\", err)\n\t}\n\n\tencapsulated := packet.Encapsulate(nil)\n\t// dhcp6message type should be SOLICIT\n\tmsg, err := encapsulated.dhcp6message()\n\tmsgType, _ := msg.Type()\n\tif msgType != Solicit {\n\t\tt.Fatalf(\"Expected type %s, got %s\", Solicit, msgType)\n\t}\n\t// XID should be the same after encapsulating\n\tencXid, err := encapsulated.XID()\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to extract XId from encapsulated message\")\n\t}\n\tif startXid != encXid {\n\t\tt.Fatalf(\"Expected xid 0x%x but got 0x%x\", startXid, encXid)\n\t}\n}", "func (s *ServiceSuite) TestMacaroonPaperFig6FailsWithoutDischarges(c *gc.C) {\n\tlocator := bakery.NewThirdPartyStore()\n\tts := newBakery(\"ts-loc\", locator)\n\tfs := newBakery(\"fs-loc\", locator)\n\tnewBakery(\"as-loc\", locator)\n\n\t// ts creates a macaroon.\n\ttsMacaroon, err := ts.Oven.NewMacaroon(testContext, bakery.LatestVersion, ages, nil, bakery.LoginOp)\n\tc.Assert(err, gc.IsNil)\n\n\t// ts somehow sends the macaroon to fs which adds a third party caveat to be discharged by as.\n\terr = fs.Oven.AddCaveat(testContext, tsMacaroon, checkers.Caveat{Location: \"as-loc\", Condition: \"user==bob\"})\n\tc.Assert(err, gc.IsNil)\n\n\t// client makes request to ts\n\t_, err = ts.Checker.Auth(macaroon.Slice{tsMacaroon.M()}).Allow(testContext, bakery.LoginOp)\n\tc.Assert(err, gc.ErrorMatches, `verification failed: cannot find discharge macaroon for caveat .*`, gc.Commentf(\"%#v\", err))\n}", "func TestAuthenticateFail(t *testing.T) {\n\tfmt.Println(\"\\nRunning TestAuthenticateFail...\")\n\ttr := NewTestRunner(t)\n\n\tassert.NoError(t, useOCSMockDriver())\n\tassert.NoError(t, usePCRFMockDriver())\n\tdefer func() {\n\t\t// Clear hss, ocs, and pcrf\n\t\tassert.NoError(t, clearOCSMockDriver())\n\t\tassert.NoError(t, clearPCRFMockDriver())\n\t\tassert.NoError(t, tr.CleanUp())\n\t}()\n\n\tues, err := tr.ConfigUEs(2)\n\tassert.NoError(t, err)\n\n\t// ----- Gx CCR-I fail -> Authentication fails -----\n\timsi := ues[0].GetImsi()\n\tgxInitReq := protos.NewGxCCRequest(imsi, protos.CCRequestType_INITIAL)\n\tgxInitAns := protos.NewGxCCAnswer(diam.AuthenticationRejected)\n\tgxInitExpectation := protos.NewGxCreditControlExpectation().Expect(gxInitReq).Return(gxInitAns)\n\n\tdefaultGxAns := protos.NewGxCCAnswer(diam.AuthenticationRejected)\n\tassert.NoError(t, setPCRFExpectations([]*protos.GxCreditControlExpectation{gxInitExpectation}, defaultGxAns))\n\n\ttr.AuthenticateAndAssertFail(imsi)\n\ttr.AssertAllGxExpectationsMetNoError()\n\n\t// Since CCR/A-I failed, pipelined should see no rules installed\n\ttr.AssertPolicyEnforcementRecordIsNil(imsi)\n\n\t// ----- Gx CCR-I success && Gy CCR-I fail -> Authentication fails -----\n\timsi = ues[1].GetImsi()\n\tgxInitReq = protos.NewGxCCRequest(imsi, protos.CCRequestType_INITIAL)\n\tgxInitAns = protos.NewGxCCAnswer(diam.Success).\n\t\tSetDynamicRuleInstall(getPassAllRuleDefinition(\"rule1\", \"\", swag.Uint32(1), 0))\n\tgxInitExpectation = gxInitExpectation.Expect(gxInitReq).Return(gxInitAns)\n\tassert.NoError(t, setPCRFExpectations([]*protos.GxCreditControlExpectation{gxInitExpectation}, defaultGxAns))\n\t// Fail on Gy\n\tgyInitReq := protos.NewGyCCRequest(imsi, protos.CCRequestType_INITIAL)\n\tgyInitAns := protos.NewGyCCAnswer(diam.AuthenticationRejected)\n\tgyInitExpectation := protos.NewGyCreditControlExpectation().Expect(gyInitReq).Return(gyInitAns)\n\tdefaultGyAns := gyInitAns\n\tassert.NoError(t, setOCSExpectations([]*protos.GyCreditControlExpectation{gyInitExpectation}, defaultGyAns))\n\n\ttr.AuthenticateAndAssertFail(imsi)\n\t// assert gx & gy init was received\n\ttr.AssertAllGxExpectationsMetNoError()\n\ttr.AssertAllGyExpectationsMetNoError()\n\n\t// Since CCR/A-I failed, pipelined should see no rules installed\n\ttr.AssertPolicyEnforcementRecordIsNil(imsi)\n}", "func (mysuit *MySuite) TestSmcManager_DeployContract(c *check.C) {\n\tutest.Init(orgID)\n\tcontractOwner := utest.DeployContract(c, contractName, orgID, contractMethods, contractInterfaces)\n\ttest := NewTestObject(contractOwner)\n\torgID := test.obj.sdk.Helper().BlockChainHelper().CalcOrgID(\"testOrg\")\n\tnewOrganization := std.Organization{\n\t\tOrgID: orgID,\n\t\tName: \"testOrg\",\n\t\tOrgOwner: test.obj.sdk.Message().Sender().Address(),\n\t\tContractAddrList: []types.Address{},\n\t\tOrgCodeHash: []byte{},\n\t}\n\ttest.obj.sdk.Helper().StateHelper().Set(\"/organization/\"+orgID, &newOrganization)\n\ttest.obj.sdk.Helper().StateHelper().Set(\"/organization/\"+test.obj.sdk.Message().Contract().OrgID(), &std.Organization{\n\t\tOrgID: test.obj.sdk.Message().Contract().OrgID(),\n\t\tOrgOwner: test.obj.sdk.Message().Sender().Address(),\n\t})\n\n\t// 部署新的合约和基础组织部署或者升级合约\n\ttestCases := []struct {\n\t\tname string\n\t\tversion string\n\t\torgID string\n\t\tcodeHash types.Hash\n\t\tcodeData []byte\n\t\tcodeDevSig string\n\t\tcodeOrgSig string\n\t\teffectHeight int64\n\t\terr types.Error\n\t}{\n\t\t{\"testName\", \"v1.0\", orgID, []byte(\"test\"), []byte(\"hello\"), \"test\", \"test\", test.obj.sdk.Block().Height() + 2, types.Error{ErrorCode: types.ErrNoAuthorization}},\n\t\t{\"\", \"v1.0\", orgID, []byte(\"test\"), []byte(\"hello\"), \"test\", \"test\", test.obj.sdk.Block().Height() + 3, types.Error{ErrorCode: types.ErrInvalidParameter}},\n\t\t{\"testName\", \"\", orgID, []byte(\"test\"), []byte(\"hello\"), \"test\", \"test\", test.obj.sdk.Block().Height() + 3, types.Error{ErrorCode: types.ErrNoAuthorization}},\n\t\t{\"testNameA\", \"v1.0\", \"\", []byte(\"test\"), []byte(\"hello\"), \"test\", \"test\", test.obj.sdk.Block().Height() + 3, types.Error{ErrorCode: types.ErrInvalidParameter}},\n\t\t{\"testNameB\", \"v1.0\", orgID, []byte{}, []byte(\"hello\"), \"test\", \"test\", test.obj.sdk.Block().Height() + 3, types.Error{ErrorCode: types.ErrNoAuthorization}},\n\t\t{\"testNameC\", \"v1.0\", orgID, []byte(\"test\"), []byte{}, \"test\", \"test\", test.obj.sdk.Block().Height() + 3, types.Error{ErrorCode: types.ErrNoAuthorization}},\n\t\t{\"testNameD\", \"v1.0\", orgID, []byte(\"test\"), []byte(\"hello\"), \"\", \"test\", test.obj.sdk.Block().Height() + 3, types.Error{ErrorCode: types.ErrNoAuthorization}},\n\t\t{\"testNameE\", \"v1.0\", orgID, []byte(\"test\"), []byte(\"hello\"), \"test\", \"\", test.obj.sdk.Block().Height() + 3, types.Error{ErrorCode: types.ErrNoAuthorization}},\n\t\t{\"testNameF\", \"v1.0\", orgID, []byte(\"test\"), []byte(\"hello\"), \"test\", \"test\", 0, types.Error{ErrorCode: types.ErrNoAuthorization}},\n\t\t{\"testNameG\", \"v1.0\", orgID, []byte(\"test\"), []byte(\"hello\"), \"test\", \"test\", test.obj.sdk.Block().Height() - 2, types.Error{ErrorCode: types.ErrNoAuthorization}},\n\t\t{\"testNameH\", \"v1.0\", orgID + \"test\", []byte(\"test\"), []byte(\"hello\"), \"test\", \"test\", test.obj.sdk.Block().Height() + 50, types.Error{ErrorCode: types.ErrInvalidParameter}},\n\t\t{\"testNameI\", \"v1.0\", test.obj.sdk.Message().Contract().OrgID(), []byte(\"test\"), []byte(\"hello\"), \"test\", \"test\", test.obj.sdk.Block().Height() + 100, types.Error{ErrorCode: types.ErrNoAuthorization}},\n\t\t{\"testName\", \"v1.0\", test.obj.sdk.Message().Contract().OrgID(), []byte(\"test\"), []byte(\"hello\"), \"test\", \"test\", test.obj.sdk.Block().Height() + 200, types.Error{ErrorCode: types.ErrNoAuthorization}},\n\t\t{\"testNameI\", \"v1.1\", test.obj.sdk.Message().Contract().OrgID(), []byte(\"testA\"), []byte(\"helloA\"), \"test\", \"test\", test.obj.sdk.Block().Height() + 200, types.Error{ErrorCode: types.ErrNoAuthorization}},\n\t}\n\n\tfor i, v := range testCases {\n\t\tconAddr, err := test.run().setSender(contractOwner).DeployContract(v.name, v.version, v.orgID, v.codeHash, v.codeData, v.codeDevSig, v.codeOrgSig, v.effectHeight)\n\t\tfmt.Println(i)\n\t\tutest.AssertError(err, v.err.ErrorCode)\n\t\tif err.ErrorCode == types.CodeOK {\n\t\t\tutest.Assert(conAddr ==\n\t\t\t\ttest.obj.sdk.Helper().BlockChainHelper().CalcContractAddress(v.name, v.version, test.obj.sdk.Message().Contract().Owner().Address()))\n\n\t\t\tvar preFix string\n\t\t\tif v.orgID != test.obj.sdk.Message().Contract().OrgID() {\n\t\t\t\tpreFix = \"/\" + orgID + \"/\" + v.name\n\t\t\t} else {\n\t\t\t\tpreFix = \"\"\n\t\t\t}\n\t\t\t// 检查合约信息\n\t\t\tutest.AssertSDB(test.obj.sdk.Message().Contract().KeyPrefix()+\"/contract/\"+conAddr, std.Contract{\n\t\t\t\tAddress: conAddr,\n\t\t\t\tAccount: test.obj.sdk.Helper().BlockChainHelper().CalcAccountFromName(v.name, orgID),\n\t\t\t\tOwner: test.obj.sdk.Message().Contract().Owner().Address(),\n\t\t\t\tName: v.name,\n\t\t\t\tVersion: v.version,\n\t\t\t\tCodeHash: v.codeHash,\n\t\t\t\tEffectHeight: v.effectHeight,\n\t\t\t\tLoseHeight: 0,\n\t\t\t\tKeyPrefix: preFix,\n\t\t\t\tMethods: nil, // 与 build 返回一致\n\t\t\t\tInterfaces: nil,\n\t\t\t\tToken: \"\",\n\t\t\t\tOrgID: v.orgID,\n\t\t\t})\n\n\t\t\t// 检查合约元数据\n\t\t\tcodeDevSigBytes, _ := jsoniter.Marshal(v.codeDevSig)\n\t\t\tcodeOrgSigBytes, _ := jsoniter.Marshal(v.codeOrgSig)\n\t\t\tutest.AssertSDB(test.obj.sdk.Message().Contract().KeyPrefix()+\"/contract/code/\"+conAddr, std.ContractMeta{\n\t\t\t\tName: v.name,\n\t\t\t\tContractAddr: conAddr,\n\t\t\t\tOrgID: v.orgID,\n\t\t\t\tEffectHeight: v.effectHeight,\n\t\t\t\tLoseHeight: 0,\n\t\t\t\tCodeData: v.codeData,\n\t\t\t\tCodeHash: v.codeHash,\n\t\t\t\tCodeDevSig: codeDevSigBytes,\n\t\t\t\tCodeOrgSig: codeOrgSigBytes,\n\t\t\t})\n\n\t\t\t// 检查组织信息\n\t\t\torgInfo := test.obj.sdk.Helper().StateHelper().Get(\"/organization/\"+v.orgID, new(std.Organization)).(*std.Organization)\n\t\t\tfound := false\n\t\t\tfor _, addr := range orgInfo.ContractAddrList {\n\t\t\t\tif addr == conAddr {\n\t\t\t\t\tfound = true\n\t\t\t\t}\n\t\t\t}\n\t\t\tutest.Assert(found)\n\n\t\t\t// 检查合约列表\n\t\t\tconList := test.obj.sdk.Helper().StateHelper().Get(\"/organization/\"+v.orgID, new(std.ContractVersionList)).(*std.ContractVersionList)\n\t\t\tfoundCon := false\n\t\t\tfor _, addr := range conList.ContractAddrList {\n\t\t\t\tif addr == conAddr {\n\t\t\t\t\tfoundCon = true\n\t\t\t\t}\n\t\t\t}\n\t\t\tutest.Assert(foundCon)\n\n\t\t\t// 检查上一个合约的失效高度\n\t\t\tconVersionInfo := *test.obj.sdk.Helper().StateHelper().Get(\"/contract/\"+v.orgID+\"/\"+v.name, new(std.ContractVersionList)).(*std.ContractVersionList)\n\t\t\tif len(conVersionInfo.ContractAddrList) > 1 {\n\t\t\t\tlastCon := test.obj.sdk.Helper().StateHelper().Get(\n\t\t\t\t\t\"/contract/\"+conVersionInfo.ContractAddrList[len(conVersionInfo.ContractAddrList)-2], new(std.Contract)).(*std.Contract)\n\t\t\t\tutest.Assert(lastCon.LoseHeight == v.effectHeight)\n\t\t\t}\n\t\t}\n\t}\n\n\t// 升级合约\n\toldContract := &std.Contract{\n\t\tName: \"oldName\",\n\t\tAddress: \"oldContractAddr\",\n\t\tVersion: \"v1.1.1\",\n\t\tOrgID: orgID,\n\t\tToken: \"oldToken\",\n\t\tAccount: \"testAccount\",\n\t\tOwner: \"testOwner\",\n\t\tKeyPrefix: \"/oldName\",\n\t}\n\ttest.obj.sdk.Helper().StateHelper().Set(\"/contract/oldContractAddr\", oldContract)\n\n\ttest.obj.sdk.Helper().StateHelper().Set(\"/contract/\"+orgID+\"/\"+\"oldName\", &std.ContractVersionList{\n\t\tName: \"oldName\",\n\t\tContractAddrList: []types.Address{\"oldContractAddr\"},\n\t\tEffectHeights: []int64{5},\n\t})\n\n\t// 升级合约\n\ttestCasesForUpgrade := []struct {\n\t\tname string\n\t\tversion string\n\t\torgID string\n\t\tcodeHash types.Hash\n\t\tcodeData []byte\n\t\tcodeDevSig string\n\t\tcodeOrgSig string\n\t\teffectHeight int64\n\t\terr types.Error\n\t}{\n\t\t{\"oldName\", \"v1.1.2\", orgID, []byte(\"testA\"), []byte(\"helloA\"), \"test\", \"test\", test.obj.sdk.Block().Height() + 20, types.Error{ErrorCode: types.ErrNoAuthorization}},\n\t\t{\"oldName\", \"v1.1.2\", orgID, []byte(\"testA\"), []byte(\"helloB\"), \"test\", \"test\", test.obj.sdk.Block().Height() + 21, types.Error{ErrorCode: types.ErrNoAuthorization}},\n\t\t{\"oldName\", \"v1.2.4.1\", orgID, []byte(\"testA\"), []byte(\"helloB\"), \"test\", \"test\", test.obj.sdk.Block().Height() + 22, types.Error{ErrorCode: types.ErrNoAuthorization}},\n\t\t{\"oldName\", \"v1.2.4\", orgID, []byte(\"testA\"), []byte(\"helloB\"), \"test\", \"test\", test.obj.sdk.Block().Height(), types.Error{ErrorCode: types.ErrNoAuthorization}},\n\t\t{\"oldName\", \"v1.2.2\", orgID + \"test\", []byte(\"testA\"), []byte(\"helloB\"), \"test\", \"test\", test.obj.sdk.Block().Height() + 26, types.Error{ErrorCode: types.ErrInvalidParameter}},\n\t\t{\"oldName\", \"v1.0.2\", orgID, []byte(\"testA\"), []byte(\"helloB\"), \"test\", \"test\", test.obj.sdk.Block().Height() + 190, types.Error{ErrorCode: types.ErrNoAuthorization}},\n\t}\n\n\tfor _, v := range testCasesForUpgrade {\n\t\tconAddr, err := test.run().setSender(contractOwner).DeployContract(v.name, v.version, v.orgID, v.codeHash, v.codeData, v.codeDevSig, v.codeOrgSig, v.effectHeight)\n\t\tutest.AssertError(err, v.err.ErrorCode)\n\t\tif err.ErrorCode == types.CodeOK {\n\t\t\tutest.Assert(conAddr ==\n\t\t\t\ttest.obj.sdk.Helper().BlockChainHelper().CalcContractAddress(v.name, v.version, test.obj.sdk.Message().Contract().Owner().Address()))\n\t\t\tutest.AssertSDB(test.obj.sdk.Message().Contract().KeyPrefix()+\"/contract/\"+conAddr, std.Contract{\n\t\t\t\tAddress: conAddr,\n\t\t\t\tAccount: oldContract.Account,\n\t\t\t\tOwner: oldContract.Owner,\n\t\t\t\tName: v.name,\n\t\t\t\tVersion: v.version,\n\t\t\t\tCodeHash: v.codeHash,\n\t\t\t\tEffectHeight: v.effectHeight,\n\t\t\t\tLoseHeight: 0,\n\t\t\t\tKeyPrefix: \"/\" + v.name,\n\t\t\t\tMethods: nil, // 与 build 返回一致\n\t\t\t\tInterfaces: nil,\n\t\t\t\tToken: oldContract.Token,\n\t\t\t\tOrgID: v.orgID,\n\t\t\t})\n\n\t\t\t// 检查合约元数据\n\t\t\tcodeDevSigBytes, _ := jsoniter.Marshal(v.codeDevSig)\n\t\t\tcodeOrgSigBytes, _ := jsoniter.Marshal(v.codeOrgSig)\n\t\t\tutest.AssertSDB(test.obj.sdk.Message().Contract().KeyPrefix()+\"/contract/code/\"+conAddr, std.ContractMeta{\n\t\t\t\tName: v.name,\n\t\t\t\tContractAddr: conAddr,\n\t\t\t\tOrgID: v.orgID,\n\t\t\t\tEffectHeight: v.effectHeight,\n\t\t\t\tLoseHeight: 0,\n\t\t\t\tCodeData: v.codeData,\n\t\t\t\tCodeHash: v.codeHash,\n\t\t\t\tCodeDevSig: codeDevSigBytes,\n\t\t\t\tCodeOrgSig: codeOrgSigBytes,\n\t\t\t})\n\n\t\t\t// 检查组织信息\n\t\t\torgInfo := test.obj.sdk.Helper().StateHelper().Get(\"/organization/\"+v.orgID, new(std.Organization)).(*std.Organization)\n\t\t\tfound := false\n\t\t\tfor _, conAddr := range orgInfo.ContractAddrList {\n\t\t\t\tif conAddr == conAddr {\n\t\t\t\t\tfound = true\n\t\t\t\t}\n\t\t\t}\n\t\t\tutest.Assert(found)\n\n\t\t\t// 检查合约列表\n\t\t\tconList := test.obj.sdk.Helper().StateHelper().Get(\"/organization/\"+v.orgID, new(std.ContractVersionList)).(*std.ContractVersionList)\n\t\t\tfoundCon := false\n\t\t\tfor _, addr := range conList.ContractAddrList {\n\t\t\t\tif addr == conAddr {\n\t\t\t\t\tfoundCon = true\n\t\t\t\t}\n\t\t\t}\n\t\t\tutest.Assert(foundCon)\n\n\t\t\t// 检查上一个合约的失效高度\n\t\t\tconVersionInfo := *test.obj.sdk.Helper().StateHelper().Get(\"/contract/\"+v.orgID+\"/\"+v.name, new(std.ContractVersionList)).(*std.ContractVersionList)\n\t\t\tif len(conVersionInfo.ContractAddrList) > 1 {\n\t\t\t\tlastCon := test.obj.sdk.Helper().StateHelper().Get(\n\t\t\t\t\t\"/contract/\"+conVersionInfo.ContractAddrList[len(conVersionInfo.ContractAddrList)-2], new(std.Contract)).(*std.Contract)\n\t\t\t\tutest.Assert(lastCon.LoseHeight == v.effectHeight)\n\t\t\t}\n\t\t}\n\t}\n}", "func TestEncrypt(t *testing.T) {\n\tC, V, T, err := Secp256k1Encrypt(testString, secpPublicKey)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tplainText, err := Secp256k1Decrypt(C, V, T, secpPrivateKey)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif plainText != testString {\n\t\tt.Fatal(fmt.Sprintf(\"Failed to decrypt string, expects %s got %s\", testString, plainText))\n\t}\n}", "func (pg *PortalIntegrationTestSuite) SetupSuite() {\n\tfmt.Println(\"Setting up the suite...\")\n\t// Kovan env\n\tpg.IncKBNTokenIDStr = \"0000000000000000000000000000000000000000000000000000000000000082\"\n\tpg.IncSALTTokenIDStr = \"0000000000000000000000000000000000000000000000000000000000000081\"\n\tpg.IncOMGTokenIDStr = \"0000000000000000000000000000000000000000000000000000000000000072\"\n\tpg.IncSNTTokenIDStr = \"0000000000000000000000000000000000000000000000000000000000000071\"\n\tpg.OMGAddressStr = \"0xdB7ec4E4784118D9733710e46F7C83fE7889596a\" // kovan\n\tpg.SNTAddressStr = \"0x4c99B04682fbF9020Fcb31677F8D8d66832d3322\" // kovan\n\tpg.DepositingEther = float64(5)\n\tpg.ETHPrivKeyStr = \"1ABA488300A9D7297A315D127837BE4219107C62C61966ECDF7A75431D75CC61\"\n\tpg.PortalAdminKey = \"B8DB29A7A43FB88AD520F762C5FDF6F1B0155637FA1E5CB2C796AFE9E5C04E31\"\n\tpg.ETHHost = \"http://localhost:8545\"\n\n\tvar err error\n\tfmt.Println(\"Pulling image if not exist, please wait...\")\n\t// remove container if already running\n\texec.Command(\"/bin/sh\", \"-c\", \"docker rm -f portalv3\").Output()\n\texec.Command(\"/bin/sh\", \"-c\", \"docker rm -f incognito\").Output()\n\t_, err = exec.Command(\"/bin/sh\", \"-c\", \"docker run -d -p 8545:8545 --name portalv3 trufflesuite/ganache-cli --account=\\\"0x1ABA488300A9D7297A315D127837BE4219107C62C61966ECDF7A75431D75CC61,10000000000000000000000000000000000,0xB8DB29A7A43FB88AD520F762C5FDF6F1B0155637FA1E5CB2C796AFE9E5C04E31,10000000000000000000000000000000000\\\"\").Output()\n\trequire.Equal(pg.T(), nil, err)\n\ttime.Sleep(10 * time.Second)\n\n\tETHPrivKey, ETHClient, err := ethInstance(pg.ETHPrivKeyStr, pg.ETHHost)\n\trequire.Equal(pg.T(), nil, err)\n\tpg.ETHClient = ETHClient\n\tpg.ETHPrivKey = ETHPrivKey\n\tpg.auth = bind.NewKeyedTransactor(ETHPrivKey)\n\n\t// admin key\n\tprivKey, err := crypto.HexToECDSA(pg.PortalAdminKey)\n\trequire.Equal(pg.T(), nil, err)\n\tadmin := bind.NewKeyedTransactor(privKey)\n\n\t//pg.Portalv3 = common.HexToAddress(\"0x8c13AFB7815f10A8333955854E6ec7503eD841B7\")\n\t//pg.portalV3Inst, err = portalv3.NewPortalv3(pg.Portalv3, pg.ETHClient)\n\t//require.Equal(pg.T(), nil, err)\n\t//incAddr := common.HexToAddress(\"0x2fe0423B148739CD9D0E49e07b5ca00d388A15ac\")\n\t//pg.incProxy, err = incognitoproxy.NewIncognitoproxy(incAddr, pg.ETHClient)\n\t//require.Equal(pg.T(), nil, err)\n\n\tc := getFixedCommittee()\n\tincAddr, _, _, err := incognitoproxy.DeployIncognitoproxy(pg.auth, pg.ETHClient, admin.From, c.beacons)\n\trequire.Equal(pg.T(), nil, err)\n\tfmt.Printf(\"Proxy address: %s\\n\", incAddr.Hex())\n\tportalv3Logic, _, _, err := portalv3.DeployPortalv3(pg.auth, pg.ETHClient)\n\trequire.Equal(pg.T(), nil, err)\n\tfmt.Printf(\"portalv3 address: %s\\n\", portalv3Logic.Hex())\n\n\tportalv3ABI, _ := abi.JSON(strings.NewReader(portalv3.Portalv3ABI))\n\tinput, _ := portalv3ABI.Pack(\"initialize\")\n\n\t//PortalV3\n\tpg.Portalv3, _, _, err = delegator.DeployDelegator(pg.auth, pg.ETHClient, portalv3Logic, admin.From, incAddr, input)\n\trequire.Equal(pg.T(), nil, err)\n\tfmt.Printf(\"delegator address: %s\\n\", pg.Portalv3.Hex())\n\tpg.portalV3Inst, err = portalv3.NewPortalv3(pg.Portalv3, pg.ETHClient)\n\trequire.Equal(pg.T(), nil, err)\n\tpg.incProxy, err = incognitoproxy.NewIncognitoproxy(incAddr, pg.ETHClient)\n\trequire.Equal(pg.T(), nil, err)\n\n\t// 0x54d28562271De782B261807a01d1D2fb97417912\n\tpg.USDTAddress, _, _, err = usdt.DeployUsdt(pg.auth, pg.ETHClient, big.NewInt(100000000000), \"Tether\", \"USDT\", big.NewInt(6))\n\trequire.Equal(pg.T(), nil, err)\n\tfmt.Printf(\"usdt address: %s\\n\", pg.USDTAddress.Hex())\n\n\t//get portalv3 ip\n\tipAddress, err := exec.Command(\"/bin/sh\", \"-c\", \"docker inspect -f \\\"{{ .NetworkSettings.IPAddress }}\\\" portalv3\").Output()\n\trequire.Equal(pg.T(), nil, err)\n\n\t// run incognito chaind\n\tincogitoWithArgument := fmt.Sprintf(\"docker run -d -p 9334:9334 -p 9338:9338 --name incognito -e GETH_NAME=%v -e PORTAL_CONTRACT=%v incognito\", string(ipAddress), pg.Portalv3.Hex())\n\tincogitoWithArgument = strings.Replace(incogitoWithArgument, \"\\n\", \"\", -1)\n\t_, err = exec.Command(\"/bin/sh\", \"-c\", incogitoWithArgument).Output()\n\trequire.Equal(pg.T(), nil, err)\n\n\tfor {\n\t\ttime.Sleep(5 * time.Second)\n\t\tif checkRepsonse(pg.IncBridgeHost) {\n\t\t\tbreak\n\t\t}\n\t}\n\ttime.Sleep(40 * time.Second)\n}", "func TestGetSupportCoins(t *testing.T) {\n\tt.Parallel()\n\tif _, err := ok.GetSupportCoins(context.Background()); err != nil {\n\t\tt.Error(\"Okx GetSupportCoins() error\", err)\n\t}\n}", "func (mr *MockInternalClientMockRecorder) CryptoApiInvoke(ctx, in interface{}, opts ...interface{}) *gomock.Call {\n\tvarargs := append([]interface{}{ctx, in}, opts...)\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"CryptoApiInvoke\", reflect.TypeOf((*MockInternalClient)(nil).CryptoApiInvoke), varargs...)\n}", "func (adminAPIOp) SkipVerification() bool { return true }", "func TestBatchCTXStandardEntryClassCode(t *testing.T) {\n\ttestBatchCTXStandardEntryClassCode(t)\n}", "func TestSignContractSuccess(t *testing.T) {\n\tsignatureHelper(t, false)\n}", "func (m *MockClient) CryptoSuite() core.CryptoSuite {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"CryptoSuite\")\n\tret0, _ := ret[0].(core.CryptoSuite)\n\treturn ret0\n}", "func (mr *MockInternalServerMockRecorder) CryptoAsymKeyDelete(arg0, arg1 interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"CryptoAsymKeyDelete\", reflect.TypeOf((*MockInternalServer)(nil).CryptoAsymKeyDelete), arg0, arg1)\n}", "func TestTerminateSectors(t *testing.T) {\n\tctx := context.Background()\n\tv := vm.NewVMWithSingletons(ctx, t, ipld.NewBlockStoreInMemory())\n\taddrs := vm.CreateAccounts(ctx, t, v, 4, big.Mul(big.NewInt(10_000), vm.FIL), 93837778)\n\towner, verifier, unverifiedClient, verifiedClient := addrs[0], addrs[1], addrs[2], addrs[3]\n\tworker := owner\n\n\tminerBalance := big.Mul(big.NewInt(1_000), vm.FIL)\n\tsectorNumber := abi.SectorNumber(100)\n\tsealedCid := tutil.MakeCID(\"100\", &miner.SealedCIDPrefix)\n\tsealProof := abi.RegisteredSealProof_StackedDrg32GiBV1_1\n\n\t// create miner\n\tret := vm.ApplyOk(t, v, addrs[0], builtin.StoragePowerActorAddr, minerBalance, builtin.MethodsPower.CreateMiner, &power.CreateMinerParams{\n\t\tOwner: owner,\n\t\tWorker: worker,\n\t\tWindowPoStProofType: abi.RegisteredPoStProof_StackedDrgWindow32GiBV1,\n\t\tPeer: abi.PeerID(\"not really a peer id\"),\n\t})\n\tminerAddrs, ok := ret.(*power.CreateMinerReturn)\n\trequire.True(t, ok)\n\n\t//\n\t// publish verified and unverified deals\n\t//\n\n\t// register verifier then verified client\n\tvm.ApplyOk(t, v, vm.VerifregRoot, builtin.VerifiedRegistryActorAddr, big.Zero(), builtin.MethodsVerifiedRegistry.AddVerifier, &verifreg.AddVerifierParams{\n\t\tAddress: verifier,\n\t\tAllowance: abi.NewStoragePower(32 << 40),\n\t})\n\n\tvm.ApplyOk(t, v, verifier, builtin.VerifiedRegistryActorAddr, big.Zero(), builtin.MethodsVerifiedRegistry.AddVerifiedClient, &verifreg.AddVerifiedClientParams{\n\t\tAddress: verifiedClient,\n\t\tAllowance: abi.NewStoragePower(32 << 40),\n\t})\n\n\t// add market collateral for clients and miner\n\tcollateral := big.Mul(big.NewInt(3), vm.FIL)\n\tvm.ApplyOk(t, v, unverifiedClient, builtin.StorageMarketActorAddr, collateral, builtin.MethodsMarket.AddBalance, &unverifiedClient)\n\tvm.ApplyOk(t, v, verifiedClient, builtin.StorageMarketActorAddr, collateral, builtin.MethodsMarket.AddBalance, &verifiedClient)\n\tminerCollateral := big.Mul(big.NewInt(64), vm.FIL)\n\tvm.ApplyOk(t, v, worker, builtin.StorageMarketActorAddr, minerCollateral, builtin.MethodsMarket.AddBalance, &minerAddrs.IDAddress)\n\n\t// create 3 deals, some verified and some not\n\tdealIDs := []abi.DealID{}\n\tdealStart := v.GetEpoch() + miner.PreCommitChallengeDelay + 1\n\tdeals := publishDeal(t, v, worker, verifiedClient, minerAddrs.IDAddress, \"deal1\", 1<<30, true, dealStart, 181*builtin.EpochsInDay)\n\tdealIDs = append(dealIDs, deals.IDs...)\n\tdeals = publishDeal(t, v, worker, verifiedClient, minerAddrs.IDAddress, \"deal2\", 1<<32, true, dealStart, 200*builtin.EpochsInDay)\n\tdealIDs = append(dealIDs, deals.IDs...)\n\tdeals = publishDeal(t, v, worker, unverifiedClient, minerAddrs.IDAddress, \"deal3\", 1<<34, false, dealStart, 210*builtin.EpochsInDay)\n\tdealIDs = append(dealIDs, deals.IDs...)\n\n\tvm.ApplyOk(t, v, builtin.SystemActorAddr, builtin.CronActorAddr, big.Zero(), builtin.MethodsCron.EpochTick, nil)\n\tfor _, id := range dealIDs {\n\t\t// deals are pending and don't yet have deal states\n\t\t_, found := vm.GetDealState(t, v, id)\n\t\trequire.False(t, found)\n\t}\n\n\t//\n\t// Precommit, Prove, Verify and PoSt sector with deals\n\t//\n\n\t// precommit sector with deals\n\tvm.ApplyOk(t, v, addrs[0], minerAddrs.RobustAddress, big.Zero(), builtin.MethodsMiner.PreCommitSector, &miner.PreCommitSectorParams{\n\t\tSealProof: sealProof,\n\t\tSectorNumber: sectorNumber,\n\t\tSealedCID: sealedCid,\n\t\tSealRandEpoch: v.GetEpoch() - 1,\n\t\tDealIDs: dealIDs,\n\t\tExpiration: v.GetEpoch() + 220*builtin.EpochsInDay,\n\t\tReplaceCapacity: false,\n\t})\n\n\t// advance time to min seal duration\n\tproveTime := v.GetEpoch() + miner.PreCommitChallengeDelay + 1\n\tv, _ = vm.AdvanceByDeadlineTillEpoch(t, v, minerAddrs.IDAddress, proveTime)\n\n\t// Prove commit sector after max seal duration\n\tv, err := v.WithEpoch(proveTime)\n\trequire.NoError(t, err)\n\tvm.ApplyOk(t, v, worker, minerAddrs.RobustAddress, big.Zero(), builtin.MethodsMiner.ProveCommitSector, &miner.ProveCommitSectorParams{\n\t\tSectorNumber: sectorNumber,\n\t})\n\n\t// In the same epoch, trigger cron to validate prove commit\n\tvm.ApplyOk(t, v, builtin.SystemActorAddr, builtin.CronActorAddr, big.Zero(), builtin.MethodsCron.EpochTick, nil)\n\n\t// advance to proving period and submit post\n\tdlInfo, pIdx, v := vm.AdvanceTillProvingDeadline(t, v, minerAddrs.IDAddress, sectorNumber)\n\tvm.ApplyOk(t, v, worker, minerAddrs.RobustAddress, big.Zero(), builtin.MethodsMiner.SubmitWindowedPoSt, &miner.SubmitWindowedPoStParams{\n\t\tDeadline: dlInfo.Index,\n\t\tPartitions: []miner.PoStPartition{{\n\t\t\tIndex: pIdx,\n\t\t\tSkipped: bitfield.New(),\n\t\t}},\n\t\tProofs: []proof.PoStProof{{\n\t\t\tPoStProof: abi.RegisteredPoStProof_StackedDrgWindow32GiBV1,\n\t\t}},\n\t\tChainCommitEpoch: dlInfo.Challenge,\n\t\tChainCommitRand: []byte(vm.RandString),\n\t})\n\n\t// proving period cron adds miner power\n\tv, err = v.WithEpoch(dlInfo.Last())\n\trequire.NoError(t, err)\n\tvm.ApplyOk(t, v, builtin.SystemActorAddr, builtin.CronActorAddr, big.Zero(), builtin.MethodsCron.EpochTick, nil)\n\n\t// market cron updates deal states indicating deals are no longer pending.\n\tfor _, id := range dealIDs {\n\t\tstate, found := vm.GetDealState(t, v, id)\n\t\trequire.True(t, found)\n\t\t// non-zero\n\t\tassert.Greater(t, uint64(state.LastUpdatedEpoch), uint64(0))\n\t\t// deal has not been slashed\n\t\tassert.Equal(t, abi.ChainEpoch(-1), state.SlashEpoch)\n\t}\n\n\t//\n\t// Terminate Sector\n\t//\n\n\tv, err = v.WithEpoch(v.GetEpoch() + 1)\n\trequire.NoError(t, err)\n\n\tvm.ApplyOk(t, v, worker, minerAddrs.RobustAddress, big.Zero(), builtin.MethodsMiner.TerminateSectors, &miner.TerminateSectorsParams{\n\t\tTerminations: []miner.TerminationDeclaration{{\n\t\t\tDeadline: dlInfo.Index,\n\t\t\tPartition: pIdx,\n\t\t\tSectors: bitfield.NewFromSet([]uint64{uint64(sectorNumber)}),\n\t\t}},\n\t})\n\n\tnoSubinvocations := []vm.ExpectInvocation{}\n\tvm.ExpectInvocation{\n\t\tTo: minerAddrs.IDAddress,\n\t\tMethod: builtin.MethodsMiner.TerminateSectors,\n\t\tSubInvocations: []vm.ExpectInvocation{\n\t\t\t{To: builtin.RewardActorAddr, Method: builtin.MethodsReward.ThisEpochReward, SubInvocations: noSubinvocations},\n\t\t\t{To: builtin.StoragePowerActorAddr, Method: builtin.MethodsPower.CurrentTotalPower, SubInvocations: noSubinvocations},\n\t\t\t{To: builtin.BurntFundsActorAddr, Method: builtin.MethodSend, SubInvocations: noSubinvocations},\n\t\t\t{To: builtin.StoragePowerActorAddr, Method: builtin.MethodsPower.UpdatePledgeTotal, SubInvocations: noSubinvocations},\n\t\t\t{To: builtin.StorageMarketActorAddr, Method: builtin.MethodsMarket.OnMinerSectorsTerminate, SubInvocations: noSubinvocations},\n\t\t\t{To: builtin.StoragePowerActorAddr, Method: builtin.MethodsPower.UpdateClaimedPower, SubInvocations: noSubinvocations},\n\t\t},\n\t}.Matches(t, v.LastInvocation())\n\n\t// expect power, market and miner to be in base state\n\tminerBalances := vm.GetMinerBalances(t, v, minerAddrs.IDAddress)\n\tassert.Equal(t, big.Zero(), minerBalances.InitialPledge)\n\tassert.Equal(t, big.Zero(), minerBalances.PreCommitDeposit)\n\n\t// expect network stats to reflect power has been removed from sector\n\tstats := vm.GetNetworkStats(t, v)\n\tassert.Equal(t, int64(0), stats.MinerAboveMinPowerCount)\n\tassert.Equal(t, big.Zero(), stats.TotalRawBytePower)\n\tassert.Equal(t, big.Zero(), stats.TotalQualityAdjPower)\n\tassert.Equal(t, big.Zero(), stats.TotalBytesCommitted)\n\tassert.Equal(t, big.Zero(), stats.TotalQABytesCommitted)\n\tassert.Equal(t, big.Zero(), stats.TotalPledgeCollateral)\n\n\t// market cron slashes deals because sector has been terminated\n\tfor _, id := range dealIDs {\n\t\tstate, found := vm.GetDealState(t, v, id)\n\t\trequire.True(t, found)\n\t\t// non-zero\n\t\tassert.Greater(t, uint64(state.LastUpdatedEpoch), uint64(0))\n\t\t// deal has not been slashed\n\t\tassert.Equal(t, v.GetEpoch(), state.SlashEpoch)\n\n\t}\n\n\t// advance a proving period and run cron to complete processing of termination\n\tv, err = v.WithEpoch(v.GetEpoch() + 2880)\n\trequire.NoError(t, err)\n\tvm.ApplyOk(t, v, builtin.SystemActorAddr, builtin.CronActorAddr, big.Zero(), builtin.MethodsCron.EpochTick, nil)\n\n\t// Verified client should be able to withdraw all all deal collateral.\n\t// Client added 3 FIL balance and had 2 deals with 1 FIL collateral apiece.\n\t// Should only be able to withdraw the full 2 FIL only if deals have been slashed and balance was unlocked.\n\twithdrawal := big.Mul(big.NewInt(2), vm.FIL)\n\tvm.ApplyOk(t, v, verifiedClient, builtin.StorageMarketActorAddr, big.Zero(), builtin.MethodsMarket.WithdrawBalance, &market.WithdrawBalanceParams{\n\t\tProviderOrClientAddress: verifiedClient,\n\t\tAmount: withdrawal,\n\t})\n\n\tverifiedIDAddr, found := v.NormalizeAddress(verifiedClient)\n\trequire.True(t, found)\n\tvm.ExpectInvocation{\n\t\tTo: builtin.StorageMarketActorAddr,\n\t\tMethod: builtin.MethodsMarket.WithdrawBalance,\n\t\tSubInvocations: []vm.ExpectInvocation{\n\t\t\t{To: verifiedIDAddr, Method: builtin.MethodSend, Value: vm.ExpectAttoFil(withdrawal)},\n\t\t},\n\t}.Matches(t, v.LastInvocation())\n\n\t// Check that miner's collateral has been slashed by attempting to withdraw all funds\n\tvm.ApplyOk(t, v, owner, builtin.StorageMarketActorAddr, big.Zero(), builtin.MethodsMarket.WithdrawBalance, &market.WithdrawBalanceParams{\n\t\tProviderOrClientAddress: minerAddrs.IDAddress,\n\t\tAmount: minerCollateral,\n\t})\n\n\t// miner add 64 balance. Each of 3 deals required 2 FIL collateral, so provider collateral should have been\n\t// slashed by 6 FIL. Miner's remaining market balance should be 64 - 6 + payment, where payment is for storage\n\t// before the slash and should be << 1 FIL. Actual amount withdrawn should be between 58 and 59 FIL.\n\tvalueWithdrawn := vm.ValueForInvocation(t, v, len(v.Invocations())-1, 1)\n\tassert.True(t, big.Mul(big.NewInt(58), vm.FIL).LessThan(valueWithdrawn))\n\tassert.True(t, big.Mul(big.NewInt(59), vm.FIL).GreaterThan(valueWithdrawn))\n}", "func testKeyCanOnlyBeAddedOnce(t *testing.T, dbStore trustmanager.KeyStore) []data.PrivateKey {\n\texpectedKeys := make([]data.PrivateKey, 2)\n\tfor i := 0; i < len(expectedKeys); i++ {\n\t\ttestKey, err := utils.GenerateECDSAKey(rand.Reader)\n\t\trequire.NoError(t, err)\n\t\texpectedKeys[i] = testKey\n\t}\n\n\t// Test writing new key in database alone, not cache\n\terr := dbStore.AddKey(trustmanager.KeyInfo{Role: data.CanonicalTimestampRole, Gun: \"gun/ignored\"}, expectedKeys[0])\n\trequire.NoError(t, err)\n\t// Currently we ignore roles\n\trequireGetKeySuccess(t, dbStore, \"\", expectedKeys[0])\n\n\t// Test writing the same key in the database. Should fail.\n\terr = dbStore.AddKey(trustmanager.KeyInfo{Role: data.CanonicalTimestampRole, Gun: \"gun/ignored\"}, expectedKeys[0])\n\trequire.Error(t, err, \"failed to add private key to database:\")\n\n\t// Test writing new key succeeds\n\terr = dbStore.AddKey(trustmanager.KeyInfo{Role: data.CanonicalTimestampRole, Gun: \"gun/ignored\"}, expectedKeys[1])\n\trequire.NoError(t, err)\n\n\treturn expectedKeys\n}" ]
[ "0.62962306", "0.5932702", "0.5895436", "0.5804088", "0.56917953", "0.5638527", "0.56172067", "0.55998623", "0.5447192", "0.53331995", "0.53276664", "0.5316853", "0.531374", "0.5311914", "0.5296386", "0.5289389", "0.52880764", "0.5248297", "0.52416706", "0.5213803", "0.5199416", "0.51966107", "0.5167562", "0.51590353", "0.513533", "0.511883", "0.5113239", "0.50859094", "0.5078352", "0.5072741", "0.507169", "0.50711286", "0.50645244", "0.5042726", "0.5019032", "0.49815342", "0.49483675", "0.49474", "0.4945302", "0.4939505", "0.49323717", "0.4917007", "0.4915529", "0.491292", "0.4905229", "0.48997256", "0.48903856", "0.4889603", "0.4888271", "0.4887784", "0.4885312", "0.4884114", "0.4876746", "0.48747557", "0.48700365", "0.48524025", "0.48409387", "0.48379245", "0.4827223", "0.48194697", "0.48114362", "0.48082373", "0.4801138", "0.47960255", "0.4794396", "0.47872135", "0.4784165", "0.47799113", "0.47753996", "0.47739425", "0.4766279", "0.47475362", "0.47437444", "0.47418836", "0.47417784", "0.47403848", "0.47384676", "0.47345057", "0.47209218", "0.47165948", "0.47072667", "0.47059292", "0.47022918", "0.47019142", "0.46990746", "0.46967092", "0.4696434", "0.469641", "0.46940696", "0.46923134", "0.46917072", "0.4690644", "0.46824107", "0.46780118", "0.46766856", "0.46731842", "0.46726876", "0.46705768", "0.46633312", "0.46545663" ]
0.6300879
0
EndpointConfig mocks base method
func (m *MockClient) EndpointConfig() fab.EndpointConfig { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "EndpointConfig") ret0, _ := ret[0].(fab.EndpointConfig) return ret0 }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (m *MockProviders) EndpointConfig() fab.EndpointConfig {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"EndpointConfig\")\n\tret0, _ := ret[0].(fab.EndpointConfig)\n\treturn ret0\n}", "func (m *MockConfiguration) IntrospectionEndpoint() op.Endpoint {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"IntrospectionEndpoint\")\n\tret0, _ := ret[0].(op.Endpoint)\n\treturn ret0\n}", "func (m *MockAPIConfigFromFlags) MakeEndpoint() (http.Endpoint, error) {\n\tret := m.ctrl.Call(m, \"MakeEndpoint\")\n\tret0, _ := ret[0].(http.Endpoint)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockConfiguration) UserinfoEndpoint() op.Endpoint {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"UserinfoEndpoint\")\n\tret0, _ := ret[0].(op.Endpoint)\n\treturn ret0\n}", "func TestEndpointCase45(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(false),\n\t\tEndpoint: ptr.String(\"https://example.com\"),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://example.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func (m *MockConfiguration) TokenEndpoint() op.Endpoint {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"TokenEndpoint\")\n\tret0, _ := ret[0].(op.Endpoint)\n\treturn ret0\n}", "func (m *MockProvider) ServiceEndpoint() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ServiceEndpoint\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func TestEndpointCase1(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"ap-east-1\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(false),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis.ap-east-1.amazonaws.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func TestEndpointCase2(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"ap-northeast-1\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(false),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis.ap-northeast-1.amazonaws.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func TestEndpointCase44(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"us-east-1\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(false),\n\t\tEndpoint: ptr.String(\"https://example.com\"),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://example.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func (m *MockConfiguration) AuthorizationEndpoint() op.Endpoint {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"AuthorizationEndpoint\")\n\tret0, _ := ret[0].(op.Endpoint)\n\treturn ret0\n}", "func Endpoint(url string, configureFunc func()) {\n\touterCurrentMockHandler := currentMockHandler\n\tSwitch(extractor.ExtractMethod(), configureFunc)\n\tcurrentMockery.Handle(url, currentMockHandler)\n\tcurrentMockHandler = outerCurrentMockHandler\n}", "func TestEndpointCase0(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"af-south-1\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(false),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis.af-south-1.amazonaws.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func Test_convertEndpointsConfig(t *testing.T) {\n\ttype args struct {\n\t\txdsEndpoint *xdsendpoint.LocalityLbEndpoints\n\t}\n\ttests := []struct {\n\t\tname string\n\t\targs args\n\t\twant []v2.Host\n\t}{\n\t\t{\n\t\t\tname: \"case1\",\n\t\t\targs: args{\n\t\t\t\txdsEndpoint: &xdsendpoint.LocalityLbEndpoints{\n\t\t\t\t\tPriority: 1,\n\t\t\t\t},\n\t\t\t},\n\t\t\twant: []v2.Host{},\n\t\t},\n\t\t{\n\t\t\tname: \"case2\",\n\t\t\targs: args{\n\t\t\t\txdsEndpoint: &xdsendpoint.LocalityLbEndpoints{\n\t\t\t\t\tLbEndpoints: []*xdsendpoint.LbEndpoint{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tHostIdentifier: &xdsendpoint.LbEndpoint_Endpoint{\n\t\t\t\t\t\t\t\tEndpoint: &xdsendpoint.Endpoint{\n\t\t\t\t\t\t\t\t\tAddress: &core.Address{\n\t\t\t\t\t\t\t\t\t\tAddress: &core.Address_SocketAddress{\n\t\t\t\t\t\t\t\t\t\t\tSocketAddress: &core.SocketAddress{\n\t\t\t\t\t\t\t\t\t\t\t\tAddress: \"192.168.0.1\",\n\t\t\t\t\t\t\t\t\t\t\t\tProtocol: core.SocketAddress_TCP,\n\t\t\t\t\t\t\t\t\t\t\t\tPortSpecifier: &core.SocketAddress_PortValue{PortValue: 8080},\n\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tLoadBalancingWeight: &wrappers.UInt32Value{Value: 20},\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tHostIdentifier: &xdsendpoint.LbEndpoint_Endpoint{\n\t\t\t\t\t\t\t\tEndpoint: &xdsendpoint.Endpoint{\n\t\t\t\t\t\t\t\t\tAddress: &core.Address{\n\t\t\t\t\t\t\t\t\t\tAddress: &core.Address_SocketAddress{\n\t\t\t\t\t\t\t\t\t\t\tSocketAddress: &core.SocketAddress{\n\t\t\t\t\t\t\t\t\t\t\t\tAddress: \"192.168.0.2\",\n\t\t\t\t\t\t\t\t\t\t\t\tProtocol: core.SocketAddress_TCP,\n\t\t\t\t\t\t\t\t\t\t\t\tPortSpecifier: &core.SocketAddress_PortValue{PortValue: 8080},\n\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tLoadBalancingWeight: &wrappers.UInt32Value{Value: 0},\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tHostIdentifier: &xdsendpoint.LbEndpoint_Endpoint{\n\t\t\t\t\t\t\t\tEndpoint: &xdsendpoint.Endpoint{\n\t\t\t\t\t\t\t\t\tAddress: &core.Address{\n\t\t\t\t\t\t\t\t\t\tAddress: &core.Address_SocketAddress{\n\t\t\t\t\t\t\t\t\t\t\tSocketAddress: &core.SocketAddress{\n\t\t\t\t\t\t\t\t\t\t\t\tAddress: \"192.168.0.3\",\n\t\t\t\t\t\t\t\t\t\t\t\tProtocol: core.SocketAddress_TCP,\n\t\t\t\t\t\t\t\t\t\t\t\tPortSpecifier: &core.SocketAddress_PortValue{PortValue: 8080},\n\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tLoadBalancingWeight: &wrappers.UInt32Value{Value: 200},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\twant: []v2.Host{\n\t\t\t\t{\n\t\t\t\t\tHostConfig: v2.HostConfig{\n\t\t\t\t\t\tAddress: \"192.168.0.1:8080\",\n\t\t\t\t\t\tWeight: 20,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tHostConfig: v2.HostConfig{\n\t\t\t\t\t\tAddress: \"192.168.0.2:8080\",\n\t\t\t\t\t\tWeight: configmanager.MinHostWeight,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tHostConfig: v2.HostConfig{\n\t\t\t\t\t\tAddress: \"192.168.0.3:8080\",\n\t\t\t\t\t\tWeight: configmanager.MaxHostWeight,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tif got := ConvertEndpointsConfig(tt.args.xdsEndpoint); !reflect.DeepEqual(got, tt.want) {\n\t\t\t\tt.Errorf(\"convertEndpointsConfig() = %v, want %v\", got, tt.want)\n\t\t\t}\n\t\t})\n\t}\n}", "func (r mockEndpointResolver) EndpointFor(service, region string, opts ...func(*endpoints.Options)) (endpoints.ResolvedEndpoint, error) {\n\treturn r.resolvedEndpoint, r.err\n}", "func (c *MockRemoteWriteClient) Endpoint() string { return \"\" }", "func EndpointForCondition(predicate predicate.Predicate, configFunc func()) {\n\touterCurrentMockHandler := currentMockHandler\n\tconfigFunc()\n\tcurrentMockery.HandleForCondition(DefaultPriority, predicate, currentMockHandler)\n\tcurrentMockHandler = outerCurrentMockHandler\n}", "func TestEndpointCase27(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"us-east-1\"),\n\t\tUseDualStack: ptr.Bool(true),\n\t\tUseFIPS: ptr.Bool(false),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis.us-east-1.api.aws\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func (pushBots *PushBots) initializeEndpoints(endpointOverride string) {\n\tendpointBase := productionEndPoint\n\n\tif endpointOverride != \"\" {\n\t\tendpointBase = endpointOverride\n\t}\n\n\tpushBots.endpoints = map[string]pushBotRequest{\n\t\t\"registerdevice\": pushBotRequest{Endpoint: endpointBase + \"deviceToken\", HttpVerb: \"PUT\"},\n\t\t\"unregisterdevice\": pushBotRequest{Endpoint: endpointBase + \"deviceToken/del\", HttpVerb: \"PUT\"},\n\t\t\"alias\": pushBotRequest{Endpoint: endpointBase + \"alias\", HttpVerb: \"PUT\"},\n\t\t\"tagdevice\": pushBotRequest{Endpoint: endpointBase + \"tag\", HttpVerb: \"PUT\"},\n\t\t\"untagdevice\": pushBotRequest{Endpoint: endpointBase + \"tag/del\", HttpVerb: \"PUT\"},\n\t\t\"geos\": pushBotRequest{Endpoint: endpointBase + \"geo\", HttpVerb: \"PUT\"},\n\t\t\"addnotificationtype\": pushBotRequest{Endpoint: endpointBase + \"activate\", HttpVerb: \"PUT\"},\n\t\t\"removenotificationtype\": pushBotRequest{Endpoint: endpointBase + \"deactivate\", HttpVerb: \"PUT\"},\n\t\t\"broadcast\": pushBotRequest{Endpoint: endpointBase + \"push/all\", HttpVerb: \"POST\"},\n\t\t\"pushone\": pushBotRequest{Endpoint: endpointBase + \"push/one\", HttpVerb: \"POST\"},\n\t\t\"batch\": pushBotRequest{Endpoint: endpointBase + \"push/all\", HttpVerb: \"POST\"},\n\t\t\"badge\": pushBotRequest{Endpoint: endpointBase + \"badge\", HttpVerb: \"PUT\"},\n\t\t\"recordanalytics\": pushBotRequest{Endpoint: endpointBase + \"stats\", HttpVerb: \"PUT\"},\n\t}\n}", "func (c *Provider) EndpointConfig() fab.EndpointConfig {\n\treturn c.endpointConfig\n}", "func (m *MockConfiguration) KeysEndpoint() op.Endpoint {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"KeysEndpoint\")\n\tret0, _ := ret[0].(op.Endpoint)\n\treturn ret0\n}", "func TestValidate1(t *testing.T) {\n\tendpoints := make(map[string]map[string]*Endpoint)\n\tendpoints[\"/test\"] = map[string]*Endpoint{\n\t\t\"get\": {\n\t\t\tParams: &Parameters{\n\t\t\t\tQuery: map[string]*ParamEntry{\"test\": {Type: \"string\", Required: true}},\n\t\t\t\tPath: map[string]*ParamEntry{\"test\": {Type: \"boolean\", Required: true}},\n\t\t\t},\n\t\t\tRecieves: &Recieves{\n\t\t\t\tHeaders: map[string]string{\"foo\": \"bar\"},\n\t\t\t\tBody: map[string]string{\"example_array.0.foo\": \"string\"},\n\t\t\t},\n\t\t\tResponses: map[int]*Response{\n\t\t\t\t200: {\n\t\t\t\t\tHeaders: map[string]string{\"foo\": \"bar\"},\n\t\t\t\t\tBody: map[string]interface{}{\"bar\": \"foo\"},\n\t\t\t\t\tWeight: 100,\n\t\t\t\t\tActions: []map[string]interface{}{\n\t\t\t\t\t\t{\"delay\": 10},\n\t\t\t\t\t\t{\"request\": map[interface{}]interface{}{\"target\": \"testService\", \"id\": \"testRequest\"}},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tActions: []map[string]interface{}{\n\t\t\t\t{\"delay\": 10},\n\t\t\t\t{\"request\": map[interface{}]interface{}{\"target\": \"testService\", \"id\": \"testRequest\"}},\n\t\t\t},\n\t\t},\n\t}\n\n\tcfg := &Config{\n\t\tVersion: 1.0,\n\t\tServices: map[string]*Service{\n\t\t\t\"testService\": {Hostname: \"localhost\", Port: 8080},\n\t\t},\n\t\tStartupActions: []map[string]interface{}{\n\t\t\t{\"delay\": 10},\n\t\t\t{\"request\": map[interface{}]interface{}{\"target\": \"testService\", \"id\": \"testRequest\"}},\n\t\t},\n\t\tRequests: map[string]*Request{\n\t\t\t\"testRequest\": {\n\t\t\t\tURL: \"/test\",\n\t\t\t\tProtocol: \"http\",\n\t\t\t\tMethod: \"get\",\n\t\t\t\tHeaders: map[string]string{\"foo\": \"bar\"},\n\t\t\t\tBody: nil,\n\t\t\t\tExpectedResponse: &Response{\n\t\t\t\t\tStatusCode: 200,\n\t\t\t\t\tBody: map[string]interface{}{\"foo.bar\": \"string\"},\n\t\t\t\t\tHeaders: nil,\n\t\t\t\t\tWeight: 100,\n\t\t\t\t\tActions: []map[string]interface{}{\n\t\t\t\t\t\t{\"delay\": 10},\n\t\t\t\t\t\t{\"request\": map[interface{}]interface{}{\"target\": \"testService\", \"id\": \"testRequest\"}},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tEndpoints: endpoints,\n\t}\n\n\tif err := Validate(cfg); err != nil {\n\t\tt.Errorf(\"Validation Failed: %s\", err.Error())\n\t}\n}", "func TestEndpointURL(t *testing.T) {\n\t// these client calls should fail since we'll break the URL paths\n\tsimulator.Test(func(ctx context.Context, vc *vim25.Client) {\n\t\tlsim.BreakLookupServiceURLs()\n\n\t\t{\n\t\t\t_, err := ssoadmin.NewClient(ctx, vc)\n\t\t\tif err == nil {\n\t\t\t\tt.Error(\"expected error\")\n\t\t\t}\n\t\t\tif !strings.Contains(err.Error(), http.StatusText(404)) {\n\t\t\t\tt.Error(err)\n\t\t\t}\n\t\t}\n\n\t\t{\n\t\t\tc, err := sts.NewClient(ctx, vc)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\n\t\t\treq := sts.TokenRequest{\n\t\t\t\tUserinfo: url.UserPassword(\"Administrator@VSPHERE.LOCAL\", \"password\"),\n\t\t\t}\n\t\t\t_, err = c.Issue(ctx, req)\n\t\t\tif err == nil {\n\t\t\t\tt.Error(\"expected error\")\n\t\t\t}\n\t\t\tif !strings.Contains(err.Error(), http.StatusText(404)) {\n\t\t\t\tt.Error(err)\n\t\t\t}\n\t\t}\n\t})\n\n\t// these client calls should not fail\n\tsimulator.Test(func(ctx context.Context, vc *vim25.Client) {\n\t\t{\n\t\t\t// NewClient calls ServiceInstance methods\n\t\t\t_, err := ssoadmin.NewClient(ctx, vc)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\t\t}\n\n\t\t{\n\t\t\tc, err := sts.NewClient(ctx, vc)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\n\t\t\treq := sts.TokenRequest{\n\t\t\t\tUserinfo: url.UserPassword(\"Administrator@VSPHERE.LOCAL\", \"password\"),\n\t\t\t}\n\n\t\t\t_, err = c.Issue(ctx, req)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\t\t}\n\t})\n}", "func TestEndpointCase10(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"eu-central-1\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(false),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis.eu-central-1.amazonaws.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func TestGetConcurrentAPIEndpoints(t *testing.T) {\n\tfor _, tc := range []struct {\n\t\tname string\n\t\tddURL, eventsDDURL, apiKey string\n\t\tadditionalEndpoints map[string][]string\n\t\tadditionalEventsEndpoints map[string][]string\n\t\texpectedEndpoints []apicfg.Endpoint\n\t\texpectedEventsEndpoints []apicfg.Endpoint\n\t}{\n\t\t{\n\t\t\tname: \"default\",\n\t\t\tapiKey: \"test\",\n\t\t\texpectedEndpoints: []apicfg.Endpoint{\n\t\t\t\t{\n\t\t\t\t\tAPIKey: \"test\",\n\t\t\t\t\tEndpoint: mkurl(config.DefaultProcessEndpoint),\n\t\t\t\t},\n\t\t\t},\n\t\t\texpectedEventsEndpoints: []apicfg.Endpoint{\n\t\t\t\t{\n\t\t\t\t\tAPIKey: \"test\",\n\t\t\t\t\tEndpoint: mkurl(config.DefaultProcessEventsEndpoint),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"set only process endpoint\",\n\t\t\tddURL: \"https://process.datadoghq.eu\",\n\t\t\tapiKey: \"test\",\n\t\t\texpectedEndpoints: []apicfg.Endpoint{\n\t\t\t\t{\n\t\t\t\t\tAPIKey: \"test\",\n\t\t\t\t\tEndpoint: mkurl(\"https://process.datadoghq.eu\"),\n\t\t\t\t},\n\t\t\t},\n\t\t\texpectedEventsEndpoints: []apicfg.Endpoint{\n\t\t\t\t{\n\t\t\t\t\tAPIKey: \"test\",\n\t\t\t\t\tEndpoint: mkurl(config.DefaultProcessEventsEndpoint),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"set only process-events endpoint\",\n\t\t\teventsDDURL: \"https://process-events.datadoghq.eu\",\n\t\t\tapiKey: \"test\",\n\t\t\texpectedEndpoints: []apicfg.Endpoint{\n\t\t\t\t{\n\t\t\t\t\tAPIKey: \"test\",\n\t\t\t\t\tEndpoint: mkurl(config.DefaultProcessEndpoint),\n\t\t\t\t},\n\t\t\t},\n\t\t\texpectedEventsEndpoints: []apicfg.Endpoint{\n\t\t\t\t{\n\t\t\t\t\tAPIKey: \"test\",\n\t\t\t\t\tEndpoint: mkurl(\"https://process-events.datadoghq.eu\"),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"multiple eps\",\n\t\t\tapiKey: \"test\",\n\t\t\tadditionalEndpoints: map[string][]string{\n\t\t\t\t\"https://mock.datadoghq.com\": {\n\t\t\t\t\t\"key1\",\n\t\t\t\t\t\"key2\",\n\t\t\t\t},\n\t\t\t\t\"https://mock2.datadoghq.com\": {\n\t\t\t\t\t\"key3\",\n\t\t\t\t},\n\t\t\t},\n\t\t\tadditionalEventsEndpoints: map[string][]string{\n\t\t\t\t\"https://mock-events.datadoghq.com\": {\n\t\t\t\t\t\"key2\",\n\t\t\t\t},\n\t\t\t\t\"https://mock2-events.datadoghq.com\": {\n\t\t\t\t\t\"key3\",\n\t\t\t\t},\n\t\t\t},\n\t\t\texpectedEndpoints: []apicfg.Endpoint{\n\t\t\t\t{\n\t\t\t\t\tEndpoint: mkurl(config.DefaultProcessEndpoint),\n\t\t\t\t\tAPIKey: \"test\",\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tEndpoint: mkurl(\"https://mock.datadoghq.com\"),\n\t\t\t\t\tAPIKey: \"key1\",\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tEndpoint: mkurl(\"https://mock.datadoghq.com\"),\n\t\t\t\t\tAPIKey: \"key2\",\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tEndpoint: mkurl(\"https://mock2.datadoghq.com\"),\n\t\t\t\t\tAPIKey: \"key3\",\n\t\t\t\t},\n\t\t\t},\n\t\t\texpectedEventsEndpoints: []apicfg.Endpoint{\n\t\t\t\t{\n\t\t\t\t\tEndpoint: mkurl(config.DefaultProcessEventsEndpoint),\n\t\t\t\t\tAPIKey: \"test\",\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tEndpoint: mkurl(\"https://mock-events.datadoghq.com\"),\n\t\t\t\t\tAPIKey: \"key2\",\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tEndpoint: mkurl(\"https://mock2-events.datadoghq.com\"),\n\t\t\t\t\tAPIKey: \"key3\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t} {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tcfg := config.Mock(t)\n\t\t\tcfg.Set(\"api_key\", tc.apiKey)\n\t\t\tif tc.ddURL != \"\" {\n\t\t\t\tcfg.Set(\"process_config.process_dd_url\", tc.ddURL)\n\t\t\t}\n\n\t\t\tif tc.eventsDDURL != \"\" {\n\t\t\t\tcfg.Set(\"process_config.events_dd_url\", tc.eventsDDURL)\n\t\t\t}\n\n\t\t\tif tc.additionalEndpoints != nil {\n\t\t\t\tcfg.Set(\"process_config.additional_endpoints\", tc.additionalEndpoints)\n\t\t\t}\n\n\t\t\tif tc.additionalEventsEndpoints != nil {\n\t\t\t\tcfg.Set(\"process_config.events_additional_endpoints\", tc.additionalEventsEndpoints)\n\t\t\t}\n\n\t\t\teps, err := endpoint.GetAPIEndpoints(cfg)\n\t\t\tassert.NoError(t, err)\n\t\t\tassert.ElementsMatch(t, tc.expectedEndpoints, eps)\n\n\t\t\teventsEps, err := endpoint.GetEventsAPIEndpoints(cfg)\n\t\t\tassert.NoError(t, err)\n\t\t\tassert.ElementsMatch(t, tc.expectedEventsEndpoints, eventsEps)\n\t\t})\n\t}\n}", "func (m *MockProvider) OnEndpointsAdd(arg0 *v1.Endpoints) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"OnEndpointsAdd\", arg0)\n}", "func WithEndpoint(endpoint string) {\n\tcfg.endpoint = strings.TrimRight(endpoint, \"/\")\n}", "func TestInvalidConfiguration(t *testing.T) {\n\tt.Parallel()\n\t// Start a test gRPC server.\n\t_ = mock.NewBase64Plugin(t, newEndpoint().path)\n\n\tctx := testContext(t)\n\n\tinvalidConfigs := []struct {\n\t\tname string\n\t\tendpoint string\n\t}{\n\t\t{\"emptyConfiguration\", \"\"},\n\t\t{\"invalidScheme\", \"tcp://localhost:6060\"},\n\t}\n\n\tfor _, testCase := range invalidConfigs {\n\t\tt.Run(testCase.name, func(t *testing.T) {\n\t\t\t_, err := NewGRPCService(ctx, testCase.endpoint, 1*time.Second)\n\t\t\tif err == nil {\n\t\t\t\tt.Fatalf(\"should fail to create envelope service for %s.\", testCase.name)\n\t\t\t}\n\t\t})\n\t}\n}", "func TestEndpointCase4(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"ap-northeast-3\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(false),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis.ap-northeast-3.amazonaws.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func testMockSourceEndpoints(t *testing.T) {\n\tfor _, tc := range []struct {\n\t\ttitle string\n\t\tgivenAndExpected []endpoint.Endpoint\n\t}{\n\t\t{\n\t\t\t\"no endpoints given return no endpoints\",\n\t\t\t[]endpoint.Endpoint{},\n\t\t},\n\t\t{\n\t\t\t\"single endpoint given returns single endpoint\",\n\t\t\t[]endpoint.Endpoint{\n\t\t\t\t{DNSName: \"foo\", Target: \"8.8.8.8\"},\n\t\t\t},\n\t\t},\n\t} {\n\t\tt.Run(tc.title, func(t *testing.T) {\n\t\t\t// Create our object under test and get the endpoints.\n\t\t\tsource := NewMockSource(tc.givenAndExpected)\n\n\t\t\tendpoints, err := source.Endpoints()\n\t\t\tif err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\n\t\t\t// Validate returned endpoints against desired endpoints.\n\t\t\tvalidateEndpoints(t, endpoints, tc.givenAndExpected)\n\t\t})\n\t}\n}", "func TestEndpointCase9(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"ca-central-1\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(false),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis.ca-central-1.amazonaws.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func TestEndpointCase5(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"ap-south-1\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(false),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis.ap-south-1.amazonaws.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func TestEndpointCase24(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"us-west-2\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(false),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis.us-west-2.amazonaws.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func TestEndpointCase18(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"us-east-1\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(false),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis.us-east-1.amazonaws.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func customSetupEndpoints(pprofActive bool, mgr manager.Manager) error {\n\tif pprofActive {\n\t\tif err := debug.RegisterEndpoint(mgr.AddMetricsExtraHandler, nil); err != nil {\n\t\t\tsetupLog.Error(err, \"Unable to register pprof endpoint\")\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func TestEndpointCase29(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"cn-northwest-1\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(false),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis.cn-northwest-1.amazonaws.com.cn\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func testEndpoint(t *testing.T, handlerFuncName string, endpoint http.HandlerFunc, vars map[string]string, reqBody io.Reader, expectedStatus int, expectedBody string) {\n\tt.Helper()\n\n\treq, _ := http.NewRequest(\"\", \"\", reqBody)\n\tif req.ContentLength > 0 {\n\t\treq.Header.Add(\"content-type\", \"application/json\")\n\t}\n\trr := httptest.NewRecorder()\n\tif vars != nil {\n\t\treq = mux.SetURLVars(req, vars)\n\t}\n\tendpoint.ServeHTTP(rr, req)\n\n\tif status := rr.Code; status != expectedStatus {\n\t\tt.Errorf(\"%v returned status %v, expected %v\", handlerFuncName, status, expectedStatus)\n\t}\n\n\tif body := rr.Body.String(); body != expectedBody {\n\t\tt.Errorf(\"%v returned body\\n%v\\nexpected\\n%v\", handlerFuncName, body, expectedBody)\n\t}\n\n}", "func TestEndpointCase15(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"eu-west-3\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(false),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis.eu-west-3.amazonaws.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func TestEndpointCase86(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"us-east-1\"),\n\t\tUseFIPS: ptr.Bool(false),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tOperationType: ptr.String(\"control\"),\n\t\tConsumerARN: ptr.String(\"arn:aws:kinesis:us-east-1:123:stream/test-stream/consumer/test-consumer:1525898737\"),\n\t\tEndpoint: ptr.String(\"https://example.com\"),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://example.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func (m *MockProvider) OnEndpointsSynced() {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"OnEndpointsSynced\")\n}", "func TestEndpointCase25(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"us-west-2\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(true),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis-fips.us-west-2.amazonaws.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func TestEndpointCase22(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"us-west-1\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(false),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis.us-west-1.amazonaws.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func TestEndpointCase88(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"us-east-1\"),\n\t\tUseFIPS: ptr.Bool(false),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tOperationType: ptr.String(\"data\"),\n\t\tConsumerARN: ptr.String(\"arn:aws:kinesis:us-east-1:123:stream/test-stream/consumer/test-consumer:1525898737\"),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://123.data-kinesis.us-east-1.amazonaws.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func TestEndpointCase59(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"us-east-1\"),\n\t\tUseFIPS: ptr.Bool(false),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tOperationType: ptr.String(\"control\"),\n\t\tStreamARN: ptr.String(\"arn:aws:kinesis:us-east-1:123:stream/test-stream\"),\n\t\tEndpoint: ptr.String(\"https://example.com\"),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://example.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func TestEndpointCase40(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"us-iso-west-1\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(false),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis.us-iso-west-1.c2s.ic.gov\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func (m *MockProc) Config() *service.Config {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Config\")\n\tret0, _ := ret[0].(*service.Config)\n\treturn ret0\n}", "func TestEndpointCase16(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"me-south-1\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(false),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis.me-south-1.amazonaws.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func TestEndpointCase20(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"us-east-2\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(false),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis.us-east-2.amazonaws.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func (swagger *MgwSwagger) getEndpoints(vendorExtensions map[string]interface{}, endpointName string) (*EndpointCluster, error) {\n\n\t// TODO: (VirajSalaka) x-wso2-production-endpoint 's type does not represent http/https, instead it indicates loadbalance and failover\n\tif endpointClusterYaml, found := vendorExtensions[endpointName]; found {\n\t\tif endpointClusterMap, ok := endpointClusterYaml.(map[string]interface{}); ok {\n\t\t\tendpointPrefix := endpointName + \"_\" + constants.XWso2EPClustersConfigNamePrefix\n\t\t\tif strings.EqualFold(endpointName, constants.XWso2ProdEndpoints) {\n\t\t\t\tendpointPrefix = constants.ProdClustersConfigNamePrefix\n\t\t\t} else if strings.EqualFold(endpointName, constants.XWso2SandbxEndpoints) {\n\t\t\t\tendpointPrefix = constants.SandClustersConfigNamePrefix\n\t\t\t}\n\t\t\tendpointCluster := EndpointCluster{\n\t\t\t\tEndpointPrefix: endpointPrefix,\n\t\t\t}\n\t\t\t// Set URLs\n\t\t\tif urlsProperty, found := endpointClusterMap[constants.Urls]; found {\n\t\t\t\tif urlsArray, ok := urlsProperty.([]interface{}); ok {\n\t\t\t\t\tendpoints, err := processEndpointUrls(urlsArray)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t}\n\t\t\t\t\tendpointCluster.Endpoints = endpoints\n\t\t\t\t\tendpointCluster.EndpointType = constants.LoadBalance\n\t\t\t\t} else {\n\t\t\t\t\treturn nil, errors.New(\"Error while parsing array of urls in \" + endpointName)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// TODO: (VirajSalaka) Throw an error and catch from an upper layer where the API name is visible.\n\t\t\t\terrMsg := \"urls property is not provided with the \" + endpointName + \" extension\"\n\t\t\t\tlogger.LoggerOasparser.Error(errMsg)\n\t\t\t\treturn nil, errors.New(errMsg)\n\t\t\t}\n\n\t\t\t// Update Endpoint Cluster type\n\t\t\tif epType, found := endpointClusterMap[constants.Type]; found {\n\t\t\t\tif endpointType, ok := epType.(string); ok {\n\t\t\t\t\tendpointCluster.EndpointType = endpointType\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Set Endpoint Config\n\t\t\tif advanceEndpointConfig, found := endpointClusterMap[constants.AdvanceEndpointConfig]; found {\n\t\t\t\tif configMap, ok := advanceEndpointConfig.(map[string]interface{}); ok {\n\t\t\t\t\tvar endpointConfig EndpointConfig\n\t\t\t\t\terr := parser.Decode(configMap, &endpointConfig)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn nil, errors.New(\"Invalid schema for advanceEndpointConfig in \" + endpointName)\n\t\t\t\t\t}\n\t\t\t\t\tendpointCluster.Config = &endpointConfig\n\t\t\t\t} else {\n\t\t\t\t\treturn nil, errors.New(\"Invalid structure for advanceEndpointConfig in \" + endpointName)\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Set Endpoint Config\n\t\t\tif securityConfig, found := endpointClusterMap[constants.SecurityConfig]; found {\n\t\t\t\tif configMap, ok := securityConfig.(map[string]interface{}); ok {\n\t\t\t\t\tvar epSecurity EndpointSecurity\n\t\t\t\t\terr := parser.Decode(configMap, &epSecurity)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn nil, errors.New(\"Invalid schema for securityConfig in API \" + swagger.title +\n\t\t\t\t\t\t\t\" : \" + swagger.version + \"for \" + endpointName)\n\t\t\t\t\t}\n\t\t\t\t\tif !strings.EqualFold(\"BASIC\", epSecurity.Type) {\n\t\t\t\t\t\treturn nil, errors.New(\"endpoint security type : \" + epSecurity.Type +\n\t\t\t\t\t\t\t\" is not currently supported with WSO2 Choreo Connect\")\n\t\t\t\t\t}\n\t\t\t\t\tepSecurity.Enabled = true\n\t\t\t\t\tendpointCluster.SecurityConfig = epSecurity\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn &endpointCluster, nil\n\t\t} else if endpointRef, ok := endpointClusterYaml.(string); ok &&\n\t\t\t(strings.EqualFold(endpointName, constants.XWso2ProdEndpoints) || strings.EqualFold(endpointName, constants.XWso2SandbxEndpoints)) {\n\t\t\trefPrefix := \"#/\" + constants.XWso2endpoints + \"/\"\n\t\t\tif strings.HasPrefix(endpointRef, refPrefix) {\n\t\t\t\tepName := strings.TrimPrefix(endpointRef, refPrefix)\n\t\t\t\tif _, found := swagger.xWso2Endpoints[epName]; found {\n\t\t\t\t\treturn swagger.xWso2Endpoints[epName], nil\n\t\t\t\t}\n\t\t\t\treturn nil, errors.New(\"Invalid endpoint reference \" + endpointRef)\n\t\t\t}\n\n\t\t}\n\t\tlogger.LoggerOasparser.Errorf(\"%v OpenAPI extension does not adhere with the schema\", endpointName)\n\t\treturn nil, errors.New(\"invalid map structure detected\")\n\t}\n\treturn nil, nil // the vendor extension for prod or sandbox just isn't present\n}", "func TestCfg(url string) *Cfg {\n\tif url == \"\" {\n\t\turl = \"http://127.0.0.1/\"\n\t} else if !strings.HasSuffix(url, \"/\") {\n\t\turl += \"/\"\n\t}\n\treturn &Cfg{\n\t\tSrc: \"test\",\n\t\tEnvironment: azure.Environment{\n\t\t\tName: azure.PublicCloud.Name,\n\t\t\tManagementPortalURL: url,\n\t\t\tPublishSettingsURL: url + \"publishsettings/index\",\n\t\t\tServiceManagementEndpoint: url,\n\t\t\tResourceManagerEndpoint: url,\n\t\t\tActiveDirectoryEndpoint: url,\n\t\t\tGalleryEndpoint: url,\n\t\t\tKeyVaultEndpoint: url,\n\t\t\tGraphEndpoint: url,\n\t\t\tServiceBusEndpoint: url,\n\t\t\tBatchManagementEndpoint: url,\n\t\t\tTokenAudience: url,\n\t\t},\n\t\tTenantID: NilGUID,\n\t\tSubscriptionID: NilGUID,\n\t\tLocation: \"eastus\",\n\t\tnewAuthz: func(string) autorest.Authorizer {\n\t\t\treturn autorest.NullAuthorizer{}\n\t\t},\n\t}\n}", "func TestEndpoint(t *testing.T) {\n\t// {\"service\":\"Service\",\"service_id\":\"ServiceId\",\"frontend\":\"Frontend\",\"deploy_path\":\"DeployPath\",\"hostname\":\"Hostname\",\"start_time\":\"StartTime\"}\n\n\t// 1. 正常的Marshal & Unmarshal\n\tendpoint := &ServiceEndpoint{\n\t\tService: \"Service\",\n\t\tServiceId: \"ServiceId\",\n\t\tFrontend: \"Frontend\",\n\t\tDeployPath: \"DeployPath\",\n\t\tHostname: \"Hostname\",\n\t\tStartTime: \"StartTime\",\n\t}\n\n\tdata, _ := json.Marshal(endpoint)\n\tfmt.Println(\"Endpoint: \", string(data))\n\n\tassert.True(t, true)\n\n\t// 2. 缺少字段时的Unmarshal(缺少的字段为空)\n\tdata21 := []byte(`{\"service\":\"Service\",\"service_id\":\"ServiceId\",\"frontend\":\"Frontend\"}`)\n\n\tendpoint2 := &ServiceEndpoint{}\n\terr2 := json.Unmarshal(data21, endpoint2)\n\tassert.True(t, err2 == nil)\n\n\tfmt.Println(\"Error2: \", err2)\n\tdata22, _ := json.Marshal(endpoint2)\n\tfmt.Println(\"Endpoint2: \", string(data22))\n\n\t// 3. 字段多的情况下的Unmarshal(多余的字段直接忽略)\n\tdata31 := []byte(`{\"service\":\"Service\", \"serviceA\":\"AService\",\"service_id\":\"ServiceId\",\"frontend\":\"Frontend\"}`)\n\tendpoint3 := &ServiceEndpoint{}\n\terr3 := json.Unmarshal(data31, endpoint3)\n\tassert.True(t, err3 == nil)\n\tfmt.Println(\"Error3: \", err3)\n\tdata32, _ := json.Marshal(endpoint3)\n\tfmt.Println(\"Endpoint3: \", string(data32))\n\n}", "func TestEndpointCase34(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"us-gov-east-1\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(true),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis.us-gov-east-1.amazonaws.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func TestEndpointCase3(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"ap-northeast-2\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(false),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis.ap-northeast-2.amazonaws.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func TestEndpointCase28(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"cn-north-1\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(false),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis.cn-north-1.amazonaws.com.cn\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func TestEndpointCase14(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"eu-west-2\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(false),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis.eu-west-2.amazonaws.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func (m *SDMock) Endpoint() string {\n\treturn m.Server.URL + \"/\"\n}", "func (policy *PolicySvc) augmentEndpoint(endpoint *common.Endpoint) error {\n\ttenantSvcUrl, err := policy.client.GetServiceUrl(\"tenant\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tif endpoint.Peer == common.Wildcard {\n\t\t// If a wildcard is specfied, there is nothing to augment\n\t\treturn nil\n\t}\n\tlog.Printf(\"Policy: Augmenting %#v\", endpoint)\n\n\t// Code below tries to resolve tenant name into tenant_network_id if possible.\n\t//\n\t// TODO this will have to be changed once we implement\n\t// https://paninetworks.kanbanize.com/ctrl_board/3/cards/319/details\n\tten := &tenant.Tenant{}\n\tif endpoint.TenantNetworkID == nil {\n\t\tif endpoint.TenantID != 0 {\n\t\t\ttenantIDToUse := strconv.FormatUint(endpoint.TenantID, 10)\n\t\t\ttenantsUrl := fmt.Sprintf(\"%s/tenants/%s\", tenantSvcUrl, tenantIDToUse)\n\t\t\tlog.Printf(\"Policy: Looking tenant up at %s\", tenantsUrl)\n\t\t\terr = policy.client.Get(tenantsUrl, ten)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tendpoint.TenantNetworkID = &ten.NetworkID\n\n\t\t} else if endpoint.TenantExternalID != \"\" || endpoint.TenantName != \"\" {\n\t\t\tif endpoint.TenantExternalID != \"\" {\n\t\t\t\tten.ExternalID = endpoint.TenantExternalID\n\t\t\t}\n\t\t\tif endpoint.TenantName != \"\" {\n\t\t\t\tten.Name = endpoint.TenantName\n\t\t\t}\n\t\t\terr = policy.client.Find(ten, common.FindLast)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tendpoint.TenantNetworkID = &ten.NetworkID\n\t\t}\n\t}\n\n\tif endpoint.SegmentNetworkID == nil {\n\t\tif ten == nil && (endpoint.SegmentID != 0 || endpoint.SegmentExternalID != \"\" || endpoint.SegmentName != \"\") {\n\t\t\treturn common.NewError400(\"No tenant information specified, cannot look up segment.\")\n\t\t}\n\t\tsegment := &tenant.Segment{}\n\t\tif endpoint.SegmentID != 0 {\n\t\t\tsegmentIDToUse := strconv.FormatUint(endpoint.SegmentID, 10)\n\t\t\tsegmentsUrl := fmt.Sprintf(\"%s/tenants/%d/segments/%s\", tenantSvcUrl, ten.ID, segmentIDToUse)\n\t\t\tlog.Printf(\"Policy: Looking segment up at %s for %#v\", segmentsUrl, endpoint)\n\t\t\terr = policy.client.Get(segmentsUrl, &segment)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tendpoint.SegmentNetworkID = &segment.NetworkID\n\t\t} else if endpoint.SegmentExternalID != \"\" || endpoint.SegmentName != \"\" {\n\t\t\tsegmentsUrl := fmt.Sprintf(\"%s/findLast/segments?tenant_id=%d&\", tenantSvcUrl, ten.ID)\n\t\t\tif endpoint.SegmentExternalID != \"\" {\n\t\t\t\tsegmentsUrl += \"external_id=\" + endpoint.TenantExternalID + \"&\"\n\t\t\t}\n\t\t\tif endpoint.SegmentName != \"\" {\n\t\t\t\tsegmentsUrl += \"name=\" + endpoint.SegmentName\n\t\t\t}\n\t\t\tlog.Printf(\"Policy: Finding segments at %s for %#v (Tenant %#v %t)\", segmentsUrl, endpoint, ten, ten == nil)\n\t\t\terr = policy.client.Get(segmentsUrl, &segment)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tendpoint.SegmentNetworkID = &segment.NetworkID\n\t\t}\n\t}\n\treturn nil\n}", "func TestEndpointCase26(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"us-east-1\"),\n\t\tUseDualStack: ptr.Bool(true),\n\t\tUseFIPS: ptr.Bool(true),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis-fips.us-east-1.api.aws\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func mockConfig(num int) *KConf {\n\tconfig := clientcmdapi.NewConfig()\n\tfor i := 0; i < num; i++ {\n\t\tvar name string\n\t\tif i == 0 {\n\t\t\tname = \"test\"\n\t\t} else {\n\t\t\tname = fmt.Sprintf(\"test-%d\", i)\n\t\t}\n\t\tconfig.Clusters[name] = &clientcmdapi.Cluster{\n\t\t\tLocationOfOrigin: \"/home/user/.kube/config\",\n\t\t\tServer: fmt.Sprintf(\"https://example-%s.com:6443\", name),\n\t\t\tInsecureSkipTLSVerify: true,\n\t\t\tCertificateAuthority: \"bbbbbbbbbbbb\",\n\t\t\tCertificateAuthorityData: []byte(\"bbbbbbbbbbbb\"),\n\t\t}\n\t\tconfig.AuthInfos[name] = &clientcmdapi.AuthInfo{\n\t\t\tLocationOfOrigin: \"/home/user/.kube/config\",\n\t\t\tToken: fmt.Sprintf(\"bbbbbbbbbbbb-%s\", name),\n\t\t}\n\t\tconfig.Contexts[name] = &clientcmdapi.Context{\n\t\t\tLocationOfOrigin: \"/home/user/.kube/config\",\n\t\t\tCluster: name,\n\t\t\tAuthInfo: name,\n\t\t\tNamespace: \"default\",\n\t\t}\n\t}\n\treturn &KConf{Config: *config}\n}", "func EndpointFactory(args *endpoint.Arg, stats *stats.Stats, workerCount uint) (endpoint.EndPoint, error) {\n\tif FailSetup {\n\t\treturn nil, errors.New(\"Forced Error\")\n\t}\n\treturn &fakeEndpoint{}, nil\n}", "func TestEndpointCase12(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"eu-south-1\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(false),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis.eu-south-1.amazonaws.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func (m *InspectorMock) Endpoint() string {\n\tif m == nil {\n\t\treturn \"https://inspector.test/v1/\"\n\t}\n\treturn m.MockServer.Endpoint()\n}", "func (n *mockAgent) configure(h hypervisor, id, sharePath string, config interface{}) error {\n\treturn nil\n}", "func TestAPIClientConfig(t *testing.T) {\n\ttestCases := []struct {\n\t\tname string\n\t\tsetup func()\n\t\tassertions func(\n\t\t\taddress string,\n\t\t\ttoken string,\n\t\t\topts restmachinery.APIClientOptions,\n\t\t\terr error,\n\t\t)\n\t}{\n\t\t{\n\t\t\tname: \"API_ADDRESS not set\",\n\t\t\tsetup: func() {},\n\t\t\tassertions: func(\n\t\t\t\t_ string,\n\t\t\t\t_ string,\n\t\t\t\t_ restmachinery.APIClientOptions,\n\t\t\t\terr error,\n\t\t\t) {\n\t\t\t\trequire.Error(t, err)\n\t\t\t\trequire.Contains(t, err.Error(), \"value not found for\")\n\t\t\t\trequire.Contains(t, err.Error(), \"API_ADDRESS\")\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"API_TOKEN not set\",\n\t\t\tsetup: func() {\n\t\t\t\tt.Setenv(\"API_ADDRESS\", \"foo\")\n\t\t\t},\n\t\t\tassertions: func(\n\t\t\t\t_ string,\n\t\t\t\t_ string,\n\t\t\t\t_ restmachinery.APIClientOptions,\n\t\t\t\terr error,\n\t\t\t) {\n\t\t\t\trequire.Error(t, err)\n\t\t\t\trequire.Contains(t, err.Error(), \"value not found for\")\n\t\t\t\trequire.Contains(t, err.Error(), \"API_TOKEN\")\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"SUCCESS not set\",\n\t\t\tsetup: func() {\n\t\t\t\tt.Setenv(\"API_TOKEN\", \"bar\")\n\t\t\t\tt.Setenv(\"API_IGNORE_CERT_WARNINGS\", \"true\")\n\t\t\t},\n\t\t\tassertions: func(\n\t\t\t\taddress string,\n\t\t\t\ttoken string,\n\t\t\t\topts restmachinery.APIClientOptions,\n\t\t\t\terr error,\n\t\t\t) {\n\t\t\t\trequire.NoError(t, err)\n\t\t\t\trequire.Equal(t, \"foo\", address)\n\t\t\t\trequire.Equal(t, \"bar\", token)\n\t\t\t\trequire.True(t, opts.AllowInsecureConnections)\n\t\t\t},\n\t\t},\n\t}\n\tfor _, testCase := range testCases {\n\t\tt.Run(testCase.name, func(t *testing.T) {\n\t\t\ttestCase.setup()\n\t\t\taddress, token, opts, err := apiClientConfig()\n\t\t\ttestCase.assertions(address, token, opts, err)\n\t\t})\n\t}\n}", "func TestEndpointCase35(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"us-gov-west-1\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(false),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis.us-gov-west-1.amazonaws.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func TestEndpointCase94(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"us-east-1\"),\n\t\tUseFIPS: ptr.Bool(false),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tOperationType: ptr.String(\"data\"),\n\t\tConsumerARN: ptr.String(\"arn:aws:kinesis:us-west-1:123:stream/testStream/consumer/test-consumer:1525898737\"),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://123.data-kinesis.us-east-1.amazonaws.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func TestEndpointCase87(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"us-east-1\"),\n\t\tUseFIPS: ptr.Bool(false),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tOperationType: ptr.String(\"control\"),\n\t\tConsumerARN: ptr.String(\"arn:aws:kinesis:us-east-1:123:stream/test-stream/consumer/test-consumer:1525898737\"),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://123.control-kinesis.us-east-1.amazonaws.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func (h Handler) TestEndpoint() error {\n\tr, err := http.Get(h.url)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif r.StatusCode != 200 {\n\t\treturn errors.New(\"Endpoint not replying typical 200 answer on ping\")\n\t}\n\n\treturn nil\n}", "func TestCustomAnchoreConfigProvider_GetConfiguration(t *testing.T) {\n\tintegratedServiceRepository := integratedservices.NewInMemoryIntegratedServiceRepository(map[uint][]integratedservices.IntegratedService{\n\t\t1: {\n\t\t\t{\n\t\t\t\tName: \"securityscan\",\n\t\t\t\tSpec: map[string]interface{}{\n\t\t\t\t\t\"customAnchore\": map[string]interface{}{\n\t\t\t\t\t\t\"enabled\": true,\n\t\t\t\t\t\t\"url\": \"https://anchore.example.com\",\n\t\t\t\t\t\t\"secretId\": \"secretId\",\n\t\t\t\t\t\t\"insecure\": true,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tOutput: nil,\n\t\t\t\tStatus: integratedservices.IntegratedServiceStatusActive,\n\t\t\t},\n\t\t},\n\t})\n\n\tsecretStore := new(SecretStore)\n\tsecretStore.On(\"GetSecretValues\", mock.Anything, \"secretId\").Return(\n\t\tmap[string]string{\n\t\t\t\"username\": \"user\",\n\t\t\t\"password\": \"password\",\n\t\t},\n\t\tnil,\n\t)\n\n\tconfigProvider := NewCustomAnchoreConfigProvider(integratedServiceRepository, secretStore, services.NoopLogger{})\n\n\tconfig, err := configProvider.GetConfiguration(context.Background(), 1)\n\trequire.NoError(t, err)\n\n\tassert.Equal(\n\t\tt,\n\t\tanchore.Config{\n\t\t\tEndpoint: \"https://anchore.example.com\",\n\t\t\tUser: \"user\",\n\t\t\tPassword: \"password\",\n\t\t\tInsecure: true,\n\t\t},\n\t\tconfig,\n\t)\n\n\tsecretStore.AssertExpectations(t)\n}", "func TestEndpointCase46(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"us-east-1\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(true),\n\t\tEndpoint: ptr.String(\"https://example.com\"),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err == nil {\n\t\tt.Fatalf(\"expect error, got none\")\n\t}\n\tif e, a := \"Invalid Configuration: FIPS and custom endpoint are not supported\", err.Error(); !strings.Contains(a, e) {\n\t\tt.Errorf(\"expect %v error in %v\", e, a)\n\t}\n}", "func TestEndpointCase6(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"ap-southeast-1\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(false),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis.ap-southeast-1.amazonaws.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func TestEndpointCase47(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"us-east-1\"),\n\t\tUseDualStack: ptr.Bool(true),\n\t\tUseFIPS: ptr.Bool(false),\n\t\tEndpoint: ptr.String(\"https://example.com\"),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err == nil {\n\t\tt.Fatalf(\"expect error, got none\")\n\t}\n\tif e, a := \"Invalid Configuration: Dualstack and custom endpoint are not supported\", err.Error(); !strings.Contains(a, e) {\n\t\tt.Errorf(\"expect %v error in %v\", e, a)\n\t}\n}", "func TestEndpointCase66(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"us-west-1\"),\n\t\tUseFIPS: ptr.Bool(false),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tOperationType: ptr.String(\"control\"),\n\t\tStreamARN: ptr.String(\"arn:aws:kinesis:us-west-1:123:stream/test-stream\"),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://123.control-kinesis.us-west-1.amazonaws.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func (m *MockAPI) SupportsJobsEndpoint() (bool, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"SupportsJobsEndpoint\")\n\tret0, _ := ret[0].(bool)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func TestGetAPIEndpointsSite(t *testing.T) {\n\tfor _, tc := range []struct {\n\t\tname string\n\t\tsite string\n\t\tddURL, eventsDDURL string\n\t\texpectedHostname, expectedEventsHostname string\n\t}{\n\t\t{\n\t\t\tname: \"site only\",\n\t\t\tsite: \"datadoghq.io\",\n\t\t\texpectedHostname: \"process.datadoghq.io\",\n\t\t\texpectedEventsHostname: \"process-events.datadoghq.io\",\n\t\t},\n\t\t{\n\t\t\tname: \"dd_url only\",\n\t\t\tddURL: \"https://process.datadoghq.eu\",\n\t\t\texpectedHostname: \"process.datadoghq.eu\",\n\t\t\texpectedEventsHostname: \"process-events.datadoghq.com\",\n\t\t},\n\t\t{\n\t\t\tname: \"events_dd_url only\",\n\t\t\teventsDDURL: \"https://process-events.datadoghq.eu\",\n\t\t\texpectedHostname: \"process.datadoghq.com\",\n\t\t\texpectedEventsHostname: \"process-events.datadoghq.eu\",\n\t\t},\n\t\t{\n\t\t\tname: \"both site and dd_url\",\n\t\t\tsite: \"datacathq.eu\",\n\t\t\tddURL: \"https://burrito.com\",\n\t\t\teventsDDURL: \"https://burrito-events.com\",\n\t\t\texpectedHostname: \"burrito.com\",\n\t\t\texpectedEventsHostname: \"burrito-events.com\",\n\t\t},\n\t} {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tcfg := config.Mock(t)\n\t\t\tif tc.site != \"\" {\n\t\t\t\tcfg.Set(\"site\", tc.site)\n\t\t\t}\n\t\t\tif tc.ddURL != \"\" {\n\t\t\t\tcfg.Set(\"process_config.process_dd_url\", tc.ddURL)\n\t\t\t}\n\t\t\tif tc.eventsDDURL != \"\" {\n\t\t\t\tcfg.Set(\"process_config.events_dd_url\", tc.eventsDDURL)\n\t\t\t}\n\n\t\t\teps, err := endpoint.GetAPIEndpoints(cfg)\n\t\t\tassert.NoError(t, err)\n\n\t\t\tmainEndpoint := eps[0]\n\t\t\tassert.Equal(t, tc.expectedHostname, mainEndpoint.Endpoint.Hostname())\n\n\t\t\teventsEps, err := endpoint.GetEventsAPIEndpoints(cfg)\n\t\t\tassert.NoError(t, err)\n\n\t\t\tmainEventEndpoint := eventsEps[0]\n\t\t\tassert.Equal(t, tc.expectedEventsHostname, mainEventEndpoint.Endpoint.Hostname())\n\t\t})\n\t}\n}", "func TestConfiguration(t *testing.T) { TestingT(t) }", "func TestGetConnectorConfig(t *testing.T) {\n\tbaseURL := \"https://fake.api\"\n\tc := NewClient(WithHost(baseURL))\n\n\thttpmock.ActivateNonDefault(c.client.GetClient())\n\tdefer httpmock.DeactivateAndReset()\n\n\thttpmock.RegisterResponder(\"GET\", baseURL+\"/connectors/datagen-product/config\", newJsonStringResponder(http.StatusOK, `{\"connector.class\":\"io.confluent.kafka.connect.datagen.DatagenConnector\",\"quickstart\":\"product\",\"tasks.max\":\"1\",\"value.converter.schemas.enable\":\"false\",\"name\":\"datagen-product\",\"kafka.topic\":\"product\",\"max.interval\":\"1000\",\"iterations\":\"10000000\"}`))\n\tinfo, err := c.GetConnectorConfig(context.Background(), \"datagen-product\")\n\tassert.NoError(t, err)\n\tassert.Equal(t, \"io.confluent.kafka.connect.datagen.DatagenConnector\", info[\"connector.class\"])\n\tassert.Equal(t, \"1000\", info[\"max.interval\"])\n}", "func (m *MockLogic) Config() *config.AppConfig {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Config\")\n\tret0, _ := ret[0].(*config.AppConfig)\n\treturn ret0\n}", "func TestEndpointCase42(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"us-isob-east-1\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(false),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis.us-isob-east-1.sc2s.sgov.gov\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func TestEndpointCase60(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"us-east-1\"),\n\t\tUseFIPS: ptr.Bool(false),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tOperationType: ptr.String(\"control\"),\n\t\tStreamARN: ptr.String(\"arn:aws:kinesis:us-east-1:123:stream/test-stream\"),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://123.control-kinesis.us-east-1.amazonaws.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func (m *MockProc) OnSvcConfigUpdate(arg0 *service.Config) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"OnSvcConfigUpdate\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func TestEndpointCase36(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"us-gov-west-1\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(true),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis.us-gov-west-1.amazonaws.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func TestEndpointCase23(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"us-west-1\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(true),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis-fips.us-west-1.amazonaws.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func (m *MockConfiguration) EndSessionEndpoint() op.Endpoint {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"EndSessionEndpoint\")\n\tret0, _ := ret[0].(op.Endpoint)\n\treturn ret0\n}", "func (_m *Knapsack) OsqueryTlsConfigEndpoint() string {\n\tret := _m.Called()\n\n\tvar r0 string\n\tif rf, ok := ret.Get(0).(func() string); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tr0 = ret.Get(0).(string)\n\t}\n\n\treturn r0\n}", "func TestConfiguration(t *testing.T) {\n\tconst (\n\t\tbbbCmdScript string = \"/path/to/cmd-script.sh\"\n\t\tbbbConfigScript string = \"/path/to/config-script.sh\"\n\t\tbbbSystemctlScript string = \"/path/to/systemctl-script.sh\"\n\t\telectrsRPCPort string = \"18442\"\n\t\timageUpdateInfoURL string = \"https://shiftcrypto.ch/updates/base.json\"\n\t\tmiddlewarePort string = \"8085\"\n\t\tmiddlewareVersion string = \"0.0.1\"\n\t\tnetwork string = \"testnet\"\n\t\tnotificationNamedPipePath string = \"/tmp/middleware-notification.pipe\"\n\t\tprometheusURL string = \"http://localhost:9090\"\n\t\tredisMock bool = false\n\t\tredisPort string = \"6379\"\n\t)\n\n\tconfig := configuration.NewConfiguration(\n\t\tconfiguration.Args{\n\t\t\tBBBCmdScript: bbbCmdScript,\n\t\t\tBBBConfigScript: bbbConfigScript,\n\t\t\tBBBSystemctlScript: bbbSystemctlScript,\n\t\t\tElectrsRPCPort: electrsRPCPort,\n\t\t\tImageUpdateInfoURL: imageUpdateInfoURL,\n\t\t\tMiddlewarePort: middlewarePort,\n\t\t\tMiddlewareVersion: middlewareVersion,\n\t\t\tNetwork: network,\n\t\t\tNotificationNamedPipePath: notificationNamedPipePath,\n\t\t\tPrometheusURL: prometheusURL,\n\t\t\tRedisMock: redisMock,\n\t\t\tRedisPort: redisPort,\n\t\t},\n\t)\n\n\trequire.Equal(t, bbbCmdScript, config.GetBBBCmdScript())\n\trequire.Equal(t, bbbConfigScript, config.GetBBBConfigScript())\n\trequire.Equal(t, bbbSystemctlScript, config.GetBBBSystemctlScript())\n\trequire.Equal(t, electrsRPCPort, config.GetElectrsRPCPort())\n\trequire.Equal(t, imageUpdateInfoURL, config.GetImageUpdateInfoURL())\n\trequire.Equal(t, middlewarePort, config.GetMiddlewarePort())\n\trequire.Equal(t, middlewareVersion, config.GetMiddlewareVersion())\n\trequire.Equal(t, network, config.GetNetwork())\n\trequire.Equal(t, notificationNamedPipePath, config.GetNotificationNamedPipePath())\n\trequire.Equal(t, prometheusURL, config.GetPrometheusURL())\n\trequire.Equal(t, redisPort, config.GetRedisPort())\n}", "func TestEndpointCase31(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"cn-north-1\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(true),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis-fips.cn-north-1.amazonaws.com.cn\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func TestFailedEndpoint1(t *testing.T) {\n\tisTesting = true\n\tvar request = Request{\n\t\tPath: \"/api/device\",\n\t\tHTTPMethod: \"GET\",\n\t}\n\tvar response, _ = Handler(request)\n\tif response.StatusCode != 404 {\n\t\tt.Errorf(\"response status code has to be 404 but is %d\", response.StatusCode)\n\t}\n\tif response.Body != `{\"message\":\"requested endpoint not found\"}` {\n\t\tt.Errorf(\"body is: %s\", response.Body)\n\t}\n}", "func TestEndpointCase21(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"us-east-2\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(true),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis-fips.us-east-2.amazonaws.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func TestConfigure(t *testing.T) {\n\tprops := map[string]interface{}{\n\t\t\"interval\": 500,\n\t\t\"path\": \"test\",\n\t}\n\tm := File().(*fileSink)\n\terr := m.Configure(props)\n\tif err != nil {\n\t\tt.Errorf(\"Configure() error = %v, wantErr nil\", err)\n\t}\n\tif m.c.Path != \"test\" {\n\t\tt.Errorf(\"Configure() Path = %v, want test\", m.c.Path)\n\t}\n\terr = m.Configure(map[string]interface{}{\"interval\": 500, \"path\": \"\"})\n\tif err == nil {\n\t\tt.Errorf(\"Configure() error = %v, wantErr not nil\", err)\n\t}\n\terr = m.Configure(map[string]interface{}{\"fileType\": \"csv2\"})\n\tif err == nil {\n\t\tt.Errorf(\"Configure() error = %v, wantErr not nil\", err)\n\t}\n\terr = m.Configure(map[string]interface{}{\n\t\t\"interval\": 500,\n\t\t\"path\": \"test\",\n\t\t\"fileType\": \"csv\",\n\t})\n\tif err == nil {\n\t\tt.Errorf(\"Configure() error = %v, wantErr not nil\", err)\n\t}\n\terr = m.Configure(map[string]interface{}{\"interval\": 60, \"path\": \"test\", \"checkInterval\": -1})\n\tif err == nil {\n\t\tt.Errorf(\"Configure() error = %v, wantErr not nil\", err)\n\t}\n\terr = m.Configure(map[string]interface{}{\"rollingInterval\": -1})\n\tif err == nil {\n\t\tt.Errorf(\"Configure() error = %v, wantErr not nil\", err)\n\t}\n\terr = m.Configure(map[string]interface{}{\"rollingCount\": -1})\n\tif err == nil {\n\t\tt.Errorf(\"Configure() error = %v, wantErr not nil\", err)\n\t}\n\terr = m.Configure(map[string]interface{}{\"rollingCount\": 0, \"rollingInterval\": 0})\n\tif err == nil {\n\t\tt.Errorf(\"Configure() error = %v, wantErr not nil\", err)\n\t}\n\terr = m.Configure(map[string]interface{}{\"RollingNamePattern\": \"test\"})\n\tif err == nil {\n\t\tt.Errorf(\"Configure() error = %v, wantErr not nil\", err)\n\t}\n\terr = m.Configure(map[string]interface{}{\"RollingNamePattern\": 0})\n\tif err == nil {\n\t\tt.Errorf(\"Configure() error = %v, wantErr not nil\", err)\n\t}\n\n\tfor k := range compressionTypes {\n\t\terr = m.Configure(map[string]interface{}{\n\t\t\t\"interval\": 500,\n\t\t\t\"path\": \"test\",\n\t\t\t\"compression\": k,\n\t\t\t\"rollingNamePattern\": \"suffix\",\n\t\t})\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Configure() error = %v, wantErr nil\", err)\n\t\t}\n\t\tif m.c.Compression != k {\n\t\t\tt.Errorf(\"Configure() Compression = %v, want %v\", m.c.Compression, k)\n\t\t}\n\t}\n\n\terr = m.Configure(map[string]interface{}{\n\t\t\"interval\": 500,\n\t\t\"path\": \"test\",\n\t\t\"compression\": \"\",\n\t\t\"rollingNamePattern\": \"suffix\",\n\t})\n\tif err != nil {\n\t\tt.Errorf(\"Configure() error = %v, wantErr nil\", err)\n\t}\n\tif m.c.Compression != \"\" {\n\t\tt.Errorf(\"Configure() Compression = %v, want %v\", m.c.Compression, \"\")\n\t}\n\n\terr = m.Configure(map[string]interface{}{\n\t\t\"interval\": 500,\n\t\t\"path\": \"test\",\n\t\t\"compression\": \"not_exist_algorithm\",\n\t})\n\tif err == nil {\n\t\tt.Errorf(\"Configure() error = %v, wantErr not nil\", err)\n\t}\n}", "func TestEndpointCase72(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"us-isob-east-1\"),\n\t\tUseFIPS: ptr.Bool(false),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tOperationType: ptr.String(\"data\"),\n\t\tStreamARN: ptr.String(\"arn:aws-iso-b:kinesis:us-isob-east-1:123:stream/test-stream\"),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis.us-isob-east-1.sc2s.sgov.gov\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func TestEndpointCase13(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"eu-west-1\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(false),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis.eu-west-1.amazonaws.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func TestEndpointCase101(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"us-isob-east-1\"),\n\t\tUseFIPS: ptr.Bool(true),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tOperationType: ptr.String(\"data\"),\n\t\tConsumerARN: ptr.String(\"arn:aws-iso-b:kinesis:us-isob-east-1:123:stream/test-stream/consumer/test-consumer:1525898737\"),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis-fips.us-isob-east-1.sc2s.sgov.gov\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func (m *MockProvider) OnEndpointsUpdate(arg0, arg1 *v1.Endpoints) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"OnEndpointsUpdate\", arg0, arg1)\n}", "func TestEndpointCase17(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"sa-east-1\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(false),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis.sa-east-1.amazonaws.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func TestEndpointCase30(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"cn-north-1\"),\n\t\tUseDualStack: ptr.Bool(true),\n\t\tUseFIPS: ptr.Bool(true),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis-fips.cn-north-1.api.amazonwebservices.com.cn\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func TestEndpointCase43(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"us-isob-east-1\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(true),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis-fips.us-isob-east-1.sc2s.sgov.gov\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func (c *ServerConfig) getConfigEndpoint() string {\n\tnurl := *c.ParsedEndpoint\n\tnurl.Path = path.Join(nurl.Path, c.APIPaths.Config)\n\treturn nurl.String()\n}", "func TestEndpointCase8(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"ap-southeast-3\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(false),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis.ap-southeast-3.amazonaws.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func TestEndpointCase74(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"us-isob-east-1\"),\n\t\tUseFIPS: ptr.Bool(true),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tOperationType: ptr.String(\"data\"),\n\t\tStreamARN: ptr.String(\"arn:aws-iso-b:kinesis:us-isob-east-1:123:stream/test-stream\"),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis-fips.us-isob-east-1.sc2s.sgov.gov\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}" ]
[ "0.7244226", "0.62881446", "0.6148093", "0.607511", "0.60254085", "0.59867734", "0.59809434", "0.5971515", "0.5964234", "0.5937066", "0.5932493", "0.5927245", "0.58994836", "0.5884062", "0.58370537", "0.5783843", "0.5769066", "0.5700508", "0.5699805", "0.56984586", "0.5690053", "0.56697416", "0.5666805", "0.5644141", "0.56359106", "0.5632857", "0.5620694", "0.56165326", "0.5609913", "0.5601592", "0.560002", "0.5598766", "0.55978227", "0.55954623", "0.55734885", "0.5563423", "0.55619204", "0.55592895", "0.5546083", "0.5543883", "0.5530128", "0.5526328", "0.55163777", "0.5507484", "0.550522", "0.5504497", "0.5502939", "0.5487244", "0.5482437", "0.54715306", "0.5469288", "0.545897", "0.54550785", "0.54540384", "0.5449529", "0.54442734", "0.5442012", "0.54413307", "0.5437899", "0.5433939", "0.5428798", "0.5427225", "0.54257876", "0.5423628", "0.5423548", "0.5418274", "0.5412066", "0.54106", "0.540735", "0.5399175", "0.53984535", "0.53755426", "0.5349576", "0.5344264", "0.53426164", "0.53404826", "0.53365374", "0.5334806", "0.53331846", "0.5327109", "0.5327019", "0.53194255", "0.5313424", "0.5313043", "0.5312203", "0.5311596", "0.5303168", "0.5302402", "0.5301216", "0.5297687", "0.5295873", "0.529197", "0.52880824", "0.5279044", "0.52784693", "0.5278219", "0.5277614", "0.5269868", "0.52644575", "0.5264322" ]
0.7284712
0
EndpointConfig indicates an expected call of EndpointConfig
func (mr *MockClientMockRecorder) EndpointConfig() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "EndpointConfig", reflect.TypeOf((*MockClient)(nil).EndpointConfig)) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (mr *MockProvidersMockRecorder) EndpointConfig() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"EndpointConfig\", reflect.TypeOf((*MockProviders)(nil).EndpointConfig))\n}", "func (m *MockClient) EndpointConfig() fab.EndpointConfig {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"EndpointConfig\")\n\tret0, _ := ret[0].(fab.EndpointConfig)\n\treturn ret0\n}", "func (m *MockProviders) EndpointConfig() fab.EndpointConfig {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"EndpointConfig\")\n\tret0, _ := ret[0].(fab.EndpointConfig)\n\treturn ret0\n}", "func (c *Provider) EndpointConfig() fab.EndpointConfig {\n\treturn c.endpointConfig\n}", "func TestInvalidConfiguration(t *testing.T) {\n\tt.Parallel()\n\t// Start a test gRPC server.\n\t_ = mock.NewBase64Plugin(t, newEndpoint().path)\n\n\tctx := testContext(t)\n\n\tinvalidConfigs := []struct {\n\t\tname string\n\t\tendpoint string\n\t}{\n\t\t{\"emptyConfiguration\", \"\"},\n\t\t{\"invalidScheme\", \"tcp://localhost:6060\"},\n\t}\n\n\tfor _, testCase := range invalidConfigs {\n\t\tt.Run(testCase.name, func(t *testing.T) {\n\t\t\t_, err := NewGRPCService(ctx, testCase.endpoint, 1*time.Second)\n\t\t\tif err == nil {\n\t\t\t\tt.Fatalf(\"should fail to create envelope service for %s.\", testCase.name)\n\t\t\t}\n\t\t})\n\t}\n}", "func WithEndpoint(endpoint string) {\n\tcfg.endpoint = strings.TrimRight(endpoint, \"/\")\n}", "func TestEndpointCase1(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"ap-east-1\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(false),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis.ap-east-1.amazonaws.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func (h Handler) TestEndpoint() error {\n\tr, err := http.Get(h.url)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif r.StatusCode != 200 {\n\t\treturn errors.New(\"Endpoint not replying typical 200 answer on ping\")\n\t}\n\n\treturn nil\n}", "func TestEndpointCase0(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"af-south-1\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(false),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis.af-south-1.amazonaws.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func TestEndpointCase46(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"us-east-1\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(true),\n\t\tEndpoint: ptr.String(\"https://example.com\"),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err == nil {\n\t\tt.Fatalf(\"expect error, got none\")\n\t}\n\tif e, a := \"Invalid Configuration: FIPS and custom endpoint are not supported\", err.Error(); !strings.Contains(a, e) {\n\t\tt.Errorf(\"expect %v error in %v\", e, a)\n\t}\n}", "func (c *ServerConfig) getConfigEndpoint() string {\n\tnurl := *c.ParsedEndpoint\n\tnurl.Path = path.Join(nurl.Path, c.APIPaths.Config)\n\treturn nurl.String()\n}", "func TestEndpointCase47(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"us-east-1\"),\n\t\tUseDualStack: ptr.Bool(true),\n\t\tUseFIPS: ptr.Bool(false),\n\t\tEndpoint: ptr.String(\"https://example.com\"),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err == nil {\n\t\tt.Fatalf(\"expect error, got none\")\n\t}\n\tif e, a := \"Invalid Configuration: Dualstack and custom endpoint are not supported\", err.Error(); !strings.Contains(a, e) {\n\t\tt.Errorf(\"expect %v error in %v\", e, a)\n\t}\n}", "func TestEndpointCase5(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"ap-south-1\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(false),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis.ap-south-1.amazonaws.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func TestEndpointCase44(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"us-east-1\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(false),\n\t\tEndpoint: ptr.String(\"https://example.com\"),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://example.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func validateAdapterEndpoint(endpoint string, adapterName string, errs []error) []error {\n\tif endpoint == \"\" {\n\t\treturn append(errs, fmt.Errorf(\"There's no default endpoint available for %s. Calls to this bidder/exchange will fail. \"+\n\t\t\t\"Please set adapters.%s.endpoint in your app config\", adapterName, adapterName))\n\t}\n\n\t// Create endpoint template\n\tendpointTemplate, err := template.New(\"endpointTemplate\").Parse(endpoint)\n\tif err != nil {\n\t\treturn append(errs, fmt.Errorf(\"Invalid endpoint template: %s for adapter: %s. %v\", endpoint, adapterName, err))\n\t}\n\t// Resolve macros (if any) in the endpoint URL\n\tresolvedEndpoint, err := macros.ResolveMacros(*endpointTemplate, macros.EndpointTemplateParams{\n\t\tHost: dummyHost,\n\t\tPublisherID: dummyPublisherID,\n\t\tAccountID: dummyAccountID,\n\t})\n\tif err != nil {\n\t\treturn append(errs, fmt.Errorf(\"Unable to resolve endpoint: %s for adapter: %s. %v\", endpoint, adapterName, err))\n\t}\n\t// Validate the resolved endpoint\n\t//\n\t// Validating using both IsURL and IsRequestURL because IsURL allows relative paths\n\t// whereas IsRequestURL requires absolute path but fails to check other valid URL\n\t// format constraints.\n\t//\n\t// For example: IsURL will allow \"abcd.com\" but IsRequestURL won't\n\t// IsRequestURL will allow \"http://http://abcd.com\" but IsURL won't\n\tif !validator.IsURL(resolvedEndpoint) || !validator.IsRequestURL(resolvedEndpoint) {\n\t\terrs = append(errs, fmt.Errorf(\"The endpoint: %s for %s is not a valid URL\", resolvedEndpoint, adapterName))\n\t}\n\treturn errs\n}", "func (nse ErrNoSuchEndpoint) NotFound() {}", "func (mr *MockConfigurationMockRecorder) IntrospectionEndpoint() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"IntrospectionEndpoint\", reflect.TypeOf((*MockConfiguration)(nil).IntrospectionEndpoint))\n}", "func (m *MockConfiguration) IntrospectionEndpoint() op.Endpoint {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"IntrospectionEndpoint\")\n\tret0, _ := ret[0].(op.Endpoint)\n\treturn ret0\n}", "func (o ClusterOutput) ConfigurationEndpoint() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Cluster) pulumi.StringOutput { return v.ConfigurationEndpoint }).(pulumi.StringOutput)\n}", "func TestEndpointCase45(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(false),\n\t\tEndpoint: ptr.String(\"https://example.com\"),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://example.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func Test_convertEndpointsConfig(t *testing.T) {\n\ttype args struct {\n\t\txdsEndpoint *xdsendpoint.LocalityLbEndpoints\n\t}\n\ttests := []struct {\n\t\tname string\n\t\targs args\n\t\twant []v2.Host\n\t}{\n\t\t{\n\t\t\tname: \"case1\",\n\t\t\targs: args{\n\t\t\t\txdsEndpoint: &xdsendpoint.LocalityLbEndpoints{\n\t\t\t\t\tPriority: 1,\n\t\t\t\t},\n\t\t\t},\n\t\t\twant: []v2.Host{},\n\t\t},\n\t\t{\n\t\t\tname: \"case2\",\n\t\t\targs: args{\n\t\t\t\txdsEndpoint: &xdsendpoint.LocalityLbEndpoints{\n\t\t\t\t\tLbEndpoints: []*xdsendpoint.LbEndpoint{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tHostIdentifier: &xdsendpoint.LbEndpoint_Endpoint{\n\t\t\t\t\t\t\t\tEndpoint: &xdsendpoint.Endpoint{\n\t\t\t\t\t\t\t\t\tAddress: &core.Address{\n\t\t\t\t\t\t\t\t\t\tAddress: &core.Address_SocketAddress{\n\t\t\t\t\t\t\t\t\t\t\tSocketAddress: &core.SocketAddress{\n\t\t\t\t\t\t\t\t\t\t\t\tAddress: \"192.168.0.1\",\n\t\t\t\t\t\t\t\t\t\t\t\tProtocol: core.SocketAddress_TCP,\n\t\t\t\t\t\t\t\t\t\t\t\tPortSpecifier: &core.SocketAddress_PortValue{PortValue: 8080},\n\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tLoadBalancingWeight: &wrappers.UInt32Value{Value: 20},\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tHostIdentifier: &xdsendpoint.LbEndpoint_Endpoint{\n\t\t\t\t\t\t\t\tEndpoint: &xdsendpoint.Endpoint{\n\t\t\t\t\t\t\t\t\tAddress: &core.Address{\n\t\t\t\t\t\t\t\t\t\tAddress: &core.Address_SocketAddress{\n\t\t\t\t\t\t\t\t\t\t\tSocketAddress: &core.SocketAddress{\n\t\t\t\t\t\t\t\t\t\t\t\tAddress: \"192.168.0.2\",\n\t\t\t\t\t\t\t\t\t\t\t\tProtocol: core.SocketAddress_TCP,\n\t\t\t\t\t\t\t\t\t\t\t\tPortSpecifier: &core.SocketAddress_PortValue{PortValue: 8080},\n\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tLoadBalancingWeight: &wrappers.UInt32Value{Value: 0},\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tHostIdentifier: &xdsendpoint.LbEndpoint_Endpoint{\n\t\t\t\t\t\t\t\tEndpoint: &xdsendpoint.Endpoint{\n\t\t\t\t\t\t\t\t\tAddress: &core.Address{\n\t\t\t\t\t\t\t\t\t\tAddress: &core.Address_SocketAddress{\n\t\t\t\t\t\t\t\t\t\t\tSocketAddress: &core.SocketAddress{\n\t\t\t\t\t\t\t\t\t\t\t\tAddress: \"192.168.0.3\",\n\t\t\t\t\t\t\t\t\t\t\t\tProtocol: core.SocketAddress_TCP,\n\t\t\t\t\t\t\t\t\t\t\t\tPortSpecifier: &core.SocketAddress_PortValue{PortValue: 8080},\n\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tLoadBalancingWeight: &wrappers.UInt32Value{Value: 200},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\twant: []v2.Host{\n\t\t\t\t{\n\t\t\t\t\tHostConfig: v2.HostConfig{\n\t\t\t\t\t\tAddress: \"192.168.0.1:8080\",\n\t\t\t\t\t\tWeight: 20,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tHostConfig: v2.HostConfig{\n\t\t\t\t\t\tAddress: \"192.168.0.2:8080\",\n\t\t\t\t\t\tWeight: configmanager.MinHostWeight,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tHostConfig: v2.HostConfig{\n\t\t\t\t\t\tAddress: \"192.168.0.3:8080\",\n\t\t\t\t\t\tWeight: configmanager.MaxHostWeight,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tif got := ConvertEndpointsConfig(tt.args.xdsEndpoint); !reflect.DeepEqual(got, tt.want) {\n\t\t\t\tt.Errorf(\"convertEndpointsConfig() = %v, want %v\", got, tt.want)\n\t\t\t}\n\t\t})\n\t}\n}", "func EndpointForCondition(predicate predicate.Predicate, configFunc func()) {\n\touterCurrentMockHandler := currentMockHandler\n\tconfigFunc()\n\tcurrentMockery.HandleForCondition(DefaultPriority, predicate, currentMockHandler)\n\tcurrentMockHandler = outerCurrentMockHandler\n}", "func TestEndpointCase2(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"ap-northeast-1\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(false),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis.ap-northeast-1.amazonaws.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func TestFailedEndpoint1(t *testing.T) {\n\tisTesting = true\n\tvar request = Request{\n\t\tPath: \"/api/device\",\n\t\tHTTPMethod: \"GET\",\n\t}\n\tvar response, _ = Handler(request)\n\tif response.StatusCode != 404 {\n\t\tt.Errorf(\"response status code has to be 404 but is %d\", response.StatusCode)\n\t}\n\tif response.Body != `{\"message\":\"requested endpoint not found\"}` {\n\t\tt.Errorf(\"body is: %s\", response.Body)\n\t}\n}", "func TestEndpointCase4(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"ap-northeast-3\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(false),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis.ap-northeast-3.amazonaws.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func assertEqualEndpoints(t *testing.T, expected, actual *Endpoint) {\n\tif !reflect.DeepEqual(*expected, *actual) {\n\t\tt.Errorf(\"Expected endpoint: %v, Actual %v\", expected, actual)\n\t}\n}", "func (h *HeaderfileWriter) WriteEndpointConfig(w io.Writer, e datapath.EndpointConfiguration) error {\n\tfw := bufio.NewWriter(w)\n\n\twriteIncludes(w)\n\th.writeStaticData(fw, e)\n\n\treturn h.writeTemplateConfig(fw, e)\n}", "func TestEndpointCase25(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"us-west-2\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(true),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis-fips.us-west-2.amazonaws.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func TestEndpointCase84(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"us-iso-west-1\"),\n\t\tUseFIPS: ptr.Bool(true),\n\t\tUseDualStack: ptr.Bool(true),\n\t\tConsumerARN: ptr.String(\"arn:aws-iso:kinesis:us-iso-west-1:123456789012:stream/testStream/consumer/test-consumer:1525898737\"),\n\t\tOperationType: ptr.String(\"control\"),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err == nil {\n\t\tt.Fatalf(\"expect error, got none\")\n\t}\n\tif e, a := \"FIPS and DualStack are enabled, but this partition does not support one or both\", err.Error(); !strings.Contains(a, e) {\n\t\tt.Errorf(\"expect %v error in %v\", e, a)\n\t}\n}", "func TestEndpointCase6(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"ap-southeast-1\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(false),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis.ap-southeast-1.amazonaws.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func (o ServiceOutput) EndpointSpec() ServiceEndpointSpecOutput {\n\treturn o.ApplyT(func(v *Service) ServiceEndpointSpecOutput { return v.EndpointSpec }).(ServiceEndpointSpecOutput)\n}", "func TestEndpointCase27(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"us-east-1\"),\n\t\tUseDualStack: ptr.Bool(true),\n\t\tUseFIPS: ptr.Bool(false),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis.us-east-1.api.aws\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func customSetupEndpoints(pprofActive bool, mgr manager.Manager) error {\n\tif pprofActive {\n\t\tif err := debug.RegisterEndpoint(mgr.AddMetricsExtraHandler, nil); err != nil {\n\t\t\tsetupLog.Error(err, \"Unable to register pprof endpoint\")\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func TestEndpointCase10(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"eu-central-1\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(false),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis.eu-central-1.amazonaws.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func TestEndpointCase12(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"eu-south-1\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(false),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis.eu-south-1.amazonaws.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func TestEndpointCase15(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"eu-west-3\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(false),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis.eu-west-3.amazonaws.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func TestEndpointCase75(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"us-east-1\"),\n\t\tUseFIPS: ptr.Bool(false),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tConsumerARN: ptr.String(\"arn\"),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err == nil {\n\t\tt.Fatalf(\"expect error, got none\")\n\t}\n\tif e, a := \"Invalid ARN: Failed to parse ARN.\", err.Error(); !strings.Contains(a, e) {\n\t\tt.Errorf(\"expect %v error in %v\", e, a)\n\t}\n}", "func TestEndpointCase40(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"us-iso-west-1\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(false),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis.us-iso-west-1.c2s.ic.gov\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func TestEndpointCase18(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"us-east-1\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(false),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis.us-east-1.amazonaws.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func (c *MockRemoteWriteClient) Endpoint() string { return \"\" }", "func TestFailedEndpoint0(t *testing.T) {\n\tisTesting = true\n\tvar request = Request{\n\t\tPath: \"/api/devices\",\n\t\tHTTPMethod: \"PUT\",\n\t}\n\tvar response, _ = Handler(request)\n\tif response.StatusCode != 404 {\n\t\tt.Errorf(\"response status code has to be 404 but is %d\", response.StatusCode)\n\t}\n\tif response.Body != `{\"message\":\"requested endpoint not found\"}` {\n\t\tt.Errorf(\"body is: %s\", response.Body)\n\t}\n}", "func TestEndpointCase34(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"us-gov-east-1\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(true),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis.us-gov-east-1.amazonaws.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func TestEndpointCase24(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"us-west-2\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(false),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis.us-west-2.amazonaws.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func IsEndpointDisabled(err error) bool {\n\treturn unwrapError(err) == ErrEndpointDisabled\n}", "func TestEndpointCase48(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"us-east-1\"),\n\t\tUseFIPS: ptr.Bool(false),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tStreamARN: ptr.String(\"arn\"),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err == nil {\n\t\tt.Fatalf(\"expect error, got none\")\n\t}\n\tif e, a := \"Invalid ARN: Failed to parse ARN.\", err.Error(); !strings.Contains(a, e) {\n\t\tt.Errorf(\"expect %v error in %v\", e, a)\n\t}\n}", "func TestEndpointCase80(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"us-east-1\"),\n\t\tUseFIPS: ptr.Bool(false),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tConsumerARN: ptr.String(\"arn:aws:kinesis: :123456789012:stream/testStream/consumer/test-consumer:1525898737\"),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err == nil {\n\t\tt.Fatalf(\"expect error, got none\")\n\t}\n\tif e, a := \"Invalid ARN: Invalid region.\", err.Error(); !strings.Contains(a, e) {\n\t\tt.Errorf(\"expect %v error in %v\", e, a)\n\t}\n}", "func TestEndpointCase20(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"us-east-2\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(false),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis.us-east-2.amazonaws.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func (p *EscalationConfig) EndPoint() string {\n\treturn \"/api/escalation/config/{id}\"\n}", "func TestEndpointCase55(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"us-east-1\"),\n\t\tUseFIPS: ptr.Bool(false),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tStreamARN: ptr.String(\"arn:aws:kinesis:us-east-1: :stream/testStream\"),\n\t\tOperationType: ptr.String(\"control\"),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err == nil {\n\t\tt.Fatalf(\"expect error, got none\")\n\t}\n\tif e, a := \"Invalid ARN: Invalid account id.\", err.Error(); !strings.Contains(a, e) {\n\t\tt.Errorf(\"expect %v error in %v\", e, a)\n\t}\n}", "func TestEndpointCase22(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"us-west-1\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(false),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis.us-west-1.amazonaws.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func TestEndpointCase3(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"ap-northeast-2\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(false),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis.ap-northeast-2.amazonaws.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func TestEndpointCase16(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"me-south-1\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(false),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis.me-south-1.amazonaws.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func (c *Client) CustomEndpoint(e string) {\n\tc.Endpoint = e\n}", "func TestEndpointCase56(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"us-east-1\"),\n\t\tUseFIPS: ptr.Bool(false),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tStreamARN: ptr.String(\"arn:aws:kinesis:us-east-1:123:accesspoint/testStream\"),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err == nil {\n\t\tt.Fatalf(\"expect error, got none\")\n\t}\n\tif e, a := \"Invalid ARN: Kinesis ARNs don't support `accesspoint` arn types.\", err.Error(); !strings.Contains(a, e) {\n\t\tt.Errorf(\"expect %v error in %v\", e, a)\n\t}\n}", "func TestEndpointCase28(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"cn-north-1\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(false),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis.cn-north-1.amazonaws.com.cn\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func TestEndpointCase14(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"eu-west-2\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(false),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis.eu-west-2.amazonaws.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func TestEndpointCase42(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"us-isob-east-1\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(false),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis.us-isob-east-1.sc2s.sgov.gov\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func editEndpointInConfig(t *testing.T, configFilePath, endpoint string) {\n\tvar config cli.Config\n\tb, err := ioutil.ReadFile(configFilePath)\n\trequire.NoError(t, err)\n\n\terr = yaml.Unmarshal(b, &config)\n\trequire.NoError(t, err)\n\n\tconfig.Endpoint = endpoint\n\n\tb, err = yaml.Marshal(&config)\n\trequire.NoError(t, err)\n\n\terr = ioutil.WriteFile(configFilePath, b, 0655)\n\trequire.NoError(t, err)\n\n}", "func (mr *MockConfigurationMockRecorder) KeysEndpoint() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"KeysEndpoint\", reflect.TypeOf((*MockConfiguration)(nil).KeysEndpoint))\n}", "func IngressEndpoint() string {\n\treturn grpcCfg.IngressEndpoint\n}", "func (r mockEndpointResolver) EndpointFor(service, region string, opts ...func(*endpoints.Options)) (endpoints.ResolvedEndpoint, error) {\n\treturn r.resolvedEndpoint, r.err\n}", "func TestEndpointCase8(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"ap-southeast-3\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(false),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis.ap-southeast-3.amazonaws.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func TestEndpointCase13(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"eu-west-1\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(false),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis.eu-west-1.amazonaws.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func validateOutpostEndpoint(req *request.Request, resource arn.Resource) error {\n\tif err := validateEndpointRequestResource(req, resource); err != nil {\n\t\treturn err\n\t}\n\n\t// DualStack not supported\n\tif isUseDualStackEndpoint(req) {\n\t\treturn s3shared.NewClientConfiguredForDualStackError(resource,\n\t\t\treq.ClientInfo.PartitionID, aws.StringValue(req.Config.Region), nil)\n\t}\n\n\treturn nil\n}", "func TestEndpointCase37(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"us-gov-east-1\"),\n\t\tUseDualStack: ptr.Bool(true),\n\t\tUseFIPS: ptr.Bool(true),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis-fips.us-gov-east-1.api.aws\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func TestEndpointCase17(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"sa-east-1\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(false),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis.sa-east-1.amazonaws.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func TestEndpointCase35(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"us-gov-west-1\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(false),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis.us-gov-west-1.amazonaws.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func TestEndpointCase26(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"us-east-1\"),\n\t\tUseDualStack: ptr.Bool(true),\n\t\tUseFIPS: ptr.Bool(true),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis-fips.us-east-1.api.aws\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func TestEndpointCase29(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"cn-northwest-1\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(false),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis.cn-northwest-1.amazonaws.com.cn\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func (r *DomainName) EndpointConfiguration() pulumi.Output {\n\treturn r.s.State[\"endpointConfiguration\"]\n}", "func (policy *PolicySvc) augmentEndpoint(endpoint *common.Endpoint) error {\n\ttenantSvcUrl, err := policy.client.GetServiceUrl(\"tenant\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tif endpoint.Peer == common.Wildcard {\n\t\t// If a wildcard is specfied, there is nothing to augment\n\t\treturn nil\n\t}\n\tlog.Printf(\"Policy: Augmenting %#v\", endpoint)\n\n\t// Code below tries to resolve tenant name into tenant_network_id if possible.\n\t//\n\t// TODO this will have to be changed once we implement\n\t// https://paninetworks.kanbanize.com/ctrl_board/3/cards/319/details\n\tten := &tenant.Tenant{}\n\tif endpoint.TenantNetworkID == nil {\n\t\tif endpoint.TenantID != 0 {\n\t\t\ttenantIDToUse := strconv.FormatUint(endpoint.TenantID, 10)\n\t\t\ttenantsUrl := fmt.Sprintf(\"%s/tenants/%s\", tenantSvcUrl, tenantIDToUse)\n\t\t\tlog.Printf(\"Policy: Looking tenant up at %s\", tenantsUrl)\n\t\t\terr = policy.client.Get(tenantsUrl, ten)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tendpoint.TenantNetworkID = &ten.NetworkID\n\n\t\t} else if endpoint.TenantExternalID != \"\" || endpoint.TenantName != \"\" {\n\t\t\tif endpoint.TenantExternalID != \"\" {\n\t\t\t\tten.ExternalID = endpoint.TenantExternalID\n\t\t\t}\n\t\t\tif endpoint.TenantName != \"\" {\n\t\t\t\tten.Name = endpoint.TenantName\n\t\t\t}\n\t\t\terr = policy.client.Find(ten, common.FindLast)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tendpoint.TenantNetworkID = &ten.NetworkID\n\t\t}\n\t}\n\n\tif endpoint.SegmentNetworkID == nil {\n\t\tif ten == nil && (endpoint.SegmentID != 0 || endpoint.SegmentExternalID != \"\" || endpoint.SegmentName != \"\") {\n\t\t\treturn common.NewError400(\"No tenant information specified, cannot look up segment.\")\n\t\t}\n\t\tsegment := &tenant.Segment{}\n\t\tif endpoint.SegmentID != 0 {\n\t\t\tsegmentIDToUse := strconv.FormatUint(endpoint.SegmentID, 10)\n\t\t\tsegmentsUrl := fmt.Sprintf(\"%s/tenants/%d/segments/%s\", tenantSvcUrl, ten.ID, segmentIDToUse)\n\t\t\tlog.Printf(\"Policy: Looking segment up at %s for %#v\", segmentsUrl, endpoint)\n\t\t\terr = policy.client.Get(segmentsUrl, &segment)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tendpoint.SegmentNetworkID = &segment.NetworkID\n\t\t} else if endpoint.SegmentExternalID != \"\" || endpoint.SegmentName != \"\" {\n\t\t\tsegmentsUrl := fmt.Sprintf(\"%s/findLast/segments?tenant_id=%d&\", tenantSvcUrl, ten.ID)\n\t\t\tif endpoint.SegmentExternalID != \"\" {\n\t\t\t\tsegmentsUrl += \"external_id=\" + endpoint.TenantExternalID + \"&\"\n\t\t\t}\n\t\t\tif endpoint.SegmentName != \"\" {\n\t\t\t\tsegmentsUrl += \"name=\" + endpoint.SegmentName\n\t\t\t}\n\t\t\tlog.Printf(\"Policy: Finding segments at %s for %#v (Tenant %#v %t)\", segmentsUrl, endpoint, ten, ten == nil)\n\t\t\terr = policy.client.Get(segmentsUrl, &segment)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tendpoint.SegmentNetworkID = &segment.NetworkID\n\t\t}\n\t}\n\treturn nil\n}", "func TestEndpointCase86(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"us-east-1\"),\n\t\tUseFIPS: ptr.Bool(false),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tOperationType: ptr.String(\"control\"),\n\t\tConsumerARN: ptr.String(\"arn:aws:kinesis:us-east-1:123:stream/test-stream/consumer/test-consumer:1525898737\"),\n\t\tEndpoint: ptr.String(\"https://example.com\"),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://example.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func TestEndpointCase11(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"eu-north-1\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(false),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis.eu-north-1.amazonaws.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func TestEndpointCase87(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"us-east-1\"),\n\t\tUseFIPS: ptr.Bool(false),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tOperationType: ptr.String(\"control\"),\n\t\tConsumerARN: ptr.String(\"arn:aws:kinesis:us-east-1:123:stream/test-stream/consumer/test-consumer:1525898737\"),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://123.control-kinesis.us-east-1.amazonaws.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func TestEndpointCase88(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"us-east-1\"),\n\t\tUseFIPS: ptr.Bool(false),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tOperationType: ptr.String(\"data\"),\n\t\tConsumerARN: ptr.String(\"arn:aws:kinesis:us-east-1:123:stream/test-stream/consumer/test-consumer:1525898737\"),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://123.data-kinesis.us-east-1.amazonaws.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func TestValidate1(t *testing.T) {\n\tendpoints := make(map[string]map[string]*Endpoint)\n\tendpoints[\"/test\"] = map[string]*Endpoint{\n\t\t\"get\": {\n\t\t\tParams: &Parameters{\n\t\t\t\tQuery: map[string]*ParamEntry{\"test\": {Type: \"string\", Required: true}},\n\t\t\t\tPath: map[string]*ParamEntry{\"test\": {Type: \"boolean\", Required: true}},\n\t\t\t},\n\t\t\tRecieves: &Recieves{\n\t\t\t\tHeaders: map[string]string{\"foo\": \"bar\"},\n\t\t\t\tBody: map[string]string{\"example_array.0.foo\": \"string\"},\n\t\t\t},\n\t\t\tResponses: map[int]*Response{\n\t\t\t\t200: {\n\t\t\t\t\tHeaders: map[string]string{\"foo\": \"bar\"},\n\t\t\t\t\tBody: map[string]interface{}{\"bar\": \"foo\"},\n\t\t\t\t\tWeight: 100,\n\t\t\t\t\tActions: []map[string]interface{}{\n\t\t\t\t\t\t{\"delay\": 10},\n\t\t\t\t\t\t{\"request\": map[interface{}]interface{}{\"target\": \"testService\", \"id\": \"testRequest\"}},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tActions: []map[string]interface{}{\n\t\t\t\t{\"delay\": 10},\n\t\t\t\t{\"request\": map[interface{}]interface{}{\"target\": \"testService\", \"id\": \"testRequest\"}},\n\t\t\t},\n\t\t},\n\t}\n\n\tcfg := &Config{\n\t\tVersion: 1.0,\n\t\tServices: map[string]*Service{\n\t\t\t\"testService\": {Hostname: \"localhost\", Port: 8080},\n\t\t},\n\t\tStartupActions: []map[string]interface{}{\n\t\t\t{\"delay\": 10},\n\t\t\t{\"request\": map[interface{}]interface{}{\"target\": \"testService\", \"id\": \"testRequest\"}},\n\t\t},\n\t\tRequests: map[string]*Request{\n\t\t\t\"testRequest\": {\n\t\t\t\tURL: \"/test\",\n\t\t\t\tProtocol: \"http\",\n\t\t\t\tMethod: \"get\",\n\t\t\t\tHeaders: map[string]string{\"foo\": \"bar\"},\n\t\t\t\tBody: nil,\n\t\t\t\tExpectedResponse: &Response{\n\t\t\t\t\tStatusCode: 200,\n\t\t\t\t\tBody: map[string]interface{}{\"foo.bar\": \"string\"},\n\t\t\t\t\tHeaders: nil,\n\t\t\t\t\tWeight: 100,\n\t\t\t\t\tActions: []map[string]interface{}{\n\t\t\t\t\t\t{\"delay\": 10},\n\t\t\t\t\t\t{\"request\": map[interface{}]interface{}{\"target\": \"testService\", \"id\": \"testRequest\"}},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tEndpoints: endpoints,\n\t}\n\n\tif err := Validate(cfg); err != nil {\n\t\tt.Errorf(\"Validation Failed: %s\", err.Error())\n\t}\n}", "func (uee *UnknownEndpointError) NotFound() {}", "func TestEndpointCase33(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"us-gov-east-1\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(false),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis.us-gov-east-1.amazonaws.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func TestEndpointCase76(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"us-east-1\"),\n\t\tUseFIPS: ptr.Bool(false),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tConsumerARN: ptr.String(\"arn::kinesis:us-west-2:123456789012:stream/testStream/consumer/test-consumer:1525898737\"),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err == nil {\n\t\tt.Fatalf(\"expect error, got none\")\n\t}\n\tif e, a := \"Invalid ARN: Failed to parse ARN.\", err.Error(); !strings.Contains(a, e) {\n\t\tt.Errorf(\"expect %v error in %v\", e, a)\n\t}\n}", "func (c *Config) Endpoint() string {\n\turi := *c.exporterURL\n\n\tif uri.Scheme == \"file\" {\n\t\turi.RawQuery = \"\"\n\t}\n\turi.Scheme = \"\"\n\n\ts := uri.String()\n\tif strings.HasPrefix(s, \"//\") {\n\t\treturn s[2:]\n\t}\n\treturn s\n}", "func TestEndpointCase101(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"us-isob-east-1\"),\n\t\tUseFIPS: ptr.Bool(true),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tOperationType: ptr.String(\"data\"),\n\t\tConsumerARN: ptr.String(\"arn:aws-iso-b:kinesis:us-isob-east-1:123:stream/test-stream/consumer/test-consumer:1525898737\"),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis-fips.us-isob-east-1.sc2s.sgov.gov\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func (e Endpoint) GetEndpoint() string {\n\treturn \"someendpoint\"\n}", "func TestEndpointCase31(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"cn-north-1\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(true),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis-fips.cn-north-1.amazonaws.com.cn\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func TestEndpointCase21(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"us-east-2\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(true),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis-fips.us-east-2.amazonaws.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func TestEndpointCase43(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"us-isob-east-1\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(true),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis-fips.us-isob-east-1.sc2s.sgov.gov\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func TestEndpointCase7(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"ap-southeast-2\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(false),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis.ap-southeast-2.amazonaws.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func MustNewEndpoints(c Configuration, alternate func() (Endpoints, error)) Endpoints {\n\t// nolint:govet\n\te, err := NewEndpoints(c, alternate)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn e\n}", "func TestEndpointCase9(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"ca-central-1\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(false),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis.ca-central-1.amazonaws.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func TestEndpointCase38(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"us-gov-east-1\"),\n\t\tUseDualStack: ptr.Bool(true),\n\t\tUseFIPS: ptr.Bool(false),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis.us-gov-east-1.api.aws\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func (a *DefaultApiService) ShowEndpoint(ctx _context.Context, id string) ApiShowEndpointRequest {\n\treturn ApiShowEndpointRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t\tid: id,\n\t}\n}", "func TestEndpointCase94(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"us-east-1\"),\n\t\tUseFIPS: ptr.Bool(false),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tOperationType: ptr.String(\"data\"),\n\t\tConsumerARN: ptr.String(\"arn:aws:kinesis:us-west-1:123:stream/testStream/consumer/test-consumer:1525898737\"),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://123.data-kinesis.us-east-1.amazonaws.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func TestEndpointCase103(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"us-east-1\"),\n\t\tUseFIPS: ptr.Bool(false),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tOperationType: ptr.String(\"data\"),\n\t\tStreamARN: ptr.String(\"arn:aws:kinesis:us-east-1:123:stream/foobar\"),\n\t\tConsumerARN: ptr.String(\"arn:aws:kinesis:us-east-1:123456789123:stream/foobar/consumer/test-consumer:1525898737\"),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://123.data-kinesis.us-east-1.amazonaws.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func (o NotificationEndpointGrpcSettingsResponseOutput) Endpoint() pulumi.StringOutput {\n\treturn o.ApplyT(func(v NotificationEndpointGrpcSettingsResponse) string { return v.Endpoint }).(pulumi.StringOutput)\n}", "func (mr *MockConfigurationMockRecorder) TokenEndpoint() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"TokenEndpoint\", reflect.TypeOf((*MockConfiguration)(nil).TokenEndpoint))\n}", "func Endpoint(url string, configureFunc func()) {\n\touterCurrentMockHandler := currentMockHandler\n\tSwitch(extractor.ExtractMethod(), configureFunc)\n\tcurrentMockery.Handle(url, currentMockHandler)\n\tcurrentMockHandler = outerCurrentMockHandler\n}", "func TestEndpointCase57(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"us-iso-west-1\"),\n\t\tUseFIPS: ptr.Bool(true),\n\t\tUseDualStack: ptr.Bool(true),\n\t\tStreamARN: ptr.String(\"arn:aws-iso:kinesis:us-iso-west-1:123456789012:stream/testStream\"),\n\t\tOperationType: ptr.String(\"control\"),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err == nil {\n\t\tt.Fatalf(\"expect error, got none\")\n\t}\n\tif e, a := \"FIPS and DualStack are enabled, but this partition does not support one or both\", err.Error(); !strings.Contains(a, e) {\n\t\tt.Errorf(\"expect %v error in %v\", e, a)\n\t}\n}", "func EndpointFactory(args *endpoint.Arg, stats *stats.Stats, workerCount uint) (endpoint.EndPoint, error) {\n\tif FailSetup {\n\t\treturn nil, errors.New(\"Forced Error\")\n\t}\n\treturn &fakeEndpoint{}, nil\n}", "func WithEndpoint(endpoint string) Option {\n\treturn wrappedOption{oconf.WithEndpoint(endpoint)}\n}", "func TestEndpointCase66(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"us-west-1\"),\n\t\tUseFIPS: ptr.Bool(false),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tOperationType: ptr.String(\"control\"),\n\t\tStreamARN: ptr.String(\"arn:aws:kinesis:us-west-1:123:stream/test-stream\"),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://123.control-kinesis.us-west-1.amazonaws.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func TestEndpointCase30(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"cn-north-1\"),\n\t\tUseDualStack: ptr.Bool(true),\n\t\tUseFIPS: ptr.Bool(true),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis-fips.cn-north-1.api.amazonwebservices.com.cn\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}" ]
[ "0.7092505", "0.6726043", "0.6712356", "0.66571766", "0.58584934", "0.58116233", "0.5779489", "0.5766345", "0.57622665", "0.5760675", "0.5710803", "0.5678078", "0.5649989", "0.5614974", "0.5614144", "0.5599985", "0.55683404", "0.5567277", "0.55581975", "0.5552659", "0.5530678", "0.5529559", "0.55251527", "0.55201447", "0.55020154", "0.5499031", "0.54889387", "0.54835933", "0.546653", "0.5456487", "0.5455556", "0.5453109", "0.5444642", "0.543209", "0.54302794", "0.54277337", "0.5411362", "0.541125", "0.54079795", "0.54054826", "0.53890795", "0.53740805", "0.5362695", "0.53610176", "0.5351729", "0.5345805", "0.5342917", "0.5342773", "0.5336695", "0.53309155", "0.5324591", "0.5313573", "0.5305016", "0.53044015", "0.52996045", "0.5298334", "0.5291975", "0.5290557", "0.52868164", "0.5286646", "0.52862954", "0.5282366", "0.5278071", "0.52718264", "0.5270581", "0.5268904", "0.5267095", "0.5259436", "0.5254905", "0.52536315", "0.5239413", "0.5230042", "0.5214853", "0.521352", "0.5208472", "0.5207432", "0.5207334", "0.52066433", "0.5206409", "0.5203227", "0.5202761", "0.5201747", "0.5196877", "0.5195382", "0.5194158", "0.51886344", "0.51862967", "0.5170254", "0.5169336", "0.51672196", "0.51670414", "0.5153476", "0.5148288", "0.5141389", "0.513643", "0.5133158", "0.51310825", "0.51307344", "0.5119995", "0.51199245" ]
0.71669585
0
EnrollmentCertificate mocks base method
func (m *MockClient) EnrollmentCertificate() []byte { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "EnrollmentCertificate") ret0, _ := ret[0].([]byte) return ret0 }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (p *MockPeer) EnrollmentCertificate() *pem.Block {\r\n\treturn p.MockCert\r\n}", "func (p *MockPeer) EnrollmentCertificate() *pem.Block {\n\treturn p.MockCert\n}", "func (p *MockPeer) SetEnrollmentCertificate(pem *pem.Block) {\r\n\tp.MockCert = pem\r\n}", "func TestCertificate(t *testing.T) {\n\tvar result Certificate\n\n\tif err := json.NewDecoder(certificateBody).Decode(&result); err != nil {\n\t\tt.Errorf(\"Error decoding JSON: %s\", err)\n\t}\n\n\tassertEquals(t, \"1\", result.ID)\n\tassertEquals(t, \"HTTPS Certificate\", result.Name)\n\tassertEquals(t, \"PEM\", string(result.CertificateType))\n\tassertEquals(t, \"Contoso\", result.Issuer.Organization)\n\tassertEquals(t, \"2019-09-07T13:22:05Z\", result.ValidNotAfter)\n\tassertEquals(t, \"TPM_ALG_SHA1\", result.FingerprintHashAlgorithm)\n\tassertEquals(t, \"sha256WithRSAEncryption\", result.SignatureAlgorithm)\n}", "func (m *MockCAClient) Enroll(arg0 *api.EnrollmentRequest) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Enroll\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (p *MockPeer) SetEnrollmentCertificate(pem *pem.Block) {\n\tp.MockCert = pem\n}", "func (m *MockPKIService) SignClientCertificate(arg0 string, arg1 models.AltNames) (*models.PEMCredential, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"SignClientCertificate\", arg0, arg1)\n\tret0, _ := ret[0].(*models.PEMCredential)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockGateway) Cert() *cert.Info {\n\tret := m.ctrl.Call(m, \"Cert\")\n\tret0, _ := ret[0].(*cert.Info)\n\treturn ret0\n}", "func TestEnroll(t *testing.T) {\n\n\tfabricCAClient, err := NewFabricCAClient(org1, configImp, cryptoSuiteProvider)\n\tif err != nil {\n\t\tt.Fatalf(\"NewFabricCAClient return error: %v\", err)\n\t}\n\t_, _, err = fabricCAClient.Enroll(\"\", \"user1\")\n\tif err == nil {\n\t\tt.Fatalf(\"Enroll didn't return error\")\n\t}\n\tif err.Error() != \"enrollmentID required\" {\n\t\tt.Fatalf(\"Enroll didn't return right error\")\n\t}\n\t_, _, err = fabricCAClient.Enroll(\"test\", \"\")\n\tif err == nil {\n\t\tt.Fatalf(\"Enroll didn't return error\")\n\t}\n\tif err.Error() != \"enrollmentSecret required\" {\n\t\tt.Fatalf(\"Enroll didn't return right error\")\n\t}\n\t_, _, err = fabricCAClient.Enroll(\"enrollmentID\", \"enrollmentSecret\")\n\tif err != nil {\n\t\tt.Fatalf(\"fabricCAClient Enroll return error %v\", err)\n\t}\n\n\twrongConfigImp := mocks.NewMockConfig(wrongCAServerURL)\n\tfabricCAClient, err = NewFabricCAClient(org1, wrongConfigImp, cryptoSuiteProvider)\n\tif err != nil {\n\t\tt.Fatalf(\"NewFabricCAClient return error: %v\", err)\n\t}\n\t_, _, err = fabricCAClient.Enroll(\"enrollmentID\", \"enrollmentSecret\")\n\tif err == nil {\n\t\tt.Fatalf(\"Enroll didn't return error\")\n\t}\n\tif !strings.Contains(err.Error(), \"enroll failed\") {\n\t\tt.Fatalf(\"Expected error enroll failed. Got: %s\", err)\n\t}\n\n}", "func TestGenerateCertificate(t *testing.T) {\n\tid, _ := GenerateIdentity()\n\tif !bytes.Equal(id.certificate().Certificate[0], id.certificate().Certificate[0]) {\n\t\tt.Fatalf(\"Secret certificate not deterministic\")\n\t}\n}", "func (m *MockisCryptoAsymApiReqSetupPrivateKeyEx_Key) isCryptoAsymApiReqSetupPrivateKeyEx_Key() {\n\tm.ctrl.Call(m, \"isCryptoAsymApiReqSetupPrivateKeyEx_Key\")\n}", "func (f *FabricCAClientImpl) Enroll(enrollmentId, password string) (*Identity, []byte, error) {\n\tif len(enrollmentId) < 1 {\n\t\treturn nil, nil, ErrEnrollmentIdMissing\n\t}\n\t// create new cert and send it to CA for signing\n\tkey, err := f.Crypto.GenerateKey()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tcsr, err := f.Crypto.CreateCertificateRequest(enrollmentId, key)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\turl := fmt.Sprintf(\"%s/api/v1/enroll\", f.Url)\n\n\tcrm, err := json.Marshal(CertificateRequest{CR: string(csr)})\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\treq, err := http.NewRequest(\"POST\", url, bytes.NewBuffer(crm))\n\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\treq.SetBasicAuth(enrollmentId, password)\n\tvar tr *http.Transport\n\tif f.Transport == nil {\n\t\ttr = &http.Transport{\n\t\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: f.SkipTLSVerification},\n\t\t}\n\t} else {\n\t\ttr = f.Transport\n\t}\n\n\thttpClient := &http.Client{Transport: tr}\n\tresp, err := httpClient.Do(req)\n\tif err != nil {\n\n\t\treturn nil, nil, err\n\t}\n\tdefer resp.Body.Close()\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\n\t\treturn nil, nil, err\n\t}\n\tenrResp := new(enrollmentResponse)\n\tif err := json.Unmarshal(body, enrResp); err != nil {\n\n\t\treturn nil, nil, err\n\t}\n\tif !enrResp.Success {\n\n\t\treturn nil, nil, ErrEnrollment\n\t}\n\trawCert, err := base64.StdEncoding.DecodeString(enrResp.Result.Cert)\n\tif err != nil {\n\n\t\treturn nil, nil, err\n\t}\n\ta, _ := pem.Decode(rawCert)\n\tcert, err := x509.ParseCertificate(a.Bytes)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treturn &Identity{Certificate: cert, PrivateKey: key}, csr, nil\n}", "func (m *MockCertificateManager) AddCertificate(arg0 *p2pcommon.AgentCertificateV1) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"AddCertificate\", arg0)\n}", "func (m *MockCertificateManager) Start() {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"Start\")\n}", "func TestDummyCreateCACertAndKey(t *testing.T) {\n\tdefer leaktest.AfterTest(t)()\n\t_, _, err := security.CreateCACertAndKey(context.Background(), nil, /* loggerFn */\n\t\ttime.Hour, \"test CA cert generation\")\n\tif err != nil {\n\t\tt.Fatalf(\"expected err=nil, got: %s\", err)\n\t}\n}", "func (m *MockRemotePeer) AddCertificate(cert *p2pcommon.AgentCertificateV1) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"AddCertificate\", cert)\n}", "func TestEnroll(t *testing.T) {\n\tInitConfigForMsp()\n\tclient := fabric_sdk.NewClient()\n\tks := &sw.FileBasedKeyStore{}\n\tif err := ks.Init(nil, config.GetKeyStorePath(), false); err != nil {\n\t\tt.Fatalf(\"Failed initializing key store [%s]\", err)\n\t}\n\n\tcryptoSuite, err := bccspFactory.GetBCCSP(&bccspFactory.SwOpts{Ephemeral_: true, SecLevel: config.GetSecurityLevel(),\n\t\tHashFamily: config.GetSecurityAlgorithm(), KeyStore: ks})\n\tif err != nil {\n\t\tt.Fatalf(\"Failed getting ephemeral software-based BCCSP [%s]\", err)\n\t}\n\tclient.SetCryptoSuite(cryptoSuite)\n\tstateStore, err := kvs.CreateNewFileKeyValueStore(\"/tmp/enroll_user\")\n\tif err != nil {\n\t\tt.Fatalf(\"CreateNewFileKeyValueStore return error[%s]\", err)\n\t}\n\tclient.SetStateStore(stateStore)\n\n\tmsps, err := msp.NewMSPServices(config.GetMspURL(), config.GetMspClientPath())\n\tif err != nil {\n\t\tt.Fatalf(\"NewMSPServices return error: %v\", err)\n\t}\n\tkey, cert, err := msps.Enroll(\"testUser2\", \"user2\")\n\tif err != nil {\n\t\tt.Fatalf(\"Enroll return error: %v\", err)\n\t}\n\tif key == nil {\n\t\tt.Fatalf(\"private key return from Enroll is nil\")\n\t}\n\tif cert == nil {\n\t\tt.Fatalf(\"cert return from Enroll is nil\")\n\t}\n\n\tcertPem, _ := pem.Decode(cert)\n\tif err != nil {\n\t\tt.Fatalf(\"pem Decode return error: %v\", err)\n\t}\n\n\tcert509, err := x509.ParseCertificate(certPem.Bytes)\n\tif err != nil {\n\t\tt.Fatalf(\"x509 ParseCertificate return error: %v\", err)\n\t}\n\tif cert509.Subject.CommonName != \"testUser2\" {\n\t\tt.Fatalf(\"CommonName in x509 cert is not the enrollmentID\")\n\t}\n\n\tkeyPem, _ := pem.Decode(key)\n\tif err != nil {\n\t\tt.Fatalf(\"pem Decode return error: %v\", err)\n\t}\n\tuser := fabric_sdk.NewUser(\"testUser2\")\n\tk, err := client.GetCryptoSuite().KeyImport(keyPem.Bytes, &bccsp.ECDSAPrivateKeyImportOpts{Temporary: false})\n\tif err != nil {\n\t\tt.Fatalf(\"KeyImport return error: %v\", err)\n\t}\n\tuser.SetPrivateKey(k)\n\tuser.SetEnrollmentCertificate(cert)\n\terr = client.SetUserContext(user, false)\n\tif err != nil {\n\t\tt.Fatalf(\"client.SetUserContext return error: %v\", err)\n\t}\n\tuser, err = client.GetUserContext(\"testUser2\")\n\tif err != nil {\n\t\tt.Fatalf(\"client.GetUserContext return error: %v\", err)\n\t}\n\tif user == nil {\n\t\tt.Fatalf(\"client.GetUserContext return nil\")\n\t}\n\n}", "func (m *MockCAClient) Reenroll(arg0 *api.ReenrollmentRequest) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Reenroll\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func getTestIdent(t *testing.T, username string, reqs ...identRequest) *identity.Identity {\n\tca, err := tlsca.FromKeys([]byte(fixtures.TLSCACertPEM), []byte(fixtures.TLSCAKeyPEM))\n\trequire.NoError(t, err)\n\n\tprivateKey, sshPublicKey, err := testauthority.New().GenerateKeyPair()\n\trequire.NoError(t, err)\n\n\tsshPrivateKey, err := ssh.ParseRawPrivateKey(privateKey)\n\trequire.NoError(t, err)\n\n\ttlsPublicKeyPEM, err := tlsca.MarshalPublicKeyFromPrivateKeyPEM(sshPrivateKey)\n\trequire.NoError(t, err)\n\n\ttlsPublicKey, err := tlsca.ParsePublicKeyPEM(tlsPublicKeyPEM)\n\trequire.NoError(t, err)\n\n\t// Note: it'd be nice to make this more universally useful in our tests at\n\t// some point.\n\tclock := clockwork.NewFakeClock()\n\tnotAfter := clock.Now().Add(time.Hour)\n\tid := tlsca.Identity{\n\t\tUsername: username,\n\t\tKubernetesUsers: []string{\"foo\"},\n\t\tKubernetesGroups: []string{\"bar\"},\n\t\tRouteToCluster: mockClusterName,\n\t}\n\tfor _, req := range reqs {\n\t\treq(&id)\n\t}\n\tsubject, err := id.Subject()\n\trequire.NoError(t, err)\n\tcertBytes, err := ca.GenerateCertificate(tlsca.CertificateRequest{\n\t\tClock: clock,\n\t\tPublicKey: tlsPublicKey,\n\t\tSubject: subject,\n\t\tNotAfter: notAfter,\n\t})\n\trequire.NoError(t, err)\n\n\tcaSigner, err := ssh.ParsePrivateKey([]byte(fixtures.SSHCAPrivateKey))\n\trequire.NoError(t, err)\n\tta := testauthority.New()\n\tsshCertBytes, err := ta.GenerateUserCert(services.UserCertParams{\n\t\tCASigner: caSigner,\n\t\tPublicUserKey: sshPublicKey,\n\t\tUsername: username,\n\t\tCertificateFormat: constants.CertificateFormatStandard,\n\t\tTTL: time.Minute,\n\t\tAllowedLogins: []string{\"foo\"},\n\t\tRouteToCluster: mockClusterName,\n\t})\n\n\trequire.NoError(t, err)\n\n\tcerts := &proto.Certs{\n\t\tSSH: sshCertBytes,\n\t\tTLS: certBytes,\n\t\tTLSCACerts: [][]byte{[]byte(fixtures.TLSCACertPEM)},\n\t\tSSHCACerts: [][]byte{[]byte(fixtures.SSHCAPublicKey)},\n\t}\n\n\tident, err := identity.ReadIdentityFromStore(&identity.LoadIdentityParams{\n\t\tPrivateKeyBytes: privateKey,\n\t\tPublicKeyBytes: tlsPublicKeyPEM,\n\t}, certs, identity.DestinationKinds()...)\n\trequire.NoError(t, err)\n\n\treturn ident\n}", "func (m *MockCertificateRefresher) Start(arg0 context.Context) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Start\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockCertificateManager) CreateCertificate(arg0 p2pcommon.PeerMeta) (*p2pcommon.AgentCertificateV1, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"CreateCertificate\", arg0)\n\tret0, _ := ret[0].(*p2pcommon.AgentCertificateV1)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func testTLSCertsAllocate(t *testing.T) {\n\tvar (\n\t\terr error\n\t)\n\n\ttestTLSCerts = &testTLSCertsStruct{}\n\n\ttestTLSCerts.caCertPEMBlock, testTLSCerts.caKeyPEMBlock, err = icertpkg.GenCACert(\n\t\ticertpkg.GenerateKeyAlgorithmEd25519,\n\t\tpkix.Name{\n\t\t\tOrganization: []string{\"Test Organization CA\"},\n\t\t\tCountry: []string{},\n\t\t\tProvince: []string{},\n\t\t\tLocality: []string{},\n\t\t\tStreetAddress: []string{},\n\t\t\tPostalCode: []string{},\n\t\t},\n\t\ttime.Hour,\n\t\t\"\",\n\t\t\"\")\n\tif nil != err {\n\t\tt.Fatalf(\"icertpkg.GenCACert() failed: %v\", err)\n\t}\n\n\ttestTLSCerts.endpointCertPEMBlock, testTLSCerts.endpointKeyPEMBlock, err = icertpkg.GenEndpointCert(\n\t\ticertpkg.GenerateKeyAlgorithmEd25519,\n\t\tpkix.Name{\n\t\t\tOrganization: []string{\"Test Organization Endpoint\"},\n\t\t\tCountry: []string{},\n\t\t\tProvince: []string{},\n\t\t\tLocality: []string{},\n\t\t\tStreetAddress: []string{},\n\t\t\tPostalCode: []string{},\n\t\t},\n\t\t[]string{},\n\t\t[]net.IP{net.ParseIP(\"127.0.0.1\")},\n\t\ttime.Hour,\n\t\ttestTLSCerts.caCertPEMBlock,\n\t\ttestTLSCerts.caKeyPEMBlock,\n\t\t\"\",\n\t\t\"\")\n\n\tif nil != err {\n\t\tt.Fatalf(\"icertpkg.genEndpointCert() failed: %v\", err)\n\t}\n\n\ttestTLSCerts.endpointTLSCert, err = tls.X509KeyPair(testTLSCerts.endpointCertPEMBlock, testTLSCerts.endpointKeyPEMBlock)\n\tif nil != err {\n\t\tt.Fatalf(\"tls.LoadX509KeyPair() failed: %v\", err)\n\t}\n}", "func (m *MockTrustDB) Chain(arg0 context.Context, arg1 []byte) ([]*x509.Certificate, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Chain\", arg0, arg1)\n\tret0, _ := ret[0].([]*x509.Certificate)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockisCryptoAsymApiRespSetupPrivateKey_KeyInfo) isCryptoAsymApiRespSetupPrivateKey_KeyInfo() {\n\tm.ctrl.Call(m, \"isCryptoAsymApiRespSetupPrivateKey_KeyInfo\")\n}", "func TestReenroll(t *testing.T) {\n\n\tfabricCAClient, err := NewFabricCAClient(org1, configImp, cryptoSuiteProvider)\n\tif err != nil {\n\t\tt.Fatalf(\"NewFabricCAClient returned error: %v\", err)\n\t}\n\tuser := mocks.NewMockUser(\"\")\n\t// Reenroll with nil user\n\t_, _, err = fabricCAClient.Reenroll(nil)\n\tif err == nil {\n\t\tt.Fatalf(\"Expected error with nil user\")\n\t}\n\tif err.Error() != \"user required\" {\n\t\tt.Fatalf(\"Expected error user required. Got: %s\", err.Error())\n\t}\n\t// Reenroll with user.Name is empty\n\t_, _, err = fabricCAClient.Reenroll(user)\n\tif err == nil {\n\t\tt.Fatalf(\"Expected error with user.Name is empty\")\n\t}\n\tif err.Error() != \"user name missing\" {\n\t\tt.Fatalf(\"Expected error user name missing. Got: %s\", err.Error())\n\t}\n\t// Reenroll with user.EnrollmentCertificate is empty\n\tuser = mocks.NewMockUser(\"testUser\")\n\t_, _, err = fabricCAClient.Reenroll(user)\n\tif err == nil {\n\t\tt.Fatalf(\"Expected error with user.EnrollmentCertificate is empty\")\n\t}\n\tif !strings.Contains(err.Error(), \"createSigningIdentity failed\") {\n\t\tt.Fatalf(\"Expected error createSigningIdentity failed. Got: %s\", err.Error())\n\t}\n\t// Reenroll with appropriate user\n\tuser.SetEnrollmentCertificate(readCert(t))\n\tkey, err := cryptosuite.GetDefault().KeyGen(cryptosuite.GetECDSAP256KeyGenOpts(true))\n\tif err != nil {\n\t\tt.Fatalf(\"KeyGen return error %v\", err)\n\t}\n\tuser.SetPrivateKey(key)\n\t_, _, err = fabricCAClient.Reenroll(user)\n\tif err != nil {\n\t\tt.Fatalf(\"Reenroll return error %v\", err)\n\t}\n\n\t// Reenroll with wrong fabric-ca server url\n\twrongConfigImp := mocks.NewMockConfig(wrongCAServerURL)\n\tfabricCAClient, err = NewFabricCAClient(org1, wrongConfigImp, cryptoSuiteProvider)\n\tif err != nil {\n\t\tt.Fatalf(\"NewFabricCAClient return error: %v\", err)\n\t}\n\t_, _, err = fabricCAClient.Reenroll(user)\n\tif err == nil {\n\t\tt.Fatalf(\"Expected error with wrong fabric-ca server url\")\n\t}\n\tif !strings.Contains(err.Error(), \"reenroll failed\") {\n\t\tt.Fatalf(\"Expected error with wrong fabric-ca server url. Got: %s\", err.Error())\n\t}\n}", "func (m *MockDynamicCertPrivate) UnsetCertKeyContent() {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"UnsetCertKeyContent\")\n}", "func TestAddCourseToStudentFailNotificationManagement(t *testing.T) {\n\t_ = config.SetConfigurationFromFile(\"../../../config/config-test.json\")\n\n\t// generate a token to be appended to the request\n\tuser := microservice.User{Name: \"name\", Surname: \"surname\", Username: \"user\",\n\t\tPassword: \"pass\", Type: \"student\", Mail: \"name@example.com\"}\n\ttoken, _ := microservice.GenerateAccessToken(user, []byte(config.Configuration.TokenPrivateKey))\n\n\t// make the body of request containing the course to add to student\n\tjsonBody := simplejson.New()\n\tjsonBody.Set(\"id\", \"idCourseFailingInNotificationManagement\")\n\tjsonBody.Set(\"name\", \"courseFailingInNotificationManagement\")\n\tjsonBody.Set(\"department\", \"department\")\n\tjsonBody.Set(\"year\", \"2019-2020\")\n\trequestBody, _ := json.Marshal(jsonBody)\n\n\t// make the PUT request for the course append\n\trequest, _ := http.NewRequest(http.MethodPut,\n\t\t\"/didattica-mobile/api/v1.0/students/user\", bytes.NewBuffer(requestBody))\n\trequest.AddCookie(&http.Cookie{Name: \"token\", Value: token})\n\n\tresponse := httptest.NewRecorder()\n\thandler := createTestGatewayAddCourseToStudent()\n\n\t// Goroutines represent the micro-services listens to the requests coming from the api gateway\n\tgo mock.LaunchCourseManagementMock()\n\tgo mock.LaunchNotificationManagementMock()\n\n\t// simulates a request-response interaction between client and api gateway\n\thandler.ServeHTTP(response, request)\n\n\tif response.Code != http.StatusBadRequest {\n\t\tt.Error(\"Expected 400 Bad request but got \" +\n\t\t\tstrconv.Itoa(response.Code) + \" \" + http.StatusText(response.Code))\n\t}\n}", "func (m *MockService) GetCertificates() *idp.CertificatesResponse {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetCertificates\")\n\tret0, _ := ret[0].(*idp.CertificatesResponse)\n\treturn ret0\n}", "func TestCMPreIssuedCert(t *testing.T) {\n\tvar b64Chain = []string{\n\t\t\"MIID+jCCAuKgAwIBAgIHBWW7shJizTANBgkqhkiG9w0BAQsFADB1MQswCQYDVQQGEwJHQjEPMA0GA1UEBwwGTG9uZG9uMTowOAYDVQQKDDFHb29nbGUgQ2VydGlmaWNhdGUgVHJhbnNwYXJlbmN5IChQcmVjZXJ0IFNpZ25pbmcpMRkwFwYDVQQFExAxNTE5MjMxNzA0MTczNDg3MB4XDTE4MDIyMTE2NDgyNFoXDTE4MTIwMTIwMzMyN1owYzELMAkGA1UEBhMCR0IxDzANBgNVBAcMBkxvbmRvbjEoMCYGA1UECgwfR29vZ2xlIENlcnRpZmljYXRlIFRyYW5zcGFyZW5jeTEZMBcGA1UEBRMQMTUxOTIzMTcwNDM5MjM5NzCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAKnKP9TP6hkEuD+d1rPeA8mxo5xFYffhCcEitP8PtTl7G2RqFrndPeAkzgvOxPB3Jrhx7LtMtg0IvS8y7Sy1qDqDou1/OrJgwCeWMc1/KSneuGP8GTX0Rqy4z8+LsiBN/tMDbt94RuiyCeltIAaHGmsNeYXV34ayD3vSIAQbtLUOD39KqrJWO0tQ//nshBuFlebiUrDP7rirPusYYW0stJKiCKeORhHvL3/I8mCYGNO0XIWMpASH2S9LGMwg+AQM13whC1KL65EGuVs4Ta0rO+Tl8Yi0is0RwdUmgdSGtl0evPTzyUXbA1n1BpkLcSQ5E3RxY3O6Ge9Whvtmg9vAJiMCAwEAAaOBoDCBnTATBgNVHSUEDDAKBggrBgEFBQcDATAjBgNVHREEHDAaghhmbG93ZXJzLXRvLXRoZS13b3JsZC5jb20wDAYDVR0TAQH/BAIwADAfBgNVHSMEGDAWgBRKCM/Ajh0Fu6FFjJ9F4gVWK2oj/jAdBgNVHQ4EFgQUVjYl6wDey3DxvmTG2HL4vdiUt+MwEwYKKwYBBAHWeQIEAwEB/wQCBQAwDQYJKoZIhvcNAQELBQADggEBAAvyEFDIAWr0URsZzrJLZEL8p6FMTzVxY/MOvGP8QMXA6xNVElxYnDPF32JERAl+poR7syByhVFcEjrw7f2FTlMc04+hT/hsYzi8cMAmfX9KA36xUBVjyqvqwofxTwoWYdf+eGZW0EG8Yp1pM7iUy9bdlh3sgdOpmT9Z5XGCRwvdW1+mctv0JMKDdWzxBqYyNMnNjvjHBmkiuHeDDGFsV2zq+wV64RwJa2eVrnkMDMV1mscL6KzNRLPP2ZpNz/8H7SPock+fk4cZrdqj+0IzFt+6ixSoKyltyD+nkbWjRGY4iyboo/nPgTQ1IQCS2OPVHWw3NijFD8hqgAnYvz0Dn+k=\",\n\t\t\"MIIE4jCCAsqgAwIBAgIHBWW7sg8LrzANBgkqhkiG9w0BAQUFADB/MQswCQYDVQQGEwJHQjEPMA0GA1UECAwGTG9uZG9uMRcwFQYDVQQKDA5Hb29nbGUgVUsgTHRkLjEhMB8GA1UECwwYQ2VydGlmaWNhdGUgVHJhbnNwYXJlbmN5MSMwIQYDVQQDDBpNZXJnZSBEZWxheSBJbnRlcm1lZGlhdGUgMTAeFw0xODAyMjExNjQ4MjRaFw0xODEyMDEyMDM0MjdaMHUxCzAJBgNVBAYTAkdCMQ8wDQYDVQQHDAZMb25kb24xOjA4BgNVBAoMMUdvb2dsZSBDZXJ0aWZpY2F0ZSBUcmFuc3BhcmVuY3kgKFByZWNlcnQgU2lnbmluZykxGTAXBgNVBAUTEDE1MTkyMzE3MDQxNzM0ODcwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCKWlc3A43kJ9IzmkCPXcsGwTxlIvtl9sNYBWlx9qqHa1i6tU6rZuH9uXAb3wsn39fqY22HzF/yrx9pd05doFfRq6dvvm4eHNFfFm4cJur1kmPe8vLKpSI/P2DPx4/mRzrHnPAI8Jo9QgKcj91AyYeB689ZFzH30ay32beo6PxQvtoJkzl+dzf9Hs1ezavS7nDCuqDnu1V1Og7J5xTHZeNyTKgD5Kx28ukmIp2wGOvg3omuInABg/ew0VxnG/txKV+69zfV9dhclU3m16L81e3RkJ8Kg4RLb0mh9X3EMn90SpJ9yw0j8FF0Esk6wxuYeUGLShUji8BPnnbactY9B6ORAgMBAAGjbTBrMBgGA1UdJQEB/wQOMAwGCisGAQQB1nkCBAQwDwYDVR0TAQH/BAUwAwEB/zAfBgNVHSMEGDAWgBTpPAThgC/ChBMtJnCe8v0az6r+xjAdBgNVHQ4EFgQUSgjPwI4dBbuhRYyfReIFVitqI/4wDQYJKoZIhvcNAQEFBQADggIBAEep2uWAFsdq1nLtLWLGh7DfVPc/K+1lcqNx64ucjpVZbDnMnYKFagf2Z9rHEWqR7kwuLac5xW8woSlLa/NHmJmdg18HGUhlS+x8iMPv7dK6hfNsRFdjLZkZOFneuf9j1b0dV+rXoRvyY+Oq+lomC98bEr+g9zq+M7wJ4wS/KeaNHpPw1pBeTtCdw+1c4ZgRTOEa2OUUpkpueJ+9psD/hbp6HLF+WYijWQ0/iYSxJ4TbjTC+omKRsGhvxSLbP8cSMt3X1pJgrFK1BvH4lqqEXGDNEiVNoPCHraEa8JtMZIo47/Af13lDfp6sBdZ0lvLAVDduWgg/2RkWCbHefAe81h+cYdDS775TF2TCMTwsR6GsM9sVCbfPvHXI/pUzamRn0i0CrhyccBBdPrUhj+cXuc9kqSkLegun9D8EBDMM9va5wb1HM0ruSno+YuLtfhCdBRHr/RG2BKJi7uUDjJ8goHov/EUJmHjAIARKz74IPWRkxMrnOvGhnNa2Hz+da3hpusz0Mj4rsqv1EKTC2wbCs6Rk2MRPSxdRbywdWLSmGn249SMfXK4An+dqoRk1fwKqdXc4swoUvxnGUi5ajBaRtc6631zBTmvmSFQnvGmS42aF7q2PjfvWPIuO+d//m8KgN6o2YyjrdPDDslI2RZUE5ngOR+JynvhjYrrB7Bat1EY7\",\n\t\t\"MIIFyDCCA7CgAwIBAgICEAEwDQYJKoZIhvcNAQEFBQAwfTELMAkGA1UEBhMCR0IxDzANBgNVBAgMBkxvbmRvbjEXMBUGA1UECgwOR29vZ2xlIFVLIEx0ZC4xITAfBgNVBAsMGENlcnRpZmljYXRlIFRyYW5zcGFyZW5jeTEhMB8GA1UEAwwYTWVyZ2UgRGVsYXkgTW9uaXRvciBSb290MB4XDTE0MDcxNzEyMjYzMFoXDTE5MDcxNjEyMjYzMFowfzELMAkGA1UEBhMCR0IxDzANBgNVBAgMBkxvbmRvbjEXMBUGA1UECgwOR29vZ2xlIFVLIEx0ZC4xITAfBgNVBAsMGENlcnRpZmljYXRlIFRyYW5zcGFyZW5jeTEjMCEGA1UEAwwaTWVyZ2UgRGVsYXkgSW50ZXJtZWRpYXRlIDEwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQDB6HT+/5ru8wO7+mNFOIH6r43BwiwJZB2vQwOB8zvBV79sTIqNV7Grx5KFnSDyGRUJxZfEN7FGc96lr0vqFDlt1DbcYgVV15U+Dt4B9/+0Tz/3zeZO0kVjTg3wqvzpw6xetj2N4dlpysiFQZVAOp+dHUw9zu3xNR7dlFdDvFSrdFsgT7Uln+Pt9pXCz5C4hsSP9oC3RP7CaRtDRSQrMcNvMRi3J8XeXCXsGqMKTCRhxRGe9ruQ2Bbm5ExbmVW/ou00Fr9uSlPJL6+sDR8Li/PTW+DU9hygXSj8Zi36WI+6PuA4BHDAEt7Z5Ru/Hnol76dFeExJ0F6vjc7gUnNh7JExJgBelyz0uGORT4NhWC7SRWP/ngPFLoqcoyZMVsGGtOxSt+aVzkKuF+x64CVxMeHb9I8t3iQubpHqMEmIE1oVSCsF/AkTVTKLOeWG6N06SjoUy5fu9o+faXKMKR8hldLM5z1K6QhFsb/F+uBAuU/DWaKVEZgbmWautW06fF5I+OyoFeW+hrPTbmon4OLE3ubjDxKnyTa4yYytWSisojjfw5z58sUkbLu7KAy2+Z60m/0deAiVOQcsFkxwgzcXRt7bxN7By5Q5Bzrz8uYPjFBfBnlhqMU5RU/FNBFY7Mx4Uy8+OcMYfJQ5/A/4julXEx1HjfBj3VCyrT/noHDpBeOGiwIDAQABo1AwTjAdBgNVHQ4EFgQU6TwE4YAvwoQTLSZwnvL9Gs+q/sYwHwYDVR0jBBgwFoAU8197dUnjeEE5aiC2fGtMXMk9WEEwDAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQUFAAOCAgEACFjL1UXy6S4JkGrDnz1VwTYHplFDY4bG6Q8Sh3Og6z9HJdivNft/iAQ2tIHyz0eAGCXeVPE/j1kgvz2RbnUxQd5eWdLeu/w/wiZyHxWhbTt6RhjqBVFjnx0st7n6rRt+Bw8jpugZfD11SbumVT/V20Gc45lHf2oEgbkPUcnTB9gssFz5Z4KKGs5lIHz4a20WeSJF3PJLTBefkRhHNufi/LhjpLXImwrC82g5ChBZS5XIVuJZx3VkMWiYz4emgX0YWF/JdtaB2dUQ7yrTforQ5J9b1JnJ7H/o9DsX3/ubfQ39gwDBxTicnqC+Q3Dcv3i9PvwjCNJQuGa7ygMcDEn/d6elQg2qHxtqRE02ZlOXTC0XnDAJhx7myJFA/Knv3yO9S4jG6665KG9Y88/CHkh08YLR7NYFiRmwOxjbe3lb6csl/FFmqUXvjhEzzWAxKjI09GSd9hZkB8u17Mg46eEYwF3ufIlqmYdlWufjSc2BZuaNNN6jtK6JKp8jhQUycehgtUK+NlBQOXTzu28miDdasoSH2mdR0PLDo1547+MLGdV4COvqLERTmQrYHrliicD5nFCA+CCSvGEjo0DGOmF/O8StwSmNiKJ4ppPvk2iGEdO07e0LbQI+2fbC6og2SDGXUlsbG85wqQw0A7CU1fQSqhFBuZZauDFMUvdy3v/BAIw=\",\n\t\t\"MIIFzTCCA7WgAwIBAgIJAJ7TzLHRLKJyMA0GCSqGSIb3DQEBBQUAMH0xCzAJBgNVBAYTAkdCMQ8wDQYDVQQIDAZMb25kb24xFzAVBgNVBAoMDkdvb2dsZSBVSyBMdGQuMSEwHwYDVQQLDBhDZXJ0aWZpY2F0ZSBUcmFuc3BhcmVuY3kxITAfBgNVBAMMGE1lcmdlIERlbGF5IE1vbml0b3IgUm9vdDAeFw0xNDA3MTcxMjA1NDNaFw00MTEyMDIxMjA1NDNaMH0xCzAJBgNVBAYTAkdCMQ8wDQYDVQQIDAZMb25kb24xFzAVBgNVBAoMDkdvb2dsZSBVSyBMdGQuMSEwHwYDVQQLDBhDZXJ0aWZpY2F0ZSBUcmFuc3BhcmVuY3kxITAfBgNVBAMMGE1lcmdlIERlbGF5IE1vbml0b3IgUm9vdDCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAKoWHPIgXtgaxWVIPNpCaj2y5Yj9t1ixe5PqjWhJXVNKAbpPbNHA/AoSivecBm3FTD9DfgW6J17mHb+cvbKSgYNzgTk5e2GJrnOP7yubYJpt2OCw0OILJD25NsApzcIiCvLA4aXkqkGgBq9FiVfisReNJxVu8MtxfhbVQCXZf0PpkW+yQPuF99V5Ri+grHbHYlaEN1C/HM3+t2yMR4hkd2RNXsMjViit9qCchIi/pQNt5xeQgVGmtYXyc92ftTMrmvduj7+pHq9DEYFt3ifFxE8v0GzCIE1xR/d7prFqKl/KRwAjYUcpU4vuazywcmRxODKuwWFVDrUBkGgCIVIjrMJWStH5i7WTSSTrVtOD/HWYvkXInZlSgcDvsNIG0pptJaEKSP4jUzI3nFymnoNZn6pnfdIII/XISpYSVeyl1IcdVMod8HdKoRew9CzW6f2n6KSKU5I8X5QEM1NUTmRLWmVi5c75/CvS/PzOMyMzXPf+fE2Dwbf4OcR5AZLTupqp8yCTqo7ny+cIBZ1TjcZjzKG4JTMaqDZ1Sg0T3mO/ZbbiBE3N8EHxoMWpw8OP50z1dtRRwj6qUZ2zLvngOb2EihlMO15BpVZC3Cg929c9Hdl65pUd4YrYnQBQB/rn6IvHo8zot8zElgOg22fHbViijUt3qnRggB40N30MXkYGwuJbAgMBAAGjUDBOMB0GA1UdDgQWBBTzX3t1SeN4QTlqILZ8a0xcyT1YQTAfBgNVHSMEGDAWgBTzX3t1SeN4QTlqILZ8a0xcyT1YQTAMBgNVHRMEBTADAQH/MA0GCSqGSIb3DQEBBQUAA4ICAQB3HP6jRXmpdSDYwkI9aOzQeJH4x/HDi/PNMOqdNje/xdNzUy7HZWVYvvSVBkZ1DG/ghcUtn/wJ5m6/orBn3ncnyzgdKyXbWLnCGX/V61PgIPQpuGo7HzegenYaZqWz7NeXxGaVo3/y1HxUEmvmvSiioQM1cifGtz9/aJsJtIkn5umlImenKKEV1Ly7R3Uz3Cjz/Ffac1o+xU+8NpkLF/67fkazJCCMH6dCWgy6SL3AOB6oKFIVJhw8SD8vptHaDbpJSRBxifMtcop/85XUNDCvO4zkvlB1vPZ9ZmYZQdyL43NA+PkoKy0qrdaQZZMq1Jdp+Lx/yeX255/zkkILp43jFyd44rZ+TfGEQN1WHlp4RMjvoGwOX1uGlfoGkRSgBRj7TBn514VYMbXu687RS4WY2v+kny3PUFv/ZBfYSyjoNZnU4Dce9kstgv+gaKMQRPcyL+4vZU7DV8nBIfNFilCXKMN/VnNBKtDV52qmtOsVghgai+QE09w15x7dg+44gIfWFHxNhvHKys+s4BBN8fSxAMLOsb5NGFHE8x58RAkmIYWHjyPM6zB5AUPw1b2A0sDtQmCqoxJZfZUKrzyLz8gS2aVujRYN13KklHQ3EKfkeKBG2KXVBe5rjMN/7Anf1MtXxsTY6O8qIuHZ5QlXhSYzE41yIlPlG6d7AGnTiBIgeg==\",\n\t}\n\trawChain := make([][]byte, len(b64Chain))\n\tfor i, b64Data := range b64Chain {\n\t\tvar err error\n\t\trawChain[i], err = base64.StdEncoding.DecodeString(b64Data)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"failed to base64.Decode(chain[%d]): %v\", i, err)\n\t\t}\n\t}\n\n\troot, err := x509.ParseCertificate(rawChain[len(rawChain)-1])\n\tif err != nil {\n\t\tt.Fatalf(\"failed to parse root cert: %v\", err)\n\t}\n\tcmRoot := x509util.NewPEMCertPool()\n\tcmRoot.AddCert(root)\n\n\tfor _, tc := range []struct {\n\t\tdesc string\n\t\teku []x509.ExtKeyUsage\n\t}{\n\t\t{\n\t\t\tdesc: \"no EKU specified\",\n\t\t}, {\n\t\t\tdesc: \"EKU ServerAuth\",\n\t\t\teku: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},\n\t\t},\n\t} {\n\t\tt.Run(tc.desc, func(t *testing.T) {\n\t\t\topts := CertValidationOpts{\n\t\t\t\ttrustedRoots: cmRoot,\n\t\t\t\textKeyUsages: tc.eku,\n\t\t\t}\n\t\t\tchain, err := ValidateChain(rawChain, opts)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatalf(\"failed to ValidateChain: %v\", err)\n\t\t\t}\n\t\t\tfor i, c := range chain {\n\t\t\t\tt.Logf(\"chain[%d] = \\n%s\", i, x509util.CertificateToString(c))\n\t\t\t}\n\t\t})\n\t}\n}", "func (m *MockPKIService) DeleteClientCertificate(arg0 string) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"DeleteClientCertificate\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockPKIService) SignServerCertificate(arg0 string, arg1 models.AltNames) (*models.PEMCredential, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"SignServerCertificate\", arg0, arg1)\n\tret0, _ := ret[0].(*models.PEMCredential)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockTrustDB) GetIssCertMaxVersion(arg0 context.Context, arg1 addr.IA) (*cert.Certificate, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetIssCertMaxVersion\", arg0, arg1)\n\tret0, _ := ret[0].(*cert.Certificate)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockSecrets) AsBase64String(fileName string) (string, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"AsBase64String\", fileName)\n\tret0, _ := ret[0].(string)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func ExpectValidCertificate(expiresAfterDays int) HTTPCertificateExpectation {\n\treturn HTTPCertificateExpectation{\n\t\tExpiresAfterDays: expiresAfterDays,\n\t}\n}", "func (m *MockPKIService) GetCA() ([]byte, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetCA\")\n\tret0, _ := ret[0].([]byte)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockInternalServer) CryptoAsymKeyWrite(arg0 context.Context, arg1 *CryptoAsymKeyWriteRequestMsg) (*CryptoAsymKeyWriteResponseMsg, error) {\n\tret := m.ctrl.Call(m, \"CryptoAsymKeyWrite\", arg0, arg1)\n\tret0, _ := ret[0].(*CryptoAsymKeyWriteResponseMsg)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func TestCreateCourseFailureCourseManagement(t *testing.T) {\n\n\t_ = config.SetConfigurationFromFile(\"../../../config/config-test.json\")\n\n\t// build the information of the course to be created (in a simplified way)\n\tjsonBody := simplejson.New()\n\tjsonBody.Set(\"name\", \"courseFailInCourseManagement\")\n\n\t// generate a token to be appended to the course creation request\n\tuser := microservice.User{Name: \"nome\", Surname: \"cognome\", Username: \"username\", Password: \"password\", Type: \"teacher\", Mail: \"name@example.com\"}\n\ttoken, _ := microservice.GenerateAccessToken(user, []byte(config.Configuration.TokenPrivateKey))\n\n\t// make the POST request for the course creation\n\trequestBody, _ := jsonBody.MarshalJSON()\n\trequest, _ := http.NewRequest(http.MethodPost, \"/didattica-mobile/api/v1.0/courses\", bytes.NewBuffer(requestBody))\n\trequest.Header.Set(\"Content-Type\", \"application/json\")\n\trequest.AddCookie(&http.Cookie{Name: \"token\", Value: token})\n\n\tresponse := httptest.NewRecorder()\n\thandler := createTestGatewayCreateCourse()\n\t// Goroutines represent the micro-services listening to the requests coming from the api gateway\n\tgo mock.LaunchCourseManagementMock()\n\tgo mock.LaunchNotificationManagementMock()\n\t// simulates a request-response interaction between client and api gateway\n\thandler.ServeHTTP(response, request)\n\n\tif response.Code != http.StatusInternalServerError {\n\t\tt.Error(\"Expected 500 Ok but got \" + strconv.Itoa(response.Code) + \" \" + http.StatusText(response.Code))\n\t}\n\n}", "func TestCreateCourseFailureNotificationManagement(t *testing.T) {\n\n\t_ = config.SetConfigurationFromFile(\"../../../config/config-test.json\")\n\n\t// build the information of the course to be created (in a simplified way)\n\tjsonBody := simplejson.New()\n\tjsonBody.Set(\"name\", \"courseFailInNotificationManagement\")\n\n\t// generate a token to be appended to the course creation request\n\tuser := microservice.User{Name: \"nome\", Surname: \"cognome\", Username: \"username\", Password: \"password\", Type: \"teacher\", Mail: \"name@example.com\"}\n\ttoken, _ := microservice.GenerateAccessToken(user, []byte(config.Configuration.TokenPrivateKey))\n\n\t// make the POST request for the course creation\n\trequestBody, _ := jsonBody.MarshalJSON()\n\trequest, _ := http.NewRequest(http.MethodPost, \"/didattica-mobile/api/v1.0/courses\", bytes.NewBuffer(requestBody))\n\trequest.Header.Set(\"Content-Type\", \"application/json\")\n\trequest.AddCookie(&http.Cookie{Name: \"token\", Value: token})\n\n\tresponse := httptest.NewRecorder()\n\thandler := createTestGatewayCreateCourse()\n\t// Goroutines represent the micro-services listening to the requests coming from the api gateway\n\tgo mock.LaunchCourseManagementMock()\n\tgo mock.LaunchNotificationManagementMock()\n\t// simulates a request-response interaction between client and api gateway\n\thandler.ServeHTTP(response, request)\n\n\tif response.Code != http.StatusInternalServerError {\n\t\tt.Error(\"Expected 500 Ok but got \" + strconv.Itoa(response.Code) + \" \" + http.StatusText(response.Code))\n\t}\n\n}", "func mockCheckDetailAddendumC() CheckDetailAddendumC {\n\tcdAddendumC := NewCheckDetailAddendumC()\n\tcdAddendumC.RecordNumber = 1\n\tcdAddendumC.EndorsingBankRoutingNumber = \"121042882\"\n\tcdAddendumC.BOFDEndorsementBusinessDate = time.Now()\n\tcdAddendumC.EndorsingBankItemSequenceNumber = \"1 \"\n\tcdAddendumC.TruncationIndicator = \"Y\"\n\tcdAddendumC.EndorsingBankConversionIndicator = \"1\"\n\tcdAddendumC.EndorsingBankCorrectionIndicator = 0\n\tcdAddendumC.ReturnReason = \"A\"\n\tcdAddendumC.UserField = \"\"\n\tcdAddendumC.EndorsingBankIdentifier = 0\n\treturn cdAddendumC\n}", "func (m *MockIDistributedEnforcer) LoadPolicy() error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"LoadPolicy\")\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockTrustDB) GetIssCertVersion(arg0 context.Context, arg1 addr.IA, arg2 uint64) (*cert.Certificate, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetIssCertVersion\", arg0, arg1, arg2)\n\tret0, _ := ret[0].(*cert.Certificate)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockVirtualMeshCertificateSigningRequestWriter) UpsertVirtualMeshCertificateSigningRequest(ctx context.Context, obj *v1alpha1.VirtualMeshCertificateSigningRequest, transitionFuncs ...v1alpha1.VirtualMeshCertificateSigningRequestTransitionFunction) error {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{ctx, obj}\n\tfor _, a := range transitionFuncs {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"UpsertVirtualMeshCertificateSigningRequest\", varargs...)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (c *Client) newEnrollmentResponse(result *api.EnrollmentResponseNet, id string, key cccsp.Key) (*api.EnrollmentResponse, error) {\n\tlog.Debugf(\"newEnrollmentResponse %s\", id)\n\tcertBytes, err := base64.StdEncoding.DecodeString(result.Cert)\n\tif err != nil {\n\t\treturn nil, errors.WithMessage(err, \"Invalid response format from server\")\n\t}\n\tsigner, err := credential.NewSigner(key, certBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tx509Cred := credential.NewCredential(c.certFile, c.keyFile, c)\n\terr = x509Cred.SetVal(signer)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tidentity := NewIdentity(c, id, x509Cred)\n\n\tresp := &api.EnrollmentResponse{\n\t\tIdentity: NewIdentity(c, identity.GetName(), identity.GetX509Credential()),\n\t}\n\terr = c.net2LocalCAInfo(&result.ServerInfo, &resp.CAInfo)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn resp, nil\n}", "func (f *FabricCAClientImpl) ReEnroll(identity *Identity) (*Identity, error) {\n\n\tif identity == nil || identity.EnrollmentId() == \"\" {\n\t\treturn nil, ErrCertificateEmpty\n\t}\n\n\t// create new cert and send it to CA for signing\n\tkey, err := f.Crypto.GenerateKey()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcsr, err := f.Crypto.CreateCertificateRequest(identity.EnrollmentId(), key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\turl := fmt.Sprintf(\"%s/api/v1/reenroll\", f.Url)\n\n\tcrm, err := json.Marshal(CertificateRequest{CR: string(csr)})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq, err := http.NewRequest(\"POST\", url, bytes.NewBuffer(crm))\n\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\ttoken, err := f.createAuthToken(identity, crm)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq.Header.Set(\"authorization\", token)\n\tvar tr *http.Transport\n\tif f.Transport == nil {\n\t\ttr = &http.Transport{\n\t\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: f.SkipTLSVerification},\n\t\t}\n\t} else {\n\t\ttr = f.Transport\n\t}\n\n\thttpClient := &http.Client{Transport: tr}\n\n\tresp, err := httpClient.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tenrResp := new(enrollmentResponse)\n\tif err := json.Unmarshal(body, enrResp); err != nil {\n\t\treturn nil, err\n\t}\n\tif !enrResp.Success {\n\t\treturn nil, ErrEnrollment\n\t}\n\trawCert, err := base64.StdEncoding.DecodeString(enrResp.Result.Cert)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ta, _ := pem.Decode(rawCert)\n\tcert, err := x509.ParseCertificate(a.Bytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Identity{Certificate: cert, PrivateKey: key}, nil\n}", "func TestAddCourseToStudentFailCourseManagement(t *testing.T) {\n\t_ = config.SetConfigurationFromFile(\"../../../config/config-test.json\")\n\n\t// generate a token to be appended to the request\n\tuser := microservice.User{Name: \"name\", Surname: \"surname\", Username: \"user\",\n\t\tPassword: \"pass\", Type: \"student\", Mail: \"name@example.com\"}\n\ttoken, _ := microservice.GenerateAccessToken(user, []byte(config.Configuration.TokenPrivateKey))\n\n\t// make the body of request containing the course to add to student\n\tjsonBody := simplejson.New()\n\tjsonBody.Set(\"id\", \"idCourseFailingInCourseManagement\")\n\tjsonBody.Set(\"name\", \"courseFailingInCourseManagement\")\n\tjsonBody.Set(\"department\", \"department\")\n\tjsonBody.Set(\"year\", \"2019-2020\")\n\trequestBody, _ := json.Marshal(jsonBody)\n\n\t// make the PUT request for the course append\n\trequest, _ := http.NewRequest(http.MethodPut,\n\t\t\"/didattica-mobile/api/v1.0/students/user\", bytes.NewBuffer(requestBody))\n\trequest.AddCookie(&http.Cookie{Name: \"token\", Value: token})\n\n\tresponse := httptest.NewRecorder()\n\thandler := createTestGatewayAddCourseToStudent()\n\n\t// Goroutines represent the micro-services listens to the requests coming from the api gateway\n\tgo mock.LaunchCourseManagementMock()\n\tgo mock.LaunchNotificationManagementMock()\n\n\t// simulates a request-response interaction between client and api gateway\n\thandler.ServeHTTP(response, request)\n\n\tif response.Code != http.StatusBadRequest {\n\t\tt.Error(\"Expected 400 Bad request but got \" +\n\t\t\tstrconv.Itoa(response.Code) + \" \" + http.StatusText(response.Code))\n\t}\n}", "func (m *MockCertificateManager) Stop() {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"Stop\")\n}", "func (m *MockIDistributedEnforcer) AddPoliciesSelf(arg0 func() bool, arg1, arg2 string, arg3 [][]string) ([][]string, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"AddPoliciesSelf\", arg0, arg1, arg2, arg3)\n\tret0, _ := ret[0].([][]string)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (self *ecdsaCreator) GenerateCertificate(key interface{}) []byte {\n\tecdsaKey := self.getKey(key)\n\tpod := self.getDashboardPod()\n\n\tnotBefore := time.Now()\n\tvalidFor, _ := time.ParseDuration(\"8760h\")\n\tnotAfter := notBefore.Add(validFor)\n\n\ttemplate := x509.Certificate{\n\t\tSerialNumber: self.generateSerialNumber(),\n\t\tNotAfter: notAfter,\n\t\tNotBefore: notBefore,\n\t}\n\n\tif len(pod.Name) > 0 && len(pod.Namespace) > 0 {\n\t\tpodDomainName := pod.Name + \".\" + pod.Namespace\n\t\ttemplate.Subject = pkix.Name{CommonName: podDomainName}\n\t\ttemplate.Issuer = pkix.Name{CommonName: podDomainName}\n\t\ttemplate.DNSNames = []string{podDomainName}\n\t} else {\n\t\ttemplate.Subject = pkix.Name{CommonName: \"kubernetes-dashboard\", OrganizationalUnit: []string{\"kubernetes-dashboard\"}, Organization: []string{\"kubernetes-dashboard\"}}\n\t\ttemplate.Issuer = pkix.Name{CommonName: \"kubernetes-dashboard\", OrganizationalUnit: []string{\"kubernetes-dashboard\"}, Organization: []string{\"kubernetes-dashboard\"}}\n\t}\n\n\tif len(pod.Status.PodIP) > 0 {\n\t\ttemplate.IPAddresses = []net.IP{net.ParseIP(pod.Status.PodIP)}\n\t}\n\n\tcertBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &ecdsaKey.PublicKey, ecdsaKey)\n\tif err != nil {\n\t\tlog.Fatalf(\"[ECDSAManager] Failed to create certificate: %s\", err)\n\t}\n\n\treturn certBytes\n}", "func TestAuthorise(t *testing.T) {\n\tt.Parallel()\n\n\tinstance := getTestInstance()\n\n\tauthRequest := &Authorise{\n\t\tCard: &Card{\n\t\t\tNumber: \"4111111111111111\",\n\t\t\tExpireMonth: \"08\",\n\t\t\tExpireYear: \"2018\",\n\t\t\tCvc: \"737\",\n\t\t\tHolderName: \"John Smith\",\n\t\t},\n\t\tAmount: &Amount{\n\t\t\tValue: 1000,\n\t\t\tCurrency: \"EUR\",\n\t\t},\n\t\tReference: \"DE-TEST-1\" + randomString(10),\n\t\tMerchantAccount: os.Getenv(\"ADYEN_ACCOUNT\"),\n\t}\n\n\tresponse, err := instance.Payment().Authorise(authRequest)\n\n\tknownError, ok := err.(APIError)\n\tif ok {\n\t\tt.Errorf(\"Response should be succesfull. Known API Error: Code - %s, Message - %s, Type - %s\", knownError.ErrorCode, knownError.Message, knownError.ErrorType)\n\t}\n\n\tif err != nil {\n\t\tt.Errorf(\"Response should be succesfull, error - %s\", err.Error())\n\t}\n\n\tresponseBytes, err := json.Marshal(response)\n\n\tif err != nil {\n\t\tt.Error(\"Response can't be converted to JSON\")\n\t}\n\n\tif response.PspReference == \"\" {\n\t\tt.Errorf(\"Response should contain PSP Reference. Response - %s\", string(responseBytes))\n\t}\n\n\tif response.ResultCode != \"Authorised\" {\n\t\tt.Errorf(\"Response resultCode should be Authorised, Response - %s\", string(responseBytes))\n\t}\n}", "func (m *MockCertificateDao) GetCertificateByID(certificateID string) (*model.Certificate, error) {\n\tret := m.ctrl.Call(m, \"GetCertificateByID\", certificateID)\n\tret0, _ := ret[0].(*model.Certificate)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockDynamicCertPrivate) Run(arg0 context.Context, arg1 int) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"Run\", arg0, arg1)\n}", "func (m *MockIDistributedEnforcer) Enforce(arg0 ...interface{}) (bool, error) {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{}\n\tfor _, a := range arg0 {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"Enforce\", varargs...)\n\tret0, _ := ret[0].(bool)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func TestDummyCreateServiceCertAndKey(t *testing.T) {\n\tdefer leaktest.AfterTest(t)()\n\tcaCert, caKey, err := security.CreateCACertAndKey(context.Background(), nil, /* loggerFn */\n\t\ttime.Hour, \"test CA cert generation\")\n\tif err != nil {\n\t\tt.Fatalf(\"expected err=nil, got: %s\", err)\n\t}\n\n\t_, _, err = security.CreateServiceCertAndKey(\n\t\tcontext.Background(), nil, /* loggerFn */\n\t\ttime.Minute,\n\t\t\"dummy-common-name\",\n\t\t\"test Service cert generation\",\n\t\t[]string{\"localhost\", \"127.0.0.1\"},\n\t\tcaCert,\n\t\tcaKey,\n\t\tfalse, /* serviceCertIsAlsoValidAsClient */\n\t)\n\tif err != nil {\n\t\tt.Fatalf(\"expected err=nil, got: %s\", err)\n\t}\n}", "func (m *MockIDistributedEnforcer) UpdatePoliciesSelf(arg0 func() bool, arg1, arg2 string, arg3, arg4 [][]string) (bool, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"UpdatePoliciesSelf\", arg0, arg1, arg2, arg3, arg4)\n\tret0, _ := ret[0].(bool)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func NewCertificate2() *orchestrator.Certificate {\n\ttimeStamp := time.Date(2014, 12, 1, 0, 0, 0, 0, time.UTC)\n\tvar mockCertificate = &orchestrator.Certificate{\n\t\tId: testdata.MockCertificateID2,\n\t\tName: testdata.MockCertificateName2,\n\t\tCloudServiceId: testdata.MockCloudServiceID2,\n\t\tIssueDate: timeStamp.AddDate(-5, 0, 0).String(),\n\t\tExpirationDate: timeStamp.AddDate(5, 0, 0).String(),\n\t\tStandard: testdata.MockCertificateName2,\n\t\tAssuranceLevel: testdata.AssuranceLevelHigh,\n\t\tCab: testdata.MockCertificateCab2,\n\t\tDescription: testdata.MockCertificateDescription2,\n\t\tStates: []*orchestrator.State{{\n\t\t\tState: testdata.MockStateState2,\n\t\t\tTreeId: testdata.MockStateTreeID2,\n\t\t\tTimestamp: timeStamp.String(),\n\t\t\tCertificateId: testdata.MockCertificateID2,\n\t\t\tId: testdata.MockStateId2,\n\t\t}},\n\t}\n\treturn mockCertificate\n}", "func (m *MockProduct) UpsertRecievedLicenses(arg0 context.Context, arg1 db.UpsertRecievedLicensesParams) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"UpsertRecievedLicenses\", arg0, arg1)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockIDistributedEnforcer) ClearPolicySelf(arg0 func() bool) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ClearPolicySelf\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func TestWorkloadAgentGenerateSecretFromFile(t *testing.T) {\n\tfakeCACli, err := mock.NewMockCAClient(0, time.Hour)\n\tif err != nil {\n\t\tt.Fatalf(\"Error creating Mock CA client: %v\", err)\n\t}\n\topt := Options{\n\t\tRotationInterval: 200 * time.Millisecond,\n\t\tEvictionDuration: 0,\n\t}\n\n\tfetcher := &secretfetcher.SecretFetcher{\n\t\tUseCaClient: true,\n\t\tCaClient: fakeCACli,\n\t}\n\n\tvar wgAddedWatch sync.WaitGroup\n\tvar notifyEvent sync.WaitGroup\n\n\taddedWatchProbe := func(_ string, _ bool) { wgAddedWatch.Done() }\n\n\tvar closed bool\n\tnotifyCallback := func(_ ConnKey, _ *model.SecretItem) error {\n\t\tif !closed {\n\t\t\tnotifyEvent.Done()\n\t\t}\n\t\treturn nil\n\t}\n\n\t// Supply a fake watcher so that we can watch file events.\n\tvar fakeWatcher *filewatcher.FakeWatcher\n\tnewFileWatcher, fakeWatcher = filewatcher.NewFakeWatcher(addedWatchProbe)\n\n\tsc := NewSecretCache(fetcher, notifyCallback, opt)\n\tdefer func() {\n\t\tclosed = true\n\t\tsc.Close()\n\t\tnewFileWatcher = filewatcher.NewWatcher\n\t}()\n\n\trootCertPath := \"./testdata/root-cert.pem\"\n\tkeyPath := \"./testdata/key.pem\"\n\tcertChainPath := \"./testdata/cert-chain.pem\"\n\tsc.existingRootCertFile = rootCertPath\n\tsc.existingKeyFile = keyPath\n\tsc.existingCertChainFile = certChainPath\n\tcertchain, err := ioutil.ReadFile(certChainPath)\n\tif err != nil {\n\t\tt.Fatalf(\"Error reading the cert chain file: %v\", err)\n\t}\n\tprivateKey, err := ioutil.ReadFile(keyPath)\n\tif err != nil {\n\t\tt.Fatalf(\"Error reading the private key file: %v\", err)\n\t}\n\trootCert, err := ioutil.ReadFile(rootCertPath)\n\tif err != nil {\n\t\tt.Fatalf(\"Error reading the root cert file: %v\", err)\n\t}\n\n\tconID := \"proxy1-id\"\n\tctx := context.Background()\n\n\twgAddedWatch.Add(1) // Watch should be added for cert file.\n\tnotifyEvent.Add(1) // Nofify should be called once.\n\n\tgotSecret, err := sc.GenerateSecret(ctx, conID, WorkloadKeyCertResourceName, \"jwtToken1\")\n\n\twgAddedWatch.Wait()\n\tnotifyEvent.Wait()\n\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to get secrets: %v\", err)\n\t}\n\tcheckBool(t, \"SecretExist\", sc.SecretExist(conID, WorkloadKeyCertResourceName, \"jwtToken1\", gotSecret.Version), true)\n\texpectedSecret := &model.SecretItem{\n\t\tResourceName: WorkloadKeyCertResourceName,\n\t\tCertificateChain: certchain,\n\t\tPrivateKey: privateKey,\n\t}\n\tif err := verifySecret(gotSecret, expectedSecret); err != nil {\n\t\tt.Errorf(\"Secret verification failed: %v\", err)\n\t}\n\n\twgAddedWatch.Add(1) // Watch should be added for root file.\n\tnotifyEvent.Add(1) // Notify should be called once.\n\n\tgotSecretRoot, err := sc.GenerateSecret(ctx, conID, RootCertReqResourceName, \"jwtToken1\")\n\n\twgAddedWatch.Wait()\n\tnotifyEvent.Wait()\n\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to get secrets: %v\", err)\n\t}\n\tcheckBool(t, \"SecretExist\", sc.SecretExist(conID, RootCertReqResourceName, \"jwtToken1\", gotSecretRoot.Version), true)\n\tif got, want := atomic.LoadUint64(&sc.rootCertChangedCount), uint64(0); got != want {\n\t\tt.Errorf(\"rootCertChangedCount: got: %v, want: %v\", got, want)\n\t}\n\n\trootExpiration, err := nodeagentutil.ParseCertAndGetExpiryTimestamp(rootCert)\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to get the expiration time from the existing root file\")\n\t}\n\texpectedSecret = &model.SecretItem{\n\t\tResourceName: RootCertReqResourceName,\n\t\tRootCert: rootCert,\n\t\tExpireTime: rootExpiration,\n\t}\n\tif err := verifyRootCASecret(gotSecretRoot, expectedSecret); err != nil {\n\t\tt.Errorf(\"Secret verification failed: %v\", err)\n\t}\n\n\tkey := ConnKey{\n\t\tConnectionID: conID,\n\t\tResourceName: WorkloadKeyCertResourceName,\n\t}\n\tcachedSecret, found := sc.secrets.Load(key)\n\tif !found {\n\t\tt.Errorf(\"Failed to find secret for proxy %q from secret store: %v\", conID, err)\n\t}\n\tif !reflect.DeepEqual(*gotSecret, cachedSecret) {\n\t\tt.Errorf(\"Secret key: got %+v, want %+v\", *gotSecret, cachedSecret)\n\t}\n\n\t// Inject a file write event and validate that Notify is called.\n\tnotifyEvent.Add(1)\n\tfakeWatcher.InjectEvent(certChainPath, fsnotify.Event{\n\t\tName: certChainPath,\n\t\tOp: fsnotify.Write,\n\t})\n\tnotifyEvent.Wait()\n}", "func SetupCertificate(mgr ctrl.Manager, l logging.Logger, rl workqueue.RateLimiter, poll time.Duration) error {\n\tname := managed.ControllerName(v1alpha1.CertificateGroupKind)\n\n\treturn ctrl.NewControllerManagedBy(mgr).\n\t\tNamed(name).\n\t\tWithOptions(controller.Options{\n\t\t\tRateLimiter: ratelimiter.NewController(rl),\n\t\t}).\n\t\tFor(&v1alpha1.Certificate{}).\n\t\tComplete(managed.NewReconciler(mgr,\n\t\t\tresource.ManagedKind(v1alpha1.CertificateGroupVersionKind),\n\t\t\tmanaged.WithExternalConnecter(&connector{client: mgr.GetClient(), newClientFn: acm.NewClient}),\n\t\t\tmanaged.WithConnectionPublishers(),\n\t\t\tmanaged.WithPollInterval(poll),\n\t\t\tmanaged.WithReferenceResolver(managed.NewAPISimpleReferenceResolver(mgr.GetClient())),\n\t\t\tmanaged.WithInitializers(),\n\t\t\tmanaged.WithLogger(l.WithValues(\"controller\", name)),\n\t\t\tmanaged.WithRecorder(event.NewAPIRecorder(mgr.GetEventRecorderFor(name)))))\n}", "func (mr *MockClientMockRecorder) EnrollmentCertificate() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"EnrollmentCertificate\", reflect.TypeOf((*MockClient)(nil).EnrollmentCertificate))\n}", "func TestAuthorize(t *testing.T) {\n\n\thelper := sleet_t.NewTestHelper(t)\n\turl := \"https://cert.api.firstdata.com/gateway/v2/payments\"\n\n\tvar authResponseRaw, responseErrorRaw []byte\n\tauthResponseRaw = helper.ReadFile(\"test_data/authResponse.json\")\n\tresponseErrorRaw = helper.ReadFile(\"test_data/400Response.json\")\n\n\trequest := sleet_t.BaseAuthorizationRequest()\n\tt.Run(\"With Successful Response\", func(t *testing.T) {\n\n\t\thttpmock.Activate()\n\t\tdefer httpmock.DeactivateAndReset()\n\n\t\thttpmock.RegisterResponder(\"POST\", url, func(req *http.Request) (*http.Response, error) {\n\t\t\tresp := httpmock.NewBytesResponse(http.StatusOK, authResponseRaw)\n\t\t\treturn resp, nil\n\t\t})\n\n\t\tfirstDataClient := NewClient(common.Sandbox, Credentials{defaultApiKey, defaultApiSecret})\n\n\t\tgot, err := firstDataClient.Authorize(request)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"ERROR THROWN: Got %q, after calling Authorize\", err)\n\t\t}\n\n\t\twant := &sleet.AuthorizationResponse{\n\t\t\tSuccess: true,\n\t\t\tTransactionReference: \"84538652787\",\n\t\t\tAvsResult: sleet.AVSResponseSkipped,\n\t\t\tCvvResult: sleet.CVVResponseSkipped,\n\t\t\tAvsResultRaw: \"NO_INPUT_DATA:NO_INPUT_DATA\",\n\t\t\tCvvResultRaw: \"NOT_CHECKED\",\n\t\t\tStatusCode: 200,\n\t\t}\n\n\t\tif !cmp.Equal(*got, *want, sleet_t.CompareUnexported) {\n\t\t\tt.Error(\"Response body does not match expected\")\n\t\t\tt.Error(cmp.Diff(*want, *got, sleet_t.CompareUnexported))\n\t\t}\n\n\t})\n\n\tt.Run(\"With Error Response\", func(t *testing.T) {\n\n\t\thttpmock.Activate()\n\t\tdefer httpmock.DeactivateAndReset()\n\n\t\thttpmock.RegisterResponder(\"POST\", url, func(req *http.Request) (*http.Response, error) {\n\t\t\tresp := httpmock.NewBytesResponse(http.StatusOK, responseErrorRaw)\n\t\t\treturn resp, nil\n\t\t})\n\n\t\tfirstDataClient := NewClient(common.Sandbox, Credentials{defaultApiKey, defaultApiSecret})\n\n\t\tgot, err := firstDataClient.Authorize(request)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"ERROR THROWN: Got %q, after calling Authorize\", err)\n\t\t}\n\n\t\twant := &sleet.AuthorizationResponse{\n\t\t\tSuccess: false,\n\t\t\tErrorCode: \"403\",\n\t\t\tStatusCode: 200,\n\t\t}\n\n\t\tif !cmp.Equal(*got, *want, sleet_t.CompareUnexported) {\n\t\t\tt.Error(\"Response body does not match expected\")\n\t\t\tt.Error(cmp.Diff(*want, *got, sleet_t.CompareUnexported))\n\t\t}\n\t})\n}", "func (p *Peer) EnrollmentCertificate() *pem.Block {\n\treturn p.enrollmentCertificate\n}", "func (m *MockVirtualMeshCertificateSigningRequestClient) UpsertVirtualMeshCertificateSigningRequest(ctx context.Context, obj *v1alpha1.VirtualMeshCertificateSigningRequest, transitionFuncs ...v1alpha1.VirtualMeshCertificateSigningRequestTransitionFunction) error {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{ctx, obj}\n\tfor _, a := range transitionFuncs {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"UpsertVirtualMeshCertificateSigningRequest\", varargs...)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (d Driver) IssueCertificate(config CertRequest) ([]byte, error) {\n\tserial, err := rand.Int(rand.Reader, MaxSerialNumber)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"error generating certificate serial number\")\n\t}\n\n\tca, err := d.ca.Load(config.CAName)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"error loading CA bundle\")\n\t}\n\n\trootCert, err := x509.ParseCertificate(ca.Certificate[0])\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"error parsing CA certificate\")\n\t}\n\n\tnow := time.Now()\n\n\tcert := x509.Certificate{\n\t\tSerialNumber: serial,\n\t\tSubject: pkix.Name{\n\t\t\tCommonName: config.CommonName,\n\t\t\tOrganizationalUnit: rootCert.Subject.OrganizationalUnit,\n\t\t\tOrganization: rootCert.Subject.Organization,\n\t\t\tCountry: rootCert.Subject.Country,\n\t\t\tProvince: rootCert.Subject.Province,\n\t\t\tLocality: rootCert.Subject.Locality,\n\t\t\tStreetAddress: rootCert.Subject.StreetAddress,\n\t\t\tPostalCode: rootCert.Subject.PostalCode,\n\t\t},\n\t\tNotBefore: now,\n\t\tNotAfter: now.Add(config.Lifetime),\n\t\tKeyUsage: x509.KeyUsageDigitalSignature,\n\t\tExtKeyUsage: config.Usage,\n\t}\n\n\tfor _, name := range config.DNSNames {\n\t\tcert.DNSNames = append(cert.DNSNames, name)\n\t}\n\n\tfor _, addr := range config.IPAddrs {\n\t\tcert.IPAddresses = append(cert.IPAddresses, addr)\n\t}\n\n\tkey, err := rsa.GenerateKey(rand.Reader, PrivateKeyLength)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"error generating private key\")\n\t}\n\n\tsigned, err := x509.CreateCertificate(rand.Reader, &cert, rootCert, &key.PublicKey, ca.PrivateKey)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"error signing certificate\")\n\t}\n\n\tbundle := &bytes.Buffer{}\n\n\tif err := pem.Encode(bundle, &pem.Block{Type: \"RSA PRIVATE KEY\", Bytes: x509.MarshalPKCS1PrivateKey(key)}); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := pem.Encode(bundle, &pem.Block{Type: \"CERTIFICATE\", Bytes: signed}); err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, cert := range ca.Certificate {\n\t\tif err := pem.Encode(bundle, &pem.Block{Type: \"CERTIFICATE\", Bytes: cert}); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn bundle.Bytes(), nil\n}", "func (m *MockAccessPolicyEnforcerLoop) Start(ctx context.Context) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Start\", ctx)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func fakeCertificate(sni string) (cert tls.Certificate, err error) {\n\tconf := getConfig()\n\tserial, err := rand.Int(rand.Reader, big.NewInt(1<<62))\n\tif err != nil {\n\t\treturn tls.Certificate{}, err\n\t}\n\ty, m, d := time.Now().Date()\n\n\ttemplate := &x509.Certificate{\n\t\tSerialNumber: serial,\n\t\tSubject: pkix.Name{CommonName: sni},\n\t\tNotBefore: time.Date(y, m, d, 0, 0, 0, 0, time.Local),\n\t\tNotAfter: time.Date(y, m+1, d, 0, 0, 0, 0, time.Local),\n\t\tKeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment,\n\t\tDNSNames: []string{sni},\n\t\tSignatureAlgorithm: x509.UnknownSignatureAlgorithm,\n\t}\n\n\tnewCertBytes, err := x509.CreateCertificate(rand.Reader, template, conf.ParsedTLSCert, conf.ParsedTLSCert.PublicKey, conf.TLSCert.PrivateKey)\n\tif err != nil {\n\t\treturn tls.Certificate{}, err\n\t}\n\n\tnewCert := tls.Certificate{\n\t\tCertificate: [][]byte{newCertBytes},\n\t\tPrivateKey: conf.TLSCert.PrivateKey,\n\t}\n\n\tnewCert.Certificate = append(newCert.Certificate, conf.TLSCert.Certificate...)\n\treturn newCert, nil\n}", "func (m *MockIDistributedEnforcer) ClearPolicy() {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"ClearPolicy\")\n}", "func (m *MockIDistributedEnforcer) EnforceEx(arg0 ...interface{}) (bool, []string, error) {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{}\n\tfor _, a := range arg0 {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"EnforceEx\", varargs...)\n\tret0, _ := ret[0].(bool)\n\tret1, _ := ret[1].([]string)\n\tret2, _ := ret[2].(error)\n\treturn ret0, ret1, ret2\n}", "func (m *MockIDistributedEnforcer) UpdatePolicySelf(arg0 func() bool, arg1, arg2 string, arg3, arg4 []string) (bool, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"UpdatePolicySelf\", arg0, arg1, arg2, arg3, arg4)\n\tret0, _ := ret[0].(bool)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockFullNode) PaychCollect(arg0 context.Context, arg1 address.Address) (cid.Cid, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"PaychCollect\", arg0, arg1)\n\tret0, _ := ret[0].(cid.Cid)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func NewCertificate(opts ...NewCertificateOption) *orchestrator.Certificate {\n\ttimeStamp := time.Date(2011, 7, 1, 0, 0, 0, 0, time.UTC)\n\tvar mockCertificate = &orchestrator.Certificate{\n\t\tId: testdata.MockCertificateID,\n\t\tName: testdata.MockCertificateName,\n\t\tCloudServiceId: testdata.MockCloudServiceID1,\n\t\tIssueDate: timeStamp.AddDate(-5, 0, 0).String(),\n\t\tExpirationDate: timeStamp.AddDate(5, 0, 0).String(),\n\t\tStandard: testdata.MockCertificateName,\n\t\tAssuranceLevel: testdata.AssuranceLevelHigh,\n\t\tCab: testdata.MockCertificateCab,\n\t\tDescription: testdata.MockCertificateDescription,\n\t\tStates: []*orchestrator.State{{\n\t\t\tState: testdata.MockStateState,\n\t\t\tTreeId: testdata.MockStateTreeID,\n\t\t\tTimestamp: timeStamp.String(),\n\t\t\tCertificateId: testdata.MockCertificateID,\n\t\t\tId: testdata.MockStateId,\n\t\t}},\n\t}\n\n\tfor _, o := range opts {\n\t\to(mockCertificate)\n\t}\n\n\treturn mockCertificate\n}", "func TestIntegration_Certificate_Create(t *testing.T) {\n\tc := qt.New(t)\n\ttoken := os.Getenv(\"PLANETSCALE_TOKEN\")\n\tc.Assert(token, qt.Not(qt.Equals), \"\", qt.Commentf(\"PLANETSCALE_TOKEN is not set\"))\n\n\torg := os.Getenv(\"PLANETSCALE_ORG\")\n\tc.Assert(org, qt.Not(qt.Equals), \"\", qt.Commentf(\"PLANETSCALE_ORG is not set\"))\n\n\tctx := context.Background()\n\n\tclient, err := NewClient(\n\t\tWithAccessToken(token),\n\t)\n\tc.Assert(err, qt.IsNil)\n\n\tpkey, err := rsa.GenerateKey(rand.Reader, 2048)\n\tc.Assert(err, qt.IsNil)\n\n\tcert, err := client.Certificates.Create(ctx, &CreateCertificateRequest{\n\t\tOrganization: org,\n\t\tDatabaseName: \"fatihs-db\",\n\t\tBranch: \"development\",\n\t\tPrivateKey: pkey,\n\t})\n\tc.Assert(err, qt.IsNil)\n\n\tfmt.Printf(\"cert = %+v\\n\", cert)\n}", "func (m *MockISubscription) UpsertSubscription(arg0 *Subscription) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"UpsertSubscription\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockisCryptoApiResponse_CryptoApiResp) isCryptoApiResponse_CryptoApiResp() {\n\tm.ctrl.Call(m, \"isCryptoApiResponse_CryptoApiResp\")\n}", "func TestGenCSR(t *testing.T) {\n\tconfig := new(ClientConfig)\n\n\thomeDir := filepath.Join(testdataDir, \"identity\")\n\n\tdefer func() {\n\t\terr := os.RemoveAll(homeDir)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"RemoveAll failed: %s\", err)\n\t\t}\n\t}()\n\n\tconfig.CSR.CN = \"identity\"\n\terr := config.GenCSR(homeDir)\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to generate CSR: %s\", err)\n\t}\n\tcsrFile := filepath.Join(homeDir, \"msp\", \"signcerts\", \"identity.csr\")\n\t_, err = os.Stat(csrFile)\n\tif os.IsNotExist(err) {\n\t\tt.Fatalf(\"CSR file does not exist at %s\", csrFile)\n\t}\n\terr = os.RemoveAll(homeDir)\n\tif err != nil {\n\t\tt.Errorf(\"RemoveAll failed: %s\", err)\n\t}\n\n\t// Error cases\n\t// CN is missing\n\tconfig.CSR.CN = \"\"\n\terr = config.GenCSR(homeDir)\n\tif err == nil {\n\t\tt.Fatalf(\"GenCSR should fail as CN is missing: %s\", err)\n\t}\n\n\t// Fail to write file\n\tconfig.CSR.CN = strings.Repeat(\"a\", 260)\n\terr = config.GenCSR(homeDir)\n\tt.Logf(\"ClientConfig.GenCSR error %v\", err)\n\tif err == nil {\n\t\tt.Error(\"ClientConfig.GenCSR should have failed due to invalid filename\")\n\t}\n\n\t// Fail to gen key\n\tconfig.CSR = api.CSRInfo{\n\t\tCN: \"TestGenCSR\",\n\t\tKeyRequest: &api.KeyRequest{\n\t\t\tAlgo: \"dsa\",\n\t\t\tSize: 256,\n\t\t},\n\t}\n\terr = config.GenCSR(homeDir)\n\tt.Logf(\"ClientConfig.GenCSR error %v\", err)\n\tif err == nil {\n\t\tt.Error(\"ClientConfig.GenCSR should have failed due to unsupported algorithm\")\n\t}\n\n\t// Fail to init client\n\tconfig.MSPDir = string(make([]byte, 1))\n\terr = config.GenCSR(homeDir)\n\tt.Logf(\"ClientConfig.GenCSR error %v\", err)\n\tif err == nil {\n\t\tt.Error(\"ClientConfig.GenCSR should have failed to init client\")\n\t}\n}", "func (m *MockCertificateManager) GetCertificates() []*p2pcommon.AgentCertificateV1 {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetCertificates\")\n\tret0, _ := ret[0].([]*p2pcommon.AgentCertificateV1)\n\treturn ret0\n}", "func (m *MockInternalClient) CryptoAsymKeyWrite(ctx context.Context, in *CryptoAsymKeyWriteRequestMsg, opts ...grpc.CallOption) (*CryptoAsymKeyWriteResponseMsg, error) {\n\tvarargs := []interface{}{ctx, in}\n\tfor _, a := range opts {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"CryptoAsymKeyWrite\", varargs...)\n\tret0, _ := ret[0].(*CryptoAsymKeyWriteResponseMsg)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func testUserAssignedIdentityOnPod(ctx context.Context, msiEndpoint, identityClientID, identityResourceID, keyvaultName, keyvaultSecretName, keyvaultSecretVersion string) error {\n\tvar authorizers []autorest.Authorizer\n\tkeyClient := keyvault.New()\n\n\tif identityClientID != \"\" {\n\t\t// When new authorizer is created, azure-sdk-for-go tries to create data plane authorizer using MSI. It checks the AZURE_CLIENT_ID to get the client id\n\t\t// for the user assigned identity. If client id not found, then NewServicePrincipalTokenFromMSI is invoked instead of using the actual\n\t\t// user assigned identity. Setting this env var ensures we validate GetSecret using the desired user assigned identity.\n\t\tos.Setenv(\"AZURE_CLIENT_ID\", identityClientID)\n\t\tdefer os.Unsetenv(\"AZURE_CLIENT_ID\")\n\n\t\tauthorizer, err := auth.NewAuthorizerFromEnvironment()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tauthorizers = append(authorizers, authorizer)\n\t\tklog.Infof(\"added authorizer with clientID: %s\", identityClientID)\n\t}\n\tif identityResourceID != \"\" {\n\t\t// The sdk doesn't support authenticating by the resource id, but we can get a token manually\n\t\ttoken, err := authenticateWithMsiResourceID(msiEndpoint, identityResourceID, \"https://vault.azure.net\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tauthorizers = append(authorizers, autorest.NewBearerAuthorizer(token))\n\t\tklog.Infof(\"added authorizer with resourceID: %s\", identityResourceID)\n\t}\n\n\tklog.Infof(\"%s %s %s\\n\", keyvaultName, keyvaultSecretName, keyvaultSecretVersion)\n\tfor _, authorizer := range authorizers {\n\t\tkeyClient.Authorizer = authorizer\n\t\tsecret, err := keyClient.GetSecret(ctx, fmt.Sprintf(\"https://%s.vault.azure.net\", keyvaultName), keyvaultSecretName, keyvaultSecretVersion)\n\t\tif err != nil || *secret.Value == \"\" {\n\t\t\treturn errors.Wrapf(err, \"Failed to verify user assigned identity on pod\")\n\t\t}\n\t}\n\tklog.Infof(\"successfully verified user-assigned identity on pod\")\n\n\treturn nil\n}", "func tpmenroll(w http.ResponseWriter, r *http.Request) {\n\tctx := r.Context()\n\taps := chi.URLParam(r, apsParamName)\n\n\t// Read and decode request.\n\tvar csr *x509.CertificateRequest\n\tvar ekCerts []*x509.Certificate\n\tvar ekPub []byte\n\tvar akPub []byte\n\n\t_, err := decodeMultipartRequest(\n\t\tr,\n\t\t[]multipartPart{\n\t\t\t{contentType: mimeTypePKCS10, data: &csr},\n\t\t\t{contentType: mimeTypePKCS7, data: &ekCerts},\n\t\t\t{contentType: mimeTypeOctetStream, data: &ekPub},\n\t\t\t{contentType: mimeTypeOctetStream, data: &akPub},\n\t\t},\n\t)\n\tif writeOnError(ctx, w, logMsgMultipartDecodeFailed, err) {\n\t\treturn\n\t}\n\n\t// Validate EK public key matches that in the EK certificate. Note that\n\t// while the name of the AK (i.e. the hash of the entire AK public area)\n\t// will be used to protect the credential, only the name algorithm and\n\t// the symmetric encryption algorithm from the EK public area will be used,\n\t// so none of the protection depends on the EK public area and in general\n\t// it can be manipulated and is unreliable.\n\tif err := validatePublicAreaPublicKey(ekPub, ekCerts[0].PublicKey); err != nil {\n\t\twriteOnError(ctx, w, logMsgPublicKeyInvalid, err)\n\t\treturn\n\t}\n\n\t// Note that we could verify if the AK public key matches that in the CSR,\n\t// but the TPM device will fail to activate the credential if a matching\n\t// key is not on the TPM, so even if we don't verify proof-of-possession,\n\t// the TPM privacy-preserving protocol will ensure that certificate can\n\t// only be decrypted by a TPM possessing that private key, so we achieve\n\t// the same end. Since it's possible a client may request a certificate for\n\t// a key which cannot be used for signing CSRs, and since the TPM privacy-\n\t// preserving protocol gives us a means to do that securely, we here choose\n\t// to allow it, and effectively ignore the public key in the CSR in a\n\t// manner similar to /serverkeygen.\n\n\t// Request credential blob and encrypted seed from backing CA.\n\tcredBlob, encSeed, cred, err := caFromContext(ctx).TPMEnroll(ctx, csr, ekCerts, ekPub, akPub, aps, r)\n\tif writeOnError(ctx, w, logMsgEnrollFailed, err) {\n\t\treturn\n\t}\n\n\t// Encode and write response.\n\tbuf, contentType, err := encodeMultiPart(\n\t\ttpmEnrollBoundary,\n\t\t[]multipartPart{\n\t\t\t{contentType: mimeTypeOctetStream, data: credBlob},\n\t\t\t{contentType: mimeTypeOctetStream, data: encSeed},\n\t\t\t{contentType: mimeTypePKCS7Enveloped, data: cred},\n\t\t},\n\t)\n\tif writeOnError(ctx, w, logMsgMultipartEncodeFailed, err) {\n\t\treturn\n\t}\n\n\twriteResponse(w, contentType, false, buf.Bytes())\n}", "func (m *MockisCryptoApiRequest_CryptoApiReq) isCryptoApiRequest_CryptoApiReq() {\n\tm.ctrl.Call(m, \"isCryptoApiRequest_CryptoApiReq\")\n}", "func TestProbeHTTPSVerifiedChains(t *testing.T) {\n\trootPrivateKey, err := rsa.GenerateKey(rand.Reader, 2048)\n\tif err != nil {\n\t\tt.Fatalf(err.Error())\n\t}\n\n\trootCertExpiry := time.Now().AddDate(0, 0, 5)\n\trootCertTmpl := test.GenerateCertificateTemplate(rootCertExpiry)\n\trootCertTmpl.IsCA = true\n\trootCertTmpl.SerialNumber = big.NewInt(1)\n\trootCert, rootCertPem := test.GenerateSelfSignedCertificateWithPrivateKey(rootCertTmpl, rootPrivateKey)\n\n\tolderRootCertExpiry := time.Now().AddDate(0, 0, 3)\n\tolderRootCertTmpl := test.GenerateCertificateTemplate(olderRootCertExpiry)\n\tolderRootCertTmpl.IsCA = true\n\tolderRootCertTmpl.SerialNumber = big.NewInt(2)\n\tolderRootCert, olderRootCertPem := test.GenerateSelfSignedCertificateWithPrivateKey(olderRootCertTmpl, rootPrivateKey)\n\n\toldestRootCertExpiry := time.Now().AddDate(0, 0, 1)\n\toldestRootCertTmpl := test.GenerateCertificateTemplate(oldestRootCertExpiry)\n\toldestRootCertTmpl.IsCA = true\n\toldestRootCertTmpl.SerialNumber = big.NewInt(3)\n\toldestRootCert, oldestRootCertPem := test.GenerateSelfSignedCertificateWithPrivateKey(oldestRootCertTmpl, rootPrivateKey)\n\n\tserverCertExpiry := time.Now().AddDate(0, 0, 4)\n\tserverCertTmpl := test.GenerateCertificateTemplate(serverCertExpiry)\n\tserverCertTmpl.SerialNumber = big.NewInt(4)\n\tserverCert, serverCertPem, serverKey := test.GenerateSignedCertificate(serverCertTmpl, olderRootCert, rootPrivateKey)\n\n\tverifiedChains := [][]*x509.Certificate{\n\t\t[]*x509.Certificate{\n\t\t\tserverCert,\n\t\t\trootCert,\n\t\t},\n\t\t[]*x509.Certificate{\n\t\t\tserverCert,\n\t\t\tolderRootCert,\n\t\t},\n\t\t[]*x509.Certificate{\n\t\t\tserverCert,\n\t\t\toldestRootCert,\n\t\t},\n\t}\n\n\tcaCertPem := bytes.Join([][]byte{oldestRootCertPem, olderRootCertPem, rootCertPem}, []byte(\"\"))\n\n\tserver, caFile, teardown, err := test.SetupHTTPSServerWithCertAndKey(\n\t\tcaCertPem,\n\t\tserverCertPem,\n\t\tserverKey,\n\t)\n\tif err != nil {\n\t\tt.Fatalf(err.Error())\n\t}\n\tdefer teardown()\n\n\tserver.StartTLS()\n\tdefer server.Close()\n\n\tmodule := config.Module{\n\t\tTLSConfig: config.TLSConfig{\n\t\t\tCAFile: caFile,\n\t\t},\n\t}\n\n\tregistry := prometheus.NewRegistry()\n\n\tctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)\n\tdefer cancel()\n\n\tif err := ProbeHTTPS(ctx, newTestLogger(), server.URL, module, registry); err != nil {\n\t\tt.Fatalf(\"error: %s\", err)\n\t}\n\n\tcheckCertificateMetrics(serverCert, registry, t)\n\tcheckOCSPMetrics([]byte{}, registry, t)\n\tcheckVerifiedChainMetrics(verifiedChains, registry, t)\n\tcheckTLSVersionMetrics(\"TLS 1.3\", registry, t)\n}", "func makeCertificate(t *testing.T) tls.Certificate {\n\tconst certPEM = `\n-----BEGIN CERTIFICATE-----\nMIID9DCCAtygAwIBAgIJAIX/1sxuqZKrMA0GCSqGSIb3DQEBCwUAMFkxCzAJBgNV\nBAYTAkFVMRMwEQYDVQQIEwpTb21lLVN0YXRlMSEwHwYDVQQKExhJbnRlcm5ldCBX\naWRnaXRzIFB0eSBMdGQxEjAQBgNVBAMTCWxvY2FsaG9zdDAeFw0xNzA1MDYxNDIy\nMjVaFw0yNzA1MDQxNDIyMjVaMFkxCzAJBgNVBAYTAkFVMRMwEQYDVQQIEwpTb21l\nLVN0YXRlMSEwHwYDVQQKExhJbnRlcm5ldCBXaWRnaXRzIFB0eSBMdGQxEjAQBgNV\nBAMTCWxvY2FsaG9zdDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALO4\nXVY5Kw9eNblqBenC03Wz6qemLFw8zLDNrehvjYuJPn5WVwvzLNP+3S02iqQD+Y1k\nvszqDIZLQdjWLiEZdtxfemyIr+RePIMclnceGYFx3Zgg5qeyvOWlJLM41ZU8YZb/\nzGj3RtXzuOZ5vePSLGS1nudjrKSBs7shRY8bYjkOqFujsSVnEK7s3Kb2Sf/rO+7N\nRZ1df3hhyKtyq4Pb5eC1mtQqcRjRSZdTxva8kO4vRQbvGgjLUakvBVrrnwbww5a4\n2wKbQPKIClEbSLyKQ62zR8gW1rPwBdokd8u9+rLbcmr7l0OuAsSn5Xi9x6VxXTNE\nbgCa1KVoE4bpoGG+KQsCAwEAAaOBvjCBuzAdBgNVHQ4EFgQUILso/fozIhaoyi05\nXNSWzP/ck+4wgYsGA1UdIwSBgzCBgIAUILso/fozIhaoyi05XNSWzP/ck+6hXaRb\nMFkxCzAJBgNVBAYTAkFVMRMwEQYDVQQIEwpTb21lLVN0YXRlMSEwHwYDVQQKExhJ\nbnRlcm5ldCBXaWRnaXRzIFB0eSBMdGQxEjAQBgNVBAMTCWxvY2FsaG9zdIIJAIX/\n1sxuqZKrMAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQELBQADggEBAIbzsvTZb8LA\nJqyaTttsMMA1szf4WBX88lVWbIk91k0nlTa0BiU/UocKrU6c9PySwJ6FOFJpgpdH\nz/kmJ+S+d4pvgqBzWbKMoMrNlMt6vL+H8Mbf/l/CN91eNM+gJZu2HgBIFGW1y4Wy\ngOzjEm9bw15Hgqqs0P4CSy7jcelWA285DJ7IG1qdPGhAKxT4/UuDin8L/u2oeYWH\n3DwTDO4kAUnKetcmNQFSX3Ge50uQypl8viYgFJ2axOfZ3imjQZrs7M1Og6Wnj/SD\nF414wVQibsZyZp8cqwR/OinvxloPkPVnf163jPRtftuqezEY8Nyj83O5u5sC1Azs\nX/Gm54QNk6w=\n-----END CERTIFICATE-----`\n\tconst keyPEM = `\n-----BEGIN RSA PRIVATE KEY-----\nMIIEowIBAAKCAQEAs7hdVjkrD141uWoF6cLTdbPqp6YsXDzMsM2t6G+Ni4k+flZX\nC/Ms0/7dLTaKpAP5jWS+zOoMhktB2NYuIRl23F96bIiv5F48gxyWdx4ZgXHdmCDm\np7K85aUkszjVlTxhlv/MaPdG1fO45nm949IsZLWe52OspIGzuyFFjxtiOQ6oW6Ox\nJWcQruzcpvZJ/+s77s1FnV1/eGHIq3Krg9vl4LWa1CpxGNFJl1PG9ryQ7i9FBu8a\nCMtRqS8FWuufBvDDlrjbAptA8ogKURtIvIpDrbNHyBbWs/AF2iR3y736sttyavuX\nQ64CxKfleL3HpXFdM0RuAJrUpWgThumgYb4pCwIDAQABAoIBAHzvYntJPKTvUhu2\nF6w8kvHVBABNpbLtVUJniUj3G4fv/bCn5tVY1EX/e9QtgU2psbbYXUdoQRKuiHTr\n15+M6zMhcKK4lsYDuL9QhU0DcKmq9WgHHzFfMK/YEN5CWT/ofNMSuhASLn0Xc+dM\npHQWrGPKWk/y25Z0z/P7mjZ0y+BrJOKlxV53A2AWpj4JtjX2YO6s/eiraFX+RNlv\nGyWzeQ7Gynm2TD9VXhS+m40VVBmmbbeZYDlziDoWWNe9r26A+C8K65gZtjKdarMd\n0LN89jJvI1pUxcIuvZJnumWUenZ7JhfBGpkfAwLB+MogUo9ekAHv1IZv/m3uWq9f\nZml2dZECgYEA2OCI8kkLRa3+IodqQNFrb/uZ16YouQ71B7nBgAxls9nuhyELKO7d\nfzf1snPx6cbaCQKTyxrlYvck4gz8P09R7nVYwJuTmP0+QIgeCCc3Y9A2dyExaC6I\nuKkFzJEqIVZNLvdjBRWQs5AiD1w58oto+wOvbagAQM483WiJ/qFaHCMCgYEA1CPo\nzwI6pCn39RSYffK25HXM1q3i8ypkYdNsG6IVqS2FqHqj8XJSnDvLeIm7W1Rtw+uM\nQdZ5O6PH31XgolG6LrFkW9vtfH+QnXQA2AnZQEfn034YZubhcexLqAkS9r0FUUZp\na1WI2jSxBBeB+to6MdNABuQOL3NHjPUidUKnOfkCgYA+HvKbE7ka2F+23DrfHh08\nEkFat8lqWJJvCBIY73QiNAZSxnA/5UukqQ7DctqUL9U8R3S19JpH4qq55SZLrBi3\nyP0HDokUhVVTfqm7hCAlgvpW3TcdtFaNLjzu/5WlvuaU0V+XkTnFdT+MTsp6YtxL\nKh8RtdF8vpZIhS0htm3tKQKBgQDQXoUp79KRtPdsrtIpw+GI/Xw50Yp9tkHrJLOn\nYMlN5vzFw9CMM/KYqtLsjryMtJ0sN40IjhV+UxzbbYq7ZPMvMeaVo6vdAZ+WSH8b\ntHDEBtzai5yEVntSXvrhDiimWnuCnVqmptlJG0BT+JMfRoKqtgjJu++DBARfm9hA\nvTtsYQKBgE1ttTzd3HJoIhBBSvSMbyDWTED6jecKvsVypb7QeDxZCbIwCkoK9zn1\ntwPDHLBcUNhHJx6JWTR6BxI5DZoIA1tcKHtdO5smjLWNSKhXTsKWee2aNkZJkNIW\nTDHSaTMOxVUEzpx84xClf561BTiTgzQy2MULpg3AK0Cv9l0+Yrvz\n-----END RSA PRIVATE KEY-----`\n\n\tcert, err := tls.X509KeyPair([]byte(certPEM), []byte(keyPEM))\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to configure TLS certificate: %v\", err)\n\t}\n\n\treturn cert\n}", "func (m *MockInternalServer) CryptoAsymKeyCreate(arg0 context.Context, arg1 *CryptoAsymKeyCreateRequestMsg) (*CryptoAsymKeyCreateResponseMsg, error) {\n\tret := m.ctrl.Call(m, \"CryptoAsymKeyCreate\", arg0, arg1)\n\tret0, _ := ret[0].(*CryptoAsymKeyCreateResponseMsg)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockTrustDB) InsertIssCert(arg0 context.Context, arg1 *cert.Certificate) (int64, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"InsertIssCert\", arg0, arg1)\n\tret0, _ := ret[0].(int64)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockProvider) KMSDecryptEnv(arg0, arg1 string) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"KMSDecryptEnv\", arg0, arg1)\n}", "func (m *MockClient) OIDCEndpoints(arg0 gin.IRouter) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"OIDCEndpoints\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockDynamicCertPrivate) CurrentCertKeyContent() ([]byte, []byte) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"CurrentCertKeyContent\")\n\tret0, _ := ret[0].([]byte)\n\tret1, _ := ret[1].([]byte)\n\treturn ret0, ret1\n}", "func (c *CA) Issue(ctx context.Context, crt *v1alpha1.Certificate) (*issuer.IssueResponse, error) {\n\t// get a copy of the existing/currently issued Certificate's private key\n\tsigneeKey, err := kube.SecretTLSKey(c.secretsLister, crt.Namespace, crt.Spec.SecretName)\n\tif k8sErrors.IsNotFound(err) || errors.IsInvalidData(err) {\n\t\t// if one does not already exist, generate a new one\n\t\tsigneeKey, err = pki.GeneratePrivateKeyForCertificate(crt)\n\t\tif err != nil {\n\t\t\tc.Recorder.Eventf(crt, corev1.EventTypeWarning, \"PrivateKeyError\", \"Error generating certificate private key: %v\", err)\n\t\t\t// don't trigger a retry. An error from this function implies some\n\t\t\t// invalid input parameters, and retrying without updating the\n\t\t\t// resource will not help.\n\t\t\treturn nil, nil\n\t\t}\n\t}\n\tif err != nil {\n\t\tklog.Errorf(\"Error getting private key %q for certificate: %v\", crt.Spec.SecretName, err)\n\t\treturn nil, err\n\t}\n\n\t// extract the public component of the key\n\tsigneePublicKey, err := pki.PublicKeyForPrivateKey(signeeKey)\n\tif err != nil {\n\t\tklog.Errorf(\"Error getting public key from private key: %v\", err)\n\t\treturn nil, err\n\t}\n\n\t// get a copy of the CA certificate named on the Issuer\n\tcaCerts, caKey, err := kube.SecretTLSKeyPair(c.secretsLister, c.resourceNamespace, c.issuer.GetSpec().CA.SecretName)\n\tif err != nil {\n\t\tklog.Errorf(\"Error getting signing CA for Issuer: %v\", err)\n\t\treturn nil, err\n\t}\n\n\t// generate a x509 certificate template for this Certificate\n\ttemplate, err := pki.GenerateTemplate(crt)\n\tif err != nil {\n\t\tc.Recorder.Eventf(crt, corev1.EventTypeWarning, \"ErrorSigning\", \"Error signing certificate: %v\", err)\n\t\treturn nil, err\n\t}\n\n\tcaCert := caCerts[0]\n\n\t// sign and encode the certificate\n\tcertPem, _, err := pki.SignCertificate(template, caCert, signeePublicKey, caKey)\n\tif err != nil {\n\t\tc.Recorder.Eventf(crt, corev1.EventTypeWarning, \"ErrorSigning\", \"Error signing certificate: %v\", err)\n\t\treturn nil, err\n\t}\n\n\t// encode the chain\n\t// TODO: replace caCerts with caCerts[1:]?\n\tchainPem, err := pki.EncodeX509Chain(caCerts)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcertPem = append(certPem, chainPem...)\n\n\t// Encode output private key and CA cert ready for return\n\tkeyPem, err := pki.EncodePrivateKey(signeeKey)\n\tif err != nil {\n\t\tc.Recorder.Eventf(crt, corev1.EventTypeWarning, \"ErrorPrivateKey\", \"Error encoding private key: %v\", err)\n\t\treturn nil, err\n\t}\n\n\t// encode the CA certificate to be bundled in the output\n\tcaPem, err := pki.EncodeX509(caCerts[0])\n\tif err != nil {\n\t\tc.Recorder.Eventf(crt, corev1.EventTypeWarning, \"ErrorSigning\", \"Error encoding certificate: %v\", err)\n\t\treturn nil, err\n\t}\n\n\treturn &issuer.IssueResponse{\n\t\tPrivateKey: keyPem,\n\t\tCertificate: certPem,\n\t\tCA: caPem,\n\t}, nil\n}", "func TestServeContextCertificateHandling(t *testing.T) {\n\ttests := map[string]struct {\n\t\tserverCredentialsDir string\n\t\tclientCredentialsDir string\n\t\texpectedServerCert string\n\t\texpectError bool\n\t}{\n\t\t\"successful TLS connection established\": {\n\t\t\tserverCredentialsDir: \"testdata/1\",\n\t\t\tclientCredentialsDir: \"testdata/1\",\n\t\t\texpectedServerCert: \"testdata/1/contourcert.pem\",\n\t\t\texpectError: false,\n\t\t},\n\t\t\"rotating server credentials returns new server cert\": {\n\t\t\tserverCredentialsDir: \"testdata/2\",\n\t\t\tclientCredentialsDir: \"testdata/2\",\n\t\t\texpectedServerCert: \"testdata/2/contourcert.pem\",\n\t\t\texpectError: false,\n\t\t},\n\t\t\"rotating server credentials again to ensure rotation can be repeated\": {\n\t\t\tserverCredentialsDir: \"testdata/1\",\n\t\t\tclientCredentialsDir: \"testdata/1\",\n\t\t\texpectedServerCert: \"testdata/1/contourcert.pem\",\n\t\t\texpectError: false,\n\t\t},\n\t\t\"fail to connect with client certificate which is not signed by correct CA\": {\n\t\t\tserverCredentialsDir: \"testdata/2\",\n\t\t\tclientCredentialsDir: \"testdata/1\",\n\t\t\texpectedServerCert: \"testdata/2/contourcert.pem\",\n\t\t\texpectError: true,\n\t\t},\n\t}\n\n\t// Create temporary directory to store certificates and key for the server.\n\tconfigDir, err := ioutil.TempDir(\"\", \"contour-testdata-\")\n\tcheckFatalErr(t, err)\n\tdefer os.RemoveAll(configDir)\n\n\tcontourTLS := &contour_api_v1alpha1.TLS{\n\t\tCAFile: filepath.Join(configDir, \"CAcert.pem\"),\n\t\tCertFile: filepath.Join(configDir, \"contourcert.pem\"),\n\t\tKeyFile: filepath.Join(configDir, \"contourkey.pem\"),\n\t\tInsecure: false,\n\t}\n\n\t// Initial set of credentials must be linked into temp directory before\n\t// starting the tests to avoid error at server startup.\n\terr = linkFiles(\"testdata/1\", configDir)\n\tcheckFatalErr(t, err)\n\n\t// Start a dummy server.\n\tlog := fixture.NewTestLogger(t)\n\topts := grpcOptions(log, contourTLS)\n\tg := grpc.NewServer(opts...)\n\tif g == nil {\n\t\tt.Error(\"failed to create server\")\n\t}\n\n\taddress := \"localhost:8001\"\n\tl, err := net.Listen(\"tcp\", address)\n\tcheckFatalErr(t, err)\n\n\tgo func() {\n\t\terr := g.Serve(l)\n\t\tcheckFatalErr(t, err)\n\t}()\n\tdefer g.GracefulStop()\n\n\tfor name, tc := range tests {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\t// Link certificates and key to temp dir used by serveContext.\n\t\t\terr = linkFiles(tc.serverCredentialsDir, configDir)\n\t\t\tcheckFatalErr(t, err)\n\t\t\treceivedCert, err := tryConnect(address, tc.clientCredentialsDir)\n\t\t\tgotError := err != nil\n\t\t\tif gotError != tc.expectError {\n\t\t\t\tt.Errorf(\"Unexpected result when connecting to the server: %s\", err)\n\t\t\t}\n\t\t\tif err == nil {\n\t\t\t\texpectedCert, err := loadCertificate(tc.expectedServerCert)\n\t\t\t\tcheckFatalErr(t, err)\n\t\t\t\tassert.Equal(t, receivedCert, expectedCert)\n\t\t\t}\n\t\t})\n\t}\n}", "func (o *oidcServer) IssueCertificate(w http.ResponseWriter, r *http.Request) {\n\n\to.Lock()\n\tdefer o.Unlock()\n\n\tzap.L().Debug(\"Issuing Certificate\")\n\n\tvar verifyKey interface{}\n\tswitch o.serverFlow {\n\tcase ServerFlowTypeInvalidCert:\n\t\tverifyKey = []byte(\"invalidKey\")\n\tcase ServerFlowTypeMissingCert:\n\t\tverifyKey = []byte(\"\")\n\tdefault:\n\t\tverifyKey = o.rsa.verifyKey()\n\t}\n\n\tjwk := jose.JSONWebKey{\n\t\tKey: verifyKey,\n\t\tKeyID: o.keyID,\n\t\tUse: \"sig\",\n\t\tAlgorithm: \"RS256\",\n\t}\n\n\tjwks := jose.JSONWebKeySet{\n\t\tKeys: []jose.JSONWebKey{jwk},\n\t}\n\n\tw.Header().Add(\"Content-Type\", \"application/json\")\n\terr := json.NewEncoder(w).Encode(jwks)\n\tif err != nil {\n\t\tzap.L().Error(\"Unable to encode JSONWebKeySet to JSON\", zap.Error(err))\n\t\treturn\n\t}\n\n\tzap.L().Debug(\"Certificate issued\")\n}", "func (m *MockManager) AddCert(arg0 string, arg1 util.CertType) error {\n\tret := m.ctrl.Call(m, \"AddCert\", arg0, arg1)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockConfiguration) Issuer() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Issuer\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func (m *MockIDistributedEnforcer) LoadIncrementalFilteredPolicy(arg0 interface{}) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"LoadIncrementalFilteredPolicy\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func TestUserCert(t *testing.T) {\n\tcert := UserCertificate(\"User1\")\n\tlogger.Infof(\"user cert: %s\\n\", cert)\n\tassert.Contains(t, cert, \"CN=User1@org1.example.com\", \"cert info should contain User1 as cn\")\n}", "func TestInsecureWebsocketRequestCertificate(t *testing.T) {\n\tmain, node, cleanup := SetupWebsocketTest(t)\n\tdefer cleanup()\n\n\tAcceptCertificateRequest(t, main)\n\n\terr := node.Connect()\n\tassert.NoError(t, err)\n\n\tWaitFor(t, 1*time.Second, \"nodes should be 1\", func() bool {\n\t\treturn len(main.Store.GetNodes()) == 1\n\t})\n\n\tassert.Contains(t, main.Store.GetNodes(), node.UUID)\n\tassert.Len(t, main.Store.GetConnections(), 1)\n\tassert.Equal(t, true, main.Store.GetNode(node.UUID).Connected())\n\n\tgo func() {\n\t\t<-time.After(50 * time.Millisecond)\n\t\tnode.Stop()\n\t}()\n\tnode.Wait()\n\n\tWaitFor(t, 1*time.Second, \"connections should be 0\", func() bool {\n\t\treturn len(main.Store.GetConnections()) == 0\n\t})\n\tassert.Len(t, main.Store.GetConnections(), 0)\n\tassert.Equal(t, false, main.Store.GetNode(node.UUID).Connected())\n}", "func (m *MockProduct) UpsertAcqRights(arg0 context.Context, arg1 db.UpsertAcqRightsParams) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"UpsertAcqRights\", arg0, arg1)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (client CertificateOrdersClient) CreateOrUpdateCertificateResponder(resp *http.Response) (result CertificateOrderCertificate, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tclient.ByInspecting(),\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(&result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (m *MockAuth) Authenticate(arg0 *common.Context) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Authenticate\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockIDistributedEnforcer) UpdatePolicy(arg0, arg1 []string) (bool, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"UpdatePolicy\", arg0, arg1)\n\tret0, _ := ret[0].(bool)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockIDistributedEnforcer) HasPolicy(arg0 ...interface{}) bool {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{}\n\tfor _, a := range arg0 {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"HasPolicy\", varargs...)\n\tret0, _ := ret[0].(bool)\n\treturn ret0\n}" ]
[ "0.65888923", "0.6234504", "0.6047892", "0.5979052", "0.59607357", "0.57190853", "0.5717269", "0.57069105", "0.570556", "0.5667811", "0.5661763", "0.56102765", "0.55863565", "0.55735624", "0.54910034", "0.543021", "0.5408378", "0.5405969", "0.53821886", "0.5354804", "0.53194904", "0.52992225", "0.5293989", "0.52881753", "0.5275595", "0.5270538", "0.52480733", "0.5244418", "0.5242154", "0.52358305", "0.52338195", "0.52319205", "0.522529", "0.5211825", "0.51915014", "0.51890594", "0.51705444", "0.516746", "0.5165354", "0.5164786", "0.51576483", "0.5156742", "0.515628", "0.515151", "0.5142539", "0.5142042", "0.5138613", "0.5113554", "0.5105256", "0.5099694", "0.50959665", "0.5071629", "0.5055174", "0.5045641", "0.50426596", "0.5042295", "0.5039306", "0.50321144", "0.50267917", "0.5022919", "0.5022481", "0.5019838", "0.501868", "0.5005441", "0.49992993", "0.49979004", "0.4988946", "0.4988286", "0.4968819", "0.49667987", "0.49646866", "0.49630687", "0.4961355", "0.49582136", "0.4952366", "0.4951375", "0.49499133", "0.4939483", "0.49357268", "0.49310437", "0.49272475", "0.49259013", "0.49216235", "0.4911223", "0.4903773", "0.48989767", "0.4890333", "0.4889183", "0.48845392", "0.48811543", "0.48796758", "0.48786175", "0.48770618", "0.4873455", "0.48726052", "0.48663172", "0.48565924", "0.48550403", "0.48504162", "0.48464805" ]
0.76188767
0
EnrollmentCertificate indicates an expected call of EnrollmentCertificate
func (mr *MockClientMockRecorder) EnrollmentCertificate() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "EnrollmentCertificate", reflect.TypeOf((*MockClient)(nil).EnrollmentCertificate)) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (p *MockPeer) EnrollmentCertificate() *pem.Block {\r\n\treturn p.MockCert\r\n}", "func (p *MockPeer) EnrollmentCertificate() *pem.Block {\n\treturn p.MockCert\n}", "func (m *MockClient) EnrollmentCertificate() []byte {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"EnrollmentCertificate\")\n\tret0, _ := ret[0].([]byte)\n\treturn ret0\n}", "func (p *Peer) EnrollmentCertificate() *pem.Block {\n\treturn p.enrollmentCertificate\n}", "func AssertCertificateHasClientAuthUsage(t *testing.T, cert *x509.Certificate) {\n\tfor i := range cert.ExtKeyUsage {\n\t\tif cert.ExtKeyUsage[i] == x509.ExtKeyUsageClientAuth {\n\t\t\treturn\n\t\t}\n\t}\n\tt.Error(\"cert has not ClientAuth usage as expected\")\n}", "func TestCertificate(t *testing.T) {\n\tvar result Certificate\n\n\tif err := json.NewDecoder(certificateBody).Decode(&result); err != nil {\n\t\tt.Errorf(\"Error decoding JSON: %s\", err)\n\t}\n\n\tassertEquals(t, \"1\", result.ID)\n\tassertEquals(t, \"HTTPS Certificate\", result.Name)\n\tassertEquals(t, \"PEM\", string(result.CertificateType))\n\tassertEquals(t, \"Contoso\", result.Issuer.Organization)\n\tassertEquals(t, \"2019-09-07T13:22:05Z\", result.ValidNotAfter)\n\tassertEquals(t, \"TPM_ALG_SHA1\", result.FingerprintHashAlgorithm)\n\tassertEquals(t, \"sha256WithRSAEncryption\", result.SignatureAlgorithm)\n}", "func (p *MockPeer) SetEnrollmentCertificate(pem *pem.Block) {\r\n\tp.MockCert = pem\r\n}", "func ExpectValidCertificate(expiresAfterDays int) HTTPCertificateExpectation {\n\treturn HTTPCertificateExpectation{\n\t\tExpiresAfterDays: expiresAfterDays,\n\t}\n}", "func ExpectValidCertificate(csr *certificatesv1.CertificateSigningRequest, _ crypto.Signer) error {\n\t_, err := pki.DecodeX509CertificateBytes(csr.Status.Certificate)\n\treturn err\n}", "func (d Driver) IssueCertificate(config CertRequest) ([]byte, error) {\n\tserial, err := rand.Int(rand.Reader, MaxSerialNumber)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"error generating certificate serial number\")\n\t}\n\n\tca, err := d.ca.Load(config.CAName)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"error loading CA bundle\")\n\t}\n\n\trootCert, err := x509.ParseCertificate(ca.Certificate[0])\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"error parsing CA certificate\")\n\t}\n\n\tnow := time.Now()\n\n\tcert := x509.Certificate{\n\t\tSerialNumber: serial,\n\t\tSubject: pkix.Name{\n\t\t\tCommonName: config.CommonName,\n\t\t\tOrganizationalUnit: rootCert.Subject.OrganizationalUnit,\n\t\t\tOrganization: rootCert.Subject.Organization,\n\t\t\tCountry: rootCert.Subject.Country,\n\t\t\tProvince: rootCert.Subject.Province,\n\t\t\tLocality: rootCert.Subject.Locality,\n\t\t\tStreetAddress: rootCert.Subject.StreetAddress,\n\t\t\tPostalCode: rootCert.Subject.PostalCode,\n\t\t},\n\t\tNotBefore: now,\n\t\tNotAfter: now.Add(config.Lifetime),\n\t\tKeyUsage: x509.KeyUsageDigitalSignature,\n\t\tExtKeyUsage: config.Usage,\n\t}\n\n\tfor _, name := range config.DNSNames {\n\t\tcert.DNSNames = append(cert.DNSNames, name)\n\t}\n\n\tfor _, addr := range config.IPAddrs {\n\t\tcert.IPAddresses = append(cert.IPAddresses, addr)\n\t}\n\n\tkey, err := rsa.GenerateKey(rand.Reader, PrivateKeyLength)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"error generating private key\")\n\t}\n\n\tsigned, err := x509.CreateCertificate(rand.Reader, &cert, rootCert, &key.PublicKey, ca.PrivateKey)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"error signing certificate\")\n\t}\n\n\tbundle := &bytes.Buffer{}\n\n\tif err := pem.Encode(bundle, &pem.Block{Type: \"RSA PRIVATE KEY\", Bytes: x509.MarshalPKCS1PrivateKey(key)}); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := pem.Encode(bundle, &pem.Block{Type: \"CERTIFICATE\", Bytes: signed}); err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, cert := range ca.Certificate {\n\t\tif err := pem.Encode(bundle, &pem.Block{Type: \"CERTIFICATE\", Bytes: cert}); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn bundle.Bytes(), nil\n}", "func TestCertificateNotExpired(t *testing.T) {\n\t// given\n\tvar expiredDate = time.Now().Add(time.Hour * 24 * (30 + 1)) // 31 days.\n\n\tvar fakeCerts = []*x509.Certificate{\n\t\t{\n\t\t\tNotAfter: expiredDate,\n\t\t\tSubject: pkix.Name{\n\t\t\t\tCommonName: \"Test cert\",\n\t\t\t},\n\t\t},\n\t}\n\n\t// when\n\tmsg := getCertificateChainMsg(fakeCerts)\n\n\t// then\n\tif msg != \"\" {\n\t\tt.Fatalf(\"Expected empty message was: %s\", msg)\n\t}\n}", "func printCertificate(cert *x509.Certificate) bool {\n\n\tfmt.Printf(\"Subject:%s\\t%s%s\\n\", Green, cert.Subject, Reset)\n\tfmt.Printf(\"Valid from:%s\\t%s%s\\n\", Yellow, cert.NotBefore, Reset)\n\tfmt.Printf(\"Valid until:%s\\t%s%s\\n\", Yellow, cert.NotAfter, Reset)\n\tfmt.Printf(\"Issuer:%s\\t\\t%s%s\\n\", Cyan, cert.Issuer.Organization[0], Reset)\n\tfmt.Printf(\"Is CA?:%s\\t\\t%t%s\\n\", Pink, cert.IsCA, Reset)\n\tfmt.Printf(\"Algorithm:%s\\t%s%s\\n\", Pink, cert.SignatureAlgorithm, Reset)\n\n\tif len(cert.DNSNames) > 0 {\n\t\tfmt.Printf(\"DNS Names:%s\\t%s%s\\n\", Purple, strings.Join(cert.DNSNames, \", \"), Reset)\n\t}\n\n\tif len(cert.OCSPServer) > 0 {\n\t\tfmt.Printf(\"OCSP Server:%s\\t%s%s\\n\", Comment, strings.Join(cert.OCSPServer, \", \"), Reset)\n\t}\n\n\treturn true\n}", "func (o *oidcServer) IssueCertificate(w http.ResponseWriter, r *http.Request) {\n\n\to.Lock()\n\tdefer o.Unlock()\n\n\tzap.L().Debug(\"Issuing Certificate\")\n\n\tvar verifyKey interface{}\n\tswitch o.serverFlow {\n\tcase ServerFlowTypeInvalidCert:\n\t\tverifyKey = []byte(\"invalidKey\")\n\tcase ServerFlowTypeMissingCert:\n\t\tverifyKey = []byte(\"\")\n\tdefault:\n\t\tverifyKey = o.rsa.verifyKey()\n\t}\n\n\tjwk := jose.JSONWebKey{\n\t\tKey: verifyKey,\n\t\tKeyID: o.keyID,\n\t\tUse: \"sig\",\n\t\tAlgorithm: \"RS256\",\n\t}\n\n\tjwks := jose.JSONWebKeySet{\n\t\tKeys: []jose.JSONWebKey{jwk},\n\t}\n\n\tw.Header().Add(\"Content-Type\", \"application/json\")\n\terr := json.NewEncoder(w).Encode(jwks)\n\tif err != nil {\n\t\tzap.L().Error(\"Unable to encode JSONWebKeySet to JSON\", zap.Error(err))\n\t\treturn\n\t}\n\n\tzap.L().Debug(\"Certificate issued\")\n}", "func TestGenerateCertificate(t *testing.T) {\n\tid, _ := GenerateIdentity()\n\tif !bytes.Equal(id.certificate().Certificate[0], id.certificate().Certificate[0]) {\n\t\tt.Fatalf(\"Secret certificate not deterministic\")\n\t}\n}", "func TestEnroll(t *testing.T) {\n\n\tfabricCAClient, err := NewFabricCAClient(org1, configImp, cryptoSuiteProvider)\n\tif err != nil {\n\t\tt.Fatalf(\"NewFabricCAClient return error: %v\", err)\n\t}\n\t_, _, err = fabricCAClient.Enroll(\"\", \"user1\")\n\tif err == nil {\n\t\tt.Fatalf(\"Enroll didn't return error\")\n\t}\n\tif err.Error() != \"enrollmentID required\" {\n\t\tt.Fatalf(\"Enroll didn't return right error\")\n\t}\n\t_, _, err = fabricCAClient.Enroll(\"test\", \"\")\n\tif err == nil {\n\t\tt.Fatalf(\"Enroll didn't return error\")\n\t}\n\tif err.Error() != \"enrollmentSecret required\" {\n\t\tt.Fatalf(\"Enroll didn't return right error\")\n\t}\n\t_, _, err = fabricCAClient.Enroll(\"enrollmentID\", \"enrollmentSecret\")\n\tif err != nil {\n\t\tt.Fatalf(\"fabricCAClient Enroll return error %v\", err)\n\t}\n\n\twrongConfigImp := mocks.NewMockConfig(wrongCAServerURL)\n\tfabricCAClient, err = NewFabricCAClient(org1, wrongConfigImp, cryptoSuiteProvider)\n\tif err != nil {\n\t\tt.Fatalf(\"NewFabricCAClient return error: %v\", err)\n\t}\n\t_, _, err = fabricCAClient.Enroll(\"enrollmentID\", \"enrollmentSecret\")\n\tif err == nil {\n\t\tt.Fatalf(\"Enroll didn't return error\")\n\t}\n\tif !strings.Contains(err.Error(), \"enroll failed\") {\n\t\tt.Fatalf(\"Expected error enroll failed. Got: %s\", err)\n\t}\n\n}", "func TestRequestAttestationReport(t *testing.T) {\n\n\tias := NewIAS()\n\tverifier := VerifierImpl{}\n\n\tquoteAsBytes, err := base64.StdEncoding.DecodeString(quote)\n\tif err != nil {\n\t\tjsonResp := \"{\\\"Error\\\":\\\" Can not parse quoteBase64 string: \" + err.Error() + \" \\\"}\"\n\t\tt.Errorf(jsonResp)\n\t}\n\n\t// send quote to intel for verification\n\tattestationReport, err := ias.RequestAttestationReport(apiKey, quoteAsBytes)\n\tif err != nil {\n\t\tjsonResp := \"{\\\"Error\\\":\\\" Error while retrieving attestation report: \" + err.Error() + \"\\\"}\"\n\t\tt.Errorf(jsonResp)\n\t}\n\n\tverificationPK, err := ias.GetIntelVerificationKey()\n\tif err != nil {\n\t\tt.Errorf(\"Can not parse verifiaction key: %s\", err)\n\t}\n\n\t// verify attestation report\n\tisValid, err := verifier.VerifyAttestionReport(verificationPK, attestationReport)\n\tif err != nil {\n\t\tjsonResp := \"{\\\"Error\\\":\\\" Error while attestation report verification: \" + err.Error() + \"\\\"}\"\n\t\tt.Errorf(jsonResp)\n\t}\n\tif !isValid {\n\t\tjsonResp := \"{\\\"Error\\\":\\\" Attestation report is not valid \\\"}\"\n\t\tt.Errorf(jsonResp)\n\t}\n\n}", "func ExpectCertificateOrganizationToMatch(csr *certificatesv1.CertificateSigningRequest, _ crypto.Signer) error {\n\tcert, err := pki.DecodeX509CertificateBytes(csr.Status.Certificate)\n\tif err != nil {\n\t\treturn err\n\t}\n\treq, err := pki.DecodeX509CertificateRequestBytes(csr.Spec.Request)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\texpectedOrganization := req.Subject.Organization\n\tif !util.EqualUnsorted(cert.Subject.Organization, expectedOrganization) {\n\t\treturn fmt.Errorf(\"Expected certificate valid for O %v, but got a certificate valid for O %v\", expectedOrganization, cert.Subject.Organization)\n\t}\n\n\treturn nil\n}", "func (f *FabricCAClientImpl) Enroll(enrollmentId, password string) (*Identity, []byte, error) {\n\tif len(enrollmentId) < 1 {\n\t\treturn nil, nil, ErrEnrollmentIdMissing\n\t}\n\t// create new cert and send it to CA for signing\n\tkey, err := f.Crypto.GenerateKey()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tcsr, err := f.Crypto.CreateCertificateRequest(enrollmentId, key)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\turl := fmt.Sprintf(\"%s/api/v1/enroll\", f.Url)\n\n\tcrm, err := json.Marshal(CertificateRequest{CR: string(csr)})\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\treq, err := http.NewRequest(\"POST\", url, bytes.NewBuffer(crm))\n\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\treq.SetBasicAuth(enrollmentId, password)\n\tvar tr *http.Transport\n\tif f.Transport == nil {\n\t\ttr = &http.Transport{\n\t\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: f.SkipTLSVerification},\n\t\t}\n\t} else {\n\t\ttr = f.Transport\n\t}\n\n\thttpClient := &http.Client{Transport: tr}\n\tresp, err := httpClient.Do(req)\n\tif err != nil {\n\n\t\treturn nil, nil, err\n\t}\n\tdefer resp.Body.Close()\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\n\t\treturn nil, nil, err\n\t}\n\tenrResp := new(enrollmentResponse)\n\tif err := json.Unmarshal(body, enrResp); err != nil {\n\n\t\treturn nil, nil, err\n\t}\n\tif !enrResp.Success {\n\n\t\treturn nil, nil, ErrEnrollment\n\t}\n\trawCert, err := base64.StdEncoding.DecodeString(enrResp.Result.Cert)\n\tif err != nil {\n\n\t\treturn nil, nil, err\n\t}\n\ta, _ := pem.Decode(rawCert)\n\tcert, err := x509.ParseCertificate(a.Bytes)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treturn &Identity{Certificate: cert, PrivateKey: key}, csr, nil\n}", "func enroll(w http.ResponseWriter, r *http.Request) {\n\tctx := r.Context()\n\taps := chi.URLParam(r, apsParamName)\n\n\tcsr, err := readCSRRequest(r.Body, true)\n\tif writeOnError(ctx, w, logMsgReadBodyFailed, err) {\n\t\treturn\n\t}\n\n\trenew := isReenroll(ctx)\n\n\tif renew {\n\n\t\t// Per RFC7030 4.2.2, for /simplereenroll the Subject and\n\t\t// SubjectAltName fields in the CSR MUST be identical to the\n\t\t// corresponding fields in the certificate being renewed. The\n\t\t// ChangeSubjectName attribute MAY be included in the CSR to request\n\t\t// that these fields be changed in the new certificate, but the\n\t\t// fields in the CSR (rather than the fields in the ChangeSubjectName\n\t\t// attribute) still must be identical with the certificate being\n\t\t// renewed. If the ChangeSubjectName attribute is included, we defer\n\t\t// it to the backing CA for handling.\n\t\t//\n\t\t// Per RFC7030 3.3.2, if the certificate to be renewed or rekeyed is\n\t\t// appropriate for the negotiated cipher suite, then the client MUST\n\t\t// use it for the TLS handshake. Otherwise, the client SHOULD use an\n\t\t// alternate certificate that is suitable for the cipher suite and\n\t\t// which contains the same subject identity information. In this case,\n\t\t// the subject fields in the CSR must still be identical with those of\n\t\t// the certificate being used for the TLS handshake.\n\t\t//\n\t\t// RFC7030 3.3.2 also says the a client MAY use a client certificate\n\t\t// issued by a third part to authenticate itself for an \"enroll\n\t\t// operation\". It is not clear if this only applies to /simpleenroll,\n\t\t// but for simplicity we here choose to interpret this as meaning that\n\t\t// a client may not use a third part certificate to authenticate itself\n\t\t// for a /simplereenroll operation, and we therefore require a client\n\t\t// to use an existing certificate for renew operations.\n\t\t//\n\t\t// This server does not support clients which do not support TLS client\n\t\t// authentication for renew operations.\n\n\t\tif len(r.TLS.PeerCertificates) == 0 {\n\t\t\terrNoClientCertificate.Write(w)\n\t\t\treturn\n\t\t}\n\n\t\t// Use PeerCertificates rather than VerifiedChains in case the server\n\t\t// requests but does not verify.\n\t\tcert := r.TLS.PeerCertificates[0]\n\n\t\t// Compare Subject fields.\n\t\tif !bytes.Equal(csr.RawSubject, cert.RawSubject) {\n\t\t\terrSubjectChanged.Write(w)\n\t\t\treturn\n\t\t}\n\n\t\t// Compare SubjectAltName fields.\n\t\tvar csrSAN pkix.Extension\n\t\tvar certSAN pkix.Extension\n\n\t\tfor _, ext := range csr.Extensions {\n\t\t\tif ext.Id.Equal(oidSubjectAltName) {\n\t\t\t\tcsrSAN = ext\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tfor _, ext := range cert.Extensions {\n\t\t\tif ext.Id.Equal(oidSubjectAltName) {\n\t\t\t\tcertSAN = ext\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !bytes.Equal(csrSAN.Value, certSAN.Value) {\n\t\t\terrSubjectChanged.Write(w)\n\t\t\treturn\n\t\t}\n\n\t\t// Verify certificate against CA certificates.\n\t\terr := certCacheFromContext(ctx).Verify(ctx, aps, cert, r)\n\t\tif writeOnError(ctx, w, logMsgVerifyFailed, err) {\n\t\t\treturn\n\t\t}\n\t}\n\n\t// Request certificate from backing CA.\n\tvar cert *x509.Certificate\n\tif renew {\n\t\tcert, err = caFromContext(ctx).Reenroll(ctx, r.TLS.PeerCertificates[0], csr, aps, r)\n\t} else {\n\t\tcert, err = caFromContext(ctx).Enroll(ctx, csr, aps, r)\n\t}\n\tif writeOnError(r.Context(), w, logMsgEnrollFailed, err) {\n\t\treturn\n\t}\n\n\twriteResponse(w, mimeTypePKCS7CertsOnly, true, cert)\n}", "func (p *MockPeer) SetEnrollmentCertificate(pem *pem.Block) {\n\tp.MockCert = pem\n}", "func (mr *MockRemotePeerMockRecorder) AddCertificate(cert interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"AddCertificate\", reflect.TypeOf((*MockRemotePeer)(nil).AddCertificate), cert)\n}", "func (t *SimpleChaincode) CheckAffiliation(stub *shim.ChaincodeStub, cert string) (int, error) { \n \n decodedCert, err := url.QueryUnescape(cert); // make % etc normal //\n \n if err != nil { return -1, errors.New(\"Could not decode certificate\") }\n \n pem, _ := pem.Decode([]byte(decodedCert)) // Make Plain text //\n\n x509Cert, err := x509.ParseCertificate(pem.Bytes); // Extract Certificate from argument //\n \n if err != nil { return -1, errors.New(\"Couldn't parse certificate\") }\n\n cn := x509Cert.Subject.CommonName\n \n res := strings.Split(cn,\"\\\\\")\n \n affiliation, _ := strconv.Atoi(res[2])\n \n return affiliation, nil\n}", "func TestCMPreIssuedCert(t *testing.T) {\n\tvar b64Chain = []string{\n\t\t\"MIID+jCCAuKgAwIBAgIHBWW7shJizTANBgkqhkiG9w0BAQsFADB1MQswCQYDVQQGEwJHQjEPMA0GA1UEBwwGTG9uZG9uMTowOAYDVQQKDDFHb29nbGUgQ2VydGlmaWNhdGUgVHJhbnNwYXJlbmN5IChQcmVjZXJ0IFNpZ25pbmcpMRkwFwYDVQQFExAxNTE5MjMxNzA0MTczNDg3MB4XDTE4MDIyMTE2NDgyNFoXDTE4MTIwMTIwMzMyN1owYzELMAkGA1UEBhMCR0IxDzANBgNVBAcMBkxvbmRvbjEoMCYGA1UECgwfR29vZ2xlIENlcnRpZmljYXRlIFRyYW5zcGFyZW5jeTEZMBcGA1UEBRMQMTUxOTIzMTcwNDM5MjM5NzCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAKnKP9TP6hkEuD+d1rPeA8mxo5xFYffhCcEitP8PtTl7G2RqFrndPeAkzgvOxPB3Jrhx7LtMtg0IvS8y7Sy1qDqDou1/OrJgwCeWMc1/KSneuGP8GTX0Rqy4z8+LsiBN/tMDbt94RuiyCeltIAaHGmsNeYXV34ayD3vSIAQbtLUOD39KqrJWO0tQ//nshBuFlebiUrDP7rirPusYYW0stJKiCKeORhHvL3/I8mCYGNO0XIWMpASH2S9LGMwg+AQM13whC1KL65EGuVs4Ta0rO+Tl8Yi0is0RwdUmgdSGtl0evPTzyUXbA1n1BpkLcSQ5E3RxY3O6Ge9Whvtmg9vAJiMCAwEAAaOBoDCBnTATBgNVHSUEDDAKBggrBgEFBQcDATAjBgNVHREEHDAaghhmbG93ZXJzLXRvLXRoZS13b3JsZC5jb20wDAYDVR0TAQH/BAIwADAfBgNVHSMEGDAWgBRKCM/Ajh0Fu6FFjJ9F4gVWK2oj/jAdBgNVHQ4EFgQUVjYl6wDey3DxvmTG2HL4vdiUt+MwEwYKKwYBBAHWeQIEAwEB/wQCBQAwDQYJKoZIhvcNAQELBQADggEBAAvyEFDIAWr0URsZzrJLZEL8p6FMTzVxY/MOvGP8QMXA6xNVElxYnDPF32JERAl+poR7syByhVFcEjrw7f2FTlMc04+hT/hsYzi8cMAmfX9KA36xUBVjyqvqwofxTwoWYdf+eGZW0EG8Yp1pM7iUy9bdlh3sgdOpmT9Z5XGCRwvdW1+mctv0JMKDdWzxBqYyNMnNjvjHBmkiuHeDDGFsV2zq+wV64RwJa2eVrnkMDMV1mscL6KzNRLPP2ZpNz/8H7SPock+fk4cZrdqj+0IzFt+6ixSoKyltyD+nkbWjRGY4iyboo/nPgTQ1IQCS2OPVHWw3NijFD8hqgAnYvz0Dn+k=\",\n\t\t\"MIIE4jCCAsqgAwIBAgIHBWW7sg8LrzANBgkqhkiG9w0BAQUFADB/MQswCQYDVQQGEwJHQjEPMA0GA1UECAwGTG9uZG9uMRcwFQYDVQQKDA5Hb29nbGUgVUsgTHRkLjEhMB8GA1UECwwYQ2VydGlmaWNhdGUgVHJhbnNwYXJlbmN5MSMwIQYDVQQDDBpNZXJnZSBEZWxheSBJbnRlcm1lZGlhdGUgMTAeFw0xODAyMjExNjQ4MjRaFw0xODEyMDEyMDM0MjdaMHUxCzAJBgNVBAYTAkdCMQ8wDQYDVQQHDAZMb25kb24xOjA4BgNVBAoMMUdvb2dsZSBDZXJ0aWZpY2F0ZSBUcmFuc3BhcmVuY3kgKFByZWNlcnQgU2lnbmluZykxGTAXBgNVBAUTEDE1MTkyMzE3MDQxNzM0ODcwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCKWlc3A43kJ9IzmkCPXcsGwTxlIvtl9sNYBWlx9qqHa1i6tU6rZuH9uXAb3wsn39fqY22HzF/yrx9pd05doFfRq6dvvm4eHNFfFm4cJur1kmPe8vLKpSI/P2DPx4/mRzrHnPAI8Jo9QgKcj91AyYeB689ZFzH30ay32beo6PxQvtoJkzl+dzf9Hs1ezavS7nDCuqDnu1V1Og7J5xTHZeNyTKgD5Kx28ukmIp2wGOvg3omuInABg/ew0VxnG/txKV+69zfV9dhclU3m16L81e3RkJ8Kg4RLb0mh9X3EMn90SpJ9yw0j8FF0Esk6wxuYeUGLShUji8BPnnbactY9B6ORAgMBAAGjbTBrMBgGA1UdJQEB/wQOMAwGCisGAQQB1nkCBAQwDwYDVR0TAQH/BAUwAwEB/zAfBgNVHSMEGDAWgBTpPAThgC/ChBMtJnCe8v0az6r+xjAdBgNVHQ4EFgQUSgjPwI4dBbuhRYyfReIFVitqI/4wDQYJKoZIhvcNAQEFBQADggIBAEep2uWAFsdq1nLtLWLGh7DfVPc/K+1lcqNx64ucjpVZbDnMnYKFagf2Z9rHEWqR7kwuLac5xW8woSlLa/NHmJmdg18HGUhlS+x8iMPv7dK6hfNsRFdjLZkZOFneuf9j1b0dV+rXoRvyY+Oq+lomC98bEr+g9zq+M7wJ4wS/KeaNHpPw1pBeTtCdw+1c4ZgRTOEa2OUUpkpueJ+9psD/hbp6HLF+WYijWQ0/iYSxJ4TbjTC+omKRsGhvxSLbP8cSMt3X1pJgrFK1BvH4lqqEXGDNEiVNoPCHraEa8JtMZIo47/Af13lDfp6sBdZ0lvLAVDduWgg/2RkWCbHefAe81h+cYdDS775TF2TCMTwsR6GsM9sVCbfPvHXI/pUzamRn0i0CrhyccBBdPrUhj+cXuc9kqSkLegun9D8EBDMM9va5wb1HM0ruSno+YuLtfhCdBRHr/RG2BKJi7uUDjJ8goHov/EUJmHjAIARKz74IPWRkxMrnOvGhnNa2Hz+da3hpusz0Mj4rsqv1EKTC2wbCs6Rk2MRPSxdRbywdWLSmGn249SMfXK4An+dqoRk1fwKqdXc4swoUvxnGUi5ajBaRtc6631zBTmvmSFQnvGmS42aF7q2PjfvWPIuO+d//m8KgN6o2YyjrdPDDslI2RZUE5ngOR+JynvhjYrrB7Bat1EY7\",\n\t\t\"MIIFyDCCA7CgAwIBAgICEAEwDQYJKoZIhvcNAQEFBQAwfTELMAkGA1UEBhMCR0IxDzANBgNVBAgMBkxvbmRvbjEXMBUGA1UECgwOR29vZ2xlIFVLIEx0ZC4xITAfBgNVBAsMGENlcnRpZmljYXRlIFRyYW5zcGFyZW5jeTEhMB8GA1UEAwwYTWVyZ2UgRGVsYXkgTW9uaXRvciBSb290MB4XDTE0MDcxNzEyMjYzMFoXDTE5MDcxNjEyMjYzMFowfzELMAkGA1UEBhMCR0IxDzANBgNVBAgMBkxvbmRvbjEXMBUGA1UECgwOR29vZ2xlIFVLIEx0ZC4xITAfBgNVBAsMGENlcnRpZmljYXRlIFRyYW5zcGFyZW5jeTEjMCEGA1UEAwwaTWVyZ2UgRGVsYXkgSW50ZXJtZWRpYXRlIDEwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQDB6HT+/5ru8wO7+mNFOIH6r43BwiwJZB2vQwOB8zvBV79sTIqNV7Grx5KFnSDyGRUJxZfEN7FGc96lr0vqFDlt1DbcYgVV15U+Dt4B9/+0Tz/3zeZO0kVjTg3wqvzpw6xetj2N4dlpysiFQZVAOp+dHUw9zu3xNR7dlFdDvFSrdFsgT7Uln+Pt9pXCz5C4hsSP9oC3RP7CaRtDRSQrMcNvMRi3J8XeXCXsGqMKTCRhxRGe9ruQ2Bbm5ExbmVW/ou00Fr9uSlPJL6+sDR8Li/PTW+DU9hygXSj8Zi36WI+6PuA4BHDAEt7Z5Ru/Hnol76dFeExJ0F6vjc7gUnNh7JExJgBelyz0uGORT4NhWC7SRWP/ngPFLoqcoyZMVsGGtOxSt+aVzkKuF+x64CVxMeHb9I8t3iQubpHqMEmIE1oVSCsF/AkTVTKLOeWG6N06SjoUy5fu9o+faXKMKR8hldLM5z1K6QhFsb/F+uBAuU/DWaKVEZgbmWautW06fF5I+OyoFeW+hrPTbmon4OLE3ubjDxKnyTa4yYytWSisojjfw5z58sUkbLu7KAy2+Z60m/0deAiVOQcsFkxwgzcXRt7bxN7By5Q5Bzrz8uYPjFBfBnlhqMU5RU/FNBFY7Mx4Uy8+OcMYfJQ5/A/4julXEx1HjfBj3VCyrT/noHDpBeOGiwIDAQABo1AwTjAdBgNVHQ4EFgQU6TwE4YAvwoQTLSZwnvL9Gs+q/sYwHwYDVR0jBBgwFoAU8197dUnjeEE5aiC2fGtMXMk9WEEwDAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQUFAAOCAgEACFjL1UXy6S4JkGrDnz1VwTYHplFDY4bG6Q8Sh3Og6z9HJdivNft/iAQ2tIHyz0eAGCXeVPE/j1kgvz2RbnUxQd5eWdLeu/w/wiZyHxWhbTt6RhjqBVFjnx0st7n6rRt+Bw8jpugZfD11SbumVT/V20Gc45lHf2oEgbkPUcnTB9gssFz5Z4KKGs5lIHz4a20WeSJF3PJLTBefkRhHNufi/LhjpLXImwrC82g5ChBZS5XIVuJZx3VkMWiYz4emgX0YWF/JdtaB2dUQ7yrTforQ5J9b1JnJ7H/o9DsX3/ubfQ39gwDBxTicnqC+Q3Dcv3i9PvwjCNJQuGa7ygMcDEn/d6elQg2qHxtqRE02ZlOXTC0XnDAJhx7myJFA/Knv3yO9S4jG6665KG9Y88/CHkh08YLR7NYFiRmwOxjbe3lb6csl/FFmqUXvjhEzzWAxKjI09GSd9hZkB8u17Mg46eEYwF3ufIlqmYdlWufjSc2BZuaNNN6jtK6JKp8jhQUycehgtUK+NlBQOXTzu28miDdasoSH2mdR0PLDo1547+MLGdV4COvqLERTmQrYHrliicD5nFCA+CCSvGEjo0DGOmF/O8StwSmNiKJ4ppPvk2iGEdO07e0LbQI+2fbC6og2SDGXUlsbG85wqQw0A7CU1fQSqhFBuZZauDFMUvdy3v/BAIw=\",\n\t\t\"MIIFzTCCA7WgAwIBAgIJAJ7TzLHRLKJyMA0GCSqGSIb3DQEBBQUAMH0xCzAJBgNVBAYTAkdCMQ8wDQYDVQQIDAZMb25kb24xFzAVBgNVBAoMDkdvb2dsZSBVSyBMdGQuMSEwHwYDVQQLDBhDZXJ0aWZpY2F0ZSBUcmFuc3BhcmVuY3kxITAfBgNVBAMMGE1lcmdlIERlbGF5IE1vbml0b3IgUm9vdDAeFw0xNDA3MTcxMjA1NDNaFw00MTEyMDIxMjA1NDNaMH0xCzAJBgNVBAYTAkdCMQ8wDQYDVQQIDAZMb25kb24xFzAVBgNVBAoMDkdvb2dsZSBVSyBMdGQuMSEwHwYDVQQLDBhDZXJ0aWZpY2F0ZSBUcmFuc3BhcmVuY3kxITAfBgNVBAMMGE1lcmdlIERlbGF5IE1vbml0b3IgUm9vdDCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAKoWHPIgXtgaxWVIPNpCaj2y5Yj9t1ixe5PqjWhJXVNKAbpPbNHA/AoSivecBm3FTD9DfgW6J17mHb+cvbKSgYNzgTk5e2GJrnOP7yubYJpt2OCw0OILJD25NsApzcIiCvLA4aXkqkGgBq9FiVfisReNJxVu8MtxfhbVQCXZf0PpkW+yQPuF99V5Ri+grHbHYlaEN1C/HM3+t2yMR4hkd2RNXsMjViit9qCchIi/pQNt5xeQgVGmtYXyc92ftTMrmvduj7+pHq9DEYFt3ifFxE8v0GzCIE1xR/d7prFqKl/KRwAjYUcpU4vuazywcmRxODKuwWFVDrUBkGgCIVIjrMJWStH5i7WTSSTrVtOD/HWYvkXInZlSgcDvsNIG0pptJaEKSP4jUzI3nFymnoNZn6pnfdIII/XISpYSVeyl1IcdVMod8HdKoRew9CzW6f2n6KSKU5I8X5QEM1NUTmRLWmVi5c75/CvS/PzOMyMzXPf+fE2Dwbf4OcR5AZLTupqp8yCTqo7ny+cIBZ1TjcZjzKG4JTMaqDZ1Sg0T3mO/ZbbiBE3N8EHxoMWpw8OP50z1dtRRwj6qUZ2zLvngOb2EihlMO15BpVZC3Cg929c9Hdl65pUd4YrYnQBQB/rn6IvHo8zot8zElgOg22fHbViijUt3qnRggB40N30MXkYGwuJbAgMBAAGjUDBOMB0GA1UdDgQWBBTzX3t1SeN4QTlqILZ8a0xcyT1YQTAfBgNVHSMEGDAWgBTzX3t1SeN4QTlqILZ8a0xcyT1YQTAMBgNVHRMEBTADAQH/MA0GCSqGSIb3DQEBBQUAA4ICAQB3HP6jRXmpdSDYwkI9aOzQeJH4x/HDi/PNMOqdNje/xdNzUy7HZWVYvvSVBkZ1DG/ghcUtn/wJ5m6/orBn3ncnyzgdKyXbWLnCGX/V61PgIPQpuGo7HzegenYaZqWz7NeXxGaVo3/y1HxUEmvmvSiioQM1cifGtz9/aJsJtIkn5umlImenKKEV1Ly7R3Uz3Cjz/Ffac1o+xU+8NpkLF/67fkazJCCMH6dCWgy6SL3AOB6oKFIVJhw8SD8vptHaDbpJSRBxifMtcop/85XUNDCvO4zkvlB1vPZ9ZmYZQdyL43NA+PkoKy0qrdaQZZMq1Jdp+Lx/yeX255/zkkILp43jFyd44rZ+TfGEQN1WHlp4RMjvoGwOX1uGlfoGkRSgBRj7TBn514VYMbXu687RS4WY2v+kny3PUFv/ZBfYSyjoNZnU4Dce9kstgv+gaKMQRPcyL+4vZU7DV8nBIfNFilCXKMN/VnNBKtDV52qmtOsVghgai+QE09w15x7dg+44gIfWFHxNhvHKys+s4BBN8fSxAMLOsb5NGFHE8x58RAkmIYWHjyPM6zB5AUPw1b2A0sDtQmCqoxJZfZUKrzyLz8gS2aVujRYN13KklHQ3EKfkeKBG2KXVBe5rjMN/7Anf1MtXxsTY6O8qIuHZ5QlXhSYzE41yIlPlG6d7AGnTiBIgeg==\",\n\t}\n\trawChain := make([][]byte, len(b64Chain))\n\tfor i, b64Data := range b64Chain {\n\t\tvar err error\n\t\trawChain[i], err = base64.StdEncoding.DecodeString(b64Data)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"failed to base64.Decode(chain[%d]): %v\", i, err)\n\t\t}\n\t}\n\n\troot, err := x509.ParseCertificate(rawChain[len(rawChain)-1])\n\tif err != nil {\n\t\tt.Fatalf(\"failed to parse root cert: %v\", err)\n\t}\n\tcmRoot := x509util.NewPEMCertPool()\n\tcmRoot.AddCert(root)\n\n\tfor _, tc := range []struct {\n\t\tdesc string\n\t\teku []x509.ExtKeyUsage\n\t}{\n\t\t{\n\t\t\tdesc: \"no EKU specified\",\n\t\t}, {\n\t\t\tdesc: \"EKU ServerAuth\",\n\t\t\teku: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},\n\t\t},\n\t} {\n\t\tt.Run(tc.desc, func(t *testing.T) {\n\t\t\topts := CertValidationOpts{\n\t\t\t\ttrustedRoots: cmRoot,\n\t\t\t\textKeyUsages: tc.eku,\n\t\t\t}\n\t\t\tchain, err := ValidateChain(rawChain, opts)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatalf(\"failed to ValidateChain: %v\", err)\n\t\t\t}\n\t\t\tfor i, c := range chain {\n\t\t\t\tt.Logf(\"chain[%d] = \\n%s\", i, x509util.CertificateToString(c))\n\t\t\t}\n\t\t})\n\t}\n}", "func (o ServiceCertificateOutput) EncodedCertificate() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ServiceCertificate) string { return v.EncodedCertificate }).(pulumi.StringOutput)\n}", "func enrollHandler(ca *pki.CA) http.HandlerFunc {\n\treturn func(res http.ResponseWriter, req *http.Request) {\n\t\tres.Header().Set(\"Content-Type\", \"application/json\")\n\t\tr := &serviceResponse{\n\t\t\tOk: false,\n\t\t\tResponse: \"\",\n\t\t}\n\n\t\t// Read request body\n\t\tdefer req.Body.Close()\n\t\tbody, err := ioutil.ReadAll(req.Body)\n\t\tif err != nil || len(body) == 0 {\n\t\t\tres.WriteHeader(400)\n\t\t\tr.Response = \"empty request\"\n\t\t\tres.Write(r.encode())\n\t\t\treturn\n\t\t}\n\n\t\t// Decode enrollment request\n\t\ter := &enrollmentRequest{}\n\t\tif err = json.Unmarshal(body, er); err != nil {\n\t\t\tres.WriteHeader(400)\n\t\t\tr.Response = \"invalid request contents\"\n\t\t\tres.Write(r.encode())\n\t\t\treturn\n\t\t}\n\n\t\t// Resolve provided DID\n\t\tid, err := resolveDID(er.Did)\n\t\tif err != nil {\n\t\t\tres.WriteHeader(400)\n\t\t\tr.Response = \"failed to resolve DID\"\n\t\t\tres.Write(r.encode())\n\t\t\treturn\n\t\t}\n\n\t\t// Validate challenge/signature\n\t\tif err = verifySignature(id, er.Challenge, er.Signature); err != nil {\n\t\t\tres.WriteHeader(400)\n\t\t\tr.Response = err.Error()\n\t\t\tres.Write(r.encode())\n\t\t\treturn\n\t\t}\n\n\t\t// Generate CSR\n\t\tbuf := bytes.NewBuffer(nil)\n\t\tif err = tplUserCSR.Execute(buf, map[string]string{\"DID\":id.String()}); err != nil {\n\t\t\tres.WriteHeader(400)\n\t\t\tr.Response = \"failed to generate CSR\"\n\t\t\tres.Write(r.encode())\n\t\t\treturn\n\t\t}\n\n\t\t// Generate certificate\n\t\tcert, key, err := ca.SignRequestJSON(buf.Bytes(), \"user\")\n\t\tif err != nil {\n\t\t\tres.WriteHeader(400)\n\t\t\tr.Response = \"failed to generate certificate\"\n\t\t\tres.Write(r.encode())\n\t\t\treturn\n\t\t}\n\n\t\t// All good!\n\t\tr.Ok = true\n\t\tr.Response = &enrollmentResponse{\n\t\t\tCert: cert,\n\t\t\tKey: key,\n\t\t}\n\t\tres.Write(r.encode())\n\t\treturn\n\t}\n}", "func (v *Verifier) VerifyDiagnosisCertificate(ctx context.Context, authApp *aamodel.AuthorizedApp, publish *verifyapi.Publish) (*VerifiedClaims, error) {\n\t// These get assigned during the ParseWithClaims closure.\n\tvar healthAuthorityID int64\n\tvar claims *verifyapi.VerificationClaims\n\n\t// Unpack JWT so we can determine issuer and key version.\n\ttoken, err := jwt.ParseWithClaims(publish.VerificationPayload, &verifyapi.VerificationClaims{}, func(token *jwt.Token) (interface{}, error) {\n\t\tif method, ok := token.Method.(*jwt.SigningMethodECDSA); !ok || method.Name != jwt.SigningMethodES256.Name {\n\t\t\treturn nil, fmt.Errorf(\"unsupported signing method, must be %v\", jwt.SigningMethodES256.Name)\n\t\t}\n\n\t\tvar ok bool\n\t\tkid, ok := token.Header[verifyapi.KeyIDHeader]\n\t\tif !ok {\n\t\t\treturn nil, fmt.Errorf(\"missing required header field, 'kid' indicating key id\")\n\t\t}\n\n\t\tclaims, ok = token.Claims.(*verifyapi.VerificationClaims)\n\t\tif !ok {\n\t\t\treturn nil, fmt.Errorf(\"does not contain expected claim set\")\n\t\t}\n\n\t\tlookup := func() (interface{}, error) {\n\t\t\t// Based on issuer, load the key versions.\n\t\t\tha, err := v.db.GetHealthAuthority(ctx, claims.Issuer)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"error looking up issuer: %v : %w\", claims.Issuer, err)\n\t\t\t}\n\t\t\treturn ha, nil\n\t\t}\n\t\tcacheVal, err := v.haCache.WriteThruLookup(claims.Issuer, lookup)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tha := cacheVal.(*model.HealthAuthority)\n\n\t\t// Find a key version.\n\t\tfor _, hak := range ha.Keys {\n\t\t\t// Key version matches and the key is valid based on the current time.\n\t\t\tif hak.Version == kid && hak.IsValid() {\n\t\t\t\thealthAuthorityID = ha.ID\n\t\t\t\t// Extract the public key from the PEM block.\n\t\t\t\treturn hak.PublicKey()\n\t\t\t}\n\t\t}\n\t\treturn nil, fmt.Errorf(\"key not found: iss: %v kid: %v\", claims.Issuer, kid)\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif !token.Valid {\n\t\treturn nil, fmt.Errorf(\"invalid verificationPayload\")\n\t}\n\tif err := claims.Valid(); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// JWT is valid and signature is valid.\n\t// This is chacked after the signature verification to prevent timing attacks.\n\tif _, ok := authApp.AllowedHealthAuthorityIDs[healthAuthorityID]; !ok {\n\t\treturn nil, fmt.Errorf(\"app %v has not authorized health authority issuer: %v\", authApp.AppPackageName, claims.Issuer)\n\t}\n\n\t// Verify our cutom claim types\n\tif err := claims.CustomClaimsValid(); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Verify the HMAC.\n\tjwtHMAC, err := base64util.DecodeString(claims.SignedMAC)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error decoding HMAC from claims: %w\", err)\n\t}\n\tsecret, err := base64util.DecodeString(publish.HMACKey)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error decoding HMAC secret from publish request: %w\", err)\n\t}\n\t// Allow the HMAC to be calculated without transmission risk values IFF all transmission risks are zero.\n\tvalidHMACs, err := utils.CalculateAllAllowedExposureKeyHMAC(publish.Keys, secret)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"calculating expected HMAC: %w\", err)\n\t}\n\n\tvalid := false\n\tfor _, wantHMAC := range validHMACs {\n\t\tvalid = valid || hmac.Equal(wantHMAC, jwtHMAC)\n\t}\n\tif !valid {\n\t\treturn nil, fmt.Errorf(\"HMAC mismatch, publish request does not match disgnosis verification certificate\")\n\t}\n\n\t// Everything looks good. Return the relevant verified claims.\n\treturn &VerifiedClaims{\n\t\tHealthAuthorityID: healthAuthorityID,\n\t\tReportType: claims.ReportType,\n\t\tSymptomOnsetInterval: claims.SymptomOnsetInterval,\n\t}, nil\n}", "func (v *VerifierImpl) VerifyAttestationReport(verificationPubKey interface{}, report IASAttestationReport) (bool, error) {\n\n\t// decode certs\n\tcerts, _ := url.QueryUnescape(report.IASReportSigningCertificate)\n\n\t// read signing cert first\n\tblock, rest := pem.Decode([]byte(certs))\n\tif block == nil {\n\t\treturn false, errors.New(\"provided cert not PEM formatted\")\n\t}\n\n\tsignCert, err := x509.ParseCertificate(block.Bytes)\n\tif err != nil {\n\t\treturn false, errors.New(\"failed to parse signing certificate:\" + err.Error())\n\t}\n\n\t// read ca cert\n\troots := x509.NewCertPool()\n\tif ok := roots.AppendCertsFromPEM(rest); !ok {\n\t\treturn false, errors.New(\"Failed to parse root certificate\")\n\t}\n\n\topts := x509.VerifyOptions{\n\t\tRoots: roots,\n\t}\n\n\t// verify signing Cert\n\tif _, err := signCert.Verify(opts); err != nil {\n\t\treturn false, errors.New(\"Failed to verify signing certificate\")\n\t}\n\n\t// verify response signature\n\tsignature, _ := base64.StdEncoding.DecodeString(report.IASReportSignature)\n\thashedBody := sha256.Sum256(report.IASReportBody)\n\n\t// check verification if its rsa key\n\trsaPublickey, ok := verificationPubKey.(*rsa.PublicKey)\n\tif !ok {\n\t\treturn false, errors.New(\"Verification key is not of type RSA\")\n\t}\n\n\t// if err = rsa.VerifyPKCS1v15(signCertPK, crypto.SHA256, hashedBody[:], signature); err != nil {\n\tif err = rsa.VerifyPKCS1v15(rsaPublickey, crypto.SHA256, hashedBody[:], signature); err != nil {\n\t\treturn false, errors.New(\"Signature verification failed: \" + err.Error())\n\t}\n\n\treturn true, nil\n}", "func (rs *RouteStatus) MarkCertificateProvisionFailed(name string) {\n\trouteCondSet.Manage(rs).MarkFalse(RouteConditionCertificateProvisioned,\n\t\t\"CertificateProvisionFailed\",\n\t\t\"Certificate %s fails to be provisioned.\", name)\n}", "func (mr *MockCertificateManagerMockRecorder) AddCertificate(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"AddCertificate\", reflect.TypeOf((*MockCertificateManager)(nil).AddCertificate), arg0)\n}", "func (this *IdpAuthnRequest) MakeAssertionEl() error {\n\tkeyPair := tls.Certificate{\n\t\tCertificate: [][]byte{this.IDP.Certificate.Raw},\n\t\tPrivateKey: this.IDP.Key,\n\t\tLeaf: this.IDP.Certificate,\n\t}\n\tfor _, cert := range this.IDP.Intermediates {\n\t\tkeyPair.Certificate = append(keyPair.Certificate, cert.Raw)\n\t}\n\tkeyStore := dsig.TLSCertKeyStore(keyPair)\n\n\tsignatureMethod := this.IDP.SignatureMethod\n\tif signatureMethod == \"\" {\n\t\tsignatureMethod = dsig.RSASHA1SignatureMethod\n\t}\n\n\tsigningContext := dsig.NewDefaultSigningContext(keyStore)\n\tsigningContext.Canonicalizer = dsig.MakeC14N10ExclusiveCanonicalizerWithPrefixList(canonicalizerPrefixList)\n\tif err := signingContext.SetSignatureMethod(signatureMethod); err != nil {\n\t\treturn err\n\t}\n\n\tassertionEl := this.Assertion.Element()\n\n\tsignedAssertionEl, err := signingContext.SignEnveloped(assertionEl)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsigEl := signedAssertionEl.Child[len(signedAssertionEl.Child)-1]\n\tthis.Assertion.Signature = sigEl.(*etree.Element)\n\tsignedAssertionEl = this.Assertion.Element()\n\n\tcertBuf, err := this.getSPEncryptionCert()\n\tif err == os.ErrNotExist {\n\t\tthis.AssertionEl = signedAssertionEl\n\t\treturn nil\n\t} else if err != nil {\n\t\treturn err\n\t}\n\n\tvar signedAssertionBuf []byte\n\t{\n\t\tdoc := etree.NewDocument()\n\t\tdoc.SetRoot(signedAssertionEl)\n\t\tsignedAssertionBuf, err = doc.WriteToBytes()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tencryptor := xmlenc.OAEP()\n\tencryptor.BlockCipher = xmlenc.AES128CBC\n\tencryptor.DigestMethod = &xmlenc.SHA1\n\tencryptedDataEl, err := encryptor.Encrypt(certBuf, signedAssertionBuf)\n\tif err != nil {\n\t\treturn err\n\t}\n\tencryptedDataEl.CreateAttr(\"Type\", \"http://www.w3.org/2001/04/xmlenc#Element\")\n\n\tencryptedAssertionEl := etree.NewElement(\"saml:EncryptedAssertion\")\n\tencryptedAssertionEl.AddChild(encryptedDataEl)\n\tthis.AssertionEl = encryptedAssertionEl\n\n\treturn nil\n}", "func ExpectIsCA(csr *certificatesv1.CertificateSigningRequest, _ crypto.Signer) error {\n\tcert, err := pki.DecodeX509CertificateBytes(csr.Status.Certificate)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tmarkedIsCA := false\n\tif csr.Annotations[experimentalapi.CertificateSigningRequestIsCAAnnotationKey] == \"true\" {\n\t\tmarkedIsCA = true\n\t}\n\n\tif cert.IsCA != markedIsCA {\n\t\treturn fmt.Errorf(\"requested certificate does not match expected IsCA, exp=%t got=%t\",\n\t\t\tmarkedIsCA, cert.IsCA)\n\t}\n\n\thasCertSign := (cert.KeyUsage & x509.KeyUsageCertSign) == x509.KeyUsageCertSign\n\tif hasCertSign != markedIsCA {\n\t\treturn fmt.Errorf(\"Expected certificate to have KeyUsageCertSign=%t, but got=%t\", markedIsCA, hasCertSign)\n\t}\n\n\treturn nil\n}", "func (mr *MockCAClientMockRecorder) Enroll(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Enroll\", reflect.TypeOf((*MockCAClient)(nil).Enroll), arg0)\n}", "func AssertCertificateIsSignedByCa(t *testing.T, cert *x509.Certificate, signingCa *x509.Certificate) {\n\tif err := cert.CheckSignatureFrom(signingCa); err != nil {\n\t\tt.Error(\"cert is not signed by signing CA as expected\")\n\t}\n}", "func (c *Client) Enroll(req *api.EnrollmentRequest, saveOnDisk bool) (*api.EnrollmentResponse, error) {\n\tlog.Debugf(\"Enrolling %+v\", req)\n\n\terr := c.Init()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn c.handleX509Enroll(req, saveOnDisk)\n}", "func AssertCertificateHasOrganizations(t *testing.T, cert *x509.Certificate, organizations ...string) {\n\tfor _, organization := range organizations {\n\t\tfound := false\n\t\tfor i := range cert.Subject.Organization {\n\t\t\tif cert.Subject.Organization[i] == organization {\n\t\t\t\tfound = true\n\t\t\t}\n\t\t}\n\t\tif !found {\n\t\t\tt.Errorf(\"cert does not contain Subject.Organization %s as expected\", organization)\n\t\t}\n\t}\n}", "func (i *Issuer) Issue(ctx context.Context, ar *api.AdcsRequest) ([]byte, []byte, error) {\n\tvar adcsResponseStatus adcs.AdcsResponseStatus\n\tvar desc string\n\tvar id string\n\tvar err error\n\tif ar.Status.State != api.Unknown {\n\t\t// Of all the statuses only Pending requires processing.\n\t\t// All others are final\n\t\tif ar.Status.State == api.Pending {\n\t\t\t// Check the status of the request on the ADCS\n\t\t\tif ar.Status.Id == \"\" {\n\t\t\t\treturn nil, nil, fmt.Errorf(\"adcs id not set\")\n\t\t\t}\n\t\t\tadcsResponseStatus, desc, id, err = i.certServ.GetExistingCertificate(ar.Status.Id)\n\t\t} else {\n\t\t\t// Nothing to do\n\t\t\treturn nil, nil, nil\n\t\t}\n\t} else {\n\t\t// New request\n\t\tadcsResponseStatus, desc, id, err = i.certServ.RequestCertificate(string(ar.Spec.CSRPEM), i.AdcsTemplateName)\n\n\t\tif klog.V(5) {\n\t\t\tklog.Infof(\"new adcsRequest: adcsResponseStatus: %v, \\n desc: %v id: %v \\n\", adcsResponseStatus, desc, id)\n\t\t}\n\t}\n\tif err != nil {\n\t\t// This is a local error\n\t\treturn nil, nil, err\n\t}\n\n\tvar cert []byte\n\tswitch adcsResponseStatus {\n\tcase adcs.Pending:\n\t\t// It must be checked again later\n\t\tar.Status.State = api.Pending\n\t\tar.Status.Id = id\n\t\tar.Status.Reason = desc\n\tcase adcs.Ready:\n\t\t// Certificate obtained successfully\n\t\tar.Status.State = api.Ready\n\t\tar.Status.Id = id\n\t\tar.Status.Reason = \"certificate obtained successfully\"\n\t\tcert = []byte(desc)\n\tcase adcs.Rejected:\n\t\t// Certificate request rejected by ADCS\n\t\tar.Status.State = api.Rejected\n\t\tar.Status.Id = id\n\t\tar.Status.Reason = desc\n\tcase adcs.Errored:\n\t\t// Unknown problem occured on ADCS\n\t\tar.Status.State = api.Errored\n\t\tar.Status.Id = id\n\t\tar.Status.Reason = desc\n\t}\n\n\t// Get a certificateChain from the server.\n\tcertChain, err := i.certServ.GetCaCertificateChain()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\t// Parse and encode the certificateChain to a valid x509 certificate.\n\tca, err := parseCaCert([]byte(certChain))\n\tif err != nil {\n\t\tklog.Error(\"something went wrong parsing to x509\")\n\t\treturn nil, nil, err\n\t}\n\n\tif klog.V(4) {\n\t\ts := string(cert)\n\t\tklog.Infof(\"parsed CaCert: \\n %v\", s)\n\t}\n\n\t// klog.V(4).Infof(\"will return cert: %v\", cert)\n\n\treturn cert, ca, nil\n\n}", "func (c *CertAgent) RequestCertificate() error {\n\tcsr, err := GenerateCSRObject(c.config)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error generating CSR Object: %v\", err)\n\t}\n\n\tduration := 10 * time.Second\n\t// wait forever for success and retry every duration interval\n\twait.PollInfinite(duration, func() (bool, error) {\n\t\t_, err := c.client.Create(csr)\n\t\tif err != nil {\n\t\t\tglog.Errorf(\"error sending CSR to signer: %v\", err)\n\t\t\treturn false, nil\n\t\t}\n\t\treturn true, nil\n\t})\n\n\trcvdCSR, err := c.WaitForCertificate()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error obtaining signed certificate from signer: %v\", err)\n\t}\n\n\t// write out signed certificate to disk\n\tcertFile := path.Join(c.config.AssetsDir, c.config.CommonName+\".crt\")\n\tif err := ioutil.WriteFile(certFile, rcvdCSR.Status.Certificate, 0644); err != nil {\n\t\treturn fmt.Errorf(\"unable to write to %s: %v\", certFile, err)\n\t}\n\treturn nil\n}", "func tpmenroll(w http.ResponseWriter, r *http.Request) {\n\tctx := r.Context()\n\taps := chi.URLParam(r, apsParamName)\n\n\t// Read and decode request.\n\tvar csr *x509.CertificateRequest\n\tvar ekCerts []*x509.Certificate\n\tvar ekPub []byte\n\tvar akPub []byte\n\n\t_, err := decodeMultipartRequest(\n\t\tr,\n\t\t[]multipartPart{\n\t\t\t{contentType: mimeTypePKCS10, data: &csr},\n\t\t\t{contentType: mimeTypePKCS7, data: &ekCerts},\n\t\t\t{contentType: mimeTypeOctetStream, data: &ekPub},\n\t\t\t{contentType: mimeTypeOctetStream, data: &akPub},\n\t\t},\n\t)\n\tif writeOnError(ctx, w, logMsgMultipartDecodeFailed, err) {\n\t\treturn\n\t}\n\n\t// Validate EK public key matches that in the EK certificate. Note that\n\t// while the name of the AK (i.e. the hash of the entire AK public area)\n\t// will be used to protect the credential, only the name algorithm and\n\t// the symmetric encryption algorithm from the EK public area will be used,\n\t// so none of the protection depends on the EK public area and in general\n\t// it can be manipulated and is unreliable.\n\tif err := validatePublicAreaPublicKey(ekPub, ekCerts[0].PublicKey); err != nil {\n\t\twriteOnError(ctx, w, logMsgPublicKeyInvalid, err)\n\t\treturn\n\t}\n\n\t// Note that we could verify if the AK public key matches that in the CSR,\n\t// but the TPM device will fail to activate the credential if a matching\n\t// key is not on the TPM, so even if we don't verify proof-of-possession,\n\t// the TPM privacy-preserving protocol will ensure that certificate can\n\t// only be decrypted by a TPM possessing that private key, so we achieve\n\t// the same end. Since it's possible a client may request a certificate for\n\t// a key which cannot be used for signing CSRs, and since the TPM privacy-\n\t// preserving protocol gives us a means to do that securely, we here choose\n\t// to allow it, and effectively ignore the public key in the CSR in a\n\t// manner similar to /serverkeygen.\n\n\t// Request credential blob and encrypted seed from backing CA.\n\tcredBlob, encSeed, cred, err := caFromContext(ctx).TPMEnroll(ctx, csr, ekCerts, ekPub, akPub, aps, r)\n\tif writeOnError(ctx, w, logMsgEnrollFailed, err) {\n\t\treturn\n\t}\n\n\t// Encode and write response.\n\tbuf, contentType, err := encodeMultiPart(\n\t\ttpmEnrollBoundary,\n\t\t[]multipartPart{\n\t\t\t{contentType: mimeTypeOctetStream, data: credBlob},\n\t\t\t{contentType: mimeTypeOctetStream, data: encSeed},\n\t\t\t{contentType: mimeTypePKCS7Enveloped, data: cred},\n\t\t},\n\t)\n\tif writeOnError(ctx, w, logMsgMultipartEncodeFailed, err) {\n\t\treturn\n\t}\n\n\twriteResponse(w, contentType, false, buf.Bytes())\n}", "func handleIdemixEnrollReq(ctx *serverRequestContextImpl) (interface{}, error) {\n\tca, err := ctx.GetCA()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tidemixEnrollResp, err := ca.issuer.IssueCredential(&idemixServerCtx{ctx})\n\tif err != nil {\n\t\tlog.Errorf(\"Error processing the /idemix/credential request: %s\", err.Error())\n\t\treturn nil, err\n\t}\n\tresp := newIdemixEnrollmentResponseNet(idemixEnrollResp)\n\terr = ctx.ca.fillCAInfo(&resp.CAInfo)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn resp, nil\n}", "func (o SslCertificateSelfManagedSslCertificateResponseOutput) Certificate() pulumi.StringOutput {\n\treturn o.ApplyT(func(v SslCertificateSelfManagedSslCertificateResponse) string { return v.Certificate }).(pulumi.StringOutput)\n}", "func GetEnrollmentIDFromX509Certificate(cert *x509.Certificate) string {\n\treturn cert.Subject.CommonName\n}", "func (f *FabricCAClientImpl) ReEnroll(identity *Identity) (*Identity, error) {\n\n\tif identity == nil || identity.EnrollmentId() == \"\" {\n\t\treturn nil, ErrCertificateEmpty\n\t}\n\n\t// create new cert and send it to CA for signing\n\tkey, err := f.Crypto.GenerateKey()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcsr, err := f.Crypto.CreateCertificateRequest(identity.EnrollmentId(), key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\turl := fmt.Sprintf(\"%s/api/v1/reenroll\", f.Url)\n\n\tcrm, err := json.Marshal(CertificateRequest{CR: string(csr)})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq, err := http.NewRequest(\"POST\", url, bytes.NewBuffer(crm))\n\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\ttoken, err := f.createAuthToken(identity, crm)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq.Header.Set(\"authorization\", token)\n\tvar tr *http.Transport\n\tif f.Transport == nil {\n\t\ttr = &http.Transport{\n\t\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: f.SkipTLSVerification},\n\t\t}\n\t} else {\n\t\ttr = f.Transport\n\t}\n\n\thttpClient := &http.Client{Transport: tr}\n\n\tresp, err := httpClient.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tenrResp := new(enrollmentResponse)\n\tif err := json.Unmarshal(body, enrResp); err != nil {\n\t\treturn nil, err\n\t}\n\tif !enrResp.Success {\n\t\treturn nil, ErrEnrollment\n\t}\n\trawCert, err := base64.StdEncoding.DecodeString(enrResp.Result.Cert)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ta, _ := pem.Decode(rawCert)\n\tcert, err := x509.ParseCertificate(a.Bytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Identity{Certificate: cert, PrivateKey: key}, nil\n}", "func TestInsecureWebsocketRequestCertificate(t *testing.T) {\n\tmain, node, cleanup := SetupWebsocketTest(t)\n\tdefer cleanup()\n\n\tAcceptCertificateRequest(t, main)\n\n\terr := node.Connect()\n\tassert.NoError(t, err)\n\n\tWaitFor(t, 1*time.Second, \"nodes should be 1\", func() bool {\n\t\treturn len(main.Store.GetNodes()) == 1\n\t})\n\n\tassert.Contains(t, main.Store.GetNodes(), node.UUID)\n\tassert.Len(t, main.Store.GetConnections(), 1)\n\tassert.Equal(t, true, main.Store.GetNode(node.UUID).Connected())\n\n\tgo func() {\n\t\t<-time.After(50 * time.Millisecond)\n\t\tnode.Stop()\n\t}()\n\tnode.Wait()\n\n\tWaitFor(t, 1*time.Second, \"connections should be 0\", func() bool {\n\t\treturn len(main.Store.GetConnections()) == 0\n\t})\n\tassert.Len(t, main.Store.GetConnections(), 0)\n\tassert.Equal(t, false, main.Store.GetNode(node.UUID).Connected())\n}", "func TestSetPolicyDigicert(t *testing.T) {\n\n\tpolicyName := test.RandAppName() + \"\\\\\" + test.RandCitName()\n\tconn := getTestConnector(ctx.CloudZone)\n\tconn.verbose = true\n\n\terr := conn.Authenticate(&endpoint.Authentication{APIKey: ctx.CloudAPIkey})\n\n\tif err != nil {\n\t\tt.Fatalf(\"%s\", err)\n\t}\n\n\tspecification := test.GetCloudPolicySpecification()\n\n\t//change default CA to Digiert\n\tcaName := os.Getenv(\"CLOUD_DIGICERT_CA_NAME\")\n\tspecification.Policy.CertificateAuthority = &caName\n\t_, err = conn.SetPolicy(policyName, specification)\n\n\tif err != nil {\n\t\tt.Fatalf(\"%s\", err)\n\t}\n\n\tps, err := conn.GetPolicy(policyName)\n\n\tif ps.Policy.CertificateAuthority == nil || *(ps.Policy.CertificateAuthority) == \"\" {\n\t\tt.Fatalf(\"venafi policy doesn't have a certificate authority\")\n\t}\n\tif *(ps.Policy.CertificateAuthority) != *(specification.Policy.CertificateAuthority) {\n\t\tt.Fatalf(\"certificate authority value doesn't match, get: %s but expected: %s\", *(ps.Policy.CertificateAuthority), *(specification.Policy.CertificateAuthority))\n\t}\n}", "func (o SslCertificateOutput) Certificate() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *SslCertificate) pulumi.StringOutput { return v.Certificate }).(pulumi.StringOutput)\n}", "func (mr *MockTrustDBMockRecorder) InsertIssCert(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"InsertIssCert\", reflect.TypeOf((*MockTrustDB)(nil).InsertIssCert), arg0, arg1)\n}", "func SetupCertificate(mgr ctrl.Manager, l logging.Logger, rl workqueue.RateLimiter, poll time.Duration) error {\n\tname := managed.ControllerName(v1alpha1.CertificateGroupKind)\n\n\treturn ctrl.NewControllerManagedBy(mgr).\n\t\tNamed(name).\n\t\tWithOptions(controller.Options{\n\t\t\tRateLimiter: ratelimiter.NewController(rl),\n\t\t}).\n\t\tFor(&v1alpha1.Certificate{}).\n\t\tComplete(managed.NewReconciler(mgr,\n\t\t\tresource.ManagedKind(v1alpha1.CertificateGroupVersionKind),\n\t\t\tmanaged.WithExternalConnecter(&connector{client: mgr.GetClient(), newClientFn: acm.NewClient}),\n\t\t\tmanaged.WithConnectionPublishers(),\n\t\t\tmanaged.WithPollInterval(poll),\n\t\t\tmanaged.WithReferenceResolver(managed.NewAPISimpleReferenceResolver(mgr.GetClient())),\n\t\t\tmanaged.WithInitializers(),\n\t\t\tmanaged.WithLogger(l.WithValues(\"controller\", name)),\n\t\t\tmanaged.WithRecorder(event.NewAPIRecorder(mgr.GetEventRecorderFor(name)))))\n}", "func (t *SimpleChaincode) addCert(APIstub shim.ChaincodeStubInterface, args []string) pb.Response {\n\n\tif len(args) != 6 {\n\t\treturn shim.Error(\"Incorrect number of arguments. Expecting 5\")\n\t}\n\tif len(args[0]) <= 0 {\n\t\treturn shim.Error(\"1 argument must be a non-empty string\")\n\t}\n\tif len(args[1]) <= 0 {\n\t\treturn shim.Error(\"2 argument must be a non-empty string\")\n\t}\n\tif len(args[2]) <= 0 {\n\t\treturn shim.Error(\"3 argument must be a non-empty string\")\n\t}\n\tif len(args[3]) <= 0 {\n\t\treturn shim.Error(\"4 argument must be a non-empty string\")\n\t}\n\tif len(args[4]) <= 0 {\n\t\treturn shim.Error(\"5 argument must be a non-empty string\")\n\t}\n\tif len(args[5]) <= 0 {\n\t\treturn shim.Error(\"6 argument must be a non-empty string\")\n\t}\n\n\tPRno := args[0]\n\tCName := args[1]\n\tSeatno := args[2]\n\texamination := args[3]\n\tYOP := args[4]\n\tsub := args[5]\n\n\t// ==== Check if certificate already exists ====\n\tcertAsBytes, err := APIstub.GetState(Seatno)\n\tif err != nil {\n\t\treturn shim.Error(\"Failed to get certificate: \" + err.Error())\n\t} else if certAsBytes != nil {\n\t\treturn shim.Error(\"This certificate already exists: \" + PRno)\n\t}\n\n\t// ==== Create certificate object and marshal to JSON ====\n\tcert := &cert{PRno, BU, CName, Seatno, examination, YOP, sub}\n\n\tcertJSONasBytes, err := json.Marshal(cert)\n\terr = APIstub.PutState(Seatno, certJSONasBytes)\n\tif err != nil {\n\t\treturn shim.Error(fmt.Sprintf(\"Failed to record Cert: %s\", Seatno))\n\t}\n\n\treturn shim.Success(nil)\n}", "func ClientHelloInfoSupportsCertificate(chi *tls.ClientHelloInfo, c *tls.Certificate,) error", "func TestSetPolicyEntrust(t *testing.T) {\n\n\tpolicyName := test.RandAppName() + \"\\\\\" + test.RandCitName()\n\tconn := getTestConnector(ctx.CloudZone)\n\tconn.verbose = true\n\n\terr := conn.Authenticate(&endpoint.Authentication{APIKey: ctx.CloudAPIkey})\n\n\tif err != nil {\n\t\tt.Fatalf(\"%s\", err)\n\t}\n\n\tspecification := test.GetCloudPolicySpecification()\n\t//change default CA to Entrust\n\tcaName := os.Getenv(\"CLOUD_ENTRUST_CA_NAME\")\n\tspecification.Policy.CertificateAuthority = &caName\n\n\t_, err = conn.SetPolicy(policyName, specification)\n\n\tif err != nil {\n\t\tt.Fatalf(\"%s\", err)\n\t}\n\n\tps, err := conn.GetPolicy(policyName)\n\n\tif ps.Policy.CertificateAuthority == nil || *(ps.Policy.CertificateAuthority) == \"\" {\n\t\tt.Fatalf(\"venafi policy doesn't have a certificate authority\")\n\t}\n\tif *(ps.Policy.CertificateAuthority) != *(specification.Policy.CertificateAuthority) {\n\t\tt.Fatalf(\"certificate authority value doesn't match, get: %s but expected: %s\", *(ps.Policy.CertificateAuthority), *(specification.Policy.CertificateAuthority))\n\t}\n\n}", "func (e HttpConnectionManager_SetCurrentClientCertDetailsValidationError) Key() bool { return e.key }", "func (c *Client) newEnrollmentResponse(result *api.EnrollmentResponseNet, id string, key cccsp.Key) (*api.EnrollmentResponse, error) {\n\tlog.Debugf(\"newEnrollmentResponse %s\", id)\n\tcertBytes, err := base64.StdEncoding.DecodeString(result.Cert)\n\tif err != nil {\n\t\treturn nil, errors.WithMessage(err, \"Invalid response format from server\")\n\t}\n\tsigner, err := credential.NewSigner(key, certBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tx509Cred := credential.NewCredential(c.certFile, c.keyFile, c)\n\terr = x509Cred.SetVal(signer)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tidentity := NewIdentity(c, id, x509Cred)\n\n\tresp := &api.EnrollmentResponse{\n\t\tIdentity: NewIdentity(c, identity.GetName(), identity.GetX509Credential()),\n\t}\n\terr = c.net2LocalCAInfo(&result.ServerInfo, &resp.CAInfo)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn resp, nil\n}", "func TestSignContractFailure(t *testing.T) {\n\tsignatureHelper(t, true)\n}", "func (ca *CA) IssueCertificate() (*x509.Certificate, error) {\n\treturn ca.issueCertificate(false /* Not a precertificate */)\n}", "func assessment(scan hooks.InternalMessage, internalChannel chan hooks.InternalMessage) {\n\t// Changes if test is done via SSL\n\tif scan.Domain.TestWithSSL {\n\n\t} else {\n\n\t}\n\n\t// Add your assessment logic\n\t//\t\trow = yourAssessment(...)\n\n\t//Handle error\n\tif err != nil {\n\t\tmanager.Logger.Errorf(\"Assessment failed for %v: %v\", scan.Domain.DomainName, err)\n\t\tscan.Results = row\n\t\tscan.StatusCode = hooks.InternalError\n\t\tinternalChannel <- scan\n\t\treturn\n\t}\n\n\t//return results\n\tscan.Results = row\n\tscan.StatusCode = hooks.InternalSuccess\n\tinternalChannel <- scan\n}", "func (o LookupDomainNameResultOutput) CertificateArn() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupDomainNameResult) string { return v.CertificateArn }).(pulumi.StringOutput)\n}", "func (o ListenerCertificateOutput) CertificateArn() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *ListenerCertificate) pulumi.StringOutput { return v.CertificateArn }).(pulumi.StringOutput)\n}", "func (cm *CertManager) IssueCertificate(opts certificate.IssueOptions) (*certificate.Certificate, error) {\n\tif cm.ca == nil {\n\t\t// TODO(#3962): metric might not be scraped before process restart resulting from this error\n\t\tlog.Error().Str(errcode.Kind, errcode.GetErrCodeWithMetric(errcode.ErrInvalidCA)).\n\t\t\tMsgf(\"Invalid CA provided for issuance of certificate with CN=%s\", opts.CommonName())\n\t\treturn nil, errNoIssuingCA\n\t}\n\n\tcertPrivKey, err := rsa.GenerateKey(rand.Reader, cm.keySize)\n\tif err != nil {\n\t\t// TODO(#3962): metric might not be scraped before process restart resulting from this error\n\t\tlog.Error().Err(err).Str(errcode.Kind, errcode.GetErrCodeWithMetric(errcode.ErrGeneratingPrivateKey)).\n\t\t\tMsgf(\"Error generating private key for certificate with CN=%s\", opts.CommonName())\n\t\treturn nil, fmt.Errorf(\"%s: %w\", errGeneratingPrivateKey.Error(), err)\n\t}\n\n\tserialNumber, err := rand.Int(rand.Reader, serialNumberLimit)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"%s: %w\", errGeneratingSerialNumber.Error(), err)\n\t}\n\n\tnow := time.Now()\n\ttemplate := x509.Certificate{\n\t\tSerialNumber: serialNumber,\n\n\t\t// even with SPIFFE, need to keep dns name which is required since ingresses currently only support this form for validation\n\t\tDNSNames: []string{string(opts.CommonName())},\n\n\t\tSubject: pkix.Name{\n\t\t\tCommonName: string(opts.CommonName()),\n\t\t\tOrganization: []string{cm.certificatesOrganization},\n\t\t},\n\t\tNotBefore: now,\n\t\tNotAfter: now.Add(opts.ValidityDuration),\n\n\t\tKeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,\n\t\tExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth},\n\t\tBasicConstraintsValid: true,\n\t}\n\n\tif opts.URISAN().String() != \"\" {\n\t\tlog.Trace().Str(\"cn\", opts.CommonName().String()).Msg(\"Generating Certificate with Uri SAN\")\n\t\ttemplate.URIs = []*url.URL{opts.URISAN()}\n\t}\n\n\tx509Root, err := certificate.DecodePEMCertificate(cm.ca.GetCertificateChain())\n\tif err != nil {\n\t\t// TODO(#3962): metric might not be scraped before process restart resulting from this error\n\t\tlog.Error().Err(err).Str(errcode.Kind, errcode.GetErrCodeWithMetric(errcode.ErrDecodingPEMCert)).\n\t\t\tMsg(\"Error decoding Root Certificate's PEM\")\n\t\treturn nil, fmt.Errorf(\"%s: %w\", errCreateCert.Error(), err)\n\t}\n\n\trsaKeyRoot, err := certificate.DecodePEMPrivateKey(cm.ca.GetPrivateKey())\n\tif err != nil {\n\t\t// TODO(#3962): metric might not be scraped before process restart resulting from this error\n\t\tlog.Error().Err(err).Str(errcode.Kind, errcode.GetErrCodeWithMetric(errcode.ErrDecodingPEMPrivateKey)).\n\t\t\tMsg(\"Error decoding Root Certificate's Private Key PEM \")\n\t\treturn nil, fmt.Errorf(\"%s: %w\", errCreateCert.Error(), err)\n\t}\n\n\tderBytes, err := x509.CreateCertificate(rand.Reader, &template, x509Root, &certPrivKey.PublicKey, rsaKeyRoot)\n\tif err != nil {\n\t\t// TODO(#3962): metric might not be scraped before process restart resulting from this error\n\t\tlog.Error().Err(err).Str(errcode.Kind, errcode.GetErrCodeWithMetric(errcode.ErrCreatingCert)).\n\t\t\tMsgf(\"Error issuing x509.CreateCertificate command for SerialNumber=%s\", serialNumber)\n\t\treturn nil, fmt.Errorf(\"%s: %w\", errCreateCert.Error(), err)\n\t}\n\n\tcertPEM, err := certificate.EncodeCertDERtoPEM(derBytes)\n\tif err != nil {\n\t\t// TODO(#3962): metric might not be scraped before process restart resulting from this error\n\t\tlog.Error().Err(err).Str(errcode.Kind, errcode.GetErrCodeWithMetric(errcode.ErrEncodingCertDERtoPEM)).\n\t\t\tMsgf(\"Error encoding certificate with SerialNumber=%s\", serialNumber)\n\t\treturn nil, err\n\t}\n\n\tprivKeyPEM, err := certificate.EncodeKeyDERtoPEM(certPrivKey)\n\tif err != nil {\n\t\t// TODO(#3962): metric might not be scraped before process restart resulting from this error\n\t\tlog.Error().Err(err).Str(errcode.Kind, errcode.GetErrCodeWithMetric(errcode.ErrEncodingKeyDERtoPEM)).\n\t\t\tMsgf(\"Error encoding private key for certificate with SerialNumber=%s\", serialNumber)\n\t\treturn nil, err\n\t}\n\n\tcert := &certificate.Certificate{\n\t\tCommonName: opts.CommonName(),\n\t\tSerialNumber: certificate.SerialNumber(serialNumber.String()),\n\t\tCertChain: certPEM,\n\t\tPrivateKey: privKeyPEM,\n\t\tIssuingCA: pem.RootCertificate(cm.ca.GetCertificateChain()),\n\t\tTrustedCAs: pem.RootCertificate(cm.ca.GetCertificateChain()),\n\t\tExpiration: template.NotAfter,\n\t}\n\n\tlog.Trace().Msgf(\"Created new certificate for SerialNumber=%s; validity=%+v; expires on %+v; serial: %x\", serialNumber, opts.ValidityDuration, template.NotAfter, template.SerialNumber)\n\n\treturn cert, nil\n}", "func (o SslCertificateSelfManagedSslCertificateOutput) Certificate() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v SslCertificateSelfManagedSslCertificate) *string { return v.Certificate }).(pulumi.StringPtrOutput)\n}", "func (rs *RouteStatus) MarkCertificateNotReady(name string) {\n\trouteCondSet.Manage(rs).MarkUnknown(RouteConditionCertificateProvisioned,\n\t\t\"CertificateNotReady\",\n\t\t\"Certificate %s is not ready.\", name)\n}", "func TestCertificateExpiryInfo(t *testing.T) {\n\t// given\n\tvar expiredDate = time.Now().Add(time.Hour * 24 * (30 - 1)) // 29 days.\n\n\tvar fakeCerts = []*x509.Certificate{\n\t\t{\n\t\t\tNotAfter: expiredDate,\n\t\t\tSubject: pkix.Name{\n\t\t\t\tCommonName: \"Test cert\",\n\t\t\t},\n\t\t},\n\t}\n\n\texpectedMsg := colorBlue(\"\\nCertificate expiry info:\\n\") +\n\t\tcolorBold(fmt.Sprintf(\"#1 Test cert will expire on %s\\n\", expiredDate))\n\n\t// When\n\tmsg := getCertificateChainMsg(fakeCerts)\n\n\t// Then\n\tif msg != expectedMsg {\n\t\tt.Fatalf(\"Expected message was: %s, got: %s\", expectedMsg, msg)\n\t}\n}", "func (mr *MockManagerMockRecorder) AddCert(arg0, arg1 interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"AddCert\", reflect.TypeOf((*MockManager)(nil).AddCert), arg0, arg1)\n}", "func verifyAccountAddition(ctx context.Context, cr *chrome.Chrome, tconn *chrome.TestConn, eduEmail string) error {\n\tui := uiauto.New(tconn).WithTimeout(20 * time.Second)\n\n\ttesting.ContextLog(ctx, \"Clicking next on the final page to wrap up\")\n\tschoolAccountAddedHeader := nodewith.Name(\"School account added\").Role(role.Heading)\n\tif err := uiauto.Combine(\"Clicking next button and wrapping up\",\n\t\tui.WaitUntilExists(schoolAccountAddedHeader),\n\t\tui.LeftClickUntil(nodewith.Name(\"Next\").Role(role.Button), ui.Gone(schoolAccountAddedHeader)))(ctx); err != nil {\n\t\treturn errors.Wrap(err, \"failed to click next button\")\n\t}\n\n\ttesting.ContextLog(ctx, \"Verifying the EDU secondary account added successfully\")\n\t// There should be a \"more actions\" button to remove the EDU secondary account.\n\tmoreActionsButton := nodewith.Name(\"More actions, \" + eduEmail).Role(role.Button)\n\tif err := ui.WaitUntilExists(moreActionsButton)(ctx); err != nil {\n\t\treturn errors.Wrap(err, \"failed to detect EDU secondary account\")\n\t}\n\n\treturn nil\n}", "func TestEnroll(t *testing.T) {\n\tInitConfigForMsp()\n\tclient := fabric_sdk.NewClient()\n\tks := &sw.FileBasedKeyStore{}\n\tif err := ks.Init(nil, config.GetKeyStorePath(), false); err != nil {\n\t\tt.Fatalf(\"Failed initializing key store [%s]\", err)\n\t}\n\n\tcryptoSuite, err := bccspFactory.GetBCCSP(&bccspFactory.SwOpts{Ephemeral_: true, SecLevel: config.GetSecurityLevel(),\n\t\tHashFamily: config.GetSecurityAlgorithm(), KeyStore: ks})\n\tif err != nil {\n\t\tt.Fatalf(\"Failed getting ephemeral software-based BCCSP [%s]\", err)\n\t}\n\tclient.SetCryptoSuite(cryptoSuite)\n\tstateStore, err := kvs.CreateNewFileKeyValueStore(\"/tmp/enroll_user\")\n\tif err != nil {\n\t\tt.Fatalf(\"CreateNewFileKeyValueStore return error[%s]\", err)\n\t}\n\tclient.SetStateStore(stateStore)\n\n\tmsps, err := msp.NewMSPServices(config.GetMspURL(), config.GetMspClientPath())\n\tif err != nil {\n\t\tt.Fatalf(\"NewMSPServices return error: %v\", err)\n\t}\n\tkey, cert, err := msps.Enroll(\"testUser2\", \"user2\")\n\tif err != nil {\n\t\tt.Fatalf(\"Enroll return error: %v\", err)\n\t}\n\tif key == nil {\n\t\tt.Fatalf(\"private key return from Enroll is nil\")\n\t}\n\tif cert == nil {\n\t\tt.Fatalf(\"cert return from Enroll is nil\")\n\t}\n\n\tcertPem, _ := pem.Decode(cert)\n\tif err != nil {\n\t\tt.Fatalf(\"pem Decode return error: %v\", err)\n\t}\n\n\tcert509, err := x509.ParseCertificate(certPem.Bytes)\n\tif err != nil {\n\t\tt.Fatalf(\"x509 ParseCertificate return error: %v\", err)\n\t}\n\tif cert509.Subject.CommonName != \"testUser2\" {\n\t\tt.Fatalf(\"CommonName in x509 cert is not the enrollmentID\")\n\t}\n\n\tkeyPem, _ := pem.Decode(key)\n\tif err != nil {\n\t\tt.Fatalf(\"pem Decode return error: %v\", err)\n\t}\n\tuser := fabric_sdk.NewUser(\"testUser2\")\n\tk, err := client.GetCryptoSuite().KeyImport(keyPem.Bytes, &bccsp.ECDSAPrivateKeyImportOpts{Temporary: false})\n\tif err != nil {\n\t\tt.Fatalf(\"KeyImport return error: %v\", err)\n\t}\n\tuser.SetPrivateKey(k)\n\tuser.SetEnrollmentCertificate(cert)\n\terr = client.SetUserContext(user, false)\n\tif err != nil {\n\t\tt.Fatalf(\"client.SetUserContext return error: %v\", err)\n\t}\n\tuser, err = client.GetUserContext(\"testUser2\")\n\tif err != nil {\n\t\tt.Fatalf(\"client.GetUserContext return error: %v\", err)\n\t}\n\tif user == nil {\n\t\tt.Fatalf(\"client.GetUserContext return nil\")\n\t}\n\n}", "func (spec *Spec) EnforcePKI(enableActions bool) error {\n\n\tupdateReason := \"\"\n\tvar currentCA *x509.Certificate\n\tvar err error\n\n\tSpecCheckCount.WithLabelValues(spec.Path).Inc()\n\n\tcurrentCA, err = spec.CA.getRemoteCert()\n\tif err != nil {\n\t\tSpecRequestFailureCount.WithLabelValues(spec.Path).Inc()\n\t\treturn errors.WithMessage(err, \"failed getting remote\")\n\t}\n\n\tif spec.renewalForced {\n\t\tupdateReason = \"key\"\n\t\terr = errors.New(\"regeneration was forced\")\n\t} else {\n\n\t\tif spec.CA.File != nil {\n\t\t\tvar existingCA *x509.Certificate\n\t\t\texistingCA, err = spec.CA.File.ReadCertificate()\n\t\t\tif err != nil {\n\t\t\t\terr = errors.WithMessagef(err, \"CA on disk is unusable\")\n\t\t\t\tupdateReason = \"CA\"\n\t\t\t} else {\n\t\t\t\tspec.updateCAExpiry(existingCA.NotAfter)\n\n\t\t\t\terr = spec.CA.File.CheckPermissions()\n\t\t\t\tif err != nil {\n\t\t\t\t\terr = errors.WithMessage(err, \"CA permissions have changed\")\n\t\t\t\t\tupdateReason = \"CA\"\n\t\t\t\t} else if !existingCA.Equal(currentCA) {\n\t\t\t\t\terr = errors.New(\"on disk CA is no longer equal to new CA\")\n\t\t\t\t\tupdateReason = \"CA\"\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif updateReason == \"\" && spec.Cert != nil {\n\t\t\terr = spec.checkDiskCertKey(currentCA)\n\t\t\tif err != nil {\n\t\t\t\terr = errors.WithMessagef(err, \"on disk PKI failed validation\")\n\t\t\t\tupdateReason = \"key\"\n\t\t\t}\n\t\t}\n\t}\n\n\tif updateReason == \"\" {\n\t\tlog.Debugf(\"spec %s: still up to date\", spec)\n\t\treturn nil\n\t}\n\n\tlog.Infof(\"spec %s: renewal is needed due to: %s\", spec, err)\n\n\tvar pair *tls.Certificate\n\tif spec.Cert != nil {\n\t\tpair, err = spec.fetchNewKeyPair()\n\t\tif err != nil {\n\t\t\treturn errors.WithMessagef(err, \"failed to fetch new certificate pair\")\n\t\t}\n\t}\n\n\terr = spec.writePKIToDisk(currentCA, pair)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif enableActions {\n\t\terr = spec.takeAction(updateReason)\n\t\tif err != nil {\n\t\t\t// Even though there was an error managing the service\n\t\t\t// associated with the certificate, the certificate has been\n\t\t\t// renewed.\n\t\t\tlog.Errorf(\"spec %s: renewed on disk but failed taking action: %s\", spec, err)\n\t\t\treturn nil\n\t\t}\n\t\tlog.Infof(\"spec %s: action successfully executed\", spec)\n\t} else {\n\t\tlog.Infof(\"skipping actions for %s due to calling mode\", spec)\n\t}\n\n\tlog.Info(\"manager: certificate successfully processed\")\n\n\treturn nil\n}", "func (o ListenerOutput) CertificateArn() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v Listener) *string { return v.CertificateArn }).(pulumi.StringPtrOutput)\n}", "func (o CustomDomainDeveloperPortalOutput) Certificate() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v CustomDomainDeveloperPortal) *string { return v.Certificate }).(pulumi.StringPtrOutput)\n}", "func (p *PCAProvisioner) Sign(ctx context.Context, cr *cmapi.CertificateRequest) ([]byte, []byte, error) {\n\tsvc := acmpca.New(p.session, &aws.Config{})\n\n\tblock, _ := pem.Decode(cr.Spec.Request)\n\tif block == nil {\n\t\treturn nil, nil, fmt.Errorf(\"failed to decode CSR\")\n\t}\n\n\tcsr, err := x509.ParseCertificateRequest(block.Bytes)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tsigAlgorithm, err := signatureAlgorithm(csr)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvalidityDays := int64(30)\n\tif cr.Spec.Duration != nil {\n\t\tvalidityDays = int64(cr.Spec.Duration.Hours() / 24)\n\t}\n\n\tissueParams := acmpca.IssueCertificateInput{\n\t\tCertificateAuthorityArn: aws.String(p.arn),\n\t\tSigningAlgorithm: aws.String(sigAlgorithm),\n\t\tCsr: cr.Spec.Request,\n\t\tValidity: &acmpca.Validity{\n\t\t\tType: aws.String(acmpca.ValidityPeriodTypeDays),\n\t\t\tValue: aws.Int64(validityDays),\n\t\t},\n\t\tIdempotencyToken: aws.String(\"awspca\"),\n\t}\n\n\tissueOutput, err := svc.IssueCertificate(&issueParams)\n\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tgetParams := acmpca.GetCertificateInput{\n\t\tCertificateArn: aws.String(*issueOutput.CertificateArn),\n\t\tCertificateAuthorityArn: aws.String(p.arn),\n\t}\n\n\terr = svc.WaitUntilCertificateIssued(&getParams)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tgetOutput, err := svc.GetCertificate(&getParams)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tcertPem := []byte(*getOutput.Certificate + \"\\n\")\n\tcaCertChainPem := []byte(*getOutput.CertificateChain)\n\n\treturn certPem, caCertChainPem, nil\n}", "func (self *ecdsaCreator) GenerateCertificate(key interface{}) []byte {\n\tecdsaKey := self.getKey(key)\n\tpod := self.getDashboardPod()\n\n\tnotBefore := time.Now()\n\tvalidFor, _ := time.ParseDuration(\"8760h\")\n\tnotAfter := notBefore.Add(validFor)\n\n\ttemplate := x509.Certificate{\n\t\tSerialNumber: self.generateSerialNumber(),\n\t\tNotAfter: notAfter,\n\t\tNotBefore: notBefore,\n\t}\n\n\tif len(pod.Name) > 0 && len(pod.Namespace) > 0 {\n\t\tpodDomainName := pod.Name + \".\" + pod.Namespace\n\t\ttemplate.Subject = pkix.Name{CommonName: podDomainName}\n\t\ttemplate.Issuer = pkix.Name{CommonName: podDomainName}\n\t\ttemplate.DNSNames = []string{podDomainName}\n\t} else {\n\t\ttemplate.Subject = pkix.Name{CommonName: \"kubernetes-dashboard\", OrganizationalUnit: []string{\"kubernetes-dashboard\"}, Organization: []string{\"kubernetes-dashboard\"}}\n\t\ttemplate.Issuer = pkix.Name{CommonName: \"kubernetes-dashboard\", OrganizationalUnit: []string{\"kubernetes-dashboard\"}, Organization: []string{\"kubernetes-dashboard\"}}\n\t}\n\n\tif len(pod.Status.PodIP) > 0 {\n\t\ttemplate.IPAddresses = []net.IP{net.ParseIP(pod.Status.PodIP)}\n\t}\n\n\tcertBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &ecdsaKey.PublicKey, ecdsaKey)\n\tif err != nil {\n\t\tlog.Fatalf(\"[ECDSAManager] Failed to create certificate: %s\", err)\n\t}\n\n\treturn certBytes\n}", "func (c *CryptohomeBinary) TPMAttestationFinishEnroll(ctx context.Context, pcaType PCAType, resp string, async bool) (bool, error) {\n\tif pcaType == TestPCA {\n\t\treturn false, errors.New(\"test PCA doesn't support automated test\")\n\t}\n\ttmpFile, err := c.tempFile(ctx, \"enroll_response\")\n\tif err != nil {\n\t\treturn false, errors.Wrap(err, \"failed to create temp file\")\n\t}\n\tdefer c.removeFile(ctx, tmpFile)\n\n\tif err := c.writeFile(ctx, tmpFile, []byte(resp)); err != nil {\n\t\treturn false, errors.Wrap(err, \"failed to write response to temp file\")\n\t}\n\n\targs := []string{\n\t\t\"--action=tpm_attestation_finish_enroll\",\n\t\t\"--input=\" + tmpFile}\n\tif async {\n\t\targs = append(args, asyncAttestationFlag)\n\t}\n\tout, err := c.call(\n\t\tctx, args...)\n\tif len(out) > 0 {\n\t\treturn false, errors.New(string(out))\n\t}\n\treturn true, nil\n}", "func ExpectCertificateURIsToMatch(csr *certificatesv1.CertificateSigningRequest, _ crypto.Signer) error {\n\tcert, err := pki.DecodeX509CertificateBytes(csr.Status.Certificate)\n\tif err != nil {\n\t\treturn err\n\t}\n\treq, err := pki.DecodeX509CertificateRequestBytes(csr.Spec.Request)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tactualURIs := pki.URLsToString(cert.URIs)\n\texpectedURIs := pki.URLsToString(req.URIs)\n\tif !util.EqualUnsorted(actualURIs, expectedURIs) {\n\t\treturn fmt.Errorf(\"Expected certificate valid for URIs %v, but got a certificate valid for URIs %v\", expectedURIs, actualURIs)\n\t}\n\n\treturn nil\n}", "func lintCertificate(work workItem) certResult {\n\t// Lint the certificate to produce a full result set\n\tcr := certResult{\n\t\tFingerprint: work.Fingerprint,\n\t\tLintSummary: make(map[string]lint.LintStatus),\n\t}\n\tresultSet := zlint.LintCertificateEx(work.Certificate, registry)\n\tfor lintName, r := range resultSet.Results {\n\t\tcr.LintSummary[lintName] = r.Status\n\t\tcr.Result.Inc(r.Status)\n\t}\n\treturn cr\n}", "func (rs *RouteStatus) MarkCertificateNotOwned(name string) {\n\trouteCondSet.Manage(rs).MarkFalse(RouteConditionCertificateProvisioned,\n\t\t\"CertificateNotOwned\",\n\t\t\"There is an existing certificate %s that we don't own.\", name)\n}", "func TestSignWithTSUIncludeCertificateChain(t *testing.T) {\n\ttsuKey := getTSURSAKey()\n\ttsuCert := getTSUCert()\n\ttsaCert := getTSACert()\n\n\th := sha256.New()\n\t_, err := h.Write([]byte(\"Hello World\"))\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tgenTime := time.Now().UTC()\n\n\tnonce := big.NewInt(0)\n\tnonce = nonce.SetBytes([]byte{0x1, 0x2, 0x3})\n\n\tduration, _ := time.ParseDuration(\"1s\")\n\n\ttimestamp := Timestamp{\n\t\tHashAlgorithm: crypto.SHA256,\n\t\tHashedMessage: h.Sum(nil),\n\t\tTime: genTime,\n\t\tNonce: nonce,\n\t\tPolicy: asn1.ObjectIdentifier{2, 4, 5, 6},\n\t\tOrdering: true,\n\t\tAccuracy: duration,\n\t\tQualified: true,\n\t\tAddTSACertificate: true,\n\t\tCertificates: []*x509.Certificate{tsaCert}, // add parent certificate\n\t}\n\ttimestampBytes, err := timestamp.CreateResponse(tsuCert, tsuKey)\n\tif err != nil {\n\t\tt.Fatalf(\"unable to generate time stamp response: %s\", err.Error())\n\t}\n\n\ttimestampRes, err := ParseResponse(timestampBytes)\n\tif err != nil {\n\t\tt.Fatalf(\"unable to parse time stamp response: %s\", err.Error())\n\t}\n\n\tif timestampRes.HashAlgorithm.HashFunc() != crypto.SHA256 {\n\t\tt.Errorf(\"expected hash algorithm is SHA256\")\n\t}\n\tif len(timestampRes.HashedMessage) != 32 {\n\t\tt.Errorf(\"got %d: expected: %d\", len(timestampRes.HashedMessage), 32)\n\t}\n\n\tif timestampRes.Accuracy != duration {\n\t\tt.Errorf(\"got accuracy %s: expected: %s\", timestampRes.Accuracy, duration)\n\t}\n\n\tif !timestampRes.Qualified {\n\t\tt.Errorf(\"got %t: expected: %t\", timestampRes.Qualified, true)\n\t}\n\n\tif !timestampRes.AddTSACertificate {\n\t\tt.Error(\"TSA certificate must be included in timestamp response\")\n\t}\n\n\tif !timestamp.Certificates[0].Equal(tsaCert) {\n\t\tt.Errorf(\"got certificate %X: expected: %X\", timestamp.Certificates[0].SubjectKeyId, tsaCert.SubjectKeyId)\n\t}\n}", "func SetupCertificate(mgr ctrl.Manager, o controller.Options) error {\n\tname := managed.ControllerName(v1beta1.CertificateGroupKind)\n\n\tcps := []managed.ConnectionPublisher{managed.NewAPISecretPublisher(mgr.GetClient(), mgr.GetScheme())}\n\tif o.Features.Enabled(features.EnableAlphaExternalSecretStores) {\n\t\tcps = append(cps, connection.NewDetailsManager(mgr.GetClient(), v1alpha1.StoreConfigGroupVersionKind))\n\t}\n\n\treturn ctrl.NewControllerManagedBy(mgr).\n\t\tNamed(name).\n\t\tWithOptions(o.ForControllerRuntime()).\n\t\tFor(&v1beta1.Certificate{}).\n\t\tComplete(managed.NewReconciler(mgr,\n\t\t\tresource.ManagedKind(v1beta1.CertificateGroupVersionKind),\n\t\t\tmanaged.WithExternalConnecter(&connector{client: mgr.GetClient(), newClientFn: acm.NewClient}),\n\t\t\tmanaged.WithConnectionPublishers(),\n\t\t\tmanaged.WithPollInterval(o.PollInterval),\n\t\t\tmanaged.WithReferenceResolver(managed.NewAPISimpleReferenceResolver(mgr.GetClient())),\n\t\t\tmanaged.WithInitializers(&tagger{kube: mgr.GetClient()}),\n\t\t\tmanaged.WithLogger(o.Logger.WithValues(\"controller\", name)),\n\t\t\tmanaged.WithRecorder(event.NewAPIRecorder(mgr.GetEventRecorderFor(name))),\n\t\t\tmanaged.WithConnectionPublishers(cps...)))\n}", "func (c Certificate) IsSelfSigned() bool {\n\tif c.Subject.CommonName != c.Issuer.CommonName ||\n\t\tlen(c.Subject.Organisation) != len(c.Issuer.Organisation) ||\n\t\tlen(c.Subject.OrgUnit) != len(c.Issuer.OrgUnit) ||\n\t\tlen(c.Subject.Country) != len(c.Issuer.Country) {\n\t\treturn false\n\t}\n\tfor i, _ := range c.Subject.Organisation {\n\t\tif c.Subject.Organisation[i] != c.Issuer.Organisation[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\tfor i, _ := range c.Subject.OrgUnit {\n\t\tif c.Subject.OrgUnit[i] != c.Issuer.OrgUnit[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\tfor i, _ := range c.Subject.Country {\n\t\tif c.Subject.Country[i] != c.Issuer.Country[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func ExpectKeyUsageUsageDataEncipherment(csr *certificatesv1.CertificateSigningRequest, _ crypto.Signer) error {\n\tcert, err := pki.DecodeX509CertificateBytes(csr.Status.Certificate)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// taking the key usage here and use a binary OR to flip all non\n\t// KeyUsageDataEncipherment bits to 0 so if KeyUsageDataEncipherment the\n\t// value will be exactly x509.KeyUsageDataEncipherment\n\tusage := cert.KeyUsage\n\tusage &= x509.KeyUsageDataEncipherment\n\tif usage != x509.KeyUsageDataEncipherment {\n\t\treturn fmt.Errorf(\"Expected certificate to have KeyUsageDataEncipherment %#b, but got %v %#b\", x509.KeyUsageDataEncipherment, usage, usage)\n\t}\n\n\treturn nil\n}", "func HasCertificateWith(preds ...predicate.Certificate) predicate.CoveredPerson {\n\treturn predicate.CoveredPerson(func(s *sql.Selector) {\n\t\tstep := sqlgraph.NewStep(\n\t\t\tsqlgraph.From(Table, FieldID),\n\t\t\tsqlgraph.To(CertificateInverseTable, FieldID),\n\t\t\tsqlgraph.Edge(sqlgraph.M2O, true, CertificateTable, CertificateColumn),\n\t\t)\n\t\tsqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {\n\t\t\tfor _, p := range preds {\n\t\t\t\tp(s)\n\t\t\t}\n\t\t})\n\t})\n}", "func (mr *MockCAClientMockRecorder) Reenroll(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Reenroll\", reflect.TypeOf((*MockCAClient)(nil).Reenroll), arg0)\n}", "func certificateCheckCallback(cert *git.Certificate, valid bool, hostname string) git.ErrorCode {\n\treturn 0\n}", "func HasCertificate() predicate.CoveredPerson {\n\treturn predicate.CoveredPerson(func(s *sql.Selector) {\n\t\tstep := sqlgraph.NewStep(\n\t\t\tsqlgraph.From(Table, FieldID),\n\t\t\tsqlgraph.To(CertificateTable, FieldID),\n\t\t\tsqlgraph.Edge(sqlgraph.M2O, true, CertificateTable, CertificateColumn),\n\t\t)\n\t\tsqlgraph.HasNeighbors(s, step)\n\t})\n}", "func TestSignWithTSUEmbedTSUCertificate(t *testing.T) {\n\ttsukey := getTSURSAKey()\n\ttsuCert := getTSUCert()\n\n\th := sha256.New()\n\t_, err := h.Write([]byte(\"Hello World\"))\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tgenTime := time.Now().UTC()\n\n\tnonce := big.NewInt(0)\n\tnonce = nonce.SetBytes([]byte{0x1, 0x2, 0x3})\n\n\tduration, _ := time.ParseDuration(\"1s\")\n\n\ttimestamp := Timestamp{\n\t\tHashAlgorithm: crypto.SHA256,\n\t\tHashedMessage: h.Sum(nil),\n\t\tTime: genTime,\n\t\tNonce: nonce,\n\t\tPolicy: asn1.ObjectIdentifier{2, 4, 5, 6},\n\t\tOrdering: true,\n\t\tAccuracy: duration,\n\t\tQualified: true,\n\t\tAddTSACertificate: true,\n\t}\n\ttimestampBytes, err := timestamp.CreateResponse(tsuCert, tsukey)\n\tif err != nil {\n\t\tt.Errorf(\"unable to generate time stamp response: %s\", err.Error())\n\t}\n\n\ttimestampRes, err := ParseResponse(timestampBytes)\n\tif err != nil {\n\t\tt.Fatalf(\"unable to parse time stamp response: %s\", err.Error())\n\t}\n\n\tif timestampRes.HashAlgorithm.HashFunc() != crypto.SHA256 {\n\t\tt.Errorf(\"expected hash algorithm is SHA256\")\n\t}\n\tif len(timestampRes.HashedMessage) != 32 {\n\t\tt.Errorf(\"got %d: expected: %d\", len(timestampRes.HashedMessage), 32)\n\t}\n\n\tif timestampRes.Accuracy != duration {\n\t\tt.Errorf(\"got accuracy %s: expected: %s\", timestampRes.Accuracy, duration)\n\t}\n\n\tif !timestampRes.Qualified {\n\t\tt.Errorf(\"got %t: expected: %t\", timestampRes.Qualified, true)\n\t}\n\n\tif !timestampRes.AddTSACertificate {\n\t\tt.Error(\"TSU certificate must be included in timestamp response\")\n\t}\n}", "func AssertCertificateHasServerAuthUsage(t *testing.T, cert *x509.Certificate) {\n\tfor i := range cert.ExtKeyUsage {\n\t\tif cert.ExtKeyUsage[i] == x509.ExtKeyUsageServerAuth {\n\t\t\treturn\n\t\t}\n\t}\n\tt.Error(\"cert is not a ServerAuth\")\n}", "func (c *CA) Issue(ctx context.Context, crt *v1alpha1.Certificate) (*issuer.IssueResponse, error) {\n\t// get a copy of the existing/currently issued Certificate's private key\n\tsigneeKey, err := kube.SecretTLSKey(c.secretsLister, crt.Namespace, crt.Spec.SecretName)\n\tif k8sErrors.IsNotFound(err) || errors.IsInvalidData(err) {\n\t\t// if one does not already exist, generate a new one\n\t\tsigneeKey, err = pki.GeneratePrivateKeyForCertificate(crt)\n\t\tif err != nil {\n\t\t\tc.Recorder.Eventf(crt, corev1.EventTypeWarning, \"PrivateKeyError\", \"Error generating certificate private key: %v\", err)\n\t\t\t// don't trigger a retry. An error from this function implies some\n\t\t\t// invalid input parameters, and retrying without updating the\n\t\t\t// resource will not help.\n\t\t\treturn nil, nil\n\t\t}\n\t}\n\tif err != nil {\n\t\tklog.Errorf(\"Error getting private key %q for certificate: %v\", crt.Spec.SecretName, err)\n\t\treturn nil, err\n\t}\n\n\t// extract the public component of the key\n\tsigneePublicKey, err := pki.PublicKeyForPrivateKey(signeeKey)\n\tif err != nil {\n\t\tklog.Errorf(\"Error getting public key from private key: %v\", err)\n\t\treturn nil, err\n\t}\n\n\t// get a copy of the CA certificate named on the Issuer\n\tcaCerts, caKey, err := kube.SecretTLSKeyPair(c.secretsLister, c.resourceNamespace, c.issuer.GetSpec().CA.SecretName)\n\tif err != nil {\n\t\tklog.Errorf(\"Error getting signing CA for Issuer: %v\", err)\n\t\treturn nil, err\n\t}\n\n\t// generate a x509 certificate template for this Certificate\n\ttemplate, err := pki.GenerateTemplate(crt)\n\tif err != nil {\n\t\tc.Recorder.Eventf(crt, corev1.EventTypeWarning, \"ErrorSigning\", \"Error signing certificate: %v\", err)\n\t\treturn nil, err\n\t}\n\n\tcaCert := caCerts[0]\n\n\t// sign and encode the certificate\n\tcertPem, _, err := pki.SignCertificate(template, caCert, signeePublicKey, caKey)\n\tif err != nil {\n\t\tc.Recorder.Eventf(crt, corev1.EventTypeWarning, \"ErrorSigning\", \"Error signing certificate: %v\", err)\n\t\treturn nil, err\n\t}\n\n\t// encode the chain\n\t// TODO: replace caCerts with caCerts[1:]?\n\tchainPem, err := pki.EncodeX509Chain(caCerts)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcertPem = append(certPem, chainPem...)\n\n\t// Encode output private key and CA cert ready for return\n\tkeyPem, err := pki.EncodePrivateKey(signeeKey)\n\tif err != nil {\n\t\tc.Recorder.Eventf(crt, corev1.EventTypeWarning, \"ErrorPrivateKey\", \"Error encoding private key: %v\", err)\n\t\treturn nil, err\n\t}\n\n\t// encode the CA certificate to be bundled in the output\n\tcaPem, err := pki.EncodeX509(caCerts[0])\n\tif err != nil {\n\t\tc.Recorder.Eventf(crt, corev1.EventTypeWarning, \"ErrorSigning\", \"Error encoding certificate: %v\", err)\n\t\treturn nil, err\n\t}\n\n\treturn &issuer.IssueResponse{\n\t\tPrivateKey: keyPem,\n\t\tCertificate: certPem,\n\t\tCA: caPem,\n\t}, nil\n}", "func (o ArgoCDSpecPrometheusRouteTlsOutput) Certificate() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ArgoCDSpecPrometheusRouteTls) *string { return v.Certificate }).(pulumi.StringPtrOutput)\n}", "func (mr *MockGatewayMockRecorder) Cert() *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Cert\", reflect.TypeOf((*MockGateway)(nil).Cert))\n}", "func (o CustomDomainGatewayOutput) Certificate() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v CustomDomainGateway) *string { return v.Certificate }).(pulumi.StringPtrOutput)\n}", "func TestDummyCreateCACertAndKey(t *testing.T) {\n\tdefer leaktest.AfterTest(t)()\n\t_, _, err := security.CreateCACertAndKey(context.Background(), nil, /* loggerFn */\n\t\ttime.Hour, \"test CA cert generation\")\n\tif err != nil {\n\t\tt.Fatalf(\"expected err=nil, got: %s\", err)\n\t}\n}", "func (u *AttestationClient) FinishCertRequest(ctx context.Context, resp, username, label string) error {\n\treply, err := u.ac.FinishCertificateRequest(ctx, &apb.FinishCertificateRequestRequest{\n\t\tPcaResponse: []byte(resp),\n\t\tKeyLabel: &label,\n\t\tUsername: &username,\n\t})\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to call |FinishCertificateRequest|\")\n\t}\n\tif reply.GetStatus() != apb.AttestationStatus_STATUS_SUCCESS {\n\t\treturn &AttestationError{\n\t\t\terrors.Errorf(\"failed |FinishCertificateRequest|: %s\", reply.GetStatus().String()),\n\t\t\treply.GetStatus(),\n\t\t}\n\t}\n\treturn nil\n}", "func waitForCertificateReady(configMap *corev1.ConfigMap) bool {\n\tlog := util.Logger()\n\tklient := util.KubeClient()\n\n\tinterval := time.Duration(3)\n\ttimeout := time.Duration(15)\n\n\terr := wait.PollUntilContextTimeout(ctx, interval*time.Second, timeout*time.Second, true, func(ctx context.Context) (bool, error) {\n\t\tif err := klient.Get(util.Context(), util.ObjectKey(configMap), configMap); err != nil {\n\t\t\tlog.Printf(\"⏳ Failed to get service ca certificate: %s\", err)\n\t\t\treturn false, nil\n\t\t}\n\t\tif configMap.Data[\"service-ca.crt\"] == \"\" {\n\t\t\treturn false, fmt.Errorf(\"service ca certificate not created\")\n\t\t}\n\n\t\treturn true, nil\n\t})\n\treturn (err == nil)\n}", "func (self *OCSPResponder) verify(rawreq []byte) ([]byte, error) {\n\tvar status int\n\tvar revokedAt time.Time\n\n\t// parse the request\n\treq, exts, err := ocsp.ParseRequest(rawreq)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn nil, err\n\t}\n\n\t//make sure the request is valid\n\tif err := self.verifyIssuer(req); err != nil {\n\t\tlog.Println(err)\n\t\treturn nil, err\n\t}\n\n\t// get the index entry, if it exists\n\tent, err := self.getIndexEntry(req.SerialNumber)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\tstatus = ocsp.Unknown\n\t} else {\n\t\tlog.Print(fmt.Sprintf(\"Found entry %+v\", ent))\n\t\tif ent.Status == StatusRevoked {\n\t\t\tlog.Print(\"This certificate is revoked\")\n\t\t\tstatus = ocsp.Revoked\n\t\t\trevokedAt = ent.RevocationTime\n\t\t} else if ent.Status == StatusValid {\n\t\t\tlog.Print(\"This certificate is valid\")\n\t\t\tstatus = ocsp.Good\n\t\t}\n\t}\n\n\t// parse key file\n\t// perhaps I should zero this out after use\n\tkeyi, err := parseKeyFile(self.RespKeyFile)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tkey, ok := keyi.(crypto.Signer)\n\tif !ok {\n\t\treturn nil, errors.New(\"Could not make key a signer\")\n\t}\n\n\t// check for nonce extension\n\tvar responseExtensions []pkix.Extension\n\tnonce := checkForNonceExtension(exts)\n\n\t// check if the nonce has been used before\n\tif self.NonceList == nil {\n\t\tself.NonceList = make([][]byte, 10)\n\t}\n\n\tif nonce != nil {\n\t\tfor _, n := range self.NonceList {\n\t\t\tif bytes.Compare(n, nonce.Value) == 0 {\n\t\t\t\treturn nil, errors.New(\"This nonce has already been used\")\n\t\t\t}\n\t\t}\n\n\t\tself.NonceList = append(self.NonceList, nonce.Value)\n\t\tresponseExtensions = append(responseExtensions, *nonce)\n\t}\n\n\t// construct response template\n\trtemplate := ocsp.Response{\n\t\tStatus: status,\n\t\tSerialNumber: req.SerialNumber,\n\t\tCertificate: self.RespCert,\n\t\tRevocationReason: ocsp.Unspecified,\n\t\tIssuerHash: req.HashAlgorithm,\n\t\tRevokedAt: revokedAt,\n\t\tThisUpdate: time.Now().AddDate(0, 0, -1).UTC(),\n\t\t//adding 1 day after the current date. This ocsp library sets the default date to epoch which makes ocsp clients freak out.\n\t\tNextUpdate: time.Now().AddDate(0, 0, 1).UTC(),\n\t\tExtensions: exts,\n\t}\n\n\t// make a response to return\n\tresp, err := ocsp.CreateResponse(self.CaCert, self.RespCert, rtemplate, key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn resp, err\n}", "func (y Slot) Attest() (*x509.Certificate, error) {\n\treturn y.yubikey.Attest(y.Id)\n}", "func (e OAuthClientAuthorizationIdentifiersValidationError) Key() bool { return e.key }", "func (u *AttestationClient) IsPreparedForEnrollment(ctx context.Context) (bool, error) {\n\tstatus, err := u.ac.GetStatus(ctx, &apb.GetStatusRequest{})\n\tif err != nil {\n\t\treturn false, errors.Wrap(err, \"failed to call |GetStatus|\")\n\t}\n\treturn status.GetPreparedForEnrollment(), nil\n}", "func (ca *CA) IssuePrecertificate() (*x509.Certificate, error) {\n\treturn ca.issueCertificate(true /* precertificate */)\n}", "func (m *MockIDistributedEnforcer) EnforceEx(arg0 ...interface{}) (bool, []string, error) {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{}\n\tfor _, a := range arg0 {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"EnforceEx\", varargs...)\n\tret0, _ := ret[0].(bool)\n\tret1, _ := ret[1].([]string)\n\tret2, _ := ret[2].(error)\n\treturn ret0, ret1, ret2\n}", "func (u *AttestationClient) IsEnrolled(ctx context.Context) (bool, error) {\n\tstatus, err := u.ac.GetStatus(ctx, &apb.GetStatusRequest{})\n\tif err != nil {\n\t\treturn false, errors.Wrap(err, \"failed to call |GetStatus|\")\n\t}\n\treturn status.GetEnrolled(), nil\n}", "func (o CustomDomainManagementOutput) Certificate() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v CustomDomainManagement) *string { return v.Certificate }).(pulumi.StringPtrOutput)\n}", "func (r *DomainName) CertificateArn() pulumi.StringOutput {\n\treturn (pulumi.StringOutput)(r.s.State[\"certificateArn\"])\n}", "func (mr *MockIDistributedEnforcerMockRecorder) EnforceEx(arg0 ...interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"EnforceEx\", reflect.TypeOf((*MockIDistributedEnforcer)(nil).EnforceEx), arg0...)\n}" ]
[ "0.6630004", "0.6410596", "0.6361011", "0.57831097", "0.56046736", "0.54577327", "0.53977334", "0.5349532", "0.5320587", "0.53166556", "0.5311917", "0.53055733", "0.5296783", "0.5271991", "0.52477646", "0.5224344", "0.521586", "0.5215032", "0.5189029", "0.5171625", "0.51155007", "0.51145864", "0.5108149", "0.50925255", "0.5073684", "0.50682515", "0.50555426", "0.5039259", "0.50238514", "0.5012137", "0.49975008", "0.4994512", "0.49906874", "0.49897188", "0.49679497", "0.4913183", "0.49082148", "0.4896804", "0.48938185", "0.48903197", "0.48769265", "0.4875108", "0.48749822", "0.48741364", "0.4869565", "0.4866477", "0.48251513", "0.482044", "0.48181576", "0.48162487", "0.4815687", "0.48139304", "0.4813894", "0.4811751", "0.48072556", "0.48026514", "0.4798447", "0.47871462", "0.47718525", "0.47698253", "0.47603813", "0.47576508", "0.47536975", "0.47530007", "0.47524014", "0.4752325", "0.47517735", "0.4730453", "0.4722861", "0.47195134", "0.47167945", "0.4716454", "0.47162572", "0.47148314", "0.47137678", "0.47092572", "0.4703398", "0.46999297", "0.46957237", "0.46908742", "0.46839806", "0.46823516", "0.46801448", "0.46673936", "0.4666401", "0.4664602", "0.4663754", "0.46508986", "0.4646228", "0.46413907", "0.4640317", "0.46378127", "0.46327978", "0.46315983", "0.46303612", "0.4627754", "0.46129236", "0.46125644", "0.46097696", "0.46050343" ]
0.6912894
0
GetMetrics mocks base method
func (m *MockClient) GetMetrics() *metrics.ClientMetrics { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetMetrics") ret0, _ := ret[0].(*metrics.ClientMetrics) return ret0 }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (m *MockTaskManager) GetMetrics() handler.Metric {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetMetrics\")\n\tret0, _ := ret[0].(handler.Metric)\n\treturn ret0\n}", "func MockMetrics() []telegraf.Metric {\n\tmetrics := make([]telegraf.Metric, 0)\n\t// Create a new point batch\n\tmetrics = append(metrics, TestMetric(1.0))\n\treturn metrics\n}", "func TestGetMetrics(t *testing.T) {\n\n\t//\t\tCreating mock request with custom params\n\t//\t\tand checking for error\n\trequest, err := http.NewRequest(\"GET\", \"/fizzbuzz-metrics\", nil)\n\tif err != nil {\n\t\tt.Errorf(\"GetMetrics() failed because of bad request: %v\", err)\n\t}\n\n\t//\t\tCreating a HTTP recorder for the test\n\trecorder := httptest.NewRecorder()\n\n\t//\t\tHitting endpoint\n\trouter := httprouter.New()\n\trouter.GET(\"/fizzbuzz-metrics\", GetMetrics)\n\trouter.ServeHTTP(recorder, request)\n\n\t//\t\tCheck status code\n\tif recorder.Code != http.StatusOK {\n\t\tt.Errorf(\"GetMetrics() failed because of status code: got %v instead of %v\", recorder.Code, http.StatusOK)\n\t}\n\n\t//\t\tCheck body\n\tgot := recorder.Body.String()\n\tif got == \"\" {\n\t\tt.Error(\"GetMetrics() failed because of empty body.\")\n\t}\n}", "func MockMetrics() []optic.Metric {\n\tmetricsEvents := make([]optic.Metric, 0)\n\tmetricsEvents = append(metricsEvents, TestMetric(1.0))\n\treturn metricsEvents\n}", "func MockGetMetricStatistics(t *testing.T, mockMatcher *sdk.MockCloudWatchAPI, metric float64, statistic string, numberOfMetrics int) {\n\tlog.Logger.Warningf(\"Mocking AWS iface: GetMetricStatistics\")\n\tif numberOfMetrics == 0 {\n\t\tnumberOfMetrics = 1\n\t}\n\n\tresult := &cloudwatch.GetMetricStatisticsOutput{}\n\tresult.Label = aws.String(\"fake\")\n\tresult.Datapoints = make([]*cloudwatch.Datapoint, numberOfMetrics)\n\tfor i := 0; i < numberOfMetrics; i++ {\n\t\td := &cloudwatch.Datapoint{}\n\n\t\tswitch statistic {\n\t\tcase cloudwatch.StatisticMaximum:\n\t\t\td.Maximum = aws.Float64(metric)\n\t\tcase cloudwatch.StatisticMinimum:\n\t\t\td.Minimum = aws.Float64(metric)\n\t\tcase cloudwatch.StatisticSum:\n\t\t\td.Sum = aws.Float64(metric)\n\t\tcase cloudwatch.StatisticSampleCount:\n\t\t\td.SampleCount = aws.Float64(metric)\n\t\tcase cloudwatch.StatisticAverage:\n\t\t\td.Average = aws.Float64(metric)\n\t\tdefault:\n\t\t\tt.Fatalf(\"Wrong metric statistic: %s\", statistic)\n\t\t}\n\t\td.Timestamp = aws.Time(time.Now().UTC())\n\t\td.Unit = aws.String(cloudwatch.StandardUnitPercent)\n\t\tresult.Datapoints[i] = d\n\t}\n\n\t// Mock as expected with our result\n\tmockMatcher.EXPECT().GetMetricStatistics(gomock.Any()).Do(func(input interface{}) {\n\t\tgotInput := input.(*cloudwatch.GetMetricStatisticsInput)\n\t\t// Check API received parameters are fine\n\t\tif aws.StringValue(gotInput.Namespace) == \"\" {\n\t\t\tt.Fatalf(\"Expected namespace, got nothing\")\n\t\t}\n\n\t\tif aws.StringValue(gotInput.MetricName) == \"\" {\n\t\t\tt.Fatalf(\"Expected metric name, got nothing\")\n\t\t}\n\n\t\tif aws.StringValue(gotInput.Unit) == \"\" {\n\t\t\tt.Fatalf(\"Expected unit, got nothing\")\n\t\t}\n\n\t\tif len(gotInput.Statistics) != 1 {\n\t\t\tt.Fatalf(\"Wrong statistics name\")\n\t\t}\n\n\t}).AnyTimes().Return(result, nil)\n\n}", "func TestGetMetrics(t *testing.T) {\n\t// set up test server and mocked LogStore\n\tmockLogStore := new(MockedLogStore)\n\tserver := newTestServer(mockLogStore)\n\ttestServer := httptest.NewServer(server.server.Handler)\n\tdefer testServer.Close()\n\tclient := testServer.Client()\n\n\t// Make a first call to a resource to make metrics middleware record some\n\t// stats. Prior to that, no stats will have been saved.\n\tresp, _ := client.Get(testServer.URL + \"/metrics\")\n\trequire.Equalf(t, http.StatusOK, resp.StatusCode, \"unexpected status code\")\n\trequire.Equalf(t, \"\", readBody(t, resp), \"expected first /metrics call to be empty\")\n\n\tresp, _ = client.Get(testServer.URL + \"/metrics\")\n\trequire.Equalf(t, http.StatusOK, resp.StatusCode, \"unexpected status code\")\n\trequire.Containsf(t, readBody(t, resp), `total_requests{method=\"GET\",path=\"/metrics\",statusCode=\"200\"} 1`, \"missing expected metric\")\n}", "func (m *MockProviders) GetMetrics() *metrics.ClientMetrics {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetMetrics\")\n\tret0, _ := ret[0].(*metrics.ClientMetrics)\n\treturn ret0\n}", "func (_e *MockDataCoord_Expecter) GetMetrics(ctx interface{}, req interface{}) *MockDataCoord_GetMetrics_Call {\n\treturn &MockDataCoord_GetMetrics_Call{Call: _e.mock.On(\"GetMetrics\", ctx, req)}\n}", "func (_e *MockQueryCoord_Expecter) GetMetrics(ctx interface{}, req interface{}) *MockQueryCoord_GetMetrics_Call {\n\treturn &MockQueryCoord_GetMetrics_Call{Call: _e.mock.On(\"GetMetrics\", ctx, req)}\n}", "func (m *MockKairosDBClient) QueryMetrics(ctx context.Context, dsInfo *datasource.DatasourceInfo, request *remote.MetricQueryRequest) ([]*remote.MetricQueryResults, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"QueryMetrics\", ctx, dsInfo, request)\n\tret0, _ := ret[0].([]*remote.MetricQueryResults)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockFlowAggregatorQuerier) GetRecordMetrics() querier.Metrics {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetRecordMetrics\")\n\tret0, _ := ret[0].(querier.Metrics)\n\treturn ret0\n}", "func (_m *MockStatusStoreIface) GetMetric() (map[string]float64, error) {\n\tret := _m.Called()\n\n\tvar r0 map[string]float64\n\tif rf, ok := ret.Get(0).(func() map[string]float64); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(map[string]float64)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func() error); ok {\n\t\tr1 = rf()\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func TestMetrics(t *testing.T) {\n\tctx := context.Background()\n\tvar err error\n\n\t// Check metrics-server deployment is ready.\n\terr = checkReadyDeployment(ctx)\n\tif err != nil {\n\t\tt.Fatalf(\"could not get metrics: %v\", err)\n\t}\n\n\t// Check metrics availability.\n\terr = checkMetricsAvailability(ctx)\n\tif err != nil {\n\t\tt.Fatalf(\"could not get metrics: %v\", err)\n\t}\n}", "func (m *MockMetrics) InitMetrics() {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"InitMetrics\")\n}", "func NewMock() *MockMetrics {\n\treturn &MockMetrics{}\n}", "func (_m *MockDataCoord) GetMetrics(ctx context.Context, req *milvuspb.GetMetricsRequest) (*milvuspb.GetMetricsResponse, error) {\n\tret := _m.Called(ctx, req)\n\n\tvar r0 *milvuspb.GetMetricsResponse\n\tvar r1 error\n\tif rf, ok := ret.Get(0).(func(context.Context, *milvuspb.GetMetricsRequest) (*milvuspb.GetMetricsResponse, error)); ok {\n\t\treturn rf(ctx, req)\n\t}\n\tif rf, ok := ret.Get(0).(func(context.Context, *milvuspb.GetMetricsRequest) *milvuspb.GetMetricsResponse); ok {\n\t\tr0 = rf(ctx, req)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*milvuspb.GetMetricsResponse)\n\t\t}\n\t}\n\n\tif rf, ok := ret.Get(1).(func(context.Context, *milvuspb.GetMetricsRequest) error); ok {\n\t\tr1 = rf(ctx, req)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (_m *MockQueryCoord) GetMetrics(ctx context.Context, req *milvuspb.GetMetricsRequest) (*milvuspb.GetMetricsResponse, error) {\n\tret := _m.Called(ctx, req)\n\n\tvar r0 *milvuspb.GetMetricsResponse\n\tvar r1 error\n\tif rf, ok := ret.Get(0).(func(context.Context, *milvuspb.GetMetricsRequest) (*milvuspb.GetMetricsResponse, error)); ok {\n\t\treturn rf(ctx, req)\n\t}\n\tif rf, ok := ret.Get(0).(func(context.Context, *milvuspb.GetMetricsRequest) *milvuspb.GetMetricsResponse); ok {\n\t\tr0 = rf(ctx, req)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*milvuspb.GetMetricsResponse)\n\t\t}\n\t}\n\n\tif rf, ok := ret.Get(1).(func(context.Context, *milvuspb.GetMetricsRequest) error); ok {\n\t\tr1 = rf(ctx, req)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (m *MockIApi) MetricsRetrieveAll(arg0 *chartmogul.MetricsFilter) (*chartmogul.MetricsResult, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"MetricsRetrieveAll\", arg0)\n\tret0, _ := ret[0].(*chartmogul.MetricsResult)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (e Entry) GetMetrics(timeout time.Duration, h heimdall.Doer, debug bool) (Metrics, error) {\n\tvar m Metrics\n\n\t// Let's set the stuff we know already.\n\tm.Address = e.Address\n\tm.Regexp = e.Regexp\n\tm.CapturedAt = time.Now().UTC()\n\n\t// Set a timeout.\n\tctx, cancel := context.WithTimeout(context.Background(), timeout)\n\tdefer cancel()\n\n\t// Setup the request.\n\treq, err := http.NewRequestWithContext(ctx, http.MethodGet, e.Address, nil)\n\tif err != nil {\n\t\treturn m, err\n\t}\n\n\tif debug {\n\t\tfmt.Printf(\"%#v\\n\", req)\n\t}\n\n\t// Let's do the request.\n\tstart := time.Now()\n\tres, err := h.Do(req)\n\tif err != nil {\n\t\treturn m, err\n\t}\n\n\t// We don't need the body unless we've got a regexp.\n\tif e.Regexp != \"\" {\n\t\tbody, err := ioutil.ReadAll(res.Body)\n\t\tif err != nil {\n\t\t\treturn m, err\n\t\t}\n\t\t// Do the regexp here and assign the value.\n\t\tmatch, _ := regexp.MatchString(e.Regexp, string(body))\n\t\tm.RegexpStatus = match\n\t}\n\ttook := time.Since(start)\n\n\t// Set the last few values\n\tm.StatusCode = res.StatusCode\n\tm.ResponseTime = took\n\n\tif debug {\n\t\tfmt.Printf(\"Result: %#v\\n\", res)\n\t\tfmt.Printf(\"Time Taken: %s\\n\", took)\n\t\tfmt.Printf(\"Metrics: %#v\\n\", m)\n\t}\n\n\tif ctx.Err() != nil {\n\t\treturn m, errors.New(\"context deadline exceeded\")\n\t}\n\treturn m, nil\n}", "func (h *singleLhcNodeHarness) getMetrics() *metrics {\n\treturn &metrics{\n\t\ttimeSinceLastCommitMillis: h.metricRegistry.Get(\"ConsensusAlgo.LeanHelix.TimeSinceLastCommit.Millis\").(*metric.Histogram),\n\t\ttimeSinceLastElectionMillis: h.metricRegistry.Get(\"ConsensusAlgo.LeanHelix.TimeSinceLastElection.Millis\").(*metric.Histogram),\n\t\tcurrentElectionCount: h.metricRegistry.Get(\"ConsensusAlgo.LeanHelix.CurrentElection.Number\").(*metric.Gauge),\n\t\tcurrentLeaderMemberId: h.metricRegistry.Get(\"ConsensusAlgo.LeanHelix.CurrentLeaderMemberId.Number\").(*metric.Text),\n\t\tlastCommittedTime: h.metricRegistry.Get(\"ConsensusAlgo.LeanHelix.LastCommitted.TimeNano\").(*metric.Gauge),\n\t}\n}", "func (m *MockDataServiceServer) CalculateMetrics(arg0 context.Context, arg1 *dataservice.MetricsRequest) (*dataservice.FeedbackMetrics, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"CalculateMetrics\", arg0, arg1)\n\tret0, _ := ret[0].(*dataservice.FeedbackMetrics)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func setupMetrics() *Metrics {\n\t// Requests duration\n\tduration := prometheus.NewHistogramVec(prometheus.HistogramOpts{\n\t\tName: \"http_request_duration\",\n\t\tHelp: \"Duration of the http requests processed.\",\n\t},\n\t\t[]string{\"status\", \"method\", \"path\"},\n\t)\n\tprometheus.MustRegister(duration)\n\n\treturn &Metrics{\n\t\tduration: duration,\n\t}\n}", "func (m *MockProduct) ListMetricsForAggregation(arg0 context.Context, arg1 string) ([]string, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ListMetricsForAggregation\", arg0, arg1)\n\tret0, _ := ret[0].([]string)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockConnectionTracer) UpdatedMetrics(arg0 *utils.RTTStats, arg1, arg2 protocol.ByteCount, arg3 int) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"UpdatedMetrics\", arg0, arg1, arg2, arg3)\n}", "func Test_CollectMetrics21(t *testing.T) {\n\tassert := assert.New(t)\n\tconfig := getTestConfig(2, 1)\n\tconfig.DataFunc = config.GetTestData1\n\n\tres := config.CollectMetrics()\n\tfmt.Println(\"21: \", res)\n\tfmt.Println(\"21: \", []cmd.MetricData{{Name: \"m1\", Help: \"h1\", MetricType: \"gauge\", Stats: []cmd.MetricRecord{{Value: 999, Labels: []string{\"l00\"}, LabelValues: []string{\"lv00\"}}}}, {Name: \"m2\", Help: \"h2\", MetricType: \"gauge\", Stats: []cmd.MetricRecord{{Value: 999, Labels: []string{\"l10\"}, LabelValues: []string{\"lv10\"}}}}})\n\tassert.Equal(true, cmp.Equal(res, []cmd.MetricData{{Name: \"m1\", Help: \"h1\", MetricType: \"gauge\", Stats: []cmd.MetricRecord{{Value: 999, Labels: []string{\"l00\"}, LabelValues: []string{\"lv00\"}}}}, {Name: \"m2\", Help: \"h2\", MetricType: \"gauge\", Stats: []cmd.MetricRecord{{Value: 999, Labels: []string{\"l10\"}, LabelValues: []string{\"lv10\"}}}}}))\n}", "func (m *MockMetrics) DestroyMetrics() {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"DestroyMetrics\")\n}", "func (ds *dockServer) GetMetrics(context.Context, *pb.GetMetricsOpts) (*pb.GenericResponse, error) {\n\treturn nil, &model.NotImplementError{\"method GetMetrics has not been implemented yet\"}\n}", "func (m *MockDataServiceClient) CalculateMetrics(ctx context.Context, in *dataservice.MetricsRequest, opts ...grpc.CallOption) (*dataservice.FeedbackMetrics, error) {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{ctx, in}\n\tfor _, a := range opts {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"CalculateMetrics\", varargs...)\n\tret0, _ := ret[0].(*dataservice.FeedbackMetrics)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockQueryer) MetricMeta(arg0 i18n.LanguageCodes, arg1, arg2 string, arg3 ...string) ([]*pb.MetricMeta, error) {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{arg0, arg1, arg2}\n\tfor _, a := range arg3 {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"MetricMeta\", varargs...)\n\tret0, _ := ret[0].([]*pb.MetricMeta)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func Test_CollectMetrics01(t *testing.T) {\n\tassert := assert.New(t)\n\tconfig := getTestConfig(0, 1)\n\tconfig.DataFunc = config.GetTestData1\n\n\tres := config.CollectMetrics()\n\tassert.Nil(res)\n}", "func Test_CollectMetrics10(t *testing.T) {\n\tassert := assert.New(t)\n\tconfig := getTestConfig(1, 0)\n\tconfig.DataFunc = config.GetTestData1\n\n\tres := config.CollectMetrics()\n\tassert.Nil(res)\n}", "func TestPrometheusMetrics(t *testing.T) {\n\tbytesProcessedMetric.WithLabelValues(\"x\")\n\tcacheHitMetric.WithLabelValues(\"x\")\n\tuploadedBytesMetric.WithLabelValues(\"x\")\n\tqueryTotalMetric.WithLabelValues(\"x\")\n\tqueryProcessedMetric.WithLabelValues(\"x\")\n\tinFlightUploadsHistogram.WithLabelValues(\"x\")\n\tuploadQueueSizeHistogram.WithLabelValues(\"x\")\n\n\tpromtest.LintMetrics(t)\n}", "func (m *MockContext) GetMetricsClient() metrics.Client {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetMetricsClient\")\n\tret0, _ := ret[0].(metrics.Client)\n\treturn ret0\n}", "func Test_CollectMetrics12(t *testing.T) {\n\tassert := assert.New(t)\n\tconfig := getTestConfig(1, 2)\n\tconfig.DataFunc = config.GetTestData1\n\n\tres := config.CollectMetrics()\n\tfmt.Println(\"12: \", res)\n\tfmt.Println(\"12: \", []cmd.MetricData{{Name: \"m1\", Help: \"h1\", MetricType: \"gauge\", Stats: []cmd.MetricRecord{{Value: 999, Labels: []string{\"l01\"}, LabelValues: []string{\"lv01\"}}, {Value: 999, Labels: []string{\"l00\"}, LabelValues: []string{\"lv00\"}}}}})\n\tassert.Equal(true, cmp.Equal(res, []cmd.MetricData{{Name: \"m1\", Help: \"h1\", MetricType: \"gauge\", Stats: []cmd.MetricRecord{{Value: 999, Labels: []string{\"l01\"}, LabelValues: []string{\"lv01\"}}, {Value: 999, Labels: []string{\"l00\"}, LabelValues: []string{\"lv00\"}}}}}))\n}", "func (h *testMetricsHandler) GetRawMetrics(apiClient kubernetes.Interface, namespace, functionName string) ([]byte, error) {\n\tsvc, err := apiClient.CoreV1().Services(namespace).Get(functionName, metav1.GetOptions{})\n\tif err != nil {\n\t\treturn []byte{}, err\n\t}\n\tb, err := http.Get(svc.SelfLink)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer b.Body.Close()\n\treturn ioutil.ReadAll(b.Body)\n}", "func NewMetrics(reg *prometheus.Registry, namespace, subsystem string, methodsFrom interface{}) (metric Metrics) {\n\tmetric.callErrTotal = prometheus.NewCounterVec(\n\t\tprometheus.CounterOpts{\n\t\t\tNamespace: namespace,\n\t\t\tSubsystem: subsystem,\n\t\t\tName: \"errors_total\",\n\t\t\tHelp: \"Amount of DAL errors.\",\n\t\t},\n\t\t[]string{methodLabel},\n\t)\n\treg.MustRegister(metric.callErrTotal)\n\tmetric.callDuration = prometheus.NewHistogramVec(\n\t\tprometheus.HistogramOpts{\n\t\t\tNamespace: namespace,\n\t\t\tSubsystem: subsystem,\n\t\t\tName: \"call_duration_seconds\",\n\t\t\tHelp: \"DAL call latency.\",\n\t\t},\n\t\t[]string{methodLabel},\n\t)\n\treg.MustRegister(metric.callDuration)\n\n\tfor _, methodName := range reflectx.MethodsOf(methodsFrom) {\n\t\tl := prometheus.Labels{\n\t\t\tmethodLabel: methodName,\n\t\t}\n\t\tmetric.callErrTotal.With(l)\n\t\tmetric.callDuration.With(l)\n\t}\n\n\treturn metric\n}", "func (m *MockServicer) CalculateStats() *service.Stats {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"CalculateStats\")\n\tret0, _ := ret[0].(*service.Stats)\n\treturn ret0\n}", "func (m *MockQueryer) GetSingleMetricsMeta(arg0 i18n.LanguageCodes, arg1, arg2, arg3 string) (*pb.MetricMeta, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetSingleMetricsMeta\", arg0, arg1, arg2, arg3)\n\tret0, _ := ret[0].(*pb.MetricMeta)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockArgusdClient) RecordMetrics(arg0 context.Context, arg1 *golang.Empty, arg2 ...grpc.CallOption) (golang.Argusd_RecordMetricsClient, error) {\n\tvarargs := []interface{}{arg0, arg1}\n\tfor _, a := range arg2 {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"RecordMetrics\", varargs...)\n\tret0, _ := ret[0].(golang.Argusd_RecordMetricsClient)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockIApi) MetricsRetrieveMRRChurnRate(arg0 *chartmogul.MetricsFilter) (*chartmogul.MRRChurnRateResult, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"MetricsRetrieveMRRChurnRate\", arg0)\n\tret0, _ := ret[0].(*chartmogul.MRRChurnRateResult)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (c *Client) GetMetrics(ctx context.Context, req *milvuspb.GetMetricsRequest) (*milvuspb.GetMetricsResponse, error) {\n\treq = typeutil.Clone(req)\n\tcommonpbutil.UpdateMsgBase(\n\t\treq.GetBase(),\n\t\tcommonpbutil.FillMsgBaseFromClient(paramtable.GetNodeID()))\n\treturn wrapGrpcCall(ctx, c, func(client querypb.QueryNodeClient) (*milvuspb.GetMetricsResponse, error) {\n\t\treturn client.GetMetrics(ctx, req)\n\t})\n}", "func (_m *Client) GetMetricValues(ctx context.Context, resourceURI string, interval string, metricnames []string, aggregations []string, logger log.Logger) (map[string]insights.MetricValue, error) {\n\tret := _m.Called(ctx, resourceURI, interval, metricnames, aggregations, logger)\n\n\tvar r0 map[string]insights.MetricValue\n\tif rf, ok := ret.Get(0).(func(context.Context, string, string, []string, []string, log.Logger) map[string]insights.MetricValue); ok {\n\t\tr0 = rf(ctx, resourceURI, interval, metricnames, aggregations, logger)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(map[string]insights.MetricValue)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(context.Context, string, string, []string, []string, log.Logger) error); ok {\n\t\tr1 = rf(ctx, resourceURI, interval, metricnames, aggregations, logger)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func NewMetrics(consume ConsumeMetricsFunc, options ...Option) (Metrics, error) {\n\tif consume == nil {\n\t\treturn nil, errNilFunc\n\t}\n\treturn &baseMetrics{\n\t\tbaseImpl: newBaseImpl(options...),\n\t\tConsumeMetricsFunc: consume,\n\t}, nil\n}", "func (_m *MockBackend) PrometheusMetrics() string {\n\tret := _m.Called()\n\n\tvar r0 string\n\tif rf, ok := ret.Get(0).(func() string); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tr0 = ret.Get(0).(string)\n\t}\n\n\treturn r0\n}", "func getMetrics() []Metric {\n\tms := make([]Metric, 0)\n\treturn append(ms, &SimpleEapMetric{})\n}", "func NewMetrics(scope tally.Scope) *Metrics {\n\tsuccessScope := scope.Tagged(map[string]string{\"result\": \"success\"})\n\tfailScope := scope.Tagged(map[string]string{\"result\": \"fail\"})\n\ttimeoutScope := scope.Tagged(map[string]string{\"result\": \"timeout\"})\n\tapiScope := scope.SubScope(\"api\")\n\tserverScope := scope.SubScope(\"server\")\n\tplacement := scope.SubScope(\"placement\")\n\trecovery := scope.SubScope(\"recovery\")\n\n\treturn &Metrics{\n\t\tAPIEnqueueGangs: apiScope.Counter(\"enqueue_gangs\"),\n\t\tEnqueueGangSuccess: successScope.Counter(\"enqueue_gang\"),\n\t\tEnqueueGangFail: failScope.Counter(\"enqueue_gang\"),\n\n\t\tAPIDequeueGangs: apiScope.Counter(\"dequeue_gangs\"),\n\t\tDequeueGangSuccess: successScope.Counter(\"dequeue_gangs\"),\n\t\tDequeueGangTimeout: timeoutScope.Counter(\"dequeue_gangs\"),\n\n\t\tAPIGetPreemptibleTasks: apiScope.Counter(\"get_preemptible_tasks\"),\n\t\tGetPreemptibleTasksSuccess: successScope.Counter(\"get_preemptible_tasks\"),\n\t\tGetPreemptibleTasksTimeout: timeoutScope.Counter(\"get_preemptible_tasks\"),\n\n\t\tAPISetPlacements: apiScope.Counter(\"set_placements\"),\n\t\tSetPlacementSuccess: successScope.Counter(\"set_placements\"),\n\t\tSetPlacementFail: failScope.Counter(\"set_placements\"),\n\n\t\tAPIGetPlacements: apiScope.Counter(\"get_placements\"),\n\t\tGetPlacementSuccess: successScope.Counter(\"get_placements\"),\n\t\tGetPlacementFail: failScope.Counter(\"get_placements\"),\n\n\t\tAPILaunchedTasks: apiScope.Counter(\"launched_tasks\"),\n\n\t\tRecoverySuccess: successScope.Counter(\"recovery\"),\n\t\tRecoveryFail: failScope.Counter(\"recovery\"),\n\t\tRecoveryRunningSuccessCount: successScope.Counter(\"task_count\"),\n\t\tRecoveryRunningFailCount: failScope.Counter(\"task_count\"),\n\t\tRecoveryEnqueueFailedCount: failScope.Counter(\"enqueue_task_count\"),\n\t\tRecoveryEnqueueSuccessCount: successScope.Counter(\"enqueue_task_count\"),\n\t\tRecoveryTimer: recovery.Timer(\"running_tasks\"),\n\n\t\tPlacementQueueLen: placement.Gauge(\"placement_queue_length\"),\n\t\tPlacementFailed: placement.Counter(\"fail\"),\n\n\t\tElected: serverScope.Gauge(\"elected\"),\n\t}\n}", "func setupMetrics() Metrics {\n\tm := Metrics{}\n\tm.LastBackupDuration = prometheus.NewGauge(prometheus.GaugeOpts{\n\t\tNamespace: \"clickhouse_backup\",\n\t\tName: \"last_backup_duration\",\n\t\tHelp: \"Backup duration in nanoseconds.\",\n\t})\n\tm.LastBackupSuccess = prometheus.NewGauge(prometheus.GaugeOpts{\n\t\tNamespace: \"clickhouse_backup\",\n\t\tName: \"last_backup_success\",\n\t\tHelp: \"Last backup success boolean: 0=failed, 1=success, 2=unknown.\",\n\t})\n\tm.LastBackupStart = prometheus.NewGauge(prometheus.GaugeOpts{\n\t\tNamespace: \"clickhouse_backup\",\n\t\tName: \"last_backup_start\",\n\t\tHelp: \"Last backup start timestamp.\",\n\t})\n\tm.LastBackupEnd = prometheus.NewGauge(prometheus.GaugeOpts{\n\t\tNamespace: \"clickhouse_backup\",\n\t\tName: \"last_backup_end\",\n\t\tHelp: \"Last backup end timestamp.\",\n\t})\n\tm.SuccessfulBackups = prometheus.NewCounter(prometheus.CounterOpts{\n\t\tNamespace: \"clickhouse_backup\",\n\t\tName: \"successful_backups\",\n\t\tHelp: \"Number of Successful Backups.\",\n\t})\n\tm.FailedBackups = prometheus.NewCounter(prometheus.CounterOpts{\n\t\tNamespace: \"clickhouse_backup\",\n\t\tName: \"failed_backups\",\n\t\tHelp: \"Number of Failed Backups.\",\n\t})\n\tprometheus.MustRegister(\n\t\tm.LastBackupDuration,\n\t\tm.LastBackupStart,\n\t\tm.LastBackupEnd,\n\t\tm.LastBackupSuccess,\n\t\tm.SuccessfulBackups,\n\t\tm.FailedBackups,\n\t)\n\tm.LastBackupSuccess.Set(2) // 0=failed, 1=success, 2=unknown\n\treturn m\n}", "func (f FakeContainerImpl) GetContainerMetrics(containerID string) (*metrics.ContainerMetrics, error) {\n\treturn nil, nil\n}", "func TestMetricsEndpoint(t *testing.T) {\n\tc := newKubeClient(t)\n\n\tlistOptions := metav1.ListOptions{LabelSelector: \"app=olm-operator\"}\n\tpodList, err := c.KubernetesInterface().CoreV1().Pods(operatorNamespace).List(listOptions)\n\tif err != nil {\n\t\tlog.Infof(\"Error %v\\n\", err)\n\t\tt.Fatalf(\"Listing pods failed: %v\\n\", err)\n\t}\n\tif len(podList.Items) > 1 {\n\t\tt.Fatalf(\"Expected only 1 olm-operator pod, got %v\", len(podList.Items))\n\t}\n\n\tpodName := podList.Items[0].GetName()\n\n\trawOutput, err := getMetricsFromPod(t, c, podName, operatorNamespace, 8080)\n\tif err != nil {\n\t\tt.Fatalf(\"Metrics test failed: %v\\n\", err)\n\t}\n\n\tlog.Debugf(\"Metrics:\\n%v\", rawOutput)\n}", "func (p *StatsDParser) GetMetrics() pdata.Metrics {\n\tmetrics := pdata.NewMetrics()\n\trm := metrics.ResourceMetrics().AppendEmpty()\n\n\tfor _, metric := range p.gauges {\n\t\trm.InstrumentationLibraryMetrics().Append(metric)\n\t}\n\n\tfor _, metric := range p.counters {\n\t\trm.InstrumentationLibraryMetrics().Append(metric)\n\t}\n\n\tfor _, metric := range p.timersAndDistributions {\n\t\trm.InstrumentationLibraryMetrics().Append(metric)\n\t}\n\n\tfor _, summaryMetric := range p.summaries {\n\t\tmetrics.ResourceMetrics().At(0).InstrumentationLibraryMetrics().Append(buildSummaryMetric(summaryMetric))\n\t}\n\n\tp.gauges = make(map[statsDMetricdescription]pdata.InstrumentationLibraryMetrics)\n\tp.counters = make(map[statsDMetricdescription]pdata.InstrumentationLibraryMetrics)\n\tp.timersAndDistributions = make([]pdata.InstrumentationLibraryMetrics, 0)\n\tp.summaries = make(map[statsDMetricdescription]summaryMetric)\n\treturn metrics\n}", "func (m *MockQueryer) MetricNames(arg0 i18n.LanguageCodes, arg1, arg2 string) ([]*pb.NameDefine, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"MetricNames\", arg0, arg1, arg2)\n\tret0, _ := ret[0].([]*pb.NameDefine)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (sb ServiceBase) Metrics() metrics.Exposer {\n\treturn sb.options.Metrics\n}", "func newMetrics() *metrics {\n\treturn new(metrics)\n}", "func (c *Client) GetMetrics(ctx context.Context, req *milvuspb.GetMetricsRequest) (*milvuspb.GetMetricsResponse, error) {\n\treq = typeutil.Clone(req)\n\tcommonpbutil.UpdateMsgBase(\n\t\treq.GetBase(),\n\t\tcommonpbutil.FillMsgBaseFromClient(paramtable.GetNodeID(), commonpbutil.WithTargetID(c.grpcClient.GetNodeID())),\n\t)\n\treturn wrapGrpcCall(ctx, c, func(client querypb.QueryCoordClient) (*milvuspb.GetMetricsResponse, error) {\n\t\treturn client.GetMetrics(ctx, req)\n\t})\n}", "func (m *MockMetricsFactory) Create() metrics.Metrics {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Create\")\n\tret0, _ := ret[0].(metrics.Metrics)\n\treturn ret0\n}", "func Test_CollectMetrics11(t *testing.T) {\n\tassert := assert.New(t)\n\tconfig := getTestConfig(1, 1)\n\tconfig.DataFunc = config.GetTestData1\n\n\tres := config.CollectMetrics()\n\t// assert.Nil(res)\n\tassert.Equal(res, []cmd.MetricData{{Name: \"m1\", Help: \"h1\", MetricType: \"gauge\", Stats: []cmd.MetricRecord{{Value: 999, Labels: []string{\"l00\"}, LabelValues: []string{\"lv00\"}}}}})\n}", "func newMetrics() *Metrics {\n\treturn newMetricsFrom(DefaultMetricsOpts)\n}", "func (m *MockIApi) MetricsRetrieveARR(arg0 *chartmogul.MetricsFilter) (*chartmogul.ARRResult, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"MetricsRetrieveARR\", arg0)\n\tret0, _ := ret[0].(*chartmogul.ARRResult)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func callMetrics(metricsAPI *metricsAPI, clock func() time.Time, timingMetrics bool) callrules.Rule {\n\ttimed := metricsAPI.callLatency\n\tif !timingMetrics {\n\t\ttimed = nil\n\t}\n\tharness := xmetrics.NewHarness(metricsAPI.callCount, metricsAPI.callErrorCount, timed, clock)\n\treturn callrules.Metrics(harness, nil)\n}", "func NewMetrics() *Metrics {\n\tm := &Metrics{}\n\tm.Reset()\n\treturn m\n}", "func (_class PIFClass) GetMetrics(sessionID SessionRef, self PIFRef) (_retval PIFMetricsRef, _err error) {\n\t_method := \"PIF.get_metrics\"\n\t_sessionIDArg, _err := convertSessionRefToXen(fmt.Sprintf(\"%s(%s)\", _method, \"session_id\"), sessionID)\n\tif _err != nil {\n\t\treturn\n\t}\n\t_selfArg, _err := convertPIFRefToXen(fmt.Sprintf(\"%s(%s)\", _method, \"self\"), self)\n\tif _err != nil {\n\t\treturn\n\t}\n\t_result, _err := _class.client.APICall(_method, _sessionIDArg, _selfArg)\n\tif _err != nil {\n\t\treturn\n\t}\n\t_retval, _err = convertPIFMetricsRefToGo(_method + \" -> \", _result.Value)\n\treturn\n}", "func NewMetrics() *Metrics {\n\treturn &Metrics{\n\t\tInputBytesTotal: promauto.NewCounterVec(\n\t\t\tprometheus.CounterOpts{\n\t\t\t\tName: \"router_input_bytes_total\",\n\t\t\t\tHelp: \"Total number of bytes received\",\n\t\t\t},\n\t\t\t[]string{\"interface\", \"isd_as\", \"neighbor_isd_as\"},\n\t\t),\n\t\tOutputBytesTotal: promauto.NewCounterVec(\n\t\t\tprometheus.CounterOpts{\n\t\t\t\tName: \"router_output_bytes_total\",\n\t\t\t\tHelp: \"Total number of bytes sent.\",\n\t\t\t},\n\t\t\t[]string{\"interface\", \"isd_as\", \"neighbor_isd_as\"},\n\t\t),\n\t\tInputPacketsTotal: promauto.NewCounterVec(\n\t\t\tprometheus.CounterOpts{\n\t\t\t\tName: \"router_input_pkts_total\",\n\t\t\t\tHelp: \"Total number of packets received\",\n\t\t\t},\n\t\t\t[]string{\"interface\", \"isd_as\", \"neighbor_isd_as\"},\n\t\t),\n\t\tOutputPacketsTotal: promauto.NewCounterVec(\n\t\t\tprometheus.CounterOpts{\n\t\t\t\tName: \"router_output_pkts_total\",\n\t\t\t\tHelp: \"Total number of packets sent.\",\n\t\t\t},\n\t\t\t[]string{\"interface\", \"isd_as\", \"neighbor_isd_as\"},\n\t\t),\n\t\tDroppedPacketsTotal: promauto.NewCounterVec(\n\t\t\tprometheus.CounterOpts{\n\t\t\t\tName: \"router_dropped_pkts_total\",\n\t\t\t\tHelp: \"Total number of packets dropped by the router. This metric reports \" +\n\t\t\t\t\t\"the number of packets that were dropped because of errors.\",\n\t\t\t},\n\t\t\t[]string{\"interface\", \"isd_as\", \"neighbor_isd_as\"},\n\t\t),\n\t\tInterfaceUp: promauto.NewGaugeVec(\n\t\t\tprometheus.GaugeOpts{\n\t\t\t\tName: \"router_interface_up\",\n\t\t\t\tHelp: \"Either zero or one depending on whether the interface is up.\",\n\t\t\t},\n\t\t\t[]string{\"interface\", \"isd_as\", \"neighbor_isd_as\"},\n\t\t),\n\t\tBFDInterfaceStateChanges: promauto.NewCounterVec(\n\t\t\tprometheus.CounterOpts{\n\t\t\t\tName: \"router_bfd_state_changes_total\",\n\t\t\t\tHelp: \"Total number of BFD state changes.\",\n\t\t\t},\n\t\t\t[]string{\"interface\", \"isd_as\", \"neighbor_isd_as\"},\n\t\t),\n\t\tBFDPacketsSent: promauto.NewCounterVec(\n\t\t\tprometheus.CounterOpts{\n\t\t\t\tName: \"router_bfd_sent_packets_total\",\n\t\t\t\tHelp: \"Number of BFD packets sent.\",\n\t\t\t},\n\t\t\t[]string{\"interface\", \"isd_as\", \"neighbor_isd_as\"},\n\t\t),\n\t\tBFDPacketsReceived: promauto.NewCounterVec(\n\t\t\tprometheus.CounterOpts{\n\t\t\t\tName: \"router_bfd_received_packets_total\",\n\t\t\t\tHelp: \"Number of BFD packets received.\",\n\t\t\t},\n\t\t\t[]string{\"interface\", \"isd_as\", \"neighbor_isd_as\"},\n\t\t),\n\t\tServiceInstanceCount: promauto.NewGaugeVec(\n\t\t\tprometheus.GaugeOpts{\n\t\t\t\tName: \"router_service_instance_count\",\n\t\t\t\tHelp: \"Number of service instances known by the data plane.\",\n\t\t\t},\n\t\t\t[]string{\"service\", \"isd_as\"},\n\t\t),\n\t\tServiceInstanceChanges: promauto.NewCounterVec(\n\t\t\tprometheus.CounterOpts{\n\t\t\t\tName: \"router_service_instance_changes_total\",\n\t\t\t\tHelp: \"Number of total service instance changes. Both addition and removal of a \" +\n\t\t\t\t\t\"service instance is accumulated.\",\n\t\t\t},\n\t\t\t[]string{\"service\", \"isd_as\"},\n\t\t),\n\t\tSiblingReachable: promauto.NewGaugeVec(\n\t\t\tprometheus.GaugeOpts{\n\t\t\t\tName: \"router_sibling_reachable\",\n\t\t\t\tHelp: \"Either zero or one depending on whether a sibling router \" +\n\t\t\t\t\t\"instance is reachable.\",\n\t\t\t},\n\t\t\t[]string{\"sibling\", \"isd_as\"},\n\t\t),\n\t\tSiblingBFDPacketsSent: promauto.NewCounterVec(\n\t\t\tprometheus.CounterOpts{\n\t\t\t\tName: \"router_bfd_sent_sibling_packets_total\",\n\t\t\t\tHelp: \"Number of BFD packets sent to sibling router instance.\",\n\t\t\t},\n\t\t\t[]string{\"sibling\", \"isd_as\"},\n\t\t),\n\t\tSiblingBFDPacketsReceived: promauto.NewCounterVec(\n\t\t\tprometheus.CounterOpts{\n\t\t\t\tName: \"router_bfd_received_sibling_packets_total\",\n\t\t\t\tHelp: \"Number of BFD packets received from sibling router instance.\",\n\t\t\t},\n\t\t\t[]string{\"sibling\", \"isd_as\"},\n\t\t),\n\t\tSiblingBFDStateChanges: promauto.NewCounterVec(\n\t\t\tprometheus.CounterOpts{\n\t\t\t\tName: \"router_bfd_sibling_state_changes_total\",\n\t\t\t\tHelp: \"Total number of BFD state changes for sibling router instances\",\n\t\t\t},\n\t\t\t[]string{\"sibling\", \"isd_as\"},\n\t\t),\n\t}\n}", "func LoadExpectedMetrics(t *testing.T, model string) []string {\n\tt.Helper()\n\tdcgmNameToMetricNameMap := map[string]string{\n\t\t\"DCGM_FI_DEV_GPU_UTIL\": \"dcgm.gpu.utilization\",\n\t\t\"DCGM_FI_DEV_FB_USED\": \"dcgm.gpu.memory.bytes_used\",\n\t\t\"DCGM_FI_DEV_FB_FREE\": \"dcgm.gpu.memory.bytes_free\",\n\t\t\"DCGM_FI_PROF_SM_ACTIVE\": \"dcgm.gpu.profiling.sm_utilization\",\n\t\t\"DCGM_FI_PROF_SM_OCCUPANCY\": \"dcgm.gpu.profiling.sm_occupancy\",\n\t\t\"DCGM_FI_PROF_PIPE_TENSOR_ACTIVE\": \"dcgm.gpu.profiling.tensor_utilization\",\n\t\t\"DCGM_FI_PROF_DRAM_ACTIVE\": \"dcgm.gpu.profiling.dram_utilization\",\n\t\t\"DCGM_FI_PROF_PIPE_FP64_ACTIVE\": \"dcgm.gpu.profiling.fp64_utilization\",\n\t\t\"DCGM_FI_PROF_PIPE_FP32_ACTIVE\": \"dcgm.gpu.profiling.fp32_utilization\",\n\t\t\"DCGM_FI_PROF_PIPE_FP16_ACTIVE\": \"dcgm.gpu.profiling.fp16_utilization\",\n\t\t\"DCGM_FI_PROF_PCIE_TX_BYTES\": \"dcgm.gpu.profiling.pcie_sent_bytes\",\n\t\t\"DCGM_FI_PROF_PCIE_RX_BYTES\": \"dcgm.gpu.profiling.pcie_received_bytes\",\n\t\t\"DCGM_FI_PROF_NVLINK_TX_BYTES\": \"dcgm.gpu.profiling.nvlink_sent_bytes\",\n\t\t\"DCGM_FI_PROF_NVLINK_RX_BYTES\": \"dcgm.gpu.profiling.nvlink_received_bytes\",\n\t}\n\tgoldenPath := getModelGoldenFilePath(t, model)\n\tgoldenFile, err := ioutil.ReadFile(goldenPath)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tvar m modelSupportedFields\n\terr = yaml.Unmarshal(goldenFile, &m)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tvar expectedMetrics []string\n\tfor _, supported := range m.SupportedFields {\n\t\texpectedMetrics = append(expectedMetrics, dcgmNameToMetricNameMap[supported])\n\t}\n\treturn expectedMetrics\n}", "func (m *MockMetrics) MeasureSince(arg0 []string, arg1 time.Time) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"MeasureSince\", arg0, arg1)\n}", "func (_m *SysProbeUtil) GetStats() (map[string]interface{}, error) {\n\tret := _m.Called()\n\n\tvar r0 map[string]interface{}\n\tvar r1 error\n\tif rf, ok := ret.Get(0).(func() (map[string]interface{}, error)); ok {\n\t\treturn rf()\n\t}\n\tif rf, ok := ret.Get(0).(func() map[string]interface{}); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(map[string]interface{})\n\t\t}\n\t}\n\n\tif rf, ok := ret.Get(1).(func() error); ok {\n\t\tr1 = rf()\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func NewMockedMetrics() *MockedMetrics {\n\treturn &MockedMetrics{}\n}", "func NewMockedMetrics() *MockedMetrics {\n\treturn &MockedMetrics{}\n}", "func (m *MockContract) GetUserStats(arg0, arg1, arg2 string) (*services.UserResponseContract, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUserStats\", arg0, arg1, arg2)\n\tret0, _ := ret[0].(*services.UserResponseContract)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (y *YarnMetrics) getMetrics() *NMMetrics {\n\tjmxResp := &JmxResp{}\n\terr := y.requestUrl(metricsSuffix, jmxResp)\n\tif err != nil {\n\t\tklog.V(5).Infof(\"request nodemanager metrics err: %v\", err)\n\t\treturn nil\n\t}\n\tif len(jmxResp.Beans) == 0 {\n\t\tklog.V(5).Infof(\"request nodemanager metrics, empty beans\")\n\t\treturn nil\n\t}\n\treturn &jmxResp.Beans[0]\n}", "func TestMetrics(t *testing.T) {\n\tmetrics, err := NewMetrics()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tmetrics.Send(&influxdb.Series{\n\t\tName: \"testing\",\n\t\tColumns: []string{\n\t\t\t\"foo\",\n\t\t},\n\t\tPoints: [][]interface{}{\n\t\t\t{\n\t\t\t\t\"bar\",\n\t\t\t},\n\t\t},\n\t})\n}", "func initMetrics() *metrics.Manager {\n\treturn metrics.New(\"calert\")\n}", "func (a *Client) GetMetrics(params *GetMetricsParams, authInfo runtime.ClientAuthInfoWriter) (*GetMetricsOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewGetMetricsParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"GetMetrics\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/cdn/v1/stacks/{stack_id}/metrics\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"https\"},\n\t\tParams: params,\n\t\tReader: &GetMetricsReader{formats: a.formats},\n\t\tAuthInfo: authInfo,\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn result.(*GetMetricsOK), nil\n\n}", "func (_m *Client) GetDefinitionMetrics(_a0 context.Context, _a1 build.GetDefinitionMetricsArgs) (*[]build.BuildMetric, error) {\n\tret := _m.Called(_a0, _a1)\n\n\tvar r0 *[]build.BuildMetric\n\tif rf, ok := ret.Get(0).(func(context.Context, build.GetDefinitionMetricsArgs) *[]build.BuildMetric); ok {\n\t\tr0 = rf(_a0, _a1)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*[]build.BuildMetric)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(context.Context, build.GetDefinitionMetricsArgs) error); ok {\n\t\tr1 = rf(_a0, _a1)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (m *MockIApi) MetricsListActivities(arg0 *chartmogul.MetricsListActivitiesParams) (*chartmogul.MetricsActivities, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"MetricsListActivities\", arg0)\n\tret0, _ := ret[0].(*chartmogul.MetricsActivities)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (c *PromMetricsClient) GetMetrics() ([]*Metric, error) {\n\tres, err := http.Get(c.URL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif res.StatusCode != 200 {\n\t\treturn nil, ErrUnexpectedHTTPStatusCode\n\t}\n\n\tdefer res.Body.Close()\n\treturn Parse(res.Body)\n}", "func (m *MockIApi) MetricsRetrieveMRR(arg0 *chartmogul.MetricsFilter) (*chartmogul.MRRResult, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"MetricsRetrieveMRR\", arg0)\n\tret0, _ := ret[0].(*chartmogul.MRRResult)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func NewMetrics(component string, sampleRate float64, client metrics.Client) BaseMetrics {\n\treturn BaseMetrics{\n\t\tcomponent: component,\n\t\trate: sampleRate,\n\t\tmetrics: client,\n\t\tmetMap: map[string]string{\n\t\t\t\"latency\": \"comp.\" + component + \".requests.latency\",\n\t\t\t\"request\": \"comp.\" + component + \".requests.%d\",\n\t\t\t\"mLatency\": \"comp.\" + component + \".requests.%s.latency\",\n\t\t\t\"mRequest\": \"comp.\" + component + \".requests.%s.%d\",\n\t\t},\n\t}\n}", "func mustGetClientMetrics() *grpc_prometheus.ClientMetrics {\n\tclientMetricsOnce.Do(func() {\n\t\tclientMetrics = grpc_prometheus.NewRegisteredClientMetrics(prometheus.DefaultRegisterer,\n\t\t\tgrpc_prometheus.WithClientCounterOptions(setCounterNamespace),\n\t\t\tgrpc_prometheus.WithClientHandlingTimeHistogram(setHistogramNamespace), // record the overall request latency for a gRPC request\n\t\t\tgrpc_prometheus.WithClientStreamRecvHistogram(setHistogramNamespace), // record how long it takes for a client to receive a message during a streaming RPC\n\t\t\tgrpc_prometheus.WithClientStreamSendHistogram(setHistogramNamespace), // record how long it takes for a client to send a message during a streaming RPC\n\t\t)\n\t})\n\n\treturn clientMetrics\n}", "func (m *MockScheduler) GetClassLoadPercents() (map[string]int32, error) {\n\tret := m.ctrl.Call(m, \"GetClassLoadPercents\")\n\tret0, _ := ret[0].(map[string]int32)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func NewMockMetrics(ctrl *gomock.Controller) *MockMetrics {\n\tmock := &MockMetrics{ctrl: ctrl}\n\tmock.recorder = &MockMetricsMockRecorder{mock}\n\treturn mock\n}", "func NewMockMetrics(ctrl *gomock.Controller) *MockMetrics {\n\tmock := &MockMetrics{ctrl: ctrl}\n\tmock.recorder = &MockMetricsMockRecorder{mock}\n\treturn mock\n}", "func NewMockMetrics(ctrl *gomock.Controller) *MockMetrics {\n\tmock := &MockMetrics{ctrl: ctrl}\n\tmock.recorder = &MockMetricsMockRecorder{mock}\n\treturn mock\n}", "func NewMockMetrics(ctrl *gomock.Controller) *MockMetrics {\n\tmock := &MockMetrics{ctrl: ctrl}\n\tmock.recorder = &MockMetricsMockRecorder{mock}\n\treturn mock\n}", "func NewMockMetrics(ctrl *gomock.Controller) *MockMetrics {\n\tmock := &MockMetrics{ctrl: ctrl}\n\tmock.recorder = &MockMetricsMockRecorder{mock}\n\treturn mock\n}", "func (m *MockMetrics) CountStart() {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"CountStart\")\n}", "func (c *CAdvisor) GetMetrics() (*Metrics, error) {\n\tlog.Printf(\"[DEBUG] [cadvisor] Get metrics\")\n\tnodeSpec, err := c.Client.MachineInfo()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlog.Printf(\"[DEBUG] [cadvisor] Receive machine info : %#v\",\n\t\tnodeSpec)\n\tnodeInfo, err := c.Client.ContainerInfo(\"/\", c.Query)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlog.Printf(\"[DEBUG] [cadvisor] Receive container info : %#v\",\n\t\tnodeInfo)\n\tcontainersInfo, err := c.Client.AllDockerContainers(c.Query)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlog.Printf(\"[DEBUG] [cadvisor] Receive all docker containers : %#v\",\n\t\tcontainersInfo)\n\tmetrics := &Metrics{\n\t\tNodeSpec: nodeSpec,\n\t\tNodeInfo: nodeInfo,\n\t\tContainersInfo: containersInfo,\n\t}\n\t//log.Printf(\"[INFO] [cadvisor] Metrics: %#v\", metrics)\n\treturn metrics, nil\n}", "func (m *MockStatsReader) GetGlobalStats() GlobalStats {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetGlobalStats\")\n\tret0, _ := ret[0].(GlobalStats)\n\treturn ret0\n}", "func (c *client) getAllTicketMetrics(endpoint string, in interface{}) ([]TicketMetric, error) {\n\tresult := make([]TicketMetric, 0)\n\tpayload, err := marshall(in)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\theaders := map[string]string{}\n\tif in != nil {\n\t\theaders[\"Content-Type\"] = \"application/json\"\n\t}\n\n\tres, err := c.request(\"GET\", endpoint, headers, bytes.NewReader(payload))\n\tdataPerPage := new(APIPayload)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tapiV2 := \"/api/v2/\"\n\tfieldName := strings.Split(endpoint[len(apiV2):], \".\")[0]\n\tdefer res.Body.Close()\n\n\terr = unmarshall(res, dataPerPage)\n\n\tapiStartIndex := strings.Index(dataPerPage.NextPage, apiV2)\n\tcurrentPage := endpoint\n\n\tvar totalWaitTime int64\n\tfor currentPage != \"\" {\n\t\t// if too many requests(res.StatusCode == 429), delay sending request\n\t\tif res.StatusCode == 429 {\n\t\t\tafter, err := strconv.ParseInt(res.Header.Get(\"Retry-After\"), 10, 64)\n\t\t\tlog.Printf(\"[zd_ticket_metrics_service][getAllTicketMetrics] too many requests. Wait for %v seconds\\n\", after)\n\t\t\ttotalWaitTime += after\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\ttime.Sleep(time.Duration(after) * time.Second)\n\t\t} else {\n\t\t\tif fieldName == \"ticket_metrics\" {\n\t\t\t\tresult = append(result, dataPerPage.TicketMetrics...)\n\t\t\t}\n\t\t\tcurrentPage = dataPerPage.NextPage\n\t\t}\n\t\tres, _ = c.request(\"GET\", dataPerPage.NextPage[apiStartIndex:], headers, bytes.NewReader(payload))\n\t\tdataPerPage = new(APIPayload)\n\t\terr = unmarshall(res, dataPerPage)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tlog.Printf(\"[zd_ticket_metrics_service][getAllTicketMetrics] number of records pulled: %v\\n\", len(result))\n\tlog.Printf(\"[zd_ticket_metrics_service][getAllTicketMetrics] total waiting time due to rate limit: %v\\n\", totalWaitTime)\n\n\treturn result, err\n}", "func TestMetrics(t *testing.T) {\n\t// Notes that ReadPairsExamined, ReadPairDups, and\n\t// ReadPairOpticalDups below are doubled because they are halved\n\t// when written to the metrics file.\n\ttests := []struct {\n\t\trecords []*sam.Record\n\t\tmetrics *MetricsCollection\n\t}{\n\t\t{\n\t\t\t[]*sam.Record{\n\t\t\t\tNewRecord(\"A:::1:10:1:1\", chr1, 0, r1F, 10, chr1, cigar0),\n\t\t\t\tNewRecord(\"A:::1:10:1:1\", chr1, 10, r2R, 0, chr1, cigar0),\n\t\t\t},\n\t\t\t&MetricsCollection{\n\t\t\t\tLibraryMetrics: map[string]*Metrics{\n\t\t\t\t\t\"Unknown Library\": &Metrics{\n\t\t\t\t\t\tUnpairedReads: 0,\n\t\t\t\t\t\tReadPairsExamined: 2,\n\t\t\t\t\t\tSecondarySupplementary: 0,\n\t\t\t\t\t\tUnmappedReads: 0,\n\t\t\t\t\t\tUnpairedDups: 0,\n\t\t\t\t\t\tReadPairDups: 0,\n\t\t\t\t\t\tReadPairOpticalDups: 0,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t[]*sam.Record{\n\t\t\t\tNewRecord(\"A:::1:10:1:1\", chr1, 0, r1F, 10, chr1, cigar0),\n\t\t\t\tNewRecord(\"B:::2:10:1:1\", chr1, 0, r1F, 10, chr1, cigar0),\n\t\t\t\tNewRecord(\"A:::1:10:1:1\", chr1, 10, r2R, 0, chr1, cigar0),\n\t\t\t\tNewRecord(\"B:::2:10:1:1\", chr1, 10, r2R, 0, chr1, cigar0),\n\t\t\t},\n\t\t\t&MetricsCollection{\n\t\t\t\tLibraryMetrics: map[string]*Metrics{\n\t\t\t\t\t\"Unknown Library\": &Metrics{\n\t\t\t\t\t\tUnpairedReads: 0,\n\t\t\t\t\t\tReadPairsExamined: 4,\n\t\t\t\t\t\tSecondarySupplementary: 0,\n\t\t\t\t\t\tUnmappedReads: 0,\n\t\t\t\t\t\tUnpairedDups: 0,\n\t\t\t\t\t\tReadPairDups: 2,\n\t\t\t\t\t\tReadPairOpticalDups: 0,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t[]*sam.Record{\n\t\t\t\tNewRecord(\"A:::1:10:1:1\", chr1, 0, r1F, 10, chr1, cigar0),\n\t\t\t\tNewRecord(\"B:::2:11:1:1\", chr1, 0, r1F, 10, chr1, cigar0),\n\t\t\t\tNewRecord(\"C:::2:11:1:1\", chr1, 0, r1F, 10, chr1, cigar0),\n\t\t\t\tNewRecord(\"A:::1:10:1:1\", chr1, 10, r2R, 0, chr1, cigar0),\n\t\t\t\tNewRecord(\"B:::2:11:1:1\", chr1, 10, r2R, 0, chr1, cigar0),\n\t\t\t\tNewRecord(\"C:::2:11:1:1\", chr1, 10, r2R, 0, chr1, cigar0),\n\t\t\t},\n\t\t\t&MetricsCollection{\n\t\t\t\tLibraryMetrics: map[string]*Metrics{\n\t\t\t\t\t\"Unknown Library\": &Metrics{\n\t\t\t\t\t\tUnpairedReads: 0,\n\t\t\t\t\t\tReadPairsExamined: 6,\n\t\t\t\t\t\tSecondarySupplementary: 0,\n\t\t\t\t\t\tUnmappedReads: 0,\n\t\t\t\t\t\tUnpairedDups: 0,\n\t\t\t\t\t\tReadPairDups: 4,\n\t\t\t\t\t\tReadPairOpticalDups: 2,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t[]*sam.Record{\n\t\t\t\tNewRecord(\"A:::1:10:1:1\", chr1, 0, s1F, 0, nil, cigar0),\n\t\t\t\tNewRecord(\"A:::1:10:1:1\", chr1, 0, u2, 0, nil, cigar0),\n\t\t\t\tNewRecord(\"B:::2:10:1:1\", chr1, 0, s1F, 0, nil, cigar0),\n\t\t\t\tNewRecord(\"B:::2:10:1:1\", chr1, 0, u2, 0, nil, cigar0),\n\t\t\t},\n\t\t\t&MetricsCollection{\n\t\t\t\tLibraryMetrics: map[string]*Metrics{\n\t\t\t\t\t\"Unknown Library\": &Metrics{\n\t\t\t\t\t\tUnpairedReads: 2,\n\t\t\t\t\t\tReadPairsExamined: 0,\n\t\t\t\t\t\tSecondarySupplementary: 0,\n\t\t\t\t\t\tUnmappedReads: 2,\n\t\t\t\t\t\tUnpairedDups: 1,\n\t\t\t\t\t\tReadPairDups: 0,\n\t\t\t\t\t\tReadPairOpticalDups: 0,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t// Cross-shard pairs\n\t\t\t[]*sam.Record{\n\t\t\t\tNewRecord(\"A:::1:10:1:1\", chr1, 0, r1F, 105, chr1, cigar0),\n\t\t\t\tNewRecord(\"B:::1:10:1:1\", chr1, 0, r1F, 105, chr1, cigar0),\n\t\t\t\tNewRecord(\"A:::1:10:1:1\", chr1, 105, r2R, 0, chr1, cigar0),\n\t\t\t\tNewRecord(\"B:::1:10:1:1\", chr1, 105, r2R, 0, chr1, cigar0),\n\t\t\t},\n\t\t\t&MetricsCollection{\n\t\t\t\tLibraryMetrics: map[string]*Metrics{\n\t\t\t\t\t\"Unknown Library\": &Metrics{\n\t\t\t\t\t\tUnpairedReads: 0,\n\t\t\t\t\t\tReadPairsExamined: 4,\n\t\t\t\t\t\tSecondarySupplementary: 0,\n\t\t\t\t\t\tUnmappedReads: 0,\n\t\t\t\t\t\tUnpairedDups: 0,\n\t\t\t\t\t\tReadPairDups: 2,\n\t\t\t\t\t\tReadPairOpticalDups: 2,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t// Secondary alignments.\n\t\t\t[]*sam.Record{\n\t\t\t\tNewRecord(\"A:::1:10:1:1\", chr1, 0, r1F, 105, chr1, cigar0),\n\t\t\t\tNewRecord(\"A:::1:10:1:1\", chr1, 105, r2R, 0, chr1, cigar0),\n\t\t\t\tNewRecord(\"A:::1:10:1:1\", chr2, 12, sec, 105, chr1, cigar0),\n\t\t\t},\n\t\t\t&MetricsCollection{\n\t\t\t\tLibraryMetrics: map[string]*Metrics{\n\t\t\t\t\t\"Unknown Library\": &Metrics{\n\t\t\t\t\t\tUnpairedReads: 0,\n\t\t\t\t\t\tReadPairsExamined: 2,\n\t\t\t\t\t\tSecondarySupplementary: 1,\n\t\t\t\t\t\tUnmappedReads: 0,\n\t\t\t\t\t\tUnpairedDups: 0,\n\t\t\t\t\t\tReadPairDups: 0,\n\t\t\t\t\t\tReadPairOpticalDups: 0,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t// Verify that we're counting dual-unmapped pairs\n\t\t\t[]*sam.Record{\n\t\t\t\tNewRecord(\"A:::1:10:1:1\", chr1, 0, r1F, 105, chr1, cigar0),\n\t\t\t\tNewRecord(\"A:::1:10:1:1\", chr1, 105, r2R, 0, chr1, cigar0),\n\t\t\t\tNewRecord(\"U:::2:11:1:1\", nil, -1, up1, -1, nil, cigar0),\n\t\t\t\tNewRecord(\"U:::2:11:1:1\", nil, -1, up2, -1, nil, cigar0),\n\t\t\t},\n\t\t\t&MetricsCollection{\n\t\t\t\tLibraryMetrics: map[string]*Metrics{\n\t\t\t\t\t\"Unknown Library\": &Metrics{\n\t\t\t\t\t\tUnpairedReads: 0,\n\t\t\t\t\t\tReadPairsExamined: 2,\n\t\t\t\t\t\tSecondarySupplementary: 0,\n\t\t\t\t\t\tUnmappedReads: 2,\n\t\t\t\t\t\tUnpairedDups: 0,\n\t\t\t\t\t\tReadPairDups: 0,\n\t\t\t\t\t\tReadPairOpticalDups: 0,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\ttempDir, cleanup := testutil.TempDir(t, \"\", \"\")\n\tdefer cleanup()\n\tfor testIdx, test := range tests {\n\t\tfor _, tagDups := range []bool{true, false} {\n\t\t\tfor _, format := range []string{\"bam\", \"pam\"} {\n\t\t\t\tt.Logf(\"---- starting tests[%d, %v] ----\", testIdx, tagDups)\n\t\t\t\tprovider := bamprovider.NewFakeProvider(header, test.records)\n\t\t\t\toutputPath := NewTestOutput(tempDir, testIdx, format)\n\t\t\t\topts := Opts{\n\t\t\t\t\tShardSize: 100,\n\t\t\t\t\tPadding: 10,\n\t\t\t\t\tParallelism: 1,\n\t\t\t\t\tQueueLength: 10,\n\t\t\t\t\tClearExisting: false,\n\t\t\t\t\tRemoveDups: false,\n\t\t\t\t\tTagDups: tagDups,\n\t\t\t\t\tEmitUnmodifiedFields: true,\n\t\t\t\t\tOutputPath: outputPath,\n\t\t\t\t\tFormat: format,\n\t\t\t\t\tOpticalDetector: &TileOpticalDetector{\n\t\t\t\t\t\tOpticalDistance: 2500,\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t\tmarkDuplicates := &MarkDuplicates{\n\t\t\t\t\tProvider: provider,\n\t\t\t\t\tOpts: &opts,\n\t\t\t\t}\n\t\t\t\tactualMetrics, err := markDuplicates.Mark(nil)\n\t\t\t\tassert.NoError(t, err)\n\n\t\t\t\tfor i, r := range ReadRecords(t, outputPath) {\n\t\t\t\t\tt.Logf(\"output[%v]: %v\", i, r)\n\t\t\t\t}\n\t\t\t\tassert.Equal(t, len(test.metrics.LibraryMetrics), len(actualMetrics.LibraryMetrics))\n\t\t\t\tfor k, m := range actualMetrics.LibraryMetrics {\n\t\t\t\t\tassert.Equal(t, *(test.metrics.LibraryMetrics[k]), *m)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func (s *GrpcServer) GetMetrics(ctx context.Context, in *api.ScaledObjectRef) (*v1beta1.ExternalMetricValueList, error) {\n\tv1beta1ExtMetrics := &v1beta1.ExternalMetricValueList{}\n\textMetrics, err := (*s.scalerHandler).GetScaledObjectMetrics(ctx, in.Name, in.Namespace, in.MetricName)\n\tif err != nil {\n\t\treturn v1beta1ExtMetrics, fmt.Errorf(\"error when getting metric values %w\", err)\n\t}\n\n\terr = v1beta1.Convert_external_metrics_ExternalMetricValueList_To_v1beta1_ExternalMetricValueList(extMetrics, v1beta1ExtMetrics, nil)\n\tif err != nil {\n\t\treturn v1beta1ExtMetrics, fmt.Errorf(\"error when converting metric values %w\", err)\n\t}\n\n\tlog.V(1).WithValues(\"scaledObjectName\", in.Name, \"scaledObjectNamespace\", in.Namespace, \"metrics\", v1beta1ExtMetrics).Info(\"Providing metrics\")\n\n\treturn v1beta1ExtMetrics, nil\n}", "func TestMetricTooMany(t *testing.T) { //nolint:maintidx\n\thelper := newHelper(t)\n\tdefer helper.Close()\n\n\thelper.preregisterAgent(t)\n\thelper.initSynchronizer(t)\n\n\tmetricResource, _ := helper.api.resources[mockAPIResourceMetric].(*genericResource)\n\tdefaultPatchHook := metricResource.PatchHook\n\n\t// API always reject more than 3 active metrics\n\tmetricResource.PatchHook = func(r *http.Request, body []byte, valuePtr interface{}, oldValue interface{}) error {\n\t\tif defaultPatchHook != nil {\n\t\t\terr := defaultPatchHook(r, body, valuePtr, oldValue)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\tmetric, _ := valuePtr.(*metricPayload)\n\n\t\tif metric.DeactivatedAt.IsZero() {\n\t\t\tmetrics := helper.MetricsFromAPI()\n\t\t\tcountActive := 0\n\n\t\t\tfor _, m := range metrics {\n\t\t\t\tif m.DeactivatedAt.IsZero() && m.ID != metric.ID {\n\t\t\t\t\tcountActive++\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif countActive >= 3 {\n\t\t\t\treturn clientError{\n\t\t\t\t\tbody: `{\"label\":[\"Too many non standard metrics\"]}`,\n\t\t\t\t\tstatusCode: http.StatusBadRequest,\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn nil\n\t}\n\n\tmetricResource.CreateHook = func(r *http.Request, body []byte, valuePtr interface{}) error {\n\t\treturn metricResource.PatchHook(r, body, valuePtr, nil)\n\t}\n\n\thelper.AddTime(time.Minute)\n\thelper.pushPoints(t, []labels.Labels{\n\t\tlabels.New(\n\t\t\tlabels.Label{Name: types.LabelName, Value: \"metric1\"},\n\t\t),\n\t\tlabels.New(\n\t\t\tlabels.Label{Name: types.LabelName, Value: \"metric2\"},\n\t\t),\n\t})\n\n\tif err := helper.runOnceWithResult(t).CheckMethodWithFull(syncMethodMetric); err != nil {\n\t\tt.Error(err)\n\t}\n\n\t// list active metrics, register agent_status + 2x metrics to register\n\thelper.api.AssertCallPerResource(t, mockAPIResourceMetric, 6)\n\n\tmetrics := helper.MetricsFromAPI()\n\tif len(metrics) != 3 { // 2 + agent_status\n\t\tt.Errorf(\"len(metrics) = %d, want 3\", len(metrics))\n\t}\n\n\thelper.AddTime(5 * time.Minute)\n\thelper.pushPoints(t, []labels.Labels{\n\t\tlabels.New(\n\t\t\tlabels.Label{Name: types.LabelName, Value: \"metric3\"},\n\t\t),\n\t\tlabels.New(\n\t\t\tlabels.Label{Name: types.LabelName, Value: \"metric4\"},\n\t\t),\n\t})\n\n\tif err := helper.runOnceWithResult(t).CheckMethodWithoutFull(syncMethodMetric); err != nil {\n\t\tt.Error(err)\n\t}\n\n\tif helper.api.ClientErrorCount == 0 {\n\t\tt.Errorf(\"We should have some client error, had %d\", helper.api.ClientErrorCount)\n\t}\n\n\t// list active metrics + 2x metrics to register\n\thelper.api.AssertCallPerResource(t, mockAPIResourceMetric, 5)\n\n\tmetrics = helper.MetricsFromAPI()\n\tif len(metrics) != 3 { // 2 + agent_status\n\t\tt.Errorf(\"len(metrics) = %d, want 3\", len(metrics))\n\t}\n\n\thelper.AddTime(5 * time.Minute)\n\n\tif err := helper.runOnceWithResult(t).CheckMethodNotRun(syncMethodMetric); err != nil {\n\t\tt.Error(err)\n\t}\n\n\thelper.SetTimeToNextFullSync()\n\t// drop all because normally store drop inactive metrics and\n\t// metric1 don't emitted for 70 minutes\n\thelper.store.DropAllMetrics()\n\thelper.pushPoints(t, []labels.Labels{\n\t\tlabels.New(\n\t\t\tlabels.Label{Name: types.LabelName, Value: \"metric2\"},\n\t\t),\n\t\tlabels.New(\n\t\t\tlabels.Label{Name: types.LabelName, Value: \"metric3\"},\n\t\t),\n\t\tlabels.New(\n\t\t\tlabels.Label{Name: types.LabelName, Value: \"metric4\"},\n\t\t),\n\t})\n\n\tif err := helper.runOnceWithResult(t).CheckMethodWithFull(syncMethodMetric); err != nil {\n\t\tt.Error(err)\n\t}\n\n\t// We need two sync: one to deactivate the metric, one to regsiter another one\n\thelper.AddTime(15 * time.Second)\n\n\tif err := helper.runOnceWithResult(t).CheckMethodWithoutFull(syncMethodMetric); err != nil {\n\t\tt.Error(err)\n\t}\n\n\tmetrics = helper.MetricsFromAPI()\n\tif len(metrics) != 4 { // metric1 is now disabled, another get registered\n\t\tt.Errorf(\"len(metrics) = %d, want 4\", len(metrics))\n\t}\n\n\tfor _, m := range metrics {\n\t\tif !m.DeactivatedAt.IsZero() && m.Name != \"metric1\" {\n\t\t\tt.Errorf(\"metric %s is deactivated, want active\", m.Name)\n\t\t}\n\n\t\tif m.DeactivatedAt.IsZero() && m.Name == \"metric1\" {\n\t\t\tt.Errorf(\"metric %s is active, want deactivated\", m.Name)\n\t\t}\n\t}\n\n\thelper.AddTime(5 * time.Minute)\n\thelper.pushPoints(t, []labels.Labels{\n\t\tlabels.New(\n\t\t\tlabels.Label{Name: types.LabelName, Value: \"metric1\"},\n\t\t),\n\t})\n\n\tif err := helper.runOnceWithResult(t).CheckMethodWithoutFull(syncMethodMetric); err != nil {\n\t\tt.Error(err)\n\t}\n\n\tif helper.api.ClientErrorCount == 0 {\n\t\tt.Errorf(\"We should have some client error, had %d\", helper.api.ClientErrorCount)\n\t}\n\n\tmetrics = helper.MetricsFromAPI()\n\tif len(metrics) != 4 { // metric1 is still disabled and no newly registered\n\t\tt.Errorf(\"len(metrics) = %d, want 4\", len(metrics))\n\t}\n\n\tfor _, m := range metrics {\n\t\tif !m.DeactivatedAt.IsZero() && m.Name != \"metric1\" {\n\t\t\tt.Errorf(\"metric %s is deactivated, want active\", m.Name)\n\t\t}\n\n\t\tif m.DeactivatedAt.IsZero() && m.Name == \"metric1\" {\n\t\t\tt.Errorf(\"metric %s is active, want deactivated\", m.Name)\n\t\t}\n\t}\n\n\t// We do not retry to register them\n\thelper.AddTime(5 * time.Minute)\n\n\tif err := helper.runOnceWithResult(t).CheckMethodNotRun(syncMethodMetric); err != nil {\n\t\tt.Error(err)\n\t}\n\n\t// Excepted ONE per full-sync\n\thelper.SetTimeToNextFullSync()\n\thelper.pushPoints(t, []labels.Labels{\n\t\tlabels.New(\n\t\t\tlabels.Label{Name: types.LabelName, Value: \"metric2\"},\n\t\t),\n\t\tlabels.New(\n\t\t\tlabels.Label{Name: types.LabelName, Value: \"metric3\"},\n\t\t),\n\t\tlabels.New(\n\t\t\tlabels.Label{Name: types.LabelName, Value: \"metric4\"},\n\t\t),\n\t})\n\n\tif err := helper.runOnceWithResult(t).CheckMethodWithFull(syncMethodMetric); err != nil {\n\t\tt.Error(err)\n\t}\n\n\tif helper.api.ClientErrorCount != 1 {\n\t\tt.Errorf(\"had %d client error, want 1\", helper.api.ClientErrorCount)\n\t}\n\n\tmetrics = helper.MetricsFromAPI()\n\tif len(metrics) != 4 {\n\t\tt.Errorf(\"len(metrics) = %d, want 4\", len(metrics))\n\t}\n\n\tfor _, m := range metrics {\n\t\tif !m.DeactivatedAt.IsZero() && m.Name != \"metric1\" {\n\t\t\tt.Errorf(\"metric %s is deactivated, want active\", m.Name)\n\t\t}\n\n\t\tif m.DeactivatedAt.IsZero() && m.Name == \"metric1\" {\n\t\t\tt.Errorf(\"metric %s is active, want deactivated\", m.Name)\n\t\t}\n\t}\n\n\t// list active metrics + check existence of the metric we want to reg +\n\t// retry to register\n\thelper.api.AssertCallPerResource(t, mockAPIResourceMetric, 3)\n}", "func (m *MockGeneralRepository) GetStats(network types.Network) (map[string]*models.NetworkStats, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetStats\", network)\n\tret0, _ := ret[0].(map[string]*models.NetworkStats)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (_m *MockBackend) Stats() (int, int, int) {\n\tret := _m.Called()\n\n\tvar r0 int\n\tif rf, ok := ret.Get(0).(func() int); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tr0 = ret.Get(0).(int)\n\t}\n\n\tvar r1 int\n\tif rf, ok := ret.Get(1).(func() int); ok {\n\t\tr1 = rf()\n\t} else {\n\t\tr1 = ret.Get(1).(int)\n\t}\n\n\tvar r2 int\n\tif rf, ok := ret.Get(2).(func() int); ok {\n\t\tr2 = rf()\n\t} else {\n\t\tr2 = ret.Get(2).(int)\n\t}\n\n\treturn r0, r1, r2\n}", "func RegisterMetrics() {\n\n\tprometheus.MustRegister(metrics.TiKVBackoffHistogram)\n\tprometheus.MustRegister(metrics.TiKVCoprocessorHistogram)\n\tprometheus.MustRegister(metrics.TiKVLoadSafepointCounter)\n\tprometheus.MustRegister(metrics.TiKVLockResolverCounter)\n\tprometheus.MustRegister(metrics.TiKVRawkvCmdHistogram)\n\tprometheus.MustRegister(metrics.TiKVRawkvSizeHistogram)\n\tprometheus.MustRegister(metrics.TiKVRegionCacheCounter)\n\tprometheus.MustRegister(metrics.TiKVRegionErrorCounter)\n\tprometheus.MustRegister(metrics.TiKVSecondaryLockCleanupFailureCounter)\n\tprometheus.MustRegister(metrics.TiKVSendReqHistogram)\n\tprometheus.MustRegister(metrics.TiKVTxnCmdHistogram)\n\tprometheus.MustRegister(metrics.TiKVTxnRegionsNumHistogram)\n\tprometheus.MustRegister(metrics.TiKVTxnWriteKVCountHistogram)\n\tprometheus.MustRegister(metrics.TiKVTxnWriteSizeHistogram)\n\tprometheus.MustRegister(metrics.TiKVLocalLatchWaitTimeHistogram)\n\tprometheus.MustRegister(metrics.TiKVPendingBatchRequests)\n\tprometheus.MustRegister(metrics.TiKVStatusDuration)\n\tprometheus.MustRegister(metrics.TiKVStatusCounter)\n\tprometheus.MustRegister(metrics.TiKVBatchWaitDuration)\n\tprometheus.MustRegister(metrics.TiKVBatchClientUnavailable)\n\tprometheus.MustRegister(metrics.TiKVRangeTaskStats)\n\tprometheus.MustRegister(metrics.TiKVRangeTaskPushDuration)\n\tprometheus.MustRegister(metrics.TiKVTokenWaitDuration)\n\tprometheus.MustRegister(metrics.TiKVTxnHeartBeatHistogram)\n\tprometheus.MustRegister(metrics.TiKVPessimisticLockKeysDuration)\n\tprometheus.MustRegister(metrics.TiKVTTLLifeTimeReachCounter)\n\tprometheus.MustRegister(metrics.TiKVNoAvailableConnectionCounter)\n\n\tprometheus.MustRegister(TSFutureWaitDuration)\n\n\t// grpc metrics\n\tprometheus.MustRegister(CreateSessionCounter)\n\tprometheus.MustRegister(DeleteSessionCounter)\n\tprometheus.MustRegister(ReadCounter)\n\tprometheus.MustRegister(SparseReadCounter)\n\tprometheus.MustRegister(StreamReadCounter)\n\tprometheus.MustRegister(CommitCounter)\n\tprometheus.MustRegister(MutateCounter)\n\tprometheus.MustRegister(ExecuteMutateDuration)\n\tprometheus.MustRegister(ExecuteReadDuration)\n\n\t// session metrics\n\tprometheus.MustRegister(SessionRetry)\n\tprometheus.MustRegister(SessionCounter)\n\tprometheus.MustRegister(SessionRetryErrorCounter)\n\tprometheus.MustRegister(TransactionCounter)\n\tprometheus.MustRegister(TransactionDuration)\n\tprometheus.MustRegister(SchemaLeaseErrorCounter)\n\n\t//tables metrics\n\tprometheus.MustRegister(FetchRowsCounter)\n\tprometheus.MustRegister(FetchSparseCounter)\n\tprometheus.MustRegister(FetchRowsDuration)\n\tprometheus.MustRegister(FetchSparseDuration)\n\n\tprometheus.MustRegister(ScanSparseCounter)\n\tprometheus.MustRegister(ScanSparseDuration)\n\n\tprometheus.MustRegister(BatchSparseCounter)\n\tprometheus.MustRegister(BatchSparseDuration)\n}", "func TestGetCPUStat(t *testing.T) {\n\t// setup the faking of `cpu.Info()`\n\toldcpuInfo := cpuInfo\n\tcpuInfo = func() ([]cpu.InfoStat, error) {\n\t\tret := []cpu.InfoStat{\n\t\t\t{\n\t\t\t\tVendorID: string(\"vendor\"),\n\t\t\t\tModelName: string(\"model\"),\n\t\t\t\tMhz: float64(100),\n\t\t\t},\n\t\t\t{\n\t\t\t\tVendorID: string(\"vendor\"), // two CPUs --> cpuinfo.count = \"2\"\n\t\t\t\tModelName: string(\"model\"),\n\t\t\t\tMhz: float64(100),\n\t\t\t},\n\t\t}\n\t\treturn ret, nil\n\t}\n\n\t// test\n\texpected := cpuStat{\n\t\tcount: strconv.FormatInt(2, 10),\n\t\tvendorID: \"vendor\",\n\t\tmodelName: \"model\",\n\t\tmhz: strconv.FormatInt(100, 10),\n\t}\n\tactual, err := getCPUStat()\n\n\tassert.NoError(t, err, \"`getCPUStat()` should not have returned an error\")\n\tassert.Equal(t, expected, actual, \"`getCPUStat()` should be equal to main.cpuStat{count:\\\"2\\\", vendorID:\\\"vendor\\\", modelName:\\\"model\\\", mhz:\\\"100\\\"}\")\n\n\t// teardown\n\tcpuInfo = oldcpuInfo\n}", "func (m *MockFullNode) NetBandwidthStats(arg0 context.Context) (metrics.Stats, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"NetBandwidthStats\", arg0)\n\tret0, _ := ret[0].(metrics.Stats)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (s *azureServiceBusScaler) GetMetrics(ctx context.Context, metricName string, metricSelector labels.Selector) ([]external_metrics.ExternalMetricValue, error) {\n\tqueuelen, err := s.GetAzureServiceBusLength(ctx)\n\n\tif err != nil {\n\t\tazureServiceBusLog.Error(err, \"error getting service bus entity length\")\n\t\treturn []external_metrics.ExternalMetricValue{}, err\n\t}\n\n\tmetric := external_metrics.ExternalMetricValue{\n\t\tMetricName: metricName,\n\t\tValue: *resource.NewQuantity(int64(queuelen), resource.DecimalSI),\n\t\tTimestamp: metav1.Now(),\n\t}\n\n\treturn append([]external_metrics.ExternalMetricValue{}, metric), nil\n}", "func NewMetrics(factory promutil.Factory) *Metrics {\n\treturn &Metrics{\n\t\tImporterEngineCounter: factory.NewCounterVec(\n\t\t\tprometheus.CounterOpts{\n\t\t\t\tNamespace: \"lightning\",\n\t\t\t\tName: \"importer_engine\",\n\t\t\t\tHelp: \"counting open and closed importer engines\",\n\t\t\t}, []string{\"type\"}),\n\n\t\tIdleWorkersGauge: factory.NewGaugeVec(\n\t\t\tprometheus.GaugeOpts{\n\t\t\t\tNamespace: \"lightning\",\n\t\t\t\tName: \"idle_workers\",\n\t\t\t\tHelp: \"counting idle workers\",\n\t\t\t}, []string{\"name\"}),\n\n\t\tKvEncoderCounter: factory.NewCounterVec(\n\t\t\tprometheus.CounterOpts{\n\t\t\t\tNamespace: \"lightning\",\n\t\t\t\tName: \"kv_encoder\",\n\t\t\t\tHelp: \"counting kv open and closed kv encoder\",\n\t\t\t}, []string{\"type\"}),\n\n\t\tTableCounter: factory.NewCounterVec(\n\t\t\tprometheus.CounterOpts{\n\t\t\t\tNamespace: \"lightning\",\n\t\t\t\tName: \"tables\",\n\t\t\t\tHelp: \"count number of tables processed\",\n\t\t\t}, []string{\"state\", \"result\"}),\n\n\t\tProcessedEngineCounter: factory.NewCounterVec(\n\t\t\tprometheus.CounterOpts{\n\t\t\t\tNamespace: \"lightning\",\n\t\t\t\tName: \"engines\",\n\t\t\t\tHelp: \"count number of engines processed\",\n\t\t\t}, []string{\"state\", \"result\"}),\n\n\t\tChunkCounter: factory.NewCounterVec(\n\t\t\tprometheus.CounterOpts{\n\t\t\t\tNamespace: \"lightning\",\n\t\t\t\tName: \"chunks\",\n\t\t\t\tHelp: \"count number of chunks processed\",\n\t\t\t}, []string{\"state\"}),\n\n\t\tBytesCounter: factory.NewCounterVec(\n\t\t\tprometheus.CounterOpts{\n\t\t\t\tNamespace: \"lightning\",\n\t\t\t\tName: \"bytes\",\n\t\t\t\tHelp: \"count of total bytes\",\n\t\t\t}, []string{\"state\"}),\n\t\t// state can be one of:\n\t\t// - estimated (an estimation derived from the file size)\n\t\t// - pending\n\t\t// - running\n\t\t// - finished\n\t\t// - failed\n\n\t\tRowsCounter: factory.NewCounterVec(\n\t\t\tprometheus.CounterOpts{\n\t\t\t\tNamespace: \"lightning\",\n\t\t\t\tName: \"rows\",\n\t\t\t\tHelp: \"count of total rows\",\n\t\t\t}, []string{\"state\", \"table\"}),\n\n\t\tImportSecondsHistogram: factory.NewHistogram(\n\t\t\tprometheus.HistogramOpts{\n\t\t\t\tNamespace: \"lightning\",\n\t\t\t\tName: \"import_seconds\",\n\t\t\t\tHelp: \"time needed to import a table\",\n\t\t\t\tBuckets: prometheus.ExponentialBuckets(0.125, 2, 6),\n\t\t\t}),\n\n\t\tChunkParserReadBlockSecondsHistogram: factory.NewHistogram(\n\t\t\tprometheus.HistogramOpts{\n\t\t\t\tNamespace: \"lightning\",\n\t\t\t\tName: \"chunk_parser_read_block_seconds\",\n\t\t\t\tHelp: \"time needed for chunk parser read a block\",\n\t\t\t\tBuckets: prometheus.ExponentialBuckets(0.001, 3.1622776601683795, 10),\n\t\t\t}),\n\n\t\tApplyWorkerSecondsHistogram: factory.NewHistogramVec(\n\t\t\tprometheus.HistogramOpts{\n\t\t\t\tNamespace: \"lightning\",\n\t\t\t\tName: \"apply_worker_seconds\",\n\t\t\t\tHelp: \"time needed to apply a worker\",\n\t\t\t\tBuckets: prometheus.ExponentialBuckets(0.001, 3.1622776601683795, 10),\n\t\t\t}, []string{\"name\"}),\n\n\t\tRowReadSecondsHistogram: factory.NewHistogram(\n\t\t\tprometheus.HistogramOpts{\n\t\t\t\tNamespace: \"lightning\",\n\t\t\t\tName: \"row_read_seconds\",\n\t\t\t\tHelp: \"time needed to parse a row\",\n\t\t\t\tBuckets: prometheus.ExponentialBuckets(0.001, 3.1622776601683795, 7),\n\t\t\t}),\n\n\t\tRowReadBytesHistogram: factory.NewHistogram(\n\t\t\tprometheus.HistogramOpts{\n\t\t\t\tNamespace: \"lightning\",\n\t\t\t\tName: \"row_read_bytes\",\n\t\t\t\tHelp: \"number of bytes being read out from data source\",\n\t\t\t\tBuckets: prometheus.ExponentialBuckets(1024, 2, 8),\n\t\t\t}),\n\n\t\tRowEncodeSecondsHistogram: factory.NewHistogram(\n\t\t\tprometheus.HistogramOpts{\n\t\t\t\tNamespace: \"lightning\",\n\t\t\t\tName: \"row_encode_seconds\",\n\t\t\t\tHelp: \"time needed to encode a row\",\n\t\t\t\tBuckets: prometheus.ExponentialBuckets(0.001, 3.1622776601683795, 10),\n\t\t\t}),\n\t\tRowKVDeliverSecondsHistogram: factory.NewHistogram(\n\t\t\tprometheus.HistogramOpts{\n\t\t\t\tNamespace: \"lightning\",\n\t\t\t\tName: \"row_kv_deliver_seconds\",\n\t\t\t\tHelp: \"time needed to deliver kvs of a single row\",\n\t\t\t\tBuckets: prometheus.ExponentialBuckets(0.001, 3.1622776601683795, 10),\n\t\t\t}),\n\n\t\tBlockDeliverSecondsHistogram: factory.NewHistogram(\n\t\t\tprometheus.HistogramOpts{\n\t\t\t\tNamespace: \"lightning\",\n\t\t\t\tName: \"block_deliver_seconds\",\n\t\t\t\tHelp: \"time needed to deliver a block\",\n\t\t\t\tBuckets: prometheus.ExponentialBuckets(0.001, 3.1622776601683795, 10),\n\t\t\t}),\n\t\tBlockDeliverBytesHistogram: factory.NewHistogramVec(\n\t\t\tprometheus.HistogramOpts{\n\t\t\t\tNamespace: \"lightning\",\n\t\t\t\tName: \"block_deliver_bytes\",\n\t\t\t\tHelp: \"number of bytes being sent out to importer\",\n\t\t\t\tBuckets: prometheus.ExponentialBuckets(512, 2, 10),\n\t\t\t}, []string{\"kind\"}),\n\t\tBlockDeliverKVPairsHistogram: factory.NewHistogramVec(\n\t\t\tprometheus.HistogramOpts{\n\t\t\t\tNamespace: \"lightning\",\n\t\t\t\tName: \"block_deliver_kv_pairs\",\n\t\t\t\tHelp: \"number of KV pairs being sent out to importer\",\n\t\t\t\tBuckets: prometheus.ExponentialBuckets(1, 2, 10),\n\t\t\t}, []string{\"kind\"}),\n\t\tChecksumSecondsHistogram: factory.NewHistogram(\n\t\t\tprometheus.HistogramOpts{\n\t\t\t\tNamespace: \"lightning\",\n\t\t\t\tName: \"checksum_seconds\",\n\t\t\t\tHelp: \"time needed to complete the checksum stage\",\n\t\t\t\tBuckets: prometheus.ExponentialBuckets(1, 2.2679331552660544, 10),\n\t\t\t}),\n\t\tSSTSecondsHistogram: factory.NewHistogramVec(\n\t\t\tprometheus.HistogramOpts{\n\t\t\t\tNamespace: \"lightning\",\n\t\t\t\tName: \"sst_seconds\",\n\t\t\t\tHelp: \"time needed to complete the sst operations\",\n\t\t\t\tBuckets: prometheus.ExponentialBuckets(1, 2.2679331552660544, 10),\n\t\t\t}, []string{\"kind\"}),\n\n\t\tLocalStorageUsageBytesGauge: factory.NewGaugeVec(\n\t\t\tprometheus.GaugeOpts{\n\t\t\t\tNamespace: \"lightning\",\n\t\t\t\tName: \"local_storage_usage_bytes\",\n\t\t\t\tHelp: \"disk/memory size currently occupied by intermediate files in local backend\",\n\t\t\t}, []string{\"medium\"}),\n\n\t\tProgressGauge: factory.NewGaugeVec(\n\t\t\tprometheus.GaugeOpts{\n\t\t\t\tNamespace: \"lightning\",\n\t\t\t\tName: \"progress\",\n\t\t\t\tHelp: \"progress of lightning phase\",\n\t\t\t}, []string{\"phase\"}),\n\t}\n}", "func (m *MockIMutantRepository) GetStatsFromCache() *models.MutantsStats {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetStatsFromCache\")\n\tret0, _ := ret[0].(*models.MutantsStats)\n\treturn ret0\n}", "func NewMetrics(consume ConsumeMetricsFunc, options ...Option) (consumer.Metrics, error) {\n\tif consume == nil {\n\t\treturn nil, errNilFunc\n\t}\n\treturn &baseMetrics{\n\t\tbaseConsumer: newBaseConsumer(options...),\n\t\tConsumeMetricsFunc: consume,\n\t}, nil\n}" ]
[ "0.7650577", "0.7016764", "0.70125824", "0.6981954", "0.69156355", "0.68423605", "0.6705235", "0.6613567", "0.6547792", "0.64580333", "0.63285154", "0.63118887", "0.624346", "0.6230752", "0.61920655", "0.6130787", "0.6118216", "0.6095558", "0.60732526", "0.6055256", "0.60451156", "0.60406727", "0.6039367", "0.60160184", "0.5988926", "0.59400934", "0.5917193", "0.58818036", "0.58630484", "0.58616287", "0.5838285", "0.58213055", "0.5820539", "0.58078825", "0.5804123", "0.5802292", "0.57988465", "0.5795632", "0.57846844", "0.57703453", "0.5741666", "0.5727525", "0.57143813", "0.571075", "0.5704046", "0.57003546", "0.56960887", "0.56942385", "0.568245", "0.56797117", "0.5678851", "0.567784", "0.56768817", "0.5676756", "0.56748635", "0.565278", "0.5647898", "0.564218", "0.5637814", "0.5631854", "0.56263345", "0.5617829", "0.56062144", "0.56024", "0.55926204", "0.559074", "0.559074", "0.55776936", "0.5576679", "0.5576555", "0.55704737", "0.55703855", "0.5567151", "0.55632174", "0.556168", "0.5558797", "0.55368197", "0.5531239", "0.552203", "0.55211157", "0.55211157", "0.55211157", "0.55211157", "0.55211157", "0.55196977", "0.5515768", "0.5498938", "0.5493261", "0.5485738", "0.54848814", "0.5481429", "0.54637814", "0.546021", "0.54598784", "0.545601", "0.54480004", "0.54472166", "0.544694", "0.54467046", "0.5445243" ]
0.6813142
6
GetMetrics indicates an expected call of GetMetrics
func (mr *MockClientMockRecorder) GetMetrics() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetMetrics", reflect.TypeOf((*MockClient)(nil).GetMetrics)) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (mr *MockTaskManagerMockRecorder) GetMetrics() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetMetrics\", reflect.TypeOf((*MockTaskManager)(nil).GetMetrics))\n}", "func testMetrics(expected map[string]int, m *Metrics) error {\n\te := &firstErr{}\n\tfor name, cnt := range expected {\n\t\tswitch name {\n\t\tcase \"incoming\":\n\t\t\te.testCounter(m.Incoming, name, cnt)\n\t\tcase \"fragments\":\n\t\t\te.testCounter(m.Fragments, name, cnt)\n\t\tcase \"defrag\":\n\t\t\te.testCounter(m.Defrag, name, cnt)\n\t\tcase \"invalid\":\n\t\t\te.testCounter(m.Invalid, name, cnt)\n\t\tcase \"seen:udp\":\n\t\t\te.testCounter(m.Seen.WithLabelValues(\"udp\"), name, cnt)\n\t\tcase \"seen:tcp\":\n\t\t\te.testCounter(m.Seen.WithLabelValues(\"tcp\"), name, cnt)\n\t\tcase \"captured:udp\":\n\t\t\te.testCounter(m.Captured.WithLabelValues(\"udp\"), name, cnt)\n\t\tcase \"captured:tcp\":\n\t\t\te.testCounter(m.Captured.WithLabelValues(\"tcp\"), name, cnt)\n\t\tdefault:\n\t\t\te.err = fmt.Errorf(\"don't know field %v\", name)\n\t\t}\n\t}\n\treturn e.err\n}", "func (_e *MockDataCoord_Expecter) GetMetrics(ctx interface{}, req interface{}) *MockDataCoord_GetMetrics_Call {\n\treturn &MockDataCoord_GetMetrics_Call{Call: _e.mock.On(\"GetMetrics\", ctx, req)}\n}", "func (mr *MockProvidersMockRecorder) GetMetrics() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetMetrics\", reflect.TypeOf((*MockProviders)(nil).GetMetrics))\n}", "func (_e *MockQueryCoord_Expecter) GetMetrics(ctx interface{}, req interface{}) *MockQueryCoord_GetMetrics_Call {\n\treturn &MockQueryCoord_GetMetrics_Call{Call: _e.mock.On(\"GetMetrics\", ctx, req)}\n}", "func (o *MonitorSearchResult) GetMetricsOk() (*[]string, bool) {\n\tif o == nil || o.Metrics == nil {\n\t\treturn nil, false\n\t}\n\treturn &o.Metrics, true\n}", "func (o *MetricsAllOf) GetMetricsOk() (*[]Metric, bool) {\n\tif o == nil || o.Metrics == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Metrics, true\n}", "func TestGetMetrics(t *testing.T) {\n\n\t//\t\tCreating mock request with custom params\n\t//\t\tand checking for error\n\trequest, err := http.NewRequest(\"GET\", \"/fizzbuzz-metrics\", nil)\n\tif err != nil {\n\t\tt.Errorf(\"GetMetrics() failed because of bad request: %v\", err)\n\t}\n\n\t//\t\tCreating a HTTP recorder for the test\n\trecorder := httptest.NewRecorder()\n\n\t//\t\tHitting endpoint\n\trouter := httprouter.New()\n\trouter.GET(\"/fizzbuzz-metrics\", GetMetrics)\n\trouter.ServeHTTP(recorder, request)\n\n\t//\t\tCheck status code\n\tif recorder.Code != http.StatusOK {\n\t\tt.Errorf(\"GetMetrics() failed because of status code: got %v instead of %v\", recorder.Code, http.StatusOK)\n\t}\n\n\t//\t\tCheck body\n\tgot := recorder.Body.String()\n\tif got == \"\" {\n\t\tt.Error(\"GetMetrics() failed because of empty body.\")\n\t}\n}", "func TestGetMetrics(t *testing.T) {\n\t// set up test server and mocked LogStore\n\tmockLogStore := new(MockedLogStore)\n\tserver := newTestServer(mockLogStore)\n\ttestServer := httptest.NewServer(server.server.Handler)\n\tdefer testServer.Close()\n\tclient := testServer.Client()\n\n\t// Make a first call to a resource to make metrics middleware record some\n\t// stats. Prior to that, no stats will have been saved.\n\tresp, _ := client.Get(testServer.URL + \"/metrics\")\n\trequire.Equalf(t, http.StatusOK, resp.StatusCode, \"unexpected status code\")\n\trequire.Equalf(t, \"\", readBody(t, resp), \"expected first /metrics call to be empty\")\n\n\tresp, _ = client.Get(testServer.URL + \"/metrics\")\n\trequire.Equalf(t, http.StatusOK, resp.StatusCode, \"unexpected status code\")\n\trequire.Containsf(t, readBody(t, resp), `total_requests{method=\"GET\",path=\"/metrics\",statusCode=\"200\"} 1`, \"missing expected metric\")\n}", "func Test_CollectMetrics10(t *testing.T) {\n\tassert := assert.New(t)\n\tconfig := getTestConfig(1, 0)\n\tconfig.DataFunc = config.GetTestData1\n\n\tres := config.CollectMetrics()\n\tassert.Nil(res)\n}", "func (o *DeviceMetricsAllOf) GetMetricsOk() (*[]DeviceMetric, bool) {\n\tif o == nil || o.Metrics == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Metrics, true\n}", "func Test_CollectMetrics21(t *testing.T) {\n\tassert := assert.New(t)\n\tconfig := getTestConfig(2, 1)\n\tconfig.DataFunc = config.GetTestData1\n\n\tres := config.CollectMetrics()\n\tfmt.Println(\"21: \", res)\n\tfmt.Println(\"21: \", []cmd.MetricData{{Name: \"m1\", Help: \"h1\", MetricType: \"gauge\", Stats: []cmd.MetricRecord{{Value: 999, Labels: []string{\"l00\"}, LabelValues: []string{\"lv00\"}}}}, {Name: \"m2\", Help: \"h2\", MetricType: \"gauge\", Stats: []cmd.MetricRecord{{Value: 999, Labels: []string{\"l10\"}, LabelValues: []string{\"lv10\"}}}}})\n\tassert.Equal(true, cmp.Equal(res, []cmd.MetricData{{Name: \"m1\", Help: \"h1\", MetricType: \"gauge\", Stats: []cmd.MetricRecord{{Value: 999, Labels: []string{\"l00\"}, LabelValues: []string{\"lv00\"}}}}, {Name: \"m2\", Help: \"h2\", MetricType: \"gauge\", Stats: []cmd.MetricRecord{{Value: 999, Labels: []string{\"l10\"}, LabelValues: []string{\"lv10\"}}}}}))\n}", "func Test_CollectMetrics01(t *testing.T) {\n\tassert := assert.New(t)\n\tconfig := getTestConfig(0, 1)\n\tconfig.DataFunc = config.GetTestData1\n\n\tres := config.CollectMetrics()\n\tassert.Nil(res)\n}", "func TestMetrics(t *testing.T) {\n\tctx := context.Background()\n\tvar err error\n\n\t// Check metrics-server deployment is ready.\n\terr = checkReadyDeployment(ctx)\n\tif err != nil {\n\t\tt.Fatalf(\"could not get metrics: %v\", err)\n\t}\n\n\t// Check metrics availability.\n\terr = checkMetricsAvailability(ctx)\n\tif err != nil {\n\t\tt.Fatalf(\"could not get metrics: %v\", err)\n\t}\n}", "func Test_CollectMetrics12(t *testing.T) {\n\tassert := assert.New(t)\n\tconfig := getTestConfig(1, 2)\n\tconfig.DataFunc = config.GetTestData1\n\n\tres := config.CollectMetrics()\n\tfmt.Println(\"12: \", res)\n\tfmt.Println(\"12: \", []cmd.MetricData{{Name: \"m1\", Help: \"h1\", MetricType: \"gauge\", Stats: []cmd.MetricRecord{{Value: 999, Labels: []string{\"l01\"}, LabelValues: []string{\"lv01\"}}, {Value: 999, Labels: []string{\"l00\"}, LabelValues: []string{\"lv00\"}}}}})\n\tassert.Equal(true, cmp.Equal(res, []cmd.MetricData{{Name: \"m1\", Help: \"h1\", MetricType: \"gauge\", Stats: []cmd.MetricRecord{{Value: 999, Labels: []string{\"l01\"}, LabelValues: []string{\"lv01\"}}, {Value: 999, Labels: []string{\"l00\"}, LabelValues: []string{\"lv00\"}}}}}))\n}", "func Test_CollectMetrics11(t *testing.T) {\n\tassert := assert.New(t)\n\tconfig := getTestConfig(1, 1)\n\tconfig.DataFunc = config.GetTestData1\n\n\tres := config.CollectMetrics()\n\t// assert.Nil(res)\n\tassert.Equal(res, []cmd.MetricData{{Name: \"m1\", Help: \"h1\", MetricType: \"gauge\", Stats: []cmd.MetricRecord{{Value: 999, Labels: []string{\"l00\"}, LabelValues: []string{\"lv00\"}}}}})\n}", "func (mr *MockFlowAggregatorQuerierMockRecorder) GetRecordMetrics() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetRecordMetrics\", reflect.TypeOf((*MockFlowAggregatorQuerier)(nil).GetRecordMetrics))\n}", "func (mr *MockKairosDBClientMockRecorder) QueryMetrics(ctx, dsInfo, request interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"QueryMetrics\", reflect.TypeOf((*MockKairosDBClient)(nil).QueryMetrics), ctx, dsInfo, request)\n}", "func LoadExpectedMetrics(t *testing.T, model string) []string {\n\tt.Helper()\n\tdcgmNameToMetricNameMap := map[string]string{\n\t\t\"DCGM_FI_DEV_GPU_UTIL\": \"dcgm.gpu.utilization\",\n\t\t\"DCGM_FI_DEV_FB_USED\": \"dcgm.gpu.memory.bytes_used\",\n\t\t\"DCGM_FI_DEV_FB_FREE\": \"dcgm.gpu.memory.bytes_free\",\n\t\t\"DCGM_FI_PROF_SM_ACTIVE\": \"dcgm.gpu.profiling.sm_utilization\",\n\t\t\"DCGM_FI_PROF_SM_OCCUPANCY\": \"dcgm.gpu.profiling.sm_occupancy\",\n\t\t\"DCGM_FI_PROF_PIPE_TENSOR_ACTIVE\": \"dcgm.gpu.profiling.tensor_utilization\",\n\t\t\"DCGM_FI_PROF_DRAM_ACTIVE\": \"dcgm.gpu.profiling.dram_utilization\",\n\t\t\"DCGM_FI_PROF_PIPE_FP64_ACTIVE\": \"dcgm.gpu.profiling.fp64_utilization\",\n\t\t\"DCGM_FI_PROF_PIPE_FP32_ACTIVE\": \"dcgm.gpu.profiling.fp32_utilization\",\n\t\t\"DCGM_FI_PROF_PIPE_FP16_ACTIVE\": \"dcgm.gpu.profiling.fp16_utilization\",\n\t\t\"DCGM_FI_PROF_PCIE_TX_BYTES\": \"dcgm.gpu.profiling.pcie_sent_bytes\",\n\t\t\"DCGM_FI_PROF_PCIE_RX_BYTES\": \"dcgm.gpu.profiling.pcie_received_bytes\",\n\t\t\"DCGM_FI_PROF_NVLINK_TX_BYTES\": \"dcgm.gpu.profiling.nvlink_sent_bytes\",\n\t\t\"DCGM_FI_PROF_NVLINK_RX_BYTES\": \"dcgm.gpu.profiling.nvlink_received_bytes\",\n\t}\n\tgoldenPath := getModelGoldenFilePath(t, model)\n\tgoldenFile, err := ioutil.ReadFile(goldenPath)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tvar m modelSupportedFields\n\terr = yaml.Unmarshal(goldenFile, &m)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tvar expectedMetrics []string\n\tfor _, supported := range m.SupportedFields {\n\t\texpectedMetrics = append(expectedMetrics, dcgmNameToMetricNameMap[supported])\n\t}\n\treturn expectedMetrics\n}", "func (m *MockTaskManager) GetMetrics() handler.Metric {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetMetrics\")\n\tret0, _ := ret[0].(handler.Metric)\n\treturn ret0\n}", "func TestMssql_GetMetrics_ItemDoesntExist_Successful(t *testing.T) {\n\n\tif runtime.GOOS != \"windows\" {\n\t\tt.Skip(\"Skipping MSSQL tests: Not on Windows\")\n\t}\n\n\t//\tArrange\n\tdb := getMSSQLDBConnection()\n\tt.Logf(\"Using - server: %v / database: %v / user: %v / password: %v\", db.Server, db.Database, db.User, db.Password)\n\n\t//\tAct\n\tresponse, err := db.GetMetrics()\n\n\t//\tAssert\n\tif err != nil {\n\t\tt.Errorf(\"GetMetrics failed: %v\", err)\n\t}\n\n\tfor _, nlogItem := range response {\n\t\tlog.Printf(\"[DEBUG] NLogItem found: %v %v %v\", nlogItem.Application, nlogItem.LogLevel, nlogItem.Count)\n\t}\n}", "func (o *EnvironmentUsageDto) GetCustomMetricsOk() (*[]CustomMetricDto, bool) {\n\tif o == nil || o.CustomMetrics == nil {\n\t\treturn nil, false\n\t}\n\treturn o.CustomMetrics, true\n}", "func TestMetrics(t *testing.T) {\n\t// Notes that ReadPairsExamined, ReadPairDups, and\n\t// ReadPairOpticalDups below are doubled because they are halved\n\t// when written to the metrics file.\n\ttests := []struct {\n\t\trecords []*sam.Record\n\t\tmetrics *MetricsCollection\n\t}{\n\t\t{\n\t\t\t[]*sam.Record{\n\t\t\t\tNewRecord(\"A:::1:10:1:1\", chr1, 0, r1F, 10, chr1, cigar0),\n\t\t\t\tNewRecord(\"A:::1:10:1:1\", chr1, 10, r2R, 0, chr1, cigar0),\n\t\t\t},\n\t\t\t&MetricsCollection{\n\t\t\t\tLibraryMetrics: map[string]*Metrics{\n\t\t\t\t\t\"Unknown Library\": &Metrics{\n\t\t\t\t\t\tUnpairedReads: 0,\n\t\t\t\t\t\tReadPairsExamined: 2,\n\t\t\t\t\t\tSecondarySupplementary: 0,\n\t\t\t\t\t\tUnmappedReads: 0,\n\t\t\t\t\t\tUnpairedDups: 0,\n\t\t\t\t\t\tReadPairDups: 0,\n\t\t\t\t\t\tReadPairOpticalDups: 0,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t[]*sam.Record{\n\t\t\t\tNewRecord(\"A:::1:10:1:1\", chr1, 0, r1F, 10, chr1, cigar0),\n\t\t\t\tNewRecord(\"B:::2:10:1:1\", chr1, 0, r1F, 10, chr1, cigar0),\n\t\t\t\tNewRecord(\"A:::1:10:1:1\", chr1, 10, r2R, 0, chr1, cigar0),\n\t\t\t\tNewRecord(\"B:::2:10:1:1\", chr1, 10, r2R, 0, chr1, cigar0),\n\t\t\t},\n\t\t\t&MetricsCollection{\n\t\t\t\tLibraryMetrics: map[string]*Metrics{\n\t\t\t\t\t\"Unknown Library\": &Metrics{\n\t\t\t\t\t\tUnpairedReads: 0,\n\t\t\t\t\t\tReadPairsExamined: 4,\n\t\t\t\t\t\tSecondarySupplementary: 0,\n\t\t\t\t\t\tUnmappedReads: 0,\n\t\t\t\t\t\tUnpairedDups: 0,\n\t\t\t\t\t\tReadPairDups: 2,\n\t\t\t\t\t\tReadPairOpticalDups: 0,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t[]*sam.Record{\n\t\t\t\tNewRecord(\"A:::1:10:1:1\", chr1, 0, r1F, 10, chr1, cigar0),\n\t\t\t\tNewRecord(\"B:::2:11:1:1\", chr1, 0, r1F, 10, chr1, cigar0),\n\t\t\t\tNewRecord(\"C:::2:11:1:1\", chr1, 0, r1F, 10, chr1, cigar0),\n\t\t\t\tNewRecord(\"A:::1:10:1:1\", chr1, 10, r2R, 0, chr1, cigar0),\n\t\t\t\tNewRecord(\"B:::2:11:1:1\", chr1, 10, r2R, 0, chr1, cigar0),\n\t\t\t\tNewRecord(\"C:::2:11:1:1\", chr1, 10, r2R, 0, chr1, cigar0),\n\t\t\t},\n\t\t\t&MetricsCollection{\n\t\t\t\tLibraryMetrics: map[string]*Metrics{\n\t\t\t\t\t\"Unknown Library\": &Metrics{\n\t\t\t\t\t\tUnpairedReads: 0,\n\t\t\t\t\t\tReadPairsExamined: 6,\n\t\t\t\t\t\tSecondarySupplementary: 0,\n\t\t\t\t\t\tUnmappedReads: 0,\n\t\t\t\t\t\tUnpairedDups: 0,\n\t\t\t\t\t\tReadPairDups: 4,\n\t\t\t\t\t\tReadPairOpticalDups: 2,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t[]*sam.Record{\n\t\t\t\tNewRecord(\"A:::1:10:1:1\", chr1, 0, s1F, 0, nil, cigar0),\n\t\t\t\tNewRecord(\"A:::1:10:1:1\", chr1, 0, u2, 0, nil, cigar0),\n\t\t\t\tNewRecord(\"B:::2:10:1:1\", chr1, 0, s1F, 0, nil, cigar0),\n\t\t\t\tNewRecord(\"B:::2:10:1:1\", chr1, 0, u2, 0, nil, cigar0),\n\t\t\t},\n\t\t\t&MetricsCollection{\n\t\t\t\tLibraryMetrics: map[string]*Metrics{\n\t\t\t\t\t\"Unknown Library\": &Metrics{\n\t\t\t\t\t\tUnpairedReads: 2,\n\t\t\t\t\t\tReadPairsExamined: 0,\n\t\t\t\t\t\tSecondarySupplementary: 0,\n\t\t\t\t\t\tUnmappedReads: 2,\n\t\t\t\t\t\tUnpairedDups: 1,\n\t\t\t\t\t\tReadPairDups: 0,\n\t\t\t\t\t\tReadPairOpticalDups: 0,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t// Cross-shard pairs\n\t\t\t[]*sam.Record{\n\t\t\t\tNewRecord(\"A:::1:10:1:1\", chr1, 0, r1F, 105, chr1, cigar0),\n\t\t\t\tNewRecord(\"B:::1:10:1:1\", chr1, 0, r1F, 105, chr1, cigar0),\n\t\t\t\tNewRecord(\"A:::1:10:1:1\", chr1, 105, r2R, 0, chr1, cigar0),\n\t\t\t\tNewRecord(\"B:::1:10:1:1\", chr1, 105, r2R, 0, chr1, cigar0),\n\t\t\t},\n\t\t\t&MetricsCollection{\n\t\t\t\tLibraryMetrics: map[string]*Metrics{\n\t\t\t\t\t\"Unknown Library\": &Metrics{\n\t\t\t\t\t\tUnpairedReads: 0,\n\t\t\t\t\t\tReadPairsExamined: 4,\n\t\t\t\t\t\tSecondarySupplementary: 0,\n\t\t\t\t\t\tUnmappedReads: 0,\n\t\t\t\t\t\tUnpairedDups: 0,\n\t\t\t\t\t\tReadPairDups: 2,\n\t\t\t\t\t\tReadPairOpticalDups: 2,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t// Secondary alignments.\n\t\t\t[]*sam.Record{\n\t\t\t\tNewRecord(\"A:::1:10:1:1\", chr1, 0, r1F, 105, chr1, cigar0),\n\t\t\t\tNewRecord(\"A:::1:10:1:1\", chr1, 105, r2R, 0, chr1, cigar0),\n\t\t\t\tNewRecord(\"A:::1:10:1:1\", chr2, 12, sec, 105, chr1, cigar0),\n\t\t\t},\n\t\t\t&MetricsCollection{\n\t\t\t\tLibraryMetrics: map[string]*Metrics{\n\t\t\t\t\t\"Unknown Library\": &Metrics{\n\t\t\t\t\t\tUnpairedReads: 0,\n\t\t\t\t\t\tReadPairsExamined: 2,\n\t\t\t\t\t\tSecondarySupplementary: 1,\n\t\t\t\t\t\tUnmappedReads: 0,\n\t\t\t\t\t\tUnpairedDups: 0,\n\t\t\t\t\t\tReadPairDups: 0,\n\t\t\t\t\t\tReadPairOpticalDups: 0,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t// Verify that we're counting dual-unmapped pairs\n\t\t\t[]*sam.Record{\n\t\t\t\tNewRecord(\"A:::1:10:1:1\", chr1, 0, r1F, 105, chr1, cigar0),\n\t\t\t\tNewRecord(\"A:::1:10:1:1\", chr1, 105, r2R, 0, chr1, cigar0),\n\t\t\t\tNewRecord(\"U:::2:11:1:1\", nil, -1, up1, -1, nil, cigar0),\n\t\t\t\tNewRecord(\"U:::2:11:1:1\", nil, -1, up2, -1, nil, cigar0),\n\t\t\t},\n\t\t\t&MetricsCollection{\n\t\t\t\tLibraryMetrics: map[string]*Metrics{\n\t\t\t\t\t\"Unknown Library\": &Metrics{\n\t\t\t\t\t\tUnpairedReads: 0,\n\t\t\t\t\t\tReadPairsExamined: 2,\n\t\t\t\t\t\tSecondarySupplementary: 0,\n\t\t\t\t\t\tUnmappedReads: 2,\n\t\t\t\t\t\tUnpairedDups: 0,\n\t\t\t\t\t\tReadPairDups: 0,\n\t\t\t\t\t\tReadPairOpticalDups: 0,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\ttempDir, cleanup := testutil.TempDir(t, \"\", \"\")\n\tdefer cleanup()\n\tfor testIdx, test := range tests {\n\t\tfor _, tagDups := range []bool{true, false} {\n\t\t\tfor _, format := range []string{\"bam\", \"pam\"} {\n\t\t\t\tt.Logf(\"---- starting tests[%d, %v] ----\", testIdx, tagDups)\n\t\t\t\tprovider := bamprovider.NewFakeProvider(header, test.records)\n\t\t\t\toutputPath := NewTestOutput(tempDir, testIdx, format)\n\t\t\t\topts := Opts{\n\t\t\t\t\tShardSize: 100,\n\t\t\t\t\tPadding: 10,\n\t\t\t\t\tParallelism: 1,\n\t\t\t\t\tQueueLength: 10,\n\t\t\t\t\tClearExisting: false,\n\t\t\t\t\tRemoveDups: false,\n\t\t\t\t\tTagDups: tagDups,\n\t\t\t\t\tEmitUnmodifiedFields: true,\n\t\t\t\t\tOutputPath: outputPath,\n\t\t\t\t\tFormat: format,\n\t\t\t\t\tOpticalDetector: &TileOpticalDetector{\n\t\t\t\t\t\tOpticalDistance: 2500,\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t\tmarkDuplicates := &MarkDuplicates{\n\t\t\t\t\tProvider: provider,\n\t\t\t\t\tOpts: &opts,\n\t\t\t\t}\n\t\t\t\tactualMetrics, err := markDuplicates.Mark(nil)\n\t\t\t\tassert.NoError(t, err)\n\n\t\t\t\tfor i, r := range ReadRecords(t, outputPath) {\n\t\t\t\t\tt.Logf(\"output[%v]: %v\", i, r)\n\t\t\t\t}\n\t\t\t\tassert.Equal(t, len(test.metrics.LibraryMetrics), len(actualMetrics.LibraryMetrics))\n\t\t\t\tfor k, m := range actualMetrics.LibraryMetrics {\n\t\t\t\t\tassert.Equal(t, *(test.metrics.LibraryMetrics[k]), *m)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func ExpectMetrics(t Validator, mt *metricTable, expect []WantMetric) {\n\tif len(mt.metrics) != len(expect) {\n\t\tt.Error(\"metric counts do not match expectations\", len(mt.metrics), len(expect))\n\t}\n\texpectedIds := make(map[metricID]struct{})\n\tfor _, e := range expect {\n\t\tid := metricID{Name: e.Name, Scope: e.Scope}\n\t\texpectedIds[id] = struct{}{}\n\t\tm := mt.metrics[id]\n\t\tif nil == m {\n\t\t\tt.Error(\"unable to find metric\", id)\n\t\t\tcontinue\n\t\t}\n\n\t\tif e.Forced != (forced == m.forced) {\n\t\t\tt.Error(\"metric forced incorrect\", e.Forced, m.forced, id)\n\t\t}\n\n\t\tif nil != e.Data {\n\t\t\texpectMetricField(t, id, e.Data[0], m.data.countSatisfied, \"countSatisfied\")\n\t\t\texpectMetricField(t, id, e.Data[1], m.data.totalTolerated, \"totalTolerated\")\n\t\t\texpectMetricField(t, id, e.Data[2], m.data.exclusiveFailed, \"exclusiveFailed\")\n\t\t\texpectMetricField(t, id, e.Data[3], m.data.min, \"min\")\n\t\t\texpectMetricField(t, id, e.Data[4], m.data.max, \"max\")\n\t\t\texpectMetricField(t, id, e.Data[5], m.data.sumSquares, \"sumSquares\")\n\t\t}\n\t}\n\tfor id := range mt.metrics {\n\t\tif _, ok := expectedIds[id]; !ok {\n\t\t\tt.Error(\"expected metrics does not contain\", id.Name, id.Scope)\n\t\t}\n\t}\n}", "func callMetrics(metricsAPI *metricsAPI, clock func() time.Time, timingMetrics bool) callrules.Rule {\n\ttimed := metricsAPI.callLatency\n\tif !timingMetrics {\n\t\ttimed = nil\n\t}\n\tharness := xmetrics.NewHarness(metricsAPI.callCount, metricsAPI.callErrorCount, timed, clock)\n\treturn callrules.Metrics(harness, nil)\n}", "func MockMetrics() []telegraf.Metric {\n\tmetrics := make([]telegraf.Metric, 0)\n\t// Create a new point batch\n\tmetrics = append(metrics, TestMetric(1.0))\n\treturn metrics\n}", "func (o *MonitorSearchResult) GetMetrics() []string {\n\tif o == nil || o.Metrics == nil {\n\t\tvar ret []string\n\t\treturn ret\n\t}\n\treturn o.Metrics\n}", "func (*SummaryMetric) IsMetric() {}", "func (c *standardComputation) GetMetrics() []string {\n\treturn c.fields\n}", "func (o *MonitorSearchResult) HasMetrics() bool {\n\tif o != nil && o.Metrics != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func TestCollectorOK(t *testing.T) {\n\tc := collector.New()\n\tctx := context.Background()\n\tmpa := NewStubMeterPoints(\"a\", 0, 100*time.Millisecond)\n\tmpb := NewStubMeterPoints(\"b\", 5, 200*time.Millisecond)\n\tmpc := NewStubMeterPoints(\"c\", 10, 50*time.Millisecond)\n\terr := c.Register(mpa, mpb, mpc)\n\tif err != nil {\n\t\tt.Errorf(\"collector register error: %v\", err)\n\t}\n\tmetrics := c.Retrieve(ctx, time.Second)\n\tif a, ok := metrics.Get(\"a.count\"); !ok || a != \"1\" {\n\t\tt.Errorf(\"illegal value a: %q\", a)\n\t}\n\tmetrics = c.Retrieve(ctx, time.Second)\n\tif b, ok := metrics.Get(\"b.count\"); !ok || b != \"7\" {\n\t\tt.Errorf(\"illegal value b: %q\", b)\n\t}\n\tmetrics = c.Retrieve(ctx, time.Second)\n\tif c, ok := metrics.Get(\"c.count\"); !ok || c != \"13\" {\n\t\tt.Errorf(\"illegal value c: %q\", c)\n\t}\n}", "func validateMetrics(m *Metrics) error {\n\tif !m.initialized {\n\t\treturn errors.New(\"Metrics struct is not initialized\")\n\t}\n\n\treturn nil\n}", "func mustGetClientMetrics() *grpc_prometheus.ClientMetrics {\n\tclientMetricsOnce.Do(func() {\n\t\tclientMetrics = grpc_prometheus.NewRegisteredClientMetrics(prometheus.DefaultRegisterer,\n\t\t\tgrpc_prometheus.WithClientCounterOptions(setCounterNamespace),\n\t\t\tgrpc_prometheus.WithClientHandlingTimeHistogram(setHistogramNamespace), // record the overall request latency for a gRPC request\n\t\t\tgrpc_prometheus.WithClientStreamRecvHistogram(setHistogramNamespace), // record how long it takes for a client to receive a message during a streaming RPC\n\t\t\tgrpc_prometheus.WithClientStreamSendHistogram(setHistogramNamespace), // record how long it takes for a client to send a message during a streaming RPC\n\t\t)\n\t})\n\n\treturn clientMetrics\n}", "func (mr *MockContextMockRecorder) GetMetricsClient() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetMetricsClient\", reflect.TypeOf((*MockContext)(nil).GetMetricsClient))\n}", "func MockMetrics() []optic.Metric {\n\tmetricsEvents := make([]optic.Metric, 0)\n\tmetricsEvents = append(metricsEvents, TestMetric(1.0))\n\treturn metricsEvents\n}", "func (*SimpleMetric) IsMetric() {}", "func TestPrometheusMetrics(t *testing.T) {\n\tbytesProcessedMetric.WithLabelValues(\"x\")\n\tcacheHitMetric.WithLabelValues(\"x\")\n\tuploadedBytesMetric.WithLabelValues(\"x\")\n\tqueryTotalMetric.WithLabelValues(\"x\")\n\tqueryProcessedMetric.WithLabelValues(\"x\")\n\tinFlightUploadsHistogram.WithLabelValues(\"x\")\n\tuploadQueueSizeHistogram.WithLabelValues(\"x\")\n\n\tpromtest.LintMetrics(t)\n}", "func validateMetrics(desc *otlp.MetricDescriptor) bool {\n\n\tif desc == nil {\n\t\treturn false\n\t}\n\n\tswitch desc.GetType() {\n\tcase otlp.MetricDescriptor_MONOTONIC_DOUBLE, otlp.MetricDescriptor_MONOTONIC_INT64,\n\t\totlp.MetricDescriptor_HISTOGRAM, otlp.MetricDescriptor_SUMMARY:\n\t\treturn desc.GetTemporality() == otlp.MetricDescriptor_CUMULATIVE\n\tcase otlp.MetricDescriptor_INT64, otlp.MetricDescriptor_DOUBLE:\n\t\treturn true\n\t}\n\n\treturn false\n}", "func TestMetrics(t *testing.T) {\n\tmetrics, err := NewMetrics()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tmetrics.Send(&influxdb.Series{\n\t\tName: \"testing\",\n\t\tColumns: []string{\n\t\t\t\"foo\",\n\t\t},\n\t\tPoints: [][]interface{}{\n\t\t\t{\n\t\t\t\t\"bar\",\n\t\t\t},\n\t\t},\n\t})\n}", "func (ds *dockServer) GetMetrics(context.Context, *pb.GetMetricsOpts) (*pb.GenericResponse, error) {\n\treturn nil, &model.NotImplementError{\"method GetMetrics has not been implemented yet\"}\n}", "func (e Entry) GetMetrics(timeout time.Duration, h heimdall.Doer, debug bool) (Metrics, error) {\n\tvar m Metrics\n\n\t// Let's set the stuff we know already.\n\tm.Address = e.Address\n\tm.Regexp = e.Regexp\n\tm.CapturedAt = time.Now().UTC()\n\n\t// Set a timeout.\n\tctx, cancel := context.WithTimeout(context.Background(), timeout)\n\tdefer cancel()\n\n\t// Setup the request.\n\treq, err := http.NewRequestWithContext(ctx, http.MethodGet, e.Address, nil)\n\tif err != nil {\n\t\treturn m, err\n\t}\n\n\tif debug {\n\t\tfmt.Printf(\"%#v\\n\", req)\n\t}\n\n\t// Let's do the request.\n\tstart := time.Now()\n\tres, err := h.Do(req)\n\tif err != nil {\n\t\treturn m, err\n\t}\n\n\t// We don't need the body unless we've got a regexp.\n\tif e.Regexp != \"\" {\n\t\tbody, err := ioutil.ReadAll(res.Body)\n\t\tif err != nil {\n\t\t\treturn m, err\n\t\t}\n\t\t// Do the regexp here and assign the value.\n\t\tmatch, _ := regexp.MatchString(e.Regexp, string(body))\n\t\tm.RegexpStatus = match\n\t}\n\ttook := time.Since(start)\n\n\t// Set the last few values\n\tm.StatusCode = res.StatusCode\n\tm.ResponseTime = took\n\n\tif debug {\n\t\tfmt.Printf(\"Result: %#v\\n\", res)\n\t\tfmt.Printf(\"Time Taken: %s\\n\", took)\n\t\tfmt.Printf(\"Metrics: %#v\\n\", m)\n\t}\n\n\tif ctx.Err() != nil {\n\t\treturn m, errors.New(\"context deadline exceeded\")\n\t}\n\treturn m, nil\n}", "func mustGetServerMetrics() *grpc_prometheus.ServerMetrics {\n\tserverMetricsOnce.Do(func() {\n\t\tserverMetrics = grpc_prometheus.NewRegisteredServerMetrics(prometheus.DefaultRegisterer,\n\t\t\tgrpc_prometheus.WithServerCounterOptions(setCounterNamespace),\n\t\t\tgrpc_prometheus.WithServerHandlingTimeHistogram(setHistogramNamespace), // record the overall response latency for a gRPC request)\n\t\t)\n\t})\n\n\treturn serverMetrics\n}", "func (mr *MockMetricsMockRecorder) InitMetrics() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"InitMetrics\", reflect.TypeOf((*MockMetrics)(nil).InitMetrics))\n}", "func TestGetStats(t *testing.T) {\n\tstats, err := GetStats()\n\tif err != nil {\n\t\tt.Errorf(\"Tests: Expected `nil`, Got %s\", err)\n\t}\n\tif stats.TotalRAM == 0 {\n\t\tt.Errorf(\"Tests: Expected `n > 0`, Got %d\", stats.TotalRAM)\n\t}\n}", "func (m *GetMetricsResponse) Validate() error {\n\treturn m.validate(false)\n}", "func (c *Client) GetMetrics(ctx context.Context, req *milvuspb.GetMetricsRequest) (*milvuspb.GetMetricsResponse, error) {\n\treq = typeutil.Clone(req)\n\tcommonpbutil.UpdateMsgBase(\n\t\treq.GetBase(),\n\t\tcommonpbutil.FillMsgBaseFromClient(paramtable.GetNodeID()))\n\treturn wrapGrpcCall(ctx, c, func(client querypb.QueryNodeClient) (*milvuspb.GetMetricsResponse, error) {\n\t\treturn client.GetMetrics(ctx, req)\n\t})\n}", "func (*HistogramMetric) IsMetric() {}", "func (_m *MockStatusStoreIface) GetMetric() (map[string]float64, error) {\n\tret := _m.Called()\n\n\tvar r0 map[string]float64\n\tif rf, ok := ret.Get(0).(func() map[string]float64); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(map[string]float64)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func() error); ok {\n\t\tr1 = rf()\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (c *Client) GetMetrics(ctx context.Context, req *milvuspb.GetMetricsRequest) (*milvuspb.GetMetricsResponse, error) {\n\treq = typeutil.Clone(req)\n\tcommonpbutil.UpdateMsgBase(\n\t\treq.GetBase(),\n\t\tcommonpbutil.FillMsgBaseFromClient(paramtable.GetNodeID(), commonpbutil.WithTargetID(c.grpcClient.GetNodeID())),\n\t)\n\treturn wrapGrpcCall(ctx, c, func(client querypb.QueryCoordClient) (*milvuspb.GetMetricsResponse, error) {\n\t\treturn client.GetMetrics(ctx, req)\n\t})\n}", "func (o *EnvironmentUsageDto) HasCustomMetrics() bool {\n\tif o != nil && o.CustomMetrics != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (mr *MockConnectionTracerMockRecorder) UpdatedMetrics(arg0, arg1, arg2, arg3 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"UpdatedMetrics\", reflect.TypeOf((*MockConnectionTracer)(nil).UpdatedMetrics), arg0, arg1, arg2, arg3)\n}", "func (m *ActiveNodeMock) ValidateCallCounters() {\n\n\tif !m.GetDeclaredPowerFinished() {\n\t\tm.t.Fatal(\"Expected call to ActiveNodeMock.GetDeclaredPower\")\n\t}\n\n\tif !m.GetIndexFinished() {\n\t\tm.t.Fatal(\"Expected call to ActiveNodeMock.GetIndex\")\n\t}\n\n\tif !m.GetNodeIDFinished() {\n\t\tm.t.Fatal(\"Expected call to ActiveNodeMock.GetNodeID\")\n\t}\n\n\tif !m.GetOpModeFinished() {\n\t\tm.t.Fatal(\"Expected call to ActiveNodeMock.GetOpMode\")\n\t}\n\n\tif !m.GetSignatureVerifierFinished() {\n\t\tm.t.Fatal(\"Expected call to ActiveNodeMock.GetSignatureVerifier\")\n\t}\n\n\tif !m.GetStaticFinished() {\n\t\tm.t.Fatal(\"Expected call to ActiveNodeMock.GetStatic\")\n\t}\n\n\tif !m.IsJoinerFinished() {\n\t\tm.t.Fatal(\"Expected call to ActiveNodeMock.IsJoiner\")\n\t}\n\n}", "func getMetrics() []Metric {\n\tms := make([]Metric, 0)\n\treturn append(ms, &SimpleEapMetric{})\n}", "func (o *DeviceMetricsAllOf) HasMetrics() bool {\n\tif o != nil && o.Metrics != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (m *Metrics) Validate() error {\n\treturn m.validate(false)\n}", "func (s *Server) GetMetrics(ctx context.Context, req *milvuspb.GetMetricsRequest) (*milvuspb.GetMetricsResponse, error) {\n\treturn s.querynode.GetMetrics(ctx, req)\n}", "func TestMetricTooMany(t *testing.T) { //nolint:maintidx\n\thelper := newHelper(t)\n\tdefer helper.Close()\n\n\thelper.preregisterAgent(t)\n\thelper.initSynchronizer(t)\n\n\tmetricResource, _ := helper.api.resources[mockAPIResourceMetric].(*genericResource)\n\tdefaultPatchHook := metricResource.PatchHook\n\n\t// API always reject more than 3 active metrics\n\tmetricResource.PatchHook = func(r *http.Request, body []byte, valuePtr interface{}, oldValue interface{}) error {\n\t\tif defaultPatchHook != nil {\n\t\t\terr := defaultPatchHook(r, body, valuePtr, oldValue)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\tmetric, _ := valuePtr.(*metricPayload)\n\n\t\tif metric.DeactivatedAt.IsZero() {\n\t\t\tmetrics := helper.MetricsFromAPI()\n\t\t\tcountActive := 0\n\n\t\t\tfor _, m := range metrics {\n\t\t\t\tif m.DeactivatedAt.IsZero() && m.ID != metric.ID {\n\t\t\t\t\tcountActive++\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif countActive >= 3 {\n\t\t\t\treturn clientError{\n\t\t\t\t\tbody: `{\"label\":[\"Too many non standard metrics\"]}`,\n\t\t\t\t\tstatusCode: http.StatusBadRequest,\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn nil\n\t}\n\n\tmetricResource.CreateHook = func(r *http.Request, body []byte, valuePtr interface{}) error {\n\t\treturn metricResource.PatchHook(r, body, valuePtr, nil)\n\t}\n\n\thelper.AddTime(time.Minute)\n\thelper.pushPoints(t, []labels.Labels{\n\t\tlabels.New(\n\t\t\tlabels.Label{Name: types.LabelName, Value: \"metric1\"},\n\t\t),\n\t\tlabels.New(\n\t\t\tlabels.Label{Name: types.LabelName, Value: \"metric2\"},\n\t\t),\n\t})\n\n\tif err := helper.runOnceWithResult(t).CheckMethodWithFull(syncMethodMetric); err != nil {\n\t\tt.Error(err)\n\t}\n\n\t// list active metrics, register agent_status + 2x metrics to register\n\thelper.api.AssertCallPerResource(t, mockAPIResourceMetric, 6)\n\n\tmetrics := helper.MetricsFromAPI()\n\tif len(metrics) != 3 { // 2 + agent_status\n\t\tt.Errorf(\"len(metrics) = %d, want 3\", len(metrics))\n\t}\n\n\thelper.AddTime(5 * time.Minute)\n\thelper.pushPoints(t, []labels.Labels{\n\t\tlabels.New(\n\t\t\tlabels.Label{Name: types.LabelName, Value: \"metric3\"},\n\t\t),\n\t\tlabels.New(\n\t\t\tlabels.Label{Name: types.LabelName, Value: \"metric4\"},\n\t\t),\n\t})\n\n\tif err := helper.runOnceWithResult(t).CheckMethodWithoutFull(syncMethodMetric); err != nil {\n\t\tt.Error(err)\n\t}\n\n\tif helper.api.ClientErrorCount == 0 {\n\t\tt.Errorf(\"We should have some client error, had %d\", helper.api.ClientErrorCount)\n\t}\n\n\t// list active metrics + 2x metrics to register\n\thelper.api.AssertCallPerResource(t, mockAPIResourceMetric, 5)\n\n\tmetrics = helper.MetricsFromAPI()\n\tif len(metrics) != 3 { // 2 + agent_status\n\t\tt.Errorf(\"len(metrics) = %d, want 3\", len(metrics))\n\t}\n\n\thelper.AddTime(5 * time.Minute)\n\n\tif err := helper.runOnceWithResult(t).CheckMethodNotRun(syncMethodMetric); err != nil {\n\t\tt.Error(err)\n\t}\n\n\thelper.SetTimeToNextFullSync()\n\t// drop all because normally store drop inactive metrics and\n\t// metric1 don't emitted for 70 minutes\n\thelper.store.DropAllMetrics()\n\thelper.pushPoints(t, []labels.Labels{\n\t\tlabels.New(\n\t\t\tlabels.Label{Name: types.LabelName, Value: \"metric2\"},\n\t\t),\n\t\tlabels.New(\n\t\t\tlabels.Label{Name: types.LabelName, Value: \"metric3\"},\n\t\t),\n\t\tlabels.New(\n\t\t\tlabels.Label{Name: types.LabelName, Value: \"metric4\"},\n\t\t),\n\t})\n\n\tif err := helper.runOnceWithResult(t).CheckMethodWithFull(syncMethodMetric); err != nil {\n\t\tt.Error(err)\n\t}\n\n\t// We need two sync: one to deactivate the metric, one to regsiter another one\n\thelper.AddTime(15 * time.Second)\n\n\tif err := helper.runOnceWithResult(t).CheckMethodWithoutFull(syncMethodMetric); err != nil {\n\t\tt.Error(err)\n\t}\n\n\tmetrics = helper.MetricsFromAPI()\n\tif len(metrics) != 4 { // metric1 is now disabled, another get registered\n\t\tt.Errorf(\"len(metrics) = %d, want 4\", len(metrics))\n\t}\n\n\tfor _, m := range metrics {\n\t\tif !m.DeactivatedAt.IsZero() && m.Name != \"metric1\" {\n\t\t\tt.Errorf(\"metric %s is deactivated, want active\", m.Name)\n\t\t}\n\n\t\tif m.DeactivatedAt.IsZero() && m.Name == \"metric1\" {\n\t\t\tt.Errorf(\"metric %s is active, want deactivated\", m.Name)\n\t\t}\n\t}\n\n\thelper.AddTime(5 * time.Minute)\n\thelper.pushPoints(t, []labels.Labels{\n\t\tlabels.New(\n\t\t\tlabels.Label{Name: types.LabelName, Value: \"metric1\"},\n\t\t),\n\t})\n\n\tif err := helper.runOnceWithResult(t).CheckMethodWithoutFull(syncMethodMetric); err != nil {\n\t\tt.Error(err)\n\t}\n\n\tif helper.api.ClientErrorCount == 0 {\n\t\tt.Errorf(\"We should have some client error, had %d\", helper.api.ClientErrorCount)\n\t}\n\n\tmetrics = helper.MetricsFromAPI()\n\tif len(metrics) != 4 { // metric1 is still disabled and no newly registered\n\t\tt.Errorf(\"len(metrics) = %d, want 4\", len(metrics))\n\t}\n\n\tfor _, m := range metrics {\n\t\tif !m.DeactivatedAt.IsZero() && m.Name != \"metric1\" {\n\t\t\tt.Errorf(\"metric %s is deactivated, want active\", m.Name)\n\t\t}\n\n\t\tif m.DeactivatedAt.IsZero() && m.Name == \"metric1\" {\n\t\t\tt.Errorf(\"metric %s is active, want deactivated\", m.Name)\n\t\t}\n\t}\n\n\t// We do not retry to register them\n\thelper.AddTime(5 * time.Minute)\n\n\tif err := helper.runOnceWithResult(t).CheckMethodNotRun(syncMethodMetric); err != nil {\n\t\tt.Error(err)\n\t}\n\n\t// Excepted ONE per full-sync\n\thelper.SetTimeToNextFullSync()\n\thelper.pushPoints(t, []labels.Labels{\n\t\tlabels.New(\n\t\t\tlabels.Label{Name: types.LabelName, Value: \"metric2\"},\n\t\t),\n\t\tlabels.New(\n\t\t\tlabels.Label{Name: types.LabelName, Value: \"metric3\"},\n\t\t),\n\t\tlabels.New(\n\t\t\tlabels.Label{Name: types.LabelName, Value: \"metric4\"},\n\t\t),\n\t})\n\n\tif err := helper.runOnceWithResult(t).CheckMethodWithFull(syncMethodMetric); err != nil {\n\t\tt.Error(err)\n\t}\n\n\tif helper.api.ClientErrorCount != 1 {\n\t\tt.Errorf(\"had %d client error, want 1\", helper.api.ClientErrorCount)\n\t}\n\n\tmetrics = helper.MetricsFromAPI()\n\tif len(metrics) != 4 {\n\t\tt.Errorf(\"len(metrics) = %d, want 4\", len(metrics))\n\t}\n\n\tfor _, m := range metrics {\n\t\tif !m.DeactivatedAt.IsZero() && m.Name != \"metric1\" {\n\t\t\tt.Errorf(\"metric %s is deactivated, want active\", m.Name)\n\t\t}\n\n\t\tif m.DeactivatedAt.IsZero() && m.Name == \"metric1\" {\n\t\t\tt.Errorf(\"metric %s is active, want deactivated\", m.Name)\n\t\t}\n\t}\n\n\t// list active metrics + check existence of the metric we want to reg +\n\t// retry to register\n\thelper.api.AssertCallPerResource(t, mockAPIResourceMetric, 3)\n}", "func (o *MetricsAllOf) GetMetrics() []Metric {\n\tif o == nil || o.Metrics == nil {\n\t\tvar ret []Metric\n\t\treturn ret\n\t}\n\treturn *o.Metrics\n}", "func (mr *MockDataServiceServerMockRecorder) CalculateMetrics(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"CalculateMetrics\", reflect.TypeOf((*MockDataServiceServer)(nil).CalculateMetrics), arg0, arg1)\n}", "func (b *B) ReportMetric(n float64, unit string) {}", "func (mr *MockQueryerMockRecorder) GetSingleMetricsMeta(arg0, arg1, arg2, arg3 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetSingleMetricsMeta\", reflect.TypeOf((*MockQueryer)(nil).GetSingleMetricsMeta), arg0, arg1, arg2, arg3)\n}", "func (a *Client) GetMetrics(params *GetMetricsParams, opts ...ClientOption) (*GetMetricsOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewGetMetricsParams()\n\t}\n\top := &runtime.ClientOperation{\n\t\tID: \"GetMetrics\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/metrics/\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"http\"},\n\t\tParams: params,\n\t\tReader: &GetMetricsReader{formats: a.formats},\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t}\n\tfor _, opt := range opts {\n\t\topt(op)\n\t}\n\n\tresult, err := a.transport.Submit(op)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsuccess, ok := result.(*GetMetricsOK)\n\tif ok {\n\t\treturn success, nil\n\t}\n\t// unexpected success response\n\t// safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue\n\tmsg := fmt.Sprintf(\"unexpected success response for GetMetrics: API contract not enforced by server. Client expected to get an error, but got: %T\", result)\n\tpanic(msg)\n}", "func (c *PromMetricsClient) GetMetrics() ([]*Metric, error) {\n\tres, err := http.Get(c.URL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif res.StatusCode != 200 {\n\t\treturn nil, ErrUnexpectedHTTPStatusCode\n\t}\n\n\tdefer res.Body.Close()\n\treturn Parse(res.Body)\n}", "func (session *Session) PerformanceGetMetrics() ([]Metric, error) {\n\tmsg, err := session.blockingSend(\"Performance.getMetrics\", &Params{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tm := make([]Metric, 0)\n\tunmarshal(msg[\"metrics\"], &m)\n\treturn m, nil\n}", "func (m *GetMetricsRequest) Validate() error {\n\treturn m.validate(false)\n}", "func (mr *MockArgusdClientMockRecorder) RecordMetrics(arg0, arg1 interface{}, arg2 ...interface{}) *gomock.Call {\n\tvarargs := append([]interface{}{arg0, arg1}, arg2...)\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"RecordMetrics\", reflect.TypeOf((*MockArgusdClient)(nil).RecordMetrics), varargs...)\n}", "func (mr *MockIApiMockRecorder) MetricsRetrieveAll(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"MetricsRetrieveAll\", reflect.TypeOf((*MockIApi)(nil).MetricsRetrieveAll), arg0)\n}", "func (o *MetricsAllOf) HasMetrics() bool {\n\tif o != nil && o.Metrics != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (Metrics) MetricStruct() {}", "func (m *OutboundMock) ValidateCallCounters() {\n\n\tif !m.AsByteStringFinished() {\n\t\tm.t.Fatal(\"Expected call to OutboundMock.AsByteString\")\n\t}\n\n\tif !m.CanAcceptFinished() {\n\t\tm.t.Fatal(\"Expected call to OutboundMock.CanAccept\")\n\t}\n\n\tif !m.GetEndpointTypeFinished() {\n\t\tm.t.Fatal(\"Expected call to OutboundMock.GetEndpointType\")\n\t}\n\n\tif !m.GetIPAddressFinished() {\n\t\tm.t.Fatal(\"Expected call to OutboundMock.GetIPAddress\")\n\t}\n\n\tif !m.GetNameAddressFinished() {\n\t\tm.t.Fatal(\"Expected call to OutboundMock.GetNameAddress\")\n\t}\n\n\tif !m.GetRelayIDFinished() {\n\t\tm.t.Fatal(\"Expected call to OutboundMock.GetRelayID\")\n\t}\n\n}", "func (mr *MockIApiMockRecorder) MetricsRetrieveARR(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"MetricsRetrieveARR\", reflect.TypeOf((*MockIApi)(nil).MetricsRetrieveARR), arg0)\n}", "func (m *MockClient) GetMetrics() *metrics.ClientMetrics {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetMetrics\")\n\tret0, _ := ret[0].(*metrics.ClientMetrics)\n\treturn ret0\n}", "func (m *MetricsCacheType) GetMetrics() ([]string, bool) {\n\tif m.IsAvailable() && !m.TimedOut() {\n\t\treturn m.metrics, true\n\t}\n\n\tif !m.updating {\n\t\tgo m.RefreshCache()\n\t}\n\treturn nil, false\n}", "func (mr *MockIApiMockRecorder) MetricsRetrieveMRRChurnRate(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"MetricsRetrieveMRRChurnRate\", reflect.TypeOf((*MockIApi)(nil).MetricsRetrieveMRRChurnRate), arg0)\n}", "func TestMetricsEndpoint(t *testing.T) {\n\tc := newKubeClient(t)\n\n\tlistOptions := metav1.ListOptions{LabelSelector: \"app=olm-operator\"}\n\tpodList, err := c.KubernetesInterface().CoreV1().Pods(operatorNamespace).List(listOptions)\n\tif err != nil {\n\t\tlog.Infof(\"Error %v\\n\", err)\n\t\tt.Fatalf(\"Listing pods failed: %v\\n\", err)\n\t}\n\tif len(podList.Items) > 1 {\n\t\tt.Fatalf(\"Expected only 1 olm-operator pod, got %v\", len(podList.Items))\n\t}\n\n\tpodName := podList.Items[0].GetName()\n\n\trawOutput, err := getMetricsFromPod(t, c, podName, operatorNamespace, 8080)\n\tif err != nil {\n\t\tt.Fatalf(\"Metrics test failed: %v\\n\", err)\n\t}\n\n\tlog.Debugf(\"Metrics:\\n%v\", rawOutput)\n}", "func (mr *MockDataServiceClientMockRecorder) CalculateMetrics(ctx, in interface{}, opts ...interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\tvarargs := append([]interface{}{ctx, in}, opts...)\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"CalculateMetrics\", reflect.TypeOf((*MockDataServiceClient)(nil).CalculateMetrics), varargs...)\n}", "func GetMetrics() []prometheus.Collector {\n\treturn []prometheus.Collector{\n\t\treqCounter,\n\t\treqDuration,\n\t\tconnDuration,\n\t}\n}", "func (o *DeviceMetricsAllOf) GetMetrics() []DeviceMetric {\n\tif o == nil || o.Metrics == nil {\n\t\tvar ret []DeviceMetric\n\t\treturn ret\n\t}\n\treturn *o.Metrics\n}", "func (_m *MockDataCoord) GetMetrics(ctx context.Context, req *milvuspb.GetMetricsRequest) (*milvuspb.GetMetricsResponse, error) {\n\tret := _m.Called(ctx, req)\n\n\tvar r0 *milvuspb.GetMetricsResponse\n\tvar r1 error\n\tif rf, ok := ret.Get(0).(func(context.Context, *milvuspb.GetMetricsRequest) (*milvuspb.GetMetricsResponse, error)); ok {\n\t\treturn rf(ctx, req)\n\t}\n\tif rf, ok := ret.Get(0).(func(context.Context, *milvuspb.GetMetricsRequest) *milvuspb.GetMetricsResponse); ok {\n\t\tr0 = rf(ctx, req)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*milvuspb.GetMetricsResponse)\n\t\t}\n\t}\n\n\tif rf, ok := ret.Get(1).(func(context.Context, *milvuspb.GetMetricsRequest) error); ok {\n\t\tr1 = rf(ctx, req)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (mr *MockIApiMockRecorder) MetricsRetrieveMRR(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"MetricsRetrieveMRR\", reflect.TypeOf((*MockIApi)(nil).MetricsRetrieveMRR), arg0)\n}", "func (m Metrics) MetricStruct() {}", "func (_m *MockQueryCoord) GetMetrics(ctx context.Context, req *milvuspb.GetMetricsRequest) (*milvuspb.GetMetricsResponse, error) {\n\tret := _m.Called(ctx, req)\n\n\tvar r0 *milvuspb.GetMetricsResponse\n\tvar r1 error\n\tif rf, ok := ret.Get(0).(func(context.Context, *milvuspb.GetMetricsRequest) (*milvuspb.GetMetricsResponse, error)); ok {\n\t\treturn rf(ctx, req)\n\t}\n\tif rf, ok := ret.Get(0).(func(context.Context, *milvuspb.GetMetricsRequest) *milvuspb.GetMetricsResponse); ok {\n\t\tr0 = rf(ctx, req)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*milvuspb.GetMetricsResponse)\n\t\t}\n\t}\n\n\tif rf, ok := ret.Get(1).(func(context.Context, *milvuspb.GetMetricsRequest) error); ok {\n\t\tr1 = rf(ctx, req)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func metricEnabled() bool {\n\treturn enabled\n}", "func TestAssessRunStatusWithMixedMetrics(t *testing.T) {\n\tf := newFixture(t)\n\tdefer f.Close()\n\tc, _, _ := f.newController(noResyncPeriodFunc)\n\n\trun := v1alpha1.AnalysisRun{\n\t\tSpec: v1alpha1.AnalysisRunSpec{\n\t\t\tMetrics: []v1alpha1.Metric{\n\t\t\t\t{\n\t\t\t\t\tName: \"run-forever\",\n\t\t\t\t\tProvider: v1alpha1.MetricProvider{\n\t\t\t\t\t\tJob: &v1alpha1.JobMetric{},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tName: \"success-metric\",\n\t\t\t\t\tProvider: v1alpha1.MetricProvider{\n\t\t\t\t\t\tJob: &v1alpha1.JobMetric{},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tDryRun: []v1alpha1.DryRun{{\n\t\t\t\tMetricName: \"success-metric\",\n\t\t\t}},\n\t\t},\n\t\tStatus: v1alpha1.AnalysisRunStatus{\n\t\t\tMetricResults: []v1alpha1.MetricResult{\n\t\t\t\t{\n\t\t\t\t\tName: \"run-forever\",\n\t\t\t\t\tInconclusive: 1,\n\t\t\t\t\tDryRun: false,\n\t\t\t\t\tPhase: v1alpha1.AnalysisPhaseRunning,\n\t\t\t\t\tMeasurements: []v1alpha1.Measurement{{\n\t\t\t\t\t\tPhase: v1alpha1.AnalysisPhaseRunning,\n\t\t\t\t\t\tStartedAt: timePtr(metav1.NewTime(time.Now().Add(-60 * time.Second))),\n\t\t\t\t\t}},\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tName: \"success-metric\",\n\t\t\t\t\tCount: 1,\n\t\t\t\t\tFailed: 1,\n\t\t\t\t\tDryRun: true,\n\t\t\t\t\tPhase: v1alpha1.AnalysisPhaseSuccessful,\n\t\t\t\t\tMeasurements: []v1alpha1.Measurement{{\n\t\t\t\t\t\tPhase: v1alpha1.AnalysisPhaseFailed,\n\t\t\t\t\t\tStartedAt: timePtr(metav1.NewTime(time.Now().Add(-60 * time.Second))),\n\t\t\t\t\t\tFinishedAt: timePtr(metav1.NewTime(time.Now().Add(-60 * time.Second))),\n\t\t\t\t\t}},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\tf.provider.On(\"Run\", mock.Anything, mock.Anything, mock.Anything).Return(newMeasurement(v1alpha1.AnalysisPhaseFailed), nil)\n\tf.provider.On(\"Resume\", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(newMeasurement(v1alpha1.AnalysisPhaseSuccessful), nil)\n\n\tnewRun := c.reconcileAnalysisRun(&run)\n\tassert.Equal(t, v1alpha1.AnalysisPhaseInconclusive, newRun.Status.Phase)\n\tassert.Equal(t, \"Metric \\\"run-forever\\\" assessed Inconclusive due to inconclusive (1) > inconclusiveLimit (0)\", newRun.Status.Message)\n}", "func (h *testMetricsHandler) GetRawMetrics(apiClient kubernetes.Interface, namespace, functionName string) ([]byte, error) {\n\tsvc, err := apiClient.CoreV1().Services(namespace).Get(functionName, metav1.GetOptions{})\n\tif err != nil {\n\t\treturn []byte{}, err\n\t}\n\tb, err := http.Get(svc.SelfLink)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer b.Body.Close()\n\treturn ioutil.ReadAll(b.Body)\n}", "func (f ConsumeMetricsFunc) ConsumeMetrics(ctx context.Context, ld pdata.Metrics) error {\n\treturn f(ctx, ld)\n}", "func (mr *MockAPIMockRecorder) ReportValidationFailedMetrics(arg0, arg1, arg2, arg3 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"ReportValidationFailedMetrics\", reflect.TypeOf((*MockAPI)(nil).ReportValidationFailedMetrics), arg0, arg1, arg2, arg3)\n}", "func testCounterMetric(t *testing.T, reporter *Reporter, m *stats.Int64Measure) {\n\ttotalNumberOfOperations := 2\n\treporter.Report(m.M(1))\n\treporter.Report(m.M(1))\n\trow, err := view.RetrieveData(m.Name())\n\tif err != nil {\n\t\tt.Errorf(\"Error when retrieving data: %v from %v\", err, m.Name())\n\t}\n\n\tcount, ok := row[0].Data.(*view.CountData)\n\tif !ok {\n\t\tt.Error(\"ReportRequest should have aggregation Count()\")\n\t}\n\tif count.Value != int64(totalNumberOfOperations) {\n\t\tt.Errorf(\"Metric: %v - Expected %v, got %v. \", m.Name(), count.Value, totalNumberOfOperations)\n\t}\n}", "func (f FakeContainerImpl) GetContainerMetrics(containerID string) (*metrics.ContainerMetrics, error) {\n\treturn nil, nil\n}", "func (s *IBMMQScaler) GetMetricsAndActivity(ctx context.Context, metricName string) ([]external_metrics.ExternalMetricValue, bool, error) {\n\tqueueDepth, err := s.getQueueDepthViaHTTP(ctx)\n\tif err != nil {\n\t\treturn []external_metrics.ExternalMetricValue{}, false, fmt.Errorf(\"error inspecting IBM MQ queue depth: %w\", err)\n\t}\n\n\tmetric := GenerateMetricInMili(metricName, float64(queueDepth))\n\n\treturn []external_metrics.ExternalMetricValue{metric}, queueDepth > s.metadata.activationQueueDepth, nil\n}", "func TestReferenceCompatibility(t *testing.T) {\n\tclient := &http.Client{\n\t\tTimeout: time.Second * 10,\n\t}\n\treq, err := http.NewRequest(\"GET\", \"http://localhost:42000/metrics\", nil)\n\tassert.Nil(t, err)\n\treq.SetBasicAuth(\"pmm\", \"/agent_id/825dcdbf-af1c-4eb4-9e96-21699aa6ff7b\")\n\tresp, err := client.Do(req)\n\tassert.Nil(t, err)\n\tdefer resp.Body.Close()\n\tcurrentMetricsBytes, err := ioutil.ReadAll(resp.Body)\n\tassert.Nil(t, err)\n\n\tcurrentMetrics := toMap(t, string(currentMetricsBytes))\n\treferenceMetrics := toMap(t, referenceMetrics)\n\n\t//remove matches\n\tfor m := range currentMetrics {\n\t\t_, found := referenceMetrics[m]\n\t\tif found {\n\t\t\tdelete(referenceMetrics, m)\n\t\t\tdelete(currentMetrics, m)\n\t\t}\n\t}\n\n\tfmt.Printf(\"Extra metrics [%d]:\\n\", len(currentMetrics))\n\tfor _, metric := range sortedKeys(currentMetrics) {\n\t\tfmt.Printf(\"\\t%s\\n\", metric)\n\t}\n\tif len(referenceMetrics) != 0 {\n\t\tfmt.Printf(\"Not Supported metrics [%d]:\\n\", len(referenceMetrics))\n\t\tfor _, metric := range sortedKeys(referenceMetrics) {\n\t\t\tfmt.Printf(\"\\t%s\\n\", metric)\n\t\t}\n\t\tassert.FailNowf(t, \"Found not supported metrics\", \"Count: %d\", len(referenceMetrics))\n\t}\n}", "func (c *SkipperCollector) GetMetrics() ([]CollectedMetric, error) {\n\tcollector, err := c.getCollector(context.TODO())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvalues, err := collector.GetMetrics()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif len(values) != 1 {\n\t\treturn nil, fmt.Errorf(\"expected to only get one metric value, got %d\", len(values))\n\t}\n\n\tvalue := values[0]\n\n\t// For Kubernetes <v1.14 we have to fall back to manual average\n\tif c.config.MetricSpec.Object.Target.AverageValue == nil {\n\t\t// get current replicas for the targeted scale object. This is used to\n\t\t// calculate an average metric instead of total.\n\t\t// targetAverageValue will be available in Kubernetes v1.12\n\t\t// https://github.com/kubernetes/kubernetes/pull/64097\n\t\treplicas, err := targetRefReplicas(c.client, c.hpa)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif replicas < 1 {\n\t\t\treturn nil, fmt.Errorf(\"unable to get average value for %d replicas\", replicas)\n\t\t}\n\n\t\tavgValue := float64(value.Custom.Value.MilliValue()) / float64(replicas)\n\t\tvalue.Custom.Value = *resource.NewMilliQuantity(int64(avgValue), resource.DecimalSI)\n\t}\n\n\treturn []CollectedMetric{value}, nil\n}", "func (in *MonitoringDashboardChart) GetMetrics() []MonitoringDashboardMetric {\n\tif len(in.Metrics) == 0 {\n\t\treturn []MonitoringDashboardMetric{\n\t\t\t{\n\t\t\t\tMetricName: in.MetricName,\n\t\t\t\tDisplayName: in.Name,\n\t\t\t},\n\t\t}\n\t}\n\treturn in.Metrics\n}", "func (in *MonitoringDashboardChart) GetMetrics() []MonitoringDashboardMetric {\n\tif len(in.Metrics) == 0 {\n\t\treturn []MonitoringDashboardMetric{\n\t\t\t{\n\t\t\t\tMetricName: in.MetricName,\n\t\t\t\tDisplayName: in.Name,\n\t\t\t},\n\t\t}\n\t}\n\treturn in.Metrics\n}", "func (*Metrics) MetricStruct() {}", "func TestRetrieveMetrics_SLOObjectiveNotGeneratedFromUnsupportedDataExplorerTile(t *testing.T) {\n\tconst testDataFolder = \"./testdata/dashboards/slo_generation/unsupported_data_explorer_tile/\"\n\n\t// TODO: 25-08-2022: Check if this test is still needed\n\tt.Skip(\"Investigate if this test is still needed\")\n\n\thandler := test.NewFileBasedURLHandler(t)\n\thandler.AddExact(dynatrace.DashboardsPath+\"/\"+testDashboardID, filepath.Join(testDataFolder, \"dashboard.json\"))\n\n\tsliResultsAssertionsFuncs := []func(t *testing.T, actual sliResult){\n\t\tcreateFailedSLIResultAssertionsFunc(\"response_time\"),\n\t}\n\n\tuploadedSLOsAssertionsFunc := func(t *testing.T, actual *keptnapi.ServiceLevelObjectives) {\n\t\tif !assert.NotNil(t, actual) {\n\t\t\treturn\n\t\t}\n\n\t\tif !assert.EqualValues(t, 1, len(actual.Objectives)) {\n\t\t\treturn\n\t\t}\n\n\t\tassert.EqualValues(t, &keptnapi.SLO{\n\t\t\tSLI: \"response_time\",\n\t\t\tDisplayName: \"response_time\",\n\t\t\tPass: []*keptnapi.SLOCriteria{{Criteria: []string{\"<1200\"}}},\n\t\t\tWeight: 1,\n\t\t}, actual.Objectives[0])\n\t}\n\n\trunGetSLIsFromDashboardTestAndCheckSLIsAndSLOs(t, handler, testGetSLIEventData, getSLIFinishedEventFailureAssertionsFunc, uploadedSLOsAssertionsFunc, sliResultsAssertionsFuncs...)\n}", "func ValidateMetric(m RextMetricDef) (hasError bool) {\n\tif len(m.GetMetricName()) == 0 {\n\t\thasError = true\n\t\tlog.Errorln(\"name is required in metric config\")\n\t}\n\tif len(m.GetMetricType()) == 0 {\n\t\thasError = true\n\t\tlog.Errorln(\"type is required in metric config\")\n\t}\n\tswitch m.GetMetricType() {\n\tcase KeyMetricTypeHistogram:\n\t\topts := m.GetOptions()\n\t\tvar err error\n\t\tvar iVal interface{}\n\t\tif iVal, err = opts.GetObject(OptKeyRextMetricDefHMetricBuckets); err != nil || iVal == nil {\n\t\t\thasError = true\n\t\t\tlog.Errorln(\"histogram metric should have some buckets defined\")\n\t\t}\n\t\tbuckets, okBuckets := iVal.([]float64)\n\t\tif !okBuckets {\n\t\t\thasError = true\n\t\t\tlog.WithFields(log.Fields{\"key\": OptKeyRextMetricDefHMetricBuckets, \"val\": iVal}).Errorln(\"error getting buckets values, histogram should have buckets defined\")\n\t\t}\n\t\tif len(buckets) == 0 {\n\t\t\thasError = true\n\t\t\tlog.Errorln(\"histogram should have buckets defined\")\n\t\t}\n\tcase KeyMetricTypeCounter, KeyMetricTypeGauge:\n\tcase KeyMetricTypeSummary:\n\t\thasError = true\n\t\tlog.Errorf(\"type %s is not supported yet\\n\", KeyMetricTypeSummary)\n\tdefault:\n\t\thasError = true\n\t\tlog.WithFields(log.Fields{\"current\": m.GetMetricType(), \"expected\": []string{KeyMetricTypeCounter, KeyMetricTypeGauge, KeyMetricTypeSummary, KeyMetricTypeHistogram}}).Errorln(\"invalid metric kind\")\n\t}\n\tif m.GetNodeSolver() == nil {\n\t\thasError = true\n\t\tlog.Errorln(\"node solver is required in metric config\")\n\t} else if m.GetNodeSolver().Validate() {\n\t\thasError = true\n\t}\n\tfor _, label := range m.GetLabels() {\n\t\tif label.Validate() {\n\t\t\thasError = true\n\t\t}\n\t}\n\treturn hasError\n}", "func (m *MockProviders) GetMetrics() *metrics.ClientMetrics {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetMetrics\")\n\tret0, _ := ret[0].(*metrics.ClientMetrics)\n\treturn ret0\n}", "func (m *HeavySyncMock) ValidateCallCounters() {\n\n\tif !m.ResetFinished() {\n\t\tm.t.Fatal(\"Expected call to HeavySyncMock.Reset\")\n\t}\n\n\tif !m.StartFinished() {\n\t\tm.t.Fatal(\"Expected call to HeavySyncMock.Start\")\n\t}\n\n\tif !m.StopFinished() {\n\t\tm.t.Fatal(\"Expected call to HeavySyncMock.Stop\")\n\t}\n\n\tif !m.StoreBlobsFinished() {\n\t\tm.t.Fatal(\"Expected call to HeavySyncMock.StoreBlobs\")\n\t}\n\n\tif !m.StoreDropFinished() {\n\t\tm.t.Fatal(\"Expected call to HeavySyncMock.StoreDrop\")\n\t}\n\n\tif !m.StoreIndicesFinished() {\n\t\tm.t.Fatal(\"Expected call to HeavySyncMock.StoreIndices\")\n\t}\n\n\tif !m.StoreRecordsFinished() {\n\t\tm.t.Fatal(\"Expected call to HeavySyncMock.StoreRecords\")\n\t}\n\n}", "func (m *Metric) Validate() error {\n\treturn m.validate(false)\n}" ]
[ "0.70336074", "0.6899806", "0.6739893", "0.6723411", "0.6642232", "0.6608507", "0.65390295", "0.65256894", "0.64755845", "0.646324", "0.64111966", "0.64071107", "0.6383326", "0.6328049", "0.62772614", "0.6275577", "0.6178393", "0.6135223", "0.6065064", "0.6054249", "0.60229427", "0.5966302", "0.59624934", "0.5909094", "0.58822215", "0.587618", "0.58700037", "0.58421135", "0.57971686", "0.57834005", "0.5770361", "0.5767841", "0.5764543", "0.5756659", "0.575464", "0.57070535", "0.5703012", "0.5694305", "0.5679976", "0.56682163", "0.5666084", "0.56321675", "0.5611974", "0.5599553", "0.55981684", "0.55849713", "0.555191", "0.55396223", "0.5523013", "0.55213267", "0.5519287", "0.5497451", "0.5492178", "0.54887056", "0.54832804", "0.54815954", "0.5476055", "0.54738426", "0.5467342", "0.54622686", "0.5448142", "0.5446926", "0.5442804", "0.5440052", "0.541637", "0.5414964", "0.54001486", "0.5398316", "0.5397985", "0.53894234", "0.5372305", "0.5362523", "0.535935", "0.53531456", "0.53525674", "0.5336813", "0.53097135", "0.5308807", "0.5298804", "0.52908105", "0.52900344", "0.5271113", "0.52710545", "0.52687633", "0.5262037", "0.52618885", "0.5257179", "0.5255343", "0.52551264", "0.5246286", "0.52348244", "0.5233717", "0.5222329", "0.5222329", "0.5222071", "0.52176476", "0.5215172", "0.521251", "0.5204873", "0.52010757" ]
0.69020057
1
Identifier mocks base method
func (m *MockClient) Identifier() *msp.IdentityIdentifier { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Identifier") ret0, _ := ret[0].(*msp.IdentityIdentifier) return ret0 }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (m *MockSpaceStorage) Id() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Id\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func (m *MockCandidatePropertyGetter) Id() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Id\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func (m *MockModel) ID() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ID\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func (m *MockStream) ID() uint64 {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ID\")\n\tret0, _ := ret[0].(uint64)\n\treturn ret0\n}", "func (m *MockSession) ID() sig_mgmt.SessionType {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ID\")\n\tret0, _ := ret[0].(sig_mgmt.SessionType)\n\treturn ret0\n}", "func (m *MockSession) ID() int64 {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ID\")\n\tret0, _ := ret[0].(int64)\n\treturn ret0\n}", "func (m *MockFullNode) ID(arg0 context.Context) (peer.ID, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ID\", arg0)\n\tret0, _ := ret[0].(peer.ID)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockWebsocketClient) ID() wspubsub.UUID {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ID\")\n\tret0, _ := ret[0].(wspubsub.UUID)\n\treturn ret0\n}", "func (_m *MockSeriesIterator) ID() ident.ID {\n\tret := _m.ctrl.Call(_m, \"ID\")\n\tret0, _ := ret[0].(ident.ID)\n\treturn ret0\n}", "func (m *MockIByIdUseCase) Id(id aggregates.Id) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"Id\", id)\n}", "func (m *MockDao) UID(steamID int64) (*model.Info, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"UID\", steamID)\n\tret0, _ := ret[0].(*model.Info)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockPostForkBlock) ID() ids.ID {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ID\")\n\tret0, _ := ret[0].(ids.ID)\n\treturn ret0\n}", "func (m *MockIRepository) Id(id aggregates.Id) (aggregates.Question, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Id\", id)\n\tret0, _ := ret[0].(aggregates.Question)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *Mockhost) ID() p2p.Peer {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ID\")\n\tret0, _ := ret[0].(p2p.Peer)\n\treturn ret0\n}", "func (m *MockSession) UID() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"UID\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func (_m *KeyManager) ID() string {\n\tret := _m.Called()\n\n\tvar r0 string\n\tif rf, ok := ret.Get(0).(func() string); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tr0 = ret.Get(0).(string)\n\t}\n\n\treturn r0\n}", "func (_m *MockBookingStorage) ByID() {\n\t_m.Called()\n}", "func (m *MockHost) ID() peer.ID {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ID\")\n\tret0, _ := ret[0].(peer.ID)\n\treturn ret0\n}", "func (m *MockEvent) ID() channelx.EventID {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ID\")\n\tret0, _ := ret[0].(channelx.EventID)\n\treturn ret0\n}", "func (m *MockMessage) ID() p2pcommon.MsgID {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ID\")\n\tret0, _ := ret[0].(p2pcommon.MsgID)\n\treturn ret0\n}", "func (m *MockIRepository) Id(id aggregates.Id) (aggregates.Topic, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Id\", id)\n\tret0, _ := ret[0].(aggregates.Topic)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockGeneralRepository) GetByID(output models.Model) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetByID\", output)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (_m *TaskStatuser) ID() string {\n\tret := _m.Called()\n\n\tvar r0 string\n\tif rf, ok := ret.Get(0).(func() string); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tr0 = ret.Get(0).(string)\n\t}\n\n\treturn r0\n}", "func (_m *Entity) ID() string {\n\tret := _m.Called()\n\n\tvar r0 string\n\tif rf, ok := ret.Get(0).(func() string); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tr0 = ret.Get(0).(string)\n\t}\n\n\treturn r0\n}", "func (m *MockChoriaProvider) Identity() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Identity\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func (m *MockMachine) Identity() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Identity\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func (_m *XMPPClient) ID() string {\n\tret := _m.Called()\n\n\tvar r0 string\n\tif rf, ok := ret.Get(0).(func() string); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tr0 = ret.Get(0).(string)\n\t}\n\n\treturn r0\n}", "func (_m *Operator) ID() string {\n\tret := _m.Called()\n\n\tvar r0 string\n\tif rf, ok := ret.Get(0).(func() string); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tr0 = ret.Get(0).(string)\n\t}\n\n\treturn r0\n}", "func (m *MockIByIdUseCase) Id(id aggregates.Id) (aggregates.Question, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Id\", id)\n\tret0, _ := ret[0].(aggregates.Question)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockInterface) ACRResourceID() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ACRResourceID\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func TestIdentifier(t *testing.T) {\n\t// Type as identifier.\n\tvar kvlf KeyValueLessFunc\n\n\tidp := TypeAsIdentifierPart(kvlf)\n\n\tif idp != \"key-value-less-func\" {\n\t\tt.Errorf(\"Identifier part for KeyValueLessFunc is wrong, returned '%v'!\", idp)\n\t}\n\n\tidp = TypeAsIdentifierPart(NewUUID())\n\n\tif idp != \"u-u-i-d\" {\n\t\tt.Errorf(\"Identifier part for UUID is wrong, returned '%v'!\", idp)\n\t}\n\n\t// Identifier.\n\tid := Identifier(\"One\", 2, \"three four\")\n\n\tif id != \"one:2:three-four\" {\n\t\tt.Errorf(\"First identifier is wrong! Id: %v\", id)\n\t}\n\n\tid = Identifier(2011, 6, 22, \"One, two, or three things.\")\n\n\tif id != \"2011:6:22:one-two-or-three-things\" {\n\t\tt.Errorf(\"Second identifier is wrong! Id: %v\", id)\n\t}\n\n\tid = SepIdentifier(\"+\", 1, \"oNe\", 2, \"TWO\", \"3\", \"ÄÖÜ\")\n\n\tif id != \"1+one+2+two+3+äöü\" {\n\t\tt.Errorf(\"Third identifier is wrong! Id: %v\", id)\n\t}\n\n\tid = LimitedSepIdentifier(\"+\", true, \" \", 1, \"oNe\", 2, \"TWO\", \"3\", \"ÄÖÜ\", \"Four\", \"+#-:,\")\n\n\tif id != \"1+one+2+two+3+four\" {\n\t\tt.Errorf(\"Fourth identifier is wrong! Id: %v\", id)\n\t}\n}", "func (m *MockFlag) FindByID(arg0 context.Context, arg1 string) (*flaggio.Flag, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"FindByID\", arg0, arg1)\n\tret0, _ := ret[0].(*flaggio.Flag)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockInterface) SubscriptionID() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"SubscriptionID\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func testIdentifier(t *testing.T, expression ast.Expression, value string) {\n\ti, ok := expression.(*ast.Identifier)\n\tif !ok {\n\t\tt.Fatalf(\"Expected Expression type: ast.Identifier, actual: %T\", expression)\n\t}\n\n\tassert.Equal(t, value, i.Value, \"Expected value of identifier\")\n\tassert.Equal(t, value, i.TokenLiteral(), \"Expected token literal of identifier\")\n}", "func TestID(t *testing.T) {\n\ttcs := []struct {\n\t\ttestcase string\n\t\tvalue string\n\t\tsanitisedValue string\n\t\tvalidationError error\n\t\texpectedID ID\n\t}{\n\t\t{\n\t\t\ttestcase: \"ForAnEmptyValue\",\n\t\t\tvalue: \"\",\n\t\t\tsanitisedValue: \"\",\n\t\t\tvalidationError: nil,\n\t\t\texpectedID: ID{},\n\t\t},\n\t\t{\n\t\t\ttestcase: \"ForAValidValue\",\n\t\t\tvalue: \"expectedID-value\",\n\t\t\tsanitisedValue: \"expectedID-value\",\n\t\t\tvalidationError: nil,\n\t\t\texpectedID: ID{id: \"expectedID-value\"},\n\t\t},\n\t\t{\n\t\t\ttestcase: \"ForAnInvalidValue\",\n\t\t\tvalue: \"!!!\",\n\t\t\tsanitisedValue: \"!!!\",\n\t\t\tvalidationError: errors.New(\"invalid expectedID value\"),\n\t\t\texpectedID: ID{},\n\t\t},\n\t}\n\n\tfor i := range tcs {\n\t\ttc := tcs[i]\n\t\tt.Run(tc.testcase, func(t *testing.T) {\n\t\t\tsanitiserMock := new(mockSanitiser)\n\t\t\tsanitiserMock.On(\"SanitiseID\", tc.value).Return(tc.sanitisedValue).Once()\n\t\t\tvalidatorMock := new(mockValidator)\n\t\t\tvalidatorMock.On(\"ValidateID\", tc.sanitisedValue).Return(tc.validationError).Once()\n\n\t\t\tid, err := NewFactory(sanitiserMock, validatorMock).ID(tc.value)\n\n\t\t\tassert.Equal(t, tc.expectedID, id)\n\t\t\tassert.Equal(t, err, tc.validationError)\n\t\t\tsanitiserMock.AssertExpectations(t)\n\t\t\tvalidatorMock.AssertExpectations(t)\n\t\t})\n\t}\n}", "func (m *MockCore) SubscriptionID() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"SubscriptionID\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func (_m *ContainerIface) ID() string {\n\tret := _m.Called()\n\n\tvar r0 string\n\tif rf, ok := ret.Get(0).(func() string); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tr0 = ret.Get(0).(string)\n\t}\n\n\treturn r0\n}", "func (m *MockAuthorizer) SubscriptionID() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"SubscriptionID\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func (m *MockMessage) OriginalID() p2pcommon.MsgID {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"OriginalID\")\n\tret0, _ := ret[0].(p2pcommon.MsgID)\n\treturn ret0\n}", "func (m *MockConn) UserID() uint64 {\n\tret := m.ctrl.Call(m, \"UserID\")\n\tret0, _ := ret[0].(uint64)\n\treturn ret0\n}", "func TestEmployeeManagerMapGetByID(t *testing.T) {\n\tdb, mock, err := sqlmock.New()\n\tif err != nil {\n\t\tt.Fatalf(\"an error '%s' was not expected when opening a stub database connection\", err)\n\t}\n\tdefer db.Close()\n\n\trows := sqlmock.NewRows([]string{\"employee_name\", \"manager_name\"}).AddRow(\"Nick\", \"Sophie\").AddRow(\"Sophie\", \"Jonas\")\n\tmock.ExpectExec(constants.EmployeeManagerMappingDeleteQuery).WillReturnResult(sqlmock.NewResult(0, 0))\n\tmock.ExpectPrepare(regexp.QuoteMeta(constants.EmployeeManagerMappingInsertQuery)).ExpectExec().WillReturnResult(sqlmock.NewResult(0, 0))\n\tmock.ExpectQuery(constants.EmployeeManagerMappingSelectQuery).WillReturnRows(rows)\n\n\templyManagerMap := NewEmployeeManagerMapHandler(db)\n\n\tw := httptest.NewRecorder()\n\tvar jsonStr = []byte(`{\"Peter\":\"Nick\", \"Barbara\":\"Nick\", \"Nick\":\"Sophie\", \"Sophie\":\"Jonas\"}`)\n\tr := httptest.NewRequest(\"POST\", \"http://localhost:9090/api/v1/emplymgrmap\", bytes.NewBuffer(jsonStr))\n\tr = r.WithContext(context.Background())\n\templyManagerMap.Create(w, r)\n\n\tr = httptest.NewRequest(\"GET\", \"http://localhost:9090/api/v1/emplymgrmap/Nick?supervisor=true&name=Nick\", nil)\n\trctx := chi.NewRouteContext()\n\trctx.URLParams.Add(\"name\", \"Nick\")\n\tr = r.WithContext(context.WithValue(r.Context(), chi.RouteCtxKey, rctx))\n\tw = httptest.NewRecorder()\n\templyManagerMap.GetByID(w, r)\n\texpectedResponse := `{\"supervisor\":\"Sophie\",\"supervisor_of_supervisor\":\"Jonas\"}`\n\tassert.Equal(t, gohttp.StatusOK, w.Code)\n\tassert.Equal(t, expectedResponse, w.Body.String())\n}", "func (m *MockFullNode) StateLookupID(arg0 context.Context, arg1 address.Address, arg2 types0.TipSetKey) (address.Address, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"StateLookupID\", arg0, arg1, arg2)\n\tret0, _ := ret[0].(address.Address)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockActivityHandler) AdminGetByID(w http.ResponseWriter, r *http.Request) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"AdminGetByID\", w, r)\n}", "func FakeID(deploymentType, deploymentName string) string {\n\treturn fmt.Sprintf(\"%s::%s\", deploymentType, deploymentName)\n}", "func (c *ConnectionMock) ID() string {\n\targs := c.Called()\n\treturn args.String(0)\n}", "func (m *MockUserDB) GenerateSID() ([]rune, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GenerateSID\")\n\tret0, _ := ret[0].([]rune)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (_m *Repository) GetID(name string) (steamapis.Domain, error) {\n\tret := _m.Called(name)\n\n\tvar r0 steamapis.Domain\n\tif rf, ok := ret.Get(0).(func(string) steamapis.Domain); ok {\n\t\tr0 = rf(name)\n\t} else {\n\t\tr0 = ret.Get(0).(steamapis.Domain)\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(string) error); ok {\n\t\tr1 = rf(name)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (m *MockClusterDescriber) SubscriptionID() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"SubscriptionID\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func (m *MockClusterScoper) SubscriptionID() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"SubscriptionID\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func (_m *Task) DotID() string {\n\tret := _m.Called()\n\n\tvar r0 string\n\tif rf, ok := ret.Get(0).(func() string); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tr0 = ret.Get(0).(string)\n\t}\n\n\treturn r0\n}", "func (m *MockCompute) ImageIDFromName(arg0 string) (string, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ImageIDFromName\", arg0)\n\tret0, _ := ret[0].(string)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockHostEvent) GetHostId() strfmt.UUID {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetHostId\")\n\tret0, _ := ret[0].(strfmt.UUID)\n\treturn ret0\n}", "func (m *MockRepository) GetByID(ctx context.Context, coffeesId int) (transaction_header.Domain, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetByID\", ctx, coffeesId)\n\tret0, _ := ret[0].(transaction_header.Domain)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockRepository) GetByID(id uint64) (*models.RestTag, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetByID\", id)\n\tret0, _ := ret[0].(*models.RestTag)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockStaker) NodeID() ids.NodeID {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"NodeID\")\n\tret0, _ := ret[0].(ids.NodeID)\n\treturn ret0\n}", "func (m *MockInterface) GenerateUID(arg0 *userService.Nothing) (*userService.Uid, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GenerateUID\", arg0)\n\tret0, _ := ret[0].(*userService.Uid)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (_m *RunInterface) GetID() string {\n\tret := _m.Called()\n\n\tvar r0 string\n\tif rf, ok := ret.Get(0).(func() string); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tr0 = ret.Get(0).(string)\n\t}\n\n\treturn r0\n}", "func (m *MockRemotePeer) ID() types.PeerID {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ID\")\n\tret0, _ := ret[0].(types.PeerID)\n\treturn ret0\n}", "func (m *MockRepository) GetByID(ctx context.Context, assetID uuid.UUID) (*model.AssetBase, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetByID\", ctx, assetID)\n\tret0, _ := ret[0].(*model.AssetBase)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (f *FakeOutput) ID() string { return \"fake\" }", "func (m *MockUsecase) GetByID(ctx context.Context, transactionId int) (transaction_header.Domain, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetByID\", ctx, transactionId)\n\tret0, _ := ret[0].(transaction_header.Domain)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func TestCustomNamedRequestID(t *testing.T) {\n\tclient := newHeaderClient(t)\n\tresult, err := client.CustomNamedRequestID(context.Background(), \"9C4D50EE-2D56-4CD3-8152-34347DC9F2B0\", nil)\n\trequire.NoError(t, err)\n\tif r := cmp.Diff(result.FooRequestID, to.Ptr(\"123\")); r != \"\" {\n\t\tt.Fatal(r)\n\t}\n}", "func (m *MockDiff) Ids() []string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Ids\")\n\tret0, _ := ret[0].([]string)\n\treturn ret0\n}", "func (m *MockSessionUsecase) GetByID(arg0 string) (*models.Session, *error_response.ErrorResponse) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetByID\", arg0)\n\tret0, _ := ret[0].(*models.Session)\n\tret1, _ := ret[1].(*error_response.ErrorResponse)\n\treturn ret0, ret1\n}", "func (m *MockDao) InfoWithID(id int32) (*model.Info, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"InfoWithID\", id)\n\tret0, _ := ret[0].(*model.Info)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockInfra) FindByID(id string) aws.Resource {\n\tret := m.ctrl.Call(m, \"FindByID\", id)\n\tret0, _ := ret[0].(aws.Resource)\n\treturn ret0\n}", "func (m *MockManagedClusterScoper) SubscriptionID() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"SubscriptionID\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func (m *MockMachine) InstanceID() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"InstanceID\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func (m *MockJobRepository) UpdateByID(arg0 *entity.Job) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"UpdateByID\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockRouterServiceIface) GetRouterID(name string, opts ...OptionFunc) (string, int, error) {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{name}\n\tfor _, a := range opts {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"GetRouterID\", varargs...)\n\tret0, _ := ret[0].(string)\n\tret1, _ := ret[1].(int)\n\tret2, _ := ret[2].(error)\n\treturn ret0, ret1, ret2\n}", "func (m *MockqueueTaskInfo) GetNamespaceId() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetNamespaceId\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func (_m *PeerManager) SelfID() string {\n\tret := _m.Called()\n\n\tvar r0 string\n\tif rf, ok := ret.Get(0).(func() string); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tr0 = ret.Get(0).(string)\n\t}\n\n\treturn r0\n}", "func (m *MockItemRepository) GetByID(arg0 int64) (*items.Item, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetByID\", arg0)\n\tret0, _ := ret[0].(*items.Item)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockSpaceStorage) SpaceSettingsId() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"SpaceSettingsId\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func (m *MockStaker) SubnetID() ids.ID {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"SubnetID\")\n\tret0, _ := ret[0].(ids.ID)\n\treturn ret0\n}", "func (m *MockInterface) GenerateSID(arg0 *userService.Nothing) (*userService.Sid, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GenerateSID\", arg0)\n\tret0, _ := ret[0].(*userService.Sid)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (mmForID *mStorageMockForID) When(ctx context.Context, pulse insolar.PulseNumber, recordID insolar.ID) *StorageMockForIDExpectation {\n\tif mmForID.mock.funcForID != nil {\n\t\tmmForID.mock.t.Fatalf(\"StorageMock.ForID mock is already set by Set\")\n\t}\n\n\texpectation := &StorageMockForIDExpectation{\n\t\tmock: mmForID.mock,\n\t\tparams: &StorageMockForIDParams{ctx, pulse, recordID},\n\t}\n\tmmForID.expectations = append(mmForID.expectations, expectation)\n\treturn expectation\n}", "func (m *MockRepository) GetByID(arg0 int) (*entity.FeiraLivre, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetByID\", arg0)\n\tret0, _ := ret[0].(*entity.FeiraLivre)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func TestCustomNamedRequestIDHead(t *testing.T) {\n\tclient := newHeaderClient(t)\n\tresult, err := client.CustomNamedRequestIDHead(context.Background(), \"9C4D50EE-2D56-4CD3-8152-34347DC9F2B0\", nil)\n\trequire.NoError(t, err)\n\tif !result.Success {\n\t\tt.Fatal(\"expected success\")\n\t}\n\tif r := cmp.Diff(result.FooRequestID, to.Ptr(\"123\")); r != \"\" {\n\t\tt.Fatal(r)\n\t}\n}", "func (m *MockUserRepo) FindByID(arg0 string) (*app.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"FindByID\", arg0)\n\tret0, _ := ret[0].(*app.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockAuthorizer) ClientID() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ClientID\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func (m *MockStore) FindByID(ctx context.Context, id int) (character.Character, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"FindByID\", ctx, id)\n\tret0, _ := ret[0].(character.Character)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockServiceReconciler) Name() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Name\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func (m *MockqueueTaskInfo) GetRunId() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetRunId\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func (m *MockApplicationStoreInterface) GetByID(arg0 string) (*model.Application, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetByID\", arg0)\n\tret0, _ := ret[0].(*model.Application)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (o *APICheck) SetIdentifier(id string) {\n\n}", "func (m *MockIAccountController) FindByID(id string) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"FindByID\", id)\n}", "func (m *MockCloudflareAPIInterface) ZoneIDByName(arg0 string) (string, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ZoneIDByName\", arg0)\n\tret0, _ := ret[0].(string)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockAPI) Name() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Name\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func (m *MockqueueTask) GetNamespaceId() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetNamespaceId\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func (m *MockManagedClusterScope) SubscriptionID() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"SubscriptionID\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func (m *MockRepository) GetByID(ctx context.Context, userID uint) (*models.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetByID\", ctx, userID)\n\tret0, _ := ret[0].(*models.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (o *APICheck) Identifier() string {\n\n\treturn \"\"\n}", "func (m *MockInterface) FPClientID() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"FPClientID\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func (m *MockCache) Name() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Name\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func (m *MockUsersRepoInterface) GetByID(arg0 string) (*user.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetByID\", arg0)\n\tret0, _ := ret[0].(*user.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockProductUC) ByID(arg0 context.Context, arg1 int) (*entity.Product, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ByID\", arg0, arg1)\n\tret0, _ := ret[0].(*entity.Product)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockSpaceStorage) Name() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Name\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func NewIdentifier(login string, password string) *Identifier {\n\treturn &Identifier{\n\t\tlogin: login,\n\t\tpassword: password,\n\t\tauthEndpoint: authEndpoint,\n\t\tHTTPClient: &http.Client{Timeout: 10 * time.Second},\n\t}\n}", "func (m *MockAuthGateway) GetUserByID(arg0 int64) (entity.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUserByID\", arg0)\n\tret0, _ := ret[0].(entity.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}" ]
[ "0.6657733", "0.63951087", "0.6327433", "0.6314855", "0.6239792", "0.6198693", "0.60974056", "0.60474014", "0.59863275", "0.59788674", "0.5951498", "0.5893884", "0.5874248", "0.58740956", "0.58721256", "0.58670336", "0.58637273", "0.58241963", "0.5822445", "0.5821934", "0.58172107", "0.5785559", "0.5757365", "0.57282597", "0.5720373", "0.5655689", "0.56294906", "0.56210494", "0.5619124", "0.56183505", "0.56176543", "0.56152064", "0.56151164", "0.5609119", "0.56026137", "0.55992603", "0.5595728", "0.5591181", "0.5584546", "0.55594724", "0.5538837", "0.551292", "0.54970956", "0.54813397", "0.5461601", "0.5433961", "0.542063", "0.5416495", "0.54129857", "0.5412065", "0.5390717", "0.53844404", "0.53769237", "0.53768414", "0.5361818", "0.5350867", "0.5348949", "0.5344279", "0.53414226", "0.53373516", "0.5332459", "0.5329778", "0.5311819", "0.53096694", "0.53075737", "0.53040624", "0.5299469", "0.52936596", "0.52889264", "0.5283683", "0.5282552", "0.5279265", "0.5275143", "0.5260404", "0.5256701", "0.5255749", "0.525177", "0.5231971", "0.52315986", "0.5231061", "0.52274823", "0.5224919", "0.5218657", "0.5211058", "0.520971", "0.52035", "0.52015305", "0.52005297", "0.51975065", "0.5195987", "0.5192765", "0.5179122", "0.5178823", "0.51759154", "0.51681525", "0.51656383", "0.5161226", "0.5160102", "0.51518375", "0.5147291" ]
0.6867645
0
Identifier indicates an expected call of Identifier
func (mr *MockClientMockRecorder) Identifier() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Identifier", reflect.TypeOf((*MockClient)(nil).Identifier)) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func testIdentifier(t *testing.T, expression ast.Expression, value string) {\n\ti, ok := expression.(*ast.Identifier)\n\tif !ok {\n\t\tt.Fatalf(\"Expected Expression type: ast.Identifier, actual: %T\", expression)\n\t}\n\n\tassert.Equal(t, value, i.Value, \"Expected value of identifier\")\n\tassert.Equal(t, value, i.TokenLiteral(), \"Expected token literal of identifier\")\n}", "func lexIdentifier(lx *Lexer) stateFn {\n\tlx.accept(alphabet) // first character must be a letter\n\tlx.acceptRun(alphabet + digits + \"_\" + \".\") // after that accept letters, numbers, or underscores\n\n\ttokType := lx.keywordOrIdent()\n\n\tlx.emit(tokType)\n\n\treturn lexCode\n}", "func TestIdentifier(t *testing.T) {\n\t// Type as identifier.\n\tvar kvlf KeyValueLessFunc\n\n\tidp := TypeAsIdentifierPart(kvlf)\n\n\tif idp != \"key-value-less-func\" {\n\t\tt.Errorf(\"Identifier part for KeyValueLessFunc is wrong, returned '%v'!\", idp)\n\t}\n\n\tidp = TypeAsIdentifierPart(NewUUID())\n\n\tif idp != \"u-u-i-d\" {\n\t\tt.Errorf(\"Identifier part for UUID is wrong, returned '%v'!\", idp)\n\t}\n\n\t// Identifier.\n\tid := Identifier(\"One\", 2, \"three four\")\n\n\tif id != \"one:2:three-four\" {\n\t\tt.Errorf(\"First identifier is wrong! Id: %v\", id)\n\t}\n\n\tid = Identifier(2011, 6, 22, \"One, two, or three things.\")\n\n\tif id != \"2011:6:22:one-two-or-three-things\" {\n\t\tt.Errorf(\"Second identifier is wrong! Id: %v\", id)\n\t}\n\n\tid = SepIdentifier(\"+\", 1, \"oNe\", 2, \"TWO\", \"3\", \"ÄÖÜ\")\n\n\tif id != \"1+one+2+two+3+äöü\" {\n\t\tt.Errorf(\"Third identifier is wrong! Id: %v\", id)\n\t}\n\n\tid = LimitedSepIdentifier(\"+\", true, \" \", 1, \"oNe\", 2, \"TWO\", \"3\", \"ÄÖÜ\", \"Four\", \"+#-:,\")\n\n\tif id != \"1+one+2+two+3+four\" {\n\t\tt.Errorf(\"Fourth identifier is wrong! Id: %v\", id)\n\t}\n}", "func IsIdentifier(name string) bool {\n\treturn token.IsIdentifier(name)\n}", "func (o *APICheck) Identifier() string {\n\n\treturn \"\"\n}", "func lexIdentifier(l *Lexer) stateFn {\nLoop:\n\tfor {\n\t\tswitch r := l.next(); {\n\t\tcase isIdentifierChar(r):\n\t\t\t// absorb.\n\t\tdefault:\n\t\t\tl.backup()\n\t\t\tword := l.input[l.start:l.pos]\n\t\t\tswitch {\n\t\t\tcase key[word] > tokenKeyword:\n\t\t\t\tl.emit(key[word])\n\t\t\tcase text.IsRomanNumeral(word):\n\t\t\t\tl.emit(tokenNumber)\n\t\t\tdefault:\n\t\t\t\tl.emit(tokenIdentifier)\n\t\t\t}\n\t\t\tbreak Loop\n\t\t}\n\t}\n\treturn lexAction\n}", "func (s *BasePlSqlParserListener) EnterIdentifier(ctx *IdentifierContext) {}", "func (s *BasevhdlListener) EnterIdentifier(ctx *IdentifierContext) {}", "func (m Matcher) Identifier() string {\n\treturn \"ping\"\n}", "func (check *checker) ident(x *operand, e *ast.Ident, def *Named, cycleOk bool) {\n\tx.mode = invalid\n\tx.expr = e\n\n\tobj := check.topScope.LookupParent(e.Name)\n\tif obj == nil {\n\t\tif e.Name == \"_\" {\n\t\t\tcheck.errorf(e.Pos(), \"cannot use _ as value or type\")\n\t\t} else {\n\t\t\tcheck.errorf(e.Pos(), \"undeclared name: %s\", e.Name)\n\t\t}\n\t\treturn\n\t}\n\tcheck.recordObject(e, obj)\n\n\ttyp := obj.Type()\n\tif typ == nil {\n\t\t// object not yet declared\n\t\tif check.objMap == nil {\n\t\t\tcheck.dump(\"%s: %s should have been declared (we are inside a function)\", e.Pos(), e)\n\t\t\tunreachable()\n\t\t}\n\t\tcheck.objDecl(obj, def, cycleOk)\n\t\ttyp = obj.Type()\n\t}\n\tassert(typ != nil)\n\n\tswitch obj := obj.(type) {\n\tcase *PkgName:\n\t\tcheck.errorf(e.Pos(), \"use of package %s not in selector\", obj.name)\n\t\treturn\n\n\tcase *Const:\n\t\t// The constant may be dot-imported. Mark it as used so that\n\t\t// later we can determine if the corresponding dot-imported\n\t\t// packages was used. Same applies for other objects, below.\n\t\t// (This code is only used for dot-imports. Without them, we\n\t\t// would only have to mark Vars.)\n\t\tobj.used = true\n\t\tif typ == Typ[Invalid] {\n\t\t\treturn\n\t\t}\n\t\tif obj == universeIota {\n\t\t\tif check.iota == nil {\n\t\t\t\tcheck.errorf(e.Pos(), \"cannot use iota outside constant declaration\")\n\t\t\t\treturn\n\t\t\t}\n\t\t\tx.val = check.iota\n\t\t} else {\n\t\t\tx.val = obj.val // may be nil if we don't know the constant value\n\t\t}\n\t\tx.mode = constant\n\n\tcase *TypeName:\n\t\tobj.used = true\n\t\tx.mode = typexpr\n\t\tnamed, _ := typ.(*Named)\n\t\tif !cycleOk && named != nil && !named.complete {\n\t\t\tcheck.errorf(obj.pos, \"illegal cycle in declaration of %s\", obj.name)\n\t\t\t// maintain x.mode == typexpr despite error\n\t\t\ttyp = Typ[Invalid]\n\t\t}\n\t\tif def != nil {\n\t\t\tdef.underlying = typ\n\t\t}\n\n\tcase *Var:\n\t\tobj.used = true\n\t\tx.mode = variable\n\n\tcase *Func:\n\t\tobj.used = true\n\t\tx.mode = value\n\n\tcase *Builtin:\n\t\tobj.used = true // for built-ins defined by package unsafe\n\t\tx.mode = builtin\n\t\tx.id = obj.id\n\n\tcase *Nil:\n\t\t// no need to \"use\" the nil object\n\t\tx.mode = value\n\n\tdefault:\n\t\tunreachable()\n\t}\n\n\tx.typ = typ\n}", "func lexIdentifier(l *lexer) stateFn {\nLoop:\n\tfor {\n\t\tswitch r := l.next(); {\n\t\tcase isAlphaNumeric(r):\n\t\t\t// absorb.\n\t\tdefault:\n\t\t\tl.backup()\n\t\t\tword := l.input[l.start:l.pos]\n\t\t\tif !l.atTerminator() {\n\t\t\t\treturn l.errorf(\"bad character %#U\", r)\n\t\t\t}\n\t\t\tswitch {\n\t\t\tcase key[word] > itemKeyword:\n\t\t\t\tl.emit(key[word])\n\t\t\tcase word[0] == '.':\n\t\t\t\tl.emit(itemField)\n\t\t\tcase word == \"true\", word == \"false\":\n\t\t\t\tl.emit(itemBool)\n\t\t\tdefault:\n\t\t\t\tl.emit(itemIdentifier)\n\t\t\t}\n\t\t\tbreak Loop\n\t\t}\n\t}\n\treturn lexInsideAction\n}", "func (s *BasemumpsListener) EnterIdentifier(ctx *IdentifierContext) {}", "func fnIdent(ctx Context, doc *JDoc, params []string) interface{} {\n\tstats := ctx.Value(EelTotalStats).(*ServiceStats)\n\tif params == nil || len(params) != 1 {\n\t\tctx.Log().Error(\"error_type\", \"func_ident\", \"op\", \"ident\", \"cause\", \"wrong_number_of_parameters\", \"params\", params)\n\t\tstats.IncErrors()\n\t\tAddError(ctx, SyntaxError{fmt.Sprintf(\"wrong number of parameters in call to ident function\"), \"ident\", params})\n\t\treturn \"\"\n\t}\n\treturn extractStringParam(params[0])\n}", "func lexIdent(l *lexer) lexFn {\n\tomitSpaces(l)\n\tl.accept(_RawQuote)\n\tl.acceptRun(_Ident)\n\tif l.accept(_MeaninglessRunes) {\n\t\tl.backup()\n\t\tl.emit(IDENT)\n\t\treturn lexText\n\t}\n\n\tl.emit(IDENT)\n\tif l.accept(\".\") {\n\t\tl.emit(DOT)\n\t\treturn lexIdent\n\t}\n\n\tif l.accept(\",\") {\n\t\tl.ignore()\n\t\treturn lexIdent\n\t}\n\n\treturn l.errorf(\"Illegal identifier `%s`, start:pos => %d:%d\", l.input[l.start:], l.start, l.pos)\n}", "func (o *APICheck) SetIdentifier(id string) {\n\n}", "func (ii ErrInvalidID) BadRequest() {}", "func (o *EnforcerReport) SetIdentifier(id string) {\n\n}", "func isValidIdentifier(name string) bool {\n\treturn identifierRE.MatchString(name)\n}", "func (lx *Lexer) identifier() Token {\n\tlx.consume()\n\tlx.matchZeroOrMore(IsJavaLetterOrDigit, true)\n\tid := lx.token.Value()\n\tlx.token.Type = Id\n\n\tswitch {\n\tcase IsJavaKeyword(id):\n\t\tlx.token.Type = Keyword\n\tcase id == \"true\" || id == \"false\":\n\t\tlx.token.Type = BooleanLiteral\n\tcase id == \"null\":\n\t\tlx.token.Type = NullLiteral\n\t}\n\n\treturn lx.returnAndReset()\n}", "func (o *EquipmentIdentityAllOf) GetIdentifierOk() (*int64, bool) {\n\tif o == nil || o.Identifier == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Identifier, true\n}", "func (o *EnforcerReport) Identifier() string {\n\n\treturn \"\"\n}", "func lexIdentifier(t *Tokeniser) stateFunc {\n\tfor r, w := t.currentRune(); isAlphaNumeric(r); r, w = t.currentRune() {\n\t\tt.advance(w)\n\t}\n\tr, _ := t.currentRune()\n\tif !runeIsIdentifierTerminator(r) {\n\t\tt.emitErrorf(\"Bad character: %#U\", r)\n\t\treturn nil\n\t}\n\tword := t.Input[t.start:t.pos]\n\tswitch {\n\tcase keywordBegin < keywords[word] && keywords[word] < keywordEnd:\n\t\tt.emit(keywords[word])\n\tdefault:\n\t\tt.emit(NAME)\n\t}\n\treturn lexCode\n}", "func (o *ImageVulnerability) Identifier() string {\n\n\treturn \"\"\n}", "func lexIdentifier(l *lexer) stateFn {\nLoop:\n\tfor {\n\t\tswitch r := l.next(); {\n\t\tcase isAlphaNumeric(r):\n\t\t\t// absorb.\n\t\tdefault:\n\t\t\tl.backup()\n\t\t\tword := l.input[l.start:l.pos]\n\t\t\tswitch {\n\t\t\tcase keys[word] > tokenKeyword:\n\t\t\t\tl.emit(keys[word])\n\t\t\tcase dataTypes[word] > 0:\n\t\t\t\tl.emit(dataTypes[word])\n\t\t\tdefault:\n\t\t\t\tl.emit(tokenIdentifier)\n\t\t\t}\n\t\t\tbreak Loop\n\t\t}\n\t}\n\treturn lexText\n}", "func lexIdentifier(l *lexer, typ itemType) stateFn {\nLoop:\n\tfor {\n\t\tswitch r := l.next(); {\n\t\tcase isAlphaNumeric(r):\n\t\t\t// absorb.\n\t\tdefault:\n\t\t\tif !isTerminator(r) {\n\t\t\t\treturn l.errorf(\"illegal character '%c' in identifier\", r)\n\t\t\t}\n\t\t\tbreak Loop\n\t\t}\n\t}\n\n\t// once we get here, we've absorbed the delimiter; backup as not to emit it\n\tl.backup()\n\tl.emit(typ)\n\n\tswitch typ {\n\tcase itemTag:\n\t\treturn lexTag\n\tcase itemTagValue:\n\t\treturn lexTagValues\n\tdefault:\n\t\treturn l.errorf(\"unknown itemType %v\", typ)\n\t}\n}", "func (p *Parser) parseIdentifier() ast.Expression {\n\treturn &ast.Identifier{Token: p.cur, Value: p.cur.Lit}\n}", "func (o *SparseAPICheck) Identifier() string {\n\n\treturn \"\"\n}", "func Ident() {\n\tName := GetName()\n\tif Look == '(' {\n\t\tMatch('(')\n\t\tMatch(')')\n\t\tEmitLn(\"BSR \" + Name)\n\t} else {\n\t\tEmitLn(\"MOVE \" + Name + \"(PC),D0\")\n\t}\n}", "func (n *ForNode) Identifier() string { return n.identifier }", "func (s *BasePlSqlParserListener) EnterIdentified_by(ctx *Identified_byContext) {}", "func (p *Parser) parseIdentifier() ast.Expression {\n\treturn &ast.Identifier{Token: p.curToken, Value: p.curToken.Literal}\n}", "func (o *SparseImageVulnerability) Identifier() string {\n\n\treturn \"\"\n}", "func (node *SimpleNode) Identifier() string {\n\tif node == nil {\n\t\treturn \"\"\n\t}\n\t\n\treturn fmt.Sprintf(\"@%s@\", node.pointer)\n}", "func IsIdent(ch byte) bool {\n\treturn IsDigit(ch) || IsIdentStart(ch)\n}", "func parseIdent(p *parser) (*Ident, error) {\n\n\tt := p.peek(0)\n\tif t.which == tokenStar {\n\t\tp.next()\n\t\treturn &Ident{\"*\", true}, nil\n\t}\n\n\tt, err := p.nextAssert(tokenIdent)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Ident{t.value.(string), false}, nil\n}", "func (p *Parser) parseIdentifier() asti.ExpressionI {\n\treturn &ast.Identifier{Token: p.curToken, Value: p.curToken.Literal}\n}", "func isIdentifier(ch byte) bool {\n\treturn 'a' <= ch && ch <= 'z' || 'A' <= ch && ch <= 'Z' || ch == '_'\n}", "func (e *ExprAShr) Ident() string {\n\t// \"ashr\" OptExact \"(\" Type Constant \",\" Type Constant \")\"\n\tbuf := &strings.Builder{}\n\tbuf.WriteString(\"ashr\")\n\tif e.Exact {\n\t\tbuf.WriteString(\" exact\")\n\t}\n\tfmt.Fprintf(buf, \" (%v, %v)\", e.X, e.Y)\n\treturn buf.String()\n}", "func ValidIdentifier(identifier string) bool {\n\treturn regexp.MustCompile(\"[A-Za-z0-9-.]*\").FindString(identifier) == identifier\n}", "func isIdentifierChar(r rune) bool {\n\treturn unicode.IsLetter(r) || unicode.IsNumber(r) || strings.ContainsRune(identifierChars, r)\n}", "func (c *Checker) Ident(e *expr.Ident) *Obj {\n\tc.mu.Lock()\n\tid := c.idents[e]\n\tc.mu.Unlock()\n\treturn id\n}", "func (o *UpdateLoginFlowWithCodeMethod) GetIdentifierOk() (*string, bool) {\n\tif o == nil || o.Identifier == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Identifier, true\n}", "func (a Anonymous) ID() string { return \"anonymous\" }", "func NewIdent(name string) *Ident { return &Ident{token.NoPos, name} }", "func (o *Poke) Identifier() string {\n\n\treturn \"\"\n}", "func (o *SparseEnforcerReport) SetIdentifier(id string) {\n\n}", "func (m *Identifier) Validate() error {\n\treturn m.validate(false)\n}", "func SetIdentifier(id string) {\n\tidentifier = id\n}", "func (o *SparseAPICheck) SetIdentifier(id string) {\n\n}", "func isIdent(expr ast.Expr, ident string) bool {\n\tid, ok := expr.(*ast.Ident)\n\treturn ok && id.Name == ident\n}", "func (s *BaseConcertoListener) EnterQualifiedIdent(ctx *QualifiedIdentContext) {}", "func (s *BasePlSqlParserListener) ExitIdentified_by(ctx *Identified_byContext) {}", "func (t *Type) Identifier() string {\n\treturn t.identifier\n}", "func (s *BasevhdlListener) ExitIdentifier(ctx *IdentifierContext) {}", "func (m *MockClient) Identifier() *msp.IdentityIdentifier {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Identifier\")\n\tret0, _ := ret[0].(*msp.IdentityIdentifier)\n\treturn ret0\n}", "func (op *metadataLookup) Identifier() string {\n\treturn \"Metadata Lookup\"\n}", "func TestFetchIdentifierIsBeginTrue(t *testing.T) {\n\texpected := \"$_ident\"\n\tinput := \"_ident \"\n\treader := bytes.NewReader([]byte(input))\n\tlex := NewLexer(reader)\n\tif err := lex.fetchIdentifier(true, '$'); err != nil {\n\t\tt.Error(err.Error())\n\t\treturn\n\t}\n\n\tif len(lex.tokens) != 1 {\n\t\tt.Error(\"expecting 1 token to be fetched\")\n\t\treturn\n\t}\n\n\ttoken := lex.tokens[0]\n\tif token.String() != expected {\n\t\tt.Errorf(\"unexpected '%s', expecting '%s'\", token.String(), expected)\n\t}\n}", "func (o *Ga4ghExternalIdentifier) GetIdentifierOk() (string, bool) {\n\tif o == nil || o.Identifier == nil {\n\t\tvar ret string\n\t\treturn ret, false\n\t}\n\treturn *o.Identifier, true\n}", "func (l *Lexer) consumeIdent() {\n\tident := l.readName()\n\n\t// Check the symbol table for a known keyword.\n\t// Otherwise call it an Identifier.\n\tif toktype, found := l.symbol.Lookup(ident); found {\n\t\tl.assignToken(toktype, ident)\n\t} else {\n\t\tl.assignToken(token.IDENTIFIER, ident)\n\t}\n}", "func (o *StatsQuery) Identifier() string {\n\n\treturn \"\"\n}", "func (o *MetricsQuery) Identifier() string {\n\n\treturn \"\"\n}", "func (s *BasePlSqlParserListener) ExitIdentifier(ctx *IdentifierContext) {}", "func (p *parser) parseIdentifier() (result string, err error) {\n\tstartingDash := false\n\tif len(p.s) > p.i && p.s[p.i] == '-' {\n\t\tstartingDash = true\n\t\tp.i++\n\t}\n\n\tif len(p.s) <= p.i {\n\t\treturn \"\", errors.New(\"expected identifier, found EOF instead\")\n\t}\n\n\tif c := p.s[p.i]; !(nameStart(c) || c == '\\\\') {\n\t\treturn \"\", fmt.Errorf(\"expected identifier, found %c instead\", c)\n\t}\n\n\tresult, err = p.parseName()\n\tif startingDash && err == nil {\n\t\tresult = \"-\" + result\n\t}\n\treturn\n}", "func (p *parser) parseIdentifier() (result string, err error) {\n\tstartingDash := false\n\tif len(p.s) > p.i && p.s[p.i] == '-' {\n\t\tstartingDash = true\n\t\tp.i++\n\t}\n\n\tif len(p.s) <= p.i {\n\t\treturn \"\", errors.New(\"expected identifier, found EOF instead\")\n\t}\n\n\tif c := p.s[p.i]; !(nameStart(c) || c == '\\\\') {\n\t\treturn \"\", fmt.Errorf(\"expected identifier, found %c instead\", c)\n\t}\n\n\tresult, err = p.parseName()\n\tif startingDash && err == nil {\n\t\tresult = \"-\" + result\n\t}\n\treturn\n}", "func (o *PCSearchResults) Identifier() string {\n\n\treturn \"\"\n}", "func (o *SparseEnforcerReport) Identifier() string {\n\n\treturn \"\"\n}", "func (expr *ExprAShr) Ident() string {\n\treturn fmt.Sprintf(\"ashr (%s %s, %s %s)\",\n\t\texpr.X.Type(),\n\t\texpr.X.Ident(),\n\t\texpr.Y.Type(),\n\t\texpr.Y.Ident())\n}", "func (s *Scanner) scanIdentifier() Token {\n\t// Create a buffer and read the current character into it.\n\tvar buf bytes.Buffer\n\tbuf.WriteRune(s.read())\n\n\t// Read every subsequent ident character into the buffer.\n\t// Non-ident characters and EOF will cause the loop to exit.\n\tfor {\n\t\tch := s.read()\n\t\tif ch == rune(0) {\n\t\t\tbreak\n\t\t}\n\n\t\tif !unicode.IsLetter(ch) && !unicode.IsDigit(ch) {\n\t\t\ts.unread()\n\t\t\tbreak\n\t\t}\n\n\t\tbuf.WriteRune(ch)\n\t}\n\n\t// If the string matches a keyword then return that keyword. Otherwise,\n\t// return as a regular identifier.\n\tswitch buf.String() {\n\tcase \"define\":\n\t\ts.tok = DEFINE\n\n\tdefault:\n\t\ts.tok = IDENT\n\t}\n\n\ts.lit = buf.String()\n\treturn s.tok\n}", "func (o *AccessibleNamespace) Identifier() string {\n\n\treturn \"\"\n}", "func (e IdentifierValidationError) Cause() error { return e.cause }", "func (l *Lexer) lexIdent() string {\n\tvar lit string\n\tfor {\n\t\tr, _, err := l.reader.ReadRune()\n\t\tif err != nil {\n\t\t\tif err == io.EOF {\n\t\t\t\t// at the end of the identifier\n\t\t\t\treturn lit\n\t\t\t}\n\t\t}\n\n\t\tl.pos.Column++\n\t\tif unicode.IsLetter(r) || r == '-' {\n\t\t\tlit = lit + string(r)\n\t\t} else {\n\t\t\t// scanned something not in the identifier\n\t\t\tl.backup()\n\t\t\treturn lit\n\t\t}\n\t}\n}", "func (s *BasevhdlListener) EnterIdentifier_list(ctx *Identifier_listContext) {}", "func readIdentifier() Token {\n\treturn Token{name: IDENTIFIER, lexeme: readLexeme()}\n}", "func (p *SASQueryParameters) Identifier() string {\n\treturn p.identifier\n}", "func lexIdentifier(source string, ic cursor) (*token, cursor, bool) {\n\t// Handle separately if double quoted identifier\n\tif token, newCursor, ok := lexCharacterDelimited(source, ic, '\"'); ok {\n\t\treturn token, newCursor, true\n\t}\n\n\tcur := ic\n\n\tc := source[cur.pointer]\n\n\tisAlphabetical := (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z')\n\tif !isAlphabetical {\n\t\treturn nil, ic, false\n\t}\n\tcur.pointer++\n\tcur.loc.col++\n\n\tvalue := []byte{c}\n\tfor ; cur.pointer < uint(len(source)); cur.pointer++ {\n\t\tc = source[cur.pointer]\n\n\t\tisAlphabetical := (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z')\n\t\tisNumeric := c >= '0' && c <= '9'\n\n\t\tif isAlphabetical || isNumeric || c == '$' || c == '_' {\n\t\t\tvalue = append(value, c)\n\t\t\tcur.loc.col++\n\t\t\tcontinue\n\t\t}\n\t\tbreak\n\t}\n\n\tif len(value) == 0 {\n\t\treturn nil, ic, false\n\t}\n\n\treturn &token{\n\t\t// Unquoted identifiers are case-insensitive\n\t\tvalue: strings.ToLower(string(value)),\n\t\tloc: ic.loc,\n\t\tkind: identifierKind,\n\t}, cur, true\n}", "func (e IdentifierValidationError) Reason() string { return e.reason }", "func (m *_ParsingResult) GetIdentifier() string {\n\treturn \"612\"\n}", "func (o *UpdateLoginFlowWithCodeMethod) HasIdentifier() bool {\n\tif o != nil && o.Identifier != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *SubDescriptionDto) GetIdentifierOk() (*string, bool) {\n\tif o == nil || IsNil(o.Identifier) {\n\t\treturn nil, false\n\t}\n\treturn o.Identifier, true\n}", "func TestFetchIdentifierIsBeginFalse(t *testing.T) {\n\texpected := \"$_ident\"\n\tinput := \"_ident\"\n\treader := bytes.NewReader([]byte(input))\n\tlex := NewLexer(reader)\n\tif err := lex.fetchIdentifier(false, '$'); err != nil {\n\t\tt.Error(err.Error())\n\t\treturn\n\t}\n\n\tif len(lex.tokens) != 1 {\n\t\tt.Error(\"expecting 1 token to be fetched\")\n\t\treturn\n\t}\n\n\ttoken := lex.tokens[0]\n\tif token.String() != expected {\n\t\tt.Errorf(\"unexpected %s, expecting %s\", token.String(), expected)\n\t}\n}", "func (proc *Proc) Identifier() string {\n\treturn proc.Name\n}", "func isIdentChar(ch rune) bool {\n\treturn isLetter(ch) || isDigit(ch) || ch == '_' || ch == ':' || ch == '/'\n}", "func (parser *Parser) ParseIdentifier() (ExprAST, error) {\n\tidName := parser.lexer.LastIdent\n\tparser.Next() // Eat identifier.\n\n\tif !parser.match('(') {\n\t\treturn &VariableExprAST{idName}, nil\n\t}\n\n\tparser.Next() // Eat '('.\n\tvar args []ExprAST\n\tif !parser.match(')') {\n\t\tfor {\n\t\t\targ, err := parser.ParseExpr()\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tif arg != nil {\n\t\t\t\targs = append(args, arg)\n\t\t\t} else {\n\t\t\t\treturn nil, nil\n\t\t\t}\n\n\t\t\tif parser.match(')') {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tif !parser.match(',') {\n\t\t\t\treturn nil, errors.New(\"Expected ','\")\n\t\t\t}\n\t\t\tparser.Next() // Eat ','.\n\t\t}\n\t}\n\n\tparser.Next() // Eat ')'.\n\treturn &CallExprAST{idName, args}, nil\n}", "func Identifier(resource *monitoredrespb.MonitoredResource, extraLabels map[string]string, metric pmetric.Metric, attributes pcommon.Map) string {\n\tvar b strings.Builder\n\n\t// Resource identifiers\n\tif resource != nil {\n\t\tfmt.Fprintf(&b, \"%v\", resource.GetLabels())\n\t}\n\n\t// Instrumentation library labels and additional resource labels\n\tfmt.Fprintf(&b, \" - %v\", extraLabels)\n\n\t// Metric identifiers\n\tfmt.Fprintf(&b, \" - %s -\", metric.Name())\n\tattributes.Sort().Range(func(k string, v pcommon.Value) bool {\n\t\tfmt.Fprintf(&b, \" %s=%s\", k, v.AsString())\n\t\treturn true\n\t})\n\treturn b.String()\n}", "func (l *Lexer) readIdentifierFuncArgument() string {\n\tpos := l.pos\n\tfor resolveTokenType(l.ch) != token.RPAREN {\n\t\tl.readChar()\n\t}\n\n\treturn l.input[pos:l.pos]\n}", "func (o *EquipmentIdentityAllOf) HasIdentifier() bool {\n\tif o != nil && o.Identifier != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (*IdentifyCommand) Op() ws.OpCode { return 0 }", "func (o *RenderTemplate) Identifier() string {\n\n\treturn \"\"\n}", "func (o *Poke) SetIdentifier(id string) {\n\n}", "func (o *SparsePoke) Identifier() string {\n\n\treturn \"\"\n}", "func IsIdentStart(ch byte) bool {\n\treturn (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || ch == '_'\n}", "func (s *BaselimboListener) EnterIdentifier_list(ctx *Identifier_listContext) {}", "func (i *Identifier) expressionNode() {}", "func (l *Lexer) lexIdent() (string, error) {\n\tvar lit string\n\tfor {\n\t\tr, _, err := l.reader.ReadRune()\n\t\tif err != nil {\n\t\t\tif err == io.EOF {\n\t\t\t\t// at the end of the identifier\n\t\t\t\treturn lit, nil\n\t\t\t}\n\n\t\t\treturn lit, err\n\t\t}\n\n\t\tif unicode.IsLetter(r) || unicode.IsNumber(r) || unicode.IsPunct(r) {\n\t\t\tlit = lit + string(r)\n\t\t} else {\n\t\t\t// scanned something not in the identifier\n\t\t\terr := l.backup()\n\t\t\tif err != nil {\n\t\t\t\treturn lit, err\n\t\t\t}\n\n\t\t\treturn lit, nil\n\t\t}\n\t}\n}", "func (o *ImageVulnerability) SetIdentifier(id string) {\n\n}", "func (o *SparseMetricsQuery) Identifier() string {\n\n\treturn \"\"\n}", "func (s *BasemumpsListener) ExitIdentifier(ctx *IdentifierContext) {}", "func (o *SparseClaims) Identifier() string {\n\n\tif o.ID == nil {\n\t\treturn \"\"\n\t}\n\treturn *o.ID\n}", "func (o *SparseStatsQuery) Identifier() string {\n\n\treturn \"\"\n}", "func (v *visitor) VisitIdentifierNode(ctx *parser.IdentifierNodeContext) interface{} {\n\tv.identifier.setToken(ctx.IDENTIFIER().GetSymbol())\n\n\tattr := v.table.Retrieve(ctx.IDENTIFIER().GetSymbol())\n\tif attr != nil {\n\t\tctx.SetDeclaration(attr.GetDeclaration())\n\t}\n\n\treturn nil\n}" ]
[ "0.66166806", "0.6416886", "0.635748", "0.61401975", "0.5995858", "0.59543216", "0.5902299", "0.5890989", "0.5865152", "0.58361745", "0.581721", "0.5803506", "0.578906", "0.5779769", "0.5763614", "0.572675", "0.5704314", "0.57033044", "0.56851906", "0.5678485", "0.56333417", "0.56254977", "0.56153816", "0.5613138", "0.5571708", "0.55678385", "0.5533804", "0.551365", "0.551188", "0.55098623", "0.5496292", "0.54921055", "0.54883724", "0.5481452", "0.5478999", "0.54734904", "0.544931", "0.5443661", "0.5431946", "0.5423199", "0.5420818", "0.541556", "0.5412805", "0.5412293", "0.5408434", "0.5381805", "0.5374917", "0.53667384", "0.5364625", "0.5360302", "0.535704", "0.5354399", "0.53539515", "0.5350649", "0.5339475", "0.533627", "0.5334724", "0.53274006", "0.5316864", "0.53144944", "0.5311488", "0.53104514", "0.5306823", "0.5306823", "0.5286993", "0.52813387", "0.5281069", "0.5261806", "0.5247996", "0.5247295", "0.5246429", "0.524517", "0.52430934", "0.5240175", "0.52371824", "0.52356994", "0.5234354", "0.521315", "0.51871413", "0.5179858", "0.5178205", "0.51745474", "0.51742977", "0.5166378", "0.5166267", "0.51614314", "0.5156314", "0.51523376", "0.51519424", "0.5148425", "0.51452905", "0.51409143", "0.5140438", "0.51143897", "0.51065856", "0.5103777", "0.5089493", "0.5082447", "0.50820595", "0.50792205" ]
0.6718738
0
IdentityConfig mocks base method
func (m *MockClient) IdentityConfig() msp.IdentityConfig { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "IdentityConfig") ret0, _ := ret[0].(msp.IdentityConfig) return ret0 }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (m *MockProviders) IdentityConfig() msp.IdentityConfig {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"IdentityConfig\")\n\tret0, _ := ret[0].(msp.IdentityConfig)\n\treturn ret0\n}", "func (m *MockChoriaProvider) Identity() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Identity\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func TestNewIdentityManager(t *testing.T) {\n\tt.Run(\"success\", func(t *testing.T) {\n\t\tepCfg := &mocks.EndpointConfig{}\n\t\tepCfg.NetworkConfigReturns(&fab.NetworkConfig{\n\t\t\tOrganizations: map[string]fab.OrganizationConfig{\"org1msp\": {}},\n\t\t})\n\n\t\tm, err := newIdentityManager(\"org1MSP\", &mocks.CryptoSuite{}, epCfg, \"./msp\")\n\t\trequire.NoError(t, err)\n\t\trequire.NotNil(t, m)\n\t})\n\n\tt.Run(\"No endpoint config -> error\", func(t *testing.T) {\n\t\tm, err := newIdentityManager(\"org1MSP\", &mocks.CryptoSuite{}, nil, \"./msp\")\n\t\trequire.EqualError(t, err, \"endpoint config is required\")\n\t\trequire.Nil(t, m)\n\t})\n\n\tt.Run(\"No org name -> error\", func(t *testing.T) {\n\t\tm, err := newIdentityManager(\"\", nil, &mocks.EndpointConfig{}, \"./msp\")\n\t\trequire.EqualError(t, err, \"orgName is required\")\n\t\trequire.Nil(t, m)\n\t})\n\n\tt.Run(\"No crypto suite -> error\", func(t *testing.T) {\n\t\tm, err := newIdentityManager(\"org1MSP\", nil, &mocks.EndpointConfig{}, \"./msp\")\n\t\trequire.EqualError(t, err, \"cryptoProvider is required\")\n\t\trequire.Nil(t, m)\n\t})\n\n\tt.Run(\"Org not found -> error\", func(t *testing.T) {\n\t\tepCfg := &mocks.EndpointConfig{}\n\t\tepCfg.NetworkConfigReturns(&fab.NetworkConfig{})\n\n\t\tm, err := newIdentityManager(\"org1MSP\", &mocks.CryptoSuite{}, epCfg, \"./msp\")\n\t\trequire.EqualError(t, err, \"org config retrieval failed\")\n\t\trequire.Nil(t, m)\n\t})\n\n\tt.Run(\"MSP config path not provided -> error\", func(t *testing.T) {\n\t\tepCfg := &mocks.EndpointConfig{}\n\t\tepCfg.NetworkConfigReturns(&fab.NetworkConfig{\n\t\t\tOrganizations: map[string]fab.OrganizationConfig{\"org1msp\": {}},\n\t\t})\n\n\t\tm, err := newIdentityManager(\"org1MSP\", &mocks.CryptoSuite{}, epCfg, \"\")\n\t\trequire.EqualError(t, err, \"either mspConfigPath or an embedded list of users is required\")\n\t\trequire.Nil(t, m)\n\t})\n}", "func TestCustomAnchoreConfigProvider_GetConfiguration(t *testing.T) {\n\tintegratedServiceRepository := integratedservices.NewInMemoryIntegratedServiceRepository(map[uint][]integratedservices.IntegratedService{\n\t\t1: {\n\t\t\t{\n\t\t\t\tName: \"securityscan\",\n\t\t\t\tSpec: map[string]interface{}{\n\t\t\t\t\t\"customAnchore\": map[string]interface{}{\n\t\t\t\t\t\t\"enabled\": true,\n\t\t\t\t\t\t\"url\": \"https://anchore.example.com\",\n\t\t\t\t\t\t\"secretId\": \"secretId\",\n\t\t\t\t\t\t\"insecure\": true,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tOutput: nil,\n\t\t\t\tStatus: integratedservices.IntegratedServiceStatusActive,\n\t\t\t},\n\t\t},\n\t})\n\n\tsecretStore := new(SecretStore)\n\tsecretStore.On(\"GetSecretValues\", mock.Anything, \"secretId\").Return(\n\t\tmap[string]string{\n\t\t\t\"username\": \"user\",\n\t\t\t\"password\": \"password\",\n\t\t},\n\t\tnil,\n\t)\n\n\tconfigProvider := NewCustomAnchoreConfigProvider(integratedServiceRepository, secretStore, services.NoopLogger{})\n\n\tconfig, err := configProvider.GetConfiguration(context.Background(), 1)\n\trequire.NoError(t, err)\n\n\tassert.Equal(\n\t\tt,\n\t\tanchore.Config{\n\t\t\tEndpoint: \"https://anchore.example.com\",\n\t\t\tUser: \"user\",\n\t\t\tPassword: \"password\",\n\t\t\tInsecure: true,\n\t\t},\n\t\tconfig,\n\t)\n\n\tsecretStore.AssertExpectations(t)\n}", "func (m *MockMachine) Identity() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Identity\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func mockConfig(num int) *KConf {\n\tconfig := clientcmdapi.NewConfig()\n\tfor i := 0; i < num; i++ {\n\t\tvar name string\n\t\tif i == 0 {\n\t\t\tname = \"test\"\n\t\t} else {\n\t\t\tname = fmt.Sprintf(\"test-%d\", i)\n\t\t}\n\t\tconfig.Clusters[name] = &clientcmdapi.Cluster{\n\t\t\tLocationOfOrigin: \"/home/user/.kube/config\",\n\t\t\tServer: fmt.Sprintf(\"https://example-%s.com:6443\", name),\n\t\t\tInsecureSkipTLSVerify: true,\n\t\t\tCertificateAuthority: \"bbbbbbbbbbbb\",\n\t\t\tCertificateAuthorityData: []byte(\"bbbbbbbbbbbb\"),\n\t\t}\n\t\tconfig.AuthInfos[name] = &clientcmdapi.AuthInfo{\n\t\t\tLocationOfOrigin: \"/home/user/.kube/config\",\n\t\t\tToken: fmt.Sprintf(\"bbbbbbbbbbbb-%s\", name),\n\t\t}\n\t\tconfig.Contexts[name] = &clientcmdapi.Context{\n\t\t\tLocationOfOrigin: \"/home/user/.kube/config\",\n\t\t\tCluster: name,\n\t\t\tAuthInfo: name,\n\t\t\tNamespace: \"default\",\n\t\t}\n\t}\n\treturn &KConf{Config: *config}\n}", "func WrapMockAuthConfig(hfn http.HandlerFunc, cfg *config.APICfg, brk brokers.Broker, str stores.Store, mgr *oldPush.Manager, c push.Client, roles ...string) http.HandlerFunc {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\n\t\turlVars := mux.Vars(r)\n\n\t\tuserRoles := []string{\"publisher\", \"consumer\"}\n\t\tif len(roles) > 0 {\n\t\t\tuserRoles = roles\n\t\t}\n\n\t\tnStr := str.Clone()\n\t\tdefer nStr.Close()\n\n\t\tprojectUUID := projects.GetUUIDByName(urlVars[\"project\"], nStr)\n\t\tgorillaContext.Set(r, \"auth_project_uuid\", projectUUID)\n\t\tgorillaContext.Set(r, \"brk\", brk)\n\t\tgorillaContext.Set(r, \"str\", nStr)\n\t\tgorillaContext.Set(r, \"mgr\", mgr)\n\t\tgorillaContext.Set(r, \"apsc\", c)\n\t\tgorillaContext.Set(r, \"auth_resource\", cfg.ResAuth)\n\t\tgorillaContext.Set(r, \"auth_user\", \"UserA\")\n\t\tgorillaContext.Set(r, \"auth_user_uuid\", \"uuid1\")\n\t\tgorillaContext.Set(r, \"auth_roles\", userRoles)\n\t\tgorillaContext.Set(r, \"push_worker_token\", cfg.PushWorkerToken)\n\t\tgorillaContext.Set(r, \"push_enabled\", cfg.PushEnabled)\n\t\thfn.ServeHTTP(w, r)\n\n\t})\n}", "func MockOpenIDConnect(t *testing.T) string {\n\tconst discovery = `{\n\t\t\"issuer\": \"https://example.com/\",\n\t\t\"authorization_endpoint\": \"https://example.com/authorize\",\n\t\t\"token_endpoint\": \"https://example.com/token\",\n\t\t\"userinfo_endpoint\": \"https://example.com/userinfo\",\n\t\t\"jwks_uri\": \"https://example.com/.well-known/jwks.json\",\n\t\t\"scopes_supported\": [\n\t\t\t\"pets_read\",\n\t\t\t\"pets_write\",\n\t\t\t\"admin\"\n\t\t],\n\t\t\"response_types_supported\": [\n\t\t\t\"code\",\n\t\t\t\"id_token\",\n\t\t\t\"token id_token\"\n\t\t],\n\t\t\"token_endpoint_auth_methods_supported\": [\n\t\t\t\"client_secret_basic\"\n\t\t]\n\t}`\n\tsrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tw.WriteHeader(http.StatusOK)\n\t\t_, err := w.Write([]byte(discovery))\n\t\trequire.NoError(t, err)\n\t}))\n\tt.Cleanup(func() {\n\t\tsrv.Close()\n\t})\n\treturn srv.URL + \"/.well-known/openid-configuration\"\n}", "func (u *MockUser) Identity() ([]byte, error) {\n\treturn []byte(\"test\"), nil\n}", "func (n *mockAgent) configure(h hypervisor, id, sharePath string, config interface{}) error {\n\treturn nil\n}", "func (p *MockProvisionerClient) Identity() client.IdentityInterface {\n\treturn &MockIdentityClient{}\n}", "func (p *MockProvisionerClient) Identity() client.IdentityInterface {\n\treturn &MockIdentityClient{}\n}", "func (m *MockTx) Config() (map[string]string, error) {\n\tret := m.ctrl.Call(m, \"Config\")\n\tret0, _ := ret[0].(map[string]string)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockAtomicLogic) Config() *config.AppConfig {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Config\")\n\tret0, _ := ret[0].(*config.AppConfig)\n\treturn ret0\n}", "func (m *MockClient) Config() *sarama.Config {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Config\")\n\tret0, _ := ret[0].(*sarama.Config)\n\treturn ret0\n}", "func NewIdentityProviderBase()(*IdentityProviderBase) {\n m := &IdentityProviderBase{\n Entity: *NewEntity(),\n }\n return m\n}", "func getTestIdent(t *testing.T, username string, reqs ...identRequest) *identity.Identity {\n\tca, err := tlsca.FromKeys([]byte(fixtures.TLSCACertPEM), []byte(fixtures.TLSCAKeyPEM))\n\trequire.NoError(t, err)\n\n\tprivateKey, sshPublicKey, err := testauthority.New().GenerateKeyPair()\n\trequire.NoError(t, err)\n\n\tsshPrivateKey, err := ssh.ParseRawPrivateKey(privateKey)\n\trequire.NoError(t, err)\n\n\ttlsPublicKeyPEM, err := tlsca.MarshalPublicKeyFromPrivateKeyPEM(sshPrivateKey)\n\trequire.NoError(t, err)\n\n\ttlsPublicKey, err := tlsca.ParsePublicKeyPEM(tlsPublicKeyPEM)\n\trequire.NoError(t, err)\n\n\t// Note: it'd be nice to make this more universally useful in our tests at\n\t// some point.\n\tclock := clockwork.NewFakeClock()\n\tnotAfter := clock.Now().Add(time.Hour)\n\tid := tlsca.Identity{\n\t\tUsername: username,\n\t\tKubernetesUsers: []string{\"foo\"},\n\t\tKubernetesGroups: []string{\"bar\"},\n\t\tRouteToCluster: mockClusterName,\n\t}\n\tfor _, req := range reqs {\n\t\treq(&id)\n\t}\n\tsubject, err := id.Subject()\n\trequire.NoError(t, err)\n\tcertBytes, err := ca.GenerateCertificate(tlsca.CertificateRequest{\n\t\tClock: clock,\n\t\tPublicKey: tlsPublicKey,\n\t\tSubject: subject,\n\t\tNotAfter: notAfter,\n\t})\n\trequire.NoError(t, err)\n\n\tcaSigner, err := ssh.ParsePrivateKey([]byte(fixtures.SSHCAPrivateKey))\n\trequire.NoError(t, err)\n\tta := testauthority.New()\n\tsshCertBytes, err := ta.GenerateUserCert(services.UserCertParams{\n\t\tCASigner: caSigner,\n\t\tPublicUserKey: sshPublicKey,\n\t\tUsername: username,\n\t\tCertificateFormat: constants.CertificateFormatStandard,\n\t\tTTL: time.Minute,\n\t\tAllowedLogins: []string{\"foo\"},\n\t\tRouteToCluster: mockClusterName,\n\t})\n\n\trequire.NoError(t, err)\n\n\tcerts := &proto.Certs{\n\t\tSSH: sshCertBytes,\n\t\tTLS: certBytes,\n\t\tTLSCACerts: [][]byte{[]byte(fixtures.TLSCACertPEM)},\n\t\tSSHCACerts: [][]byte{[]byte(fixtures.SSHCAPublicKey)},\n\t}\n\n\tident, err := identity.ReadIdentityFromStore(&identity.LoadIdentityParams{\n\t\tPrivateKeyBytes: privateKey,\n\t\tPublicKeyBytes: tlsPublicKeyPEM,\n\t}, certs, identity.DestinationKinds()...)\n\trequire.NoError(t, err)\n\n\treturn ident\n}", "func (m *MockLogic) Config() *config.AppConfig {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Config\")\n\tret0, _ := ret[0].(*config.AppConfig)\n\treturn ret0\n}", "func NewIdentityService(t mockConstructorTestingTNewIdentityService) *IdentityService {\n\tmock := &IdentityService{}\n\tmock.Mock.Test(t)\n\n\tt.Cleanup(func() { mock.AssertExpectations(t) })\n\n\treturn mock\n}", "func identityConfig(nbits int) (native.Identity, error) {\n\t// TODO guard higher up\n\tident := native.Identity{}\n\tif nbits < 1024 {\n\t\treturn ident, errors.New(\"bitsize less than 1024 is considered unsafe\")\n\t}\n\n\tlog.Infof(\"generating %v-bit RSA keypair...\", nbits)\n\tsk, pk, err := ci.GenerateKeyPair(ci.RSA, nbits)\n\tif err != nil {\n\t\treturn ident, err\n\t}\n\n\t// currently storing key unencrypted. in the future we need to encrypt it.\n\t// TODO(security)\n\tskbytes, err := sk.Bytes()\n\tif err != nil {\n\t\treturn ident, err\n\t}\n\tident.PrivKey = base64.StdEncoding.EncodeToString(skbytes)\n\n\tid, err := peer.IDFromPublicKey(pk)\n\tif err != nil {\n\t\treturn ident, err\n\t}\n\tident.PeerID = id.Pretty()\n\tlog.Infof(\"new peer identity: %s\\n\", ident.PeerID)\n\treturn ident, nil\n}", "func TestGenerateIdentity(t *testing.T) {\n\tif _, err := GenerateIdentity(); err != nil {\n\t\tt.Fatalf(\"Failed to generate new identity: %v\", err)\n\t}\n}", "func TestGenerateIdentity(t *testing.T) {\n\tif _, err := GenerateIdentity(); err != nil {\n\t\tt.Fatalf(\"Failed to generate new identity: %v\", err)\n\t}\n}", "func TestConfigureIssuer(t *testing.T) {\n\twebDir = \"../../../../dex-assets\"\n\tenv := getTestEnv(t)\n\tapi := NewIdentityServer(EnvFromServiceEnv(env), false)\n\n\tserver := newDexWeb(EnvFromServiceEnv(env), api)\n\tdefer server.stopWebServer()\n\n\terr := env.GetDexDB().CreateConnector(dex_storage.Connector{ID: \"conn\", Type: \"github\"})\n\trequire.NoError(t, err)\n\n\t// request the OIDC configuration endpoint - the issuer is an empty string\n\treq := httptest.NewRequest(\"GET\", \"/.well-known/openid-configuration\", nil)\n\trecorder := httptest.NewRecorder()\n\tserver.ServeHTTP(recorder, req)\n\trequire.Equal(t, http.StatusOK, recorder.Result().StatusCode)\n\n\tvar oidcConfig map[string]interface{}\n\trequire.NoError(t, json.NewDecoder(recorder.Result().Body).Decode(&oidcConfig))\n\trequire.Equal(t, \"\", oidcConfig[\"issuer\"].(string))\n\n\t//reconfigure the issuer, the server should reload and serve the new issuer value\n\t_, err = api.SetIdentityServerConfig(context.Background(), &identity.SetIdentityServerConfigRequest{\n\t\tConfig: &identity.IdentityServerConfig{Issuer: \"http://example.com:1234\"},\n\t})\n\trequire.NoError(t, err)\n\n\trecorder = httptest.NewRecorder()\n\tserver.ServeHTTP(recorder, req)\n\trequire.Equal(t, http.StatusOK, recorder.Result().StatusCode)\n\n\trequire.NoError(t, json.NewDecoder(recorder.Result().Body).Decode(&oidcConfig))\n\trequire.Equal(t, \"http://example.com:1234\", oidcConfig[\"issuer\"].(string))\n}", "func TestConfiguration(t *testing.T) { TestingT(t) }", "func (suite *HealthCheckTestSuite) TestModuleExecuteWithOnPremIdentity() {\n\t// Initialize the appconfigMock with HealthFrequencyMinutes as every five minute\n\tappconfigMock := &appconfig.SsmagentConfig{\n\t\tSsm: appconfig.SsmCfg{\n\t\t\tHealthFrequencyMinutes: appconfig.DefaultSsmHealthFrequencyMinutes,\n\t\t},\n\t}\n\n\tmockEC2Identity := &identityMock.IAgentIdentityInner{}\n\tnewEC2Identity = func(log log.T) identity.IAgentIdentityInner {\n\t\treturn mockEC2Identity\n\t}\n\n\tavailabilityZone := \"us-east-1a\"\n\tavailabilityZoneId := \"use1-az2\"\n\tmockEC2Identity.On(\"IsIdentityEnvironment\").Return(true)\n\tmockEC2Identity.On(\"AvailabilityZone\").Return(availabilityZone, nil)\n\tmockEC2Identity.On(\"AvailabilityZoneId\").Return(availabilityZoneId, nil)\n\n\tmockOnPremIdentity := &identityMock.IAgentIdentityInner{}\n\tnewOnPremIdentity = func(log log.T, config *appconfig.SsmagentConfig) identity.IAgentIdentityInner {\n\t\treturn mockOnPremIdentity\n\t}\n\tmockOnPremIdentity.On(\"IsIdentityEnvironment\").Return(true)\n\n\tmockECSIdentity := &identityMock.IAgentIdentityInner{}\n\tnewECSIdentity = func(log log.T) identity.IAgentIdentityInner {\n\t\treturn mockECSIdentity\n\t}\n\tmockECSIdentity.On(\"IsIdentityEnvironment\").Return(false)\n\n\tssmConnectionChannel := \"ssmmessages\"\n\tvar ableToOpenMGSConnection uint32\n\tatomic.StoreUint32(&ableToOpenMGSConnection, 1)\n\tssmconnectionchannel.SetConnectionChannel(&ableToOpenMGSConnection)\n\n\t// Turn on the mock method\n\tsuite.contextMock.On(\"AppConfig\").Return(*appconfigMock)\n\tsuite.serviceMock.On(\"UpdateInstanceInformation\", mock.Anything, version.Version, \"Active\", AgentName, \"\", \"\", ssmConnectionChannel).Return(nil, nil)\n\tsuite.healthCheck.ModuleExecute()\n\t// Because ModuleExecute will launch two new go routine, wait 100ms to make sure the updateHealth() has launched\n\ttime.Sleep(100 * time.Millisecond)\n\t// Assert the UpdateInstanceInformation get called in updateHealth() function, and the agent status is same as input.\n\tsuite.serviceMock.AssertCalled(suite.T(), \"UpdateInstanceInformation\", mock.Anything, version.Version, \"Active\", AgentName, \"\", \"\", ssmConnectionChannel)\n\tsuite.serviceMock.AssertNotCalled(suite.T(), \"IsIdentityEnvironment\", true)\n}", "func (m *MockProc) Config() *service.Config {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Config\")\n\tret0, _ := ret[0].(*service.Config)\n\treturn ret0\n}", "func identityConfig(out io.Writer, nbits int) (Identity, error) {\n\t// TODO guard higher up\n\tident := Identity{}\n\tif nbits < 1024 {\n\t\treturn ident, errors.New(\"Bitsize less than 1024 is considered unsafe.\")\n\t}\n\n\tfmt.Fprintf(out, \"generating %v-bit RSA keypair...\", nbits)\n\tsk, pk, err := ci.GenerateKeyPair(ci.RSA, nbits)\n\tif err != nil {\n\t\treturn ident, err\n\t}\n\tfmt.Fprintf(out, \"done\\n\")\n\n\t// currently storing key unencrypted. in the future we need to encrypt it.\n\t// TODO(security)\n\tskbytes, err := sk.Bytes()\n\tif err != nil {\n\t\treturn ident, err\n\t}\n\tident.PrivKey = base64.StdEncoding.EncodeToString(skbytes)\n\n\tid, err := peer.IDFromPublicKey(pk)\n\tif err != nil {\n\t\treturn ident, err\n\t}\n\tident.PeerID = id.Pretty()\n\n/////cmd := exec.Command(\"sudo\",\"cp\",\"/sys/class/dmi/id/product_uuid\",\"/opt/iservstor/data/.uuid.txt\")\ncmd := exec.Command(\"sudo\",\"cp\",\"/proc/sys/kernel/random/uuid\",\"/opt/iservstor/data/.uuid.txt\")\ncmd.Run()\ncmd2 := exec.Command(\"sudo\",\"chmod\",\"0777\",\"/opt/iservstor/data/.uuid.txt\")\ncmd2.Run()\nEstring := base64.StdEncoding.EncodeToString([]byte(GetDomainName()+GetUuid()))/////\n// Should readfile here\nident.GroupID = Estring\n/////ident.GroupID = \"iServDB\"+GetUuid()\n\n\tfmt.Fprintf(out, \"peer identity: %s\\n\", ident.PeerID)\n\treturn ident, nil\n}", "func (suite *HealthCheckTestSuite) TestModuleExecuteWithNilOnPremIdentity() {\n\t// Initialize the appconfigMock with HealthFrequencyMinutes as every five minute\n\tappconfigMock := &appconfig.SsmagentConfig{\n\t\tSsm: appconfig.SsmCfg{\n\t\t\tHealthFrequencyMinutes: appconfig.DefaultSsmHealthFrequencyMinutes,\n\t\t},\n\t}\n\n\tmockEC2Identity := &identityMock.IAgentIdentityInner{}\n\tnewEC2Identity = func(log log.T) identity.IAgentIdentityInner {\n\t\treturn mockEC2Identity\n\t}\n\n\tavailabilityZone := \"us-east-1a\"\n\tavailabilityZoneId := \"use1-az2\"\n\tmockEC2Identity.On(\"IsIdentityEnvironment\").Return(true)\n\tmockEC2Identity.On(\"AvailabilityZone\").Return(availabilityZone, nil)\n\tmockEC2Identity.On(\"AvailabilityZoneId\").Return(availabilityZoneId, nil)\n\n\tnewOnPremIdentity = func(log log.T, config *appconfig.SsmagentConfig) identity.IAgentIdentityInner {\n\t\treturn nil\n\t}\n\n\tmockECSIdentity := &identityMock.IAgentIdentityInner{}\n\tnewECSIdentity = func(log log.T) identity.IAgentIdentityInner {\n\t\treturn mockECSIdentity\n\t}\n\tmockECSIdentity.On(\"IsIdentityEnvironment\").Return(false)\n\n\tssmConnectionChannel := \"ssmmessages\"\n\tvar ableToOpenMGSConnection uint32\n\tatomic.StoreUint32(&ableToOpenMGSConnection, 1)\n\tssmconnectionchannel.SetConnectionChannel(&ableToOpenMGSConnection)\n\n\t// Turn on the mock method\n\tsuite.contextMock.On(\"AppConfig\").Return(*appconfigMock)\n\tsuite.serviceMock.On(\"UpdateInstanceInformation\", mock.Anything, version.Version, \"Active\", AgentName, availabilityZone, availabilityZoneId, ssmConnectionChannel).Return(nil, nil)\n\tsuite.healthCheck.ModuleExecute()\n\t// Because ModuleExecute will launch two new go routine, wait 100ms to make sure the updateHealth() has launched\n\ttime.Sleep(100 * time.Millisecond)\n\t// Assert the UpdateInstanceInformation get called in updateHealth() function, and the agent status is same as input.\n\tsuite.serviceMock.AssertCalled(suite.T(), \"UpdateInstanceInformation\", mock.Anything, version.Version, \"Active\", AgentName, availabilityZone, availabilityZoneId, ssmConnectionChannel)\n}", "func (m *MockProviders) IdentityManager(arg0 string) (msp.IdentityManager, bool) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"IdentityManager\", arg0)\n\tret0, _ := ret[0].(msp.IdentityManager)\n\tret1, _ := ret[1].(bool)\n\treturn ret0, ret1\n}", "func mockChildPackages() {\n\n\t// Fake an AWS credentials file so that the mfile package will nehave as if it is happy\n\tsetFakeCredentials()\n\n\t// Fake out the creds package into using an apparently credentials response from AWS\n\tcreds.SetGetSessionTokenFunc(func(awsService *sts.STS, input *sts.GetSessionTokenInput) (*sts.GetSessionTokenOutput, error) {\n\t\treturn getSessionTokenOutput, nil\n\t})\n\n}", "func (m *MockClient) IdentityManager(arg0 string) (msp.IdentityManager, bool) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"IdentityManager\", arg0)\n\tret0, _ := ret[0].(msp.IdentityManager)\n\tret1, _ := ret[1].(bool)\n\treturn ret0, ret1\n}", "func GetAPIWithMocks(mockedAreaStore api.AreaStore) *api.API {\n\tmu.Lock()\n\tdefer mu.Unlock()\n\tcfg, err := config.Get()\n\tSo(err, ShouldBeNil)\n\tcfg.DefaultLimit = 0\n\tcfg.DefaultOffset = 0\n\treturn api.Setup(context.Background(), cfg, mux.NewRouter(), mockedAreaStore)\n}", "func (spec *Spec) identity() (*core.Identity, error) {\n\tident := &core.Identity{\n\t\tRequest: spec.Request,\n\t\tRoots: []*core.Root{\n\t\t\t&core.Root{\n\t\t\t\tType: \"system\",\n\t\t\t},\n\t\t\t&core.Root{\n\t\t\t\tType: \"cfssl\",\n\t\t\t\tMetadata: map[string]string{\n\t\t\t\t\t\"host\": spec.CA.Remote,\n\t\t\t\t\t\"profile\": spec.CA.Profile,\n\t\t\t\t\t\"label\": spec.CA.Label,\n\t\t\t\t\t\"tls-remote-ca\": spec.CA.RootCACert,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tProfiles: map[string]map[string]string{\n\t\t\t\"cfssl\": map[string]string{\n\t\t\t\t\"remote\": spec.CA.Remote,\n\t\t\t\t\"profile\": spec.CA.Profile,\n\t\t\t\t\"label\": spec.CA.Label,\n\t\t\t\t\"tls-remote-ca\": spec.CA.RootCACert,\n\t\t\t},\n\t\t},\n\t}\n\n\tauthkey := spec.CA.AuthKey\n\tif spec.CA.AuthKeyFile != \"\" {\n\t\tlog.Debugf(\"loading auth_key_file %v\", spec.CA.AuthKeyFile)\n\t\tcontent, err := ioutil.ReadFile(spec.CA.AuthKeyFile)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed reading auth_key_file %v: %v\", spec.CA.AuthKeyFile, err)\n\t\t}\n\t\tauthkey = strings.TrimSpace(string(content))\n\t}\n\tif authkey != \"\" {\n\t\tident.Profiles[\"cfssl\"][\"auth-type\"] = \"standard\"\n\t\tident.Profiles[\"cfssl\"][\"auth-key\"] = authkey\n\t}\n\n\treturn ident, nil\n}", "func (spec *Spec) identity() (*core.Identity, error) {\n\tident := &core.Identity{\n\t\tRequest: spec.Request,\n\t\tRoots: []*core.Root{\n\t\t\t&core.Root{\n\t\t\t\tType: \"system\",\n\t\t\t},\n\t\t\t&core.Root{\n\t\t\t\tType: \"cfssl\",\n\t\t\t\tMetadata: map[string]string{\n\t\t\t\t\t\"host\": spec.CA.Remote,\n\t\t\t\t\t\"profile\": spec.CA.Profile,\n\t\t\t\t\t\"label\": spec.CA.Label,\n\t\t\t\t\t\"tls-remote-ca\": spec.CA.RootCACert,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tProfiles: map[string]map[string]string{\n\t\t\t\"cfssl\": map[string]string{\n\t\t\t\t\"remote\": spec.CA.Remote,\n\t\t\t\t\"profile\": spec.CA.Profile,\n\t\t\t\t\"label\": spec.CA.Label,\n\t\t\t\t\"tls-remote-ca\": spec.CA.RootCACert,\n\t\t\t},\n\t\t},\n\t}\n\n\tauthkey := spec.CA.AuthKey\n\tif spec.CA.AuthKeyFile != \"\" {\n\t\tlog.Debugf(\"loading auth_key_file %v\", spec.CA.AuthKeyFile)\n\t\tcontent, err := ioutil.ReadFile(spec.CA.AuthKeyFile)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed reading auth_key_file %v: %v\", spec.CA.AuthKeyFile, err)\n\t\t}\n\t\tauthkey = strings.TrimSpace(string(content))\n\t}\n\tif authkey != \"\" {\n\t\tident.Profiles[\"cfssl\"][\"auth-type\"] = \"standard\"\n\t\tident.Profiles[\"cfssl\"][\"auth-key\"] = authkey\n\t}\n\n\treturn ident, nil\n}", "func (c *IdentityConfig) loadIdentityConfigEntities() error {\n\tconfigEntity := identityConfigEntity{}\n\n\terr := c.backend.UnmarshalKey(\"client\", &configEntity.Client)\n\tlogger.Debugf(\"Client is: %+v\", configEntity.Client)\n\tif err != nil {\n\t\treturn errors.WithMessage(err, \"failed to parse 'client' config item to identityConfigEntity.Client type\")\n\t}\n\n\terr = c.backend.UnmarshalKey(\"organizations\", &configEntity.Organizations)\n\tlogger.Debugf(\"organizations are: %+v\", configEntity.Organizations)\n\tif err != nil {\n\t\treturn errors.WithMessage(err, \"failed to parse 'organizations' config item to identityConfigEntity.Organizations type\")\n\t}\n\n\terr = c.backend.UnmarshalKey(\"certificateAuthorities\", &configEntity.CertificateAuthorities)\n\tlogger.Debugf(\"certificateAuthorities are: %+v\", configEntity.CertificateAuthorities)\n\tif err != nil {\n\t\treturn errors.WithMessage(err, \"failed to parse 'certificateAuthorities' config item to identityConfigEntity.CertificateAuthorities type\")\n\t}\n\t// Populate ID from the lookup keys\n\tfor caID := range configEntity.CertificateAuthorities {\n\t\tca := configEntity.CertificateAuthorities[caID]\n\t\tca.ID = caID\n\t\tconfigEntity.CertificateAuthorities[caID] = ca\n\t}\n\n\t//compile CA matchers\n\terr = c.compileMatchers()\n\tif err != nil {\n\t\treturn errors.WithMessage(err, \"failed to compile certificate authority matchers\")\n\t}\n\n\terr = c.loadClientTLSConfig(&configEntity)\n\tif err != nil {\n\t\treturn errors.WithMessage(err, \"failed to load client TLSConfig \")\n\t}\n\n\terr = c.loadCATLSConfig(&configEntity)\n\tif err != nil {\n\t\treturn errors.WithMessage(err, \"failed to load CA TLSConfig \")\n\t}\n\n\terr = c.loadAllCAConfigs(&configEntity)\n\tif err != nil {\n\t\treturn errors.WithMessage(err, \"failed to load all CA configs \")\n\t}\n\n\terr = c.loadTLSCertPool(&configEntity)\n\tif err != nil {\n\t\treturn errors.WithMessage(err, \"failed to load TLS Cert Pool\")\n\t}\n\n\tc.caKeyStorePath = pathvar.Subst(c.backend.GetString(\"client.credentialStore.cryptoStore.path\"))\n\tc.credentialStorePath = pathvar.Subst(c.backend.GetString(\"client.credentialStore.path\"))\n\n\treturn nil\n}", "func createKeycloakInterfaceMock() (keycloakCommon.KeycloakInterface, *mockClientContext) {\n\tcontext := mockClientContext{\n\t\tGroups: []*keycloakCommon.Group{},\n\t\tDefaultGroups: []*keycloakCommon.Group{},\n\t\tClientRoles: map[string][]*keycloak.KeycloakUserRole{},\n\t\tRealmRoles: map[string][]*keycloak.KeycloakUserRole{},\n\t\tAuthenticationFlowsExecutions: map[string][]*keycloak.AuthenticationExecutionInfo{\n\t\t\tfirstBrokerLoginFlowAlias: []*keycloak.AuthenticationExecutionInfo{\n\t\t\t\t&keycloak.AuthenticationExecutionInfo{\n\t\t\t\t\tRequirement: \"REQUIRED\",\n\t\t\t\t\tAlias: reviewProfileExecutionAlias,\n\t\t\t\t},\n\t\t\t\t// dummy ones\n\t\t\t\t&keycloak.AuthenticationExecutionInfo{\n\t\t\t\t\tRequirement: \"REQUIRED\",\n\t\t\t\t\tAlias: \"dummy execution\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\tavailableGroupClientRoles := []*keycloak.KeycloakUserRole{\n\t\t&keycloak.KeycloakUserRole{\n\t\t\tID: \"create-client\",\n\t\t\tName: \"create-client\",\n\t\t},\n\t\t&keycloak.KeycloakUserRole{\n\t\t\tID: \"manage-authorization\",\n\t\t\tName: \"manage-authorization\",\n\t\t},\n\t\t&keycloak.KeycloakUserRole{\n\t\t\tID: \"manage-clients\",\n\t\t\tName: \"manage-clients\",\n\t\t},\n\t\t&keycloak.KeycloakUserRole{\n\t\t\tID: \"manage-events\",\n\t\t\tName: \"manage-events\",\n\t\t},\n\t\t&keycloak.KeycloakUserRole{\n\t\t\tID: \"manage-identity-providers\",\n\t\t\tName: \"manage-identity-providers\",\n\t\t},\n\t\t&keycloak.KeycloakUserRole{\n\t\t\tID: \"manage-realm\",\n\t\t\tName: \"manage-realm\",\n\t\t},\n\t\t&keycloak.KeycloakUserRole{\n\t\t\tID: \"manage-users\",\n\t\t\tName: \"manage-users\",\n\t\t},\n\t\t&keycloak.KeycloakUserRole{\n\t\t\tID: \"query-clients\",\n\t\t\tName: \"query-clients\",\n\t\t},\n\t\t&keycloak.KeycloakUserRole{\n\t\t\tID: \"query-groups\",\n\t\t\tName: \"query-groups\",\n\t\t},\n\t\t&keycloak.KeycloakUserRole{\n\t\t\tID: \"query-realms\",\n\t\t\tName: \"query-realms\",\n\t\t},\n\t\t&keycloak.KeycloakUserRole{\n\t\t\tID: \"query-users\",\n\t\t\tName: \"query-users\",\n\t\t},\n\t\t&keycloak.KeycloakUserRole{\n\t\t\tID: \"view-authorization\",\n\t\t\tName: \"view-authorization\",\n\t\t},\n\t\t&keycloak.KeycloakUserRole{\n\t\t\tID: \"view-clients\",\n\t\t\tName: \"view-clients\",\n\t\t},\n\t\t&keycloak.KeycloakUserRole{\n\t\t\tID: \"view-events\",\n\t\t\tName: \"view-events\",\n\t\t},\n\t\t&keycloak.KeycloakUserRole{\n\t\t\tID: \"view-identity-providers\",\n\t\t\tName: \"view-identity-providers\",\n\t\t},\n\t\t&keycloak.KeycloakUserRole{\n\t\t\tID: \"view-realm\",\n\t\t\tName: \"view-realm\",\n\t\t},\n\t\t&keycloak.KeycloakUserRole{\n\t\t\tID: \"view-users\",\n\t\t\tName: \"view-users\",\n\t\t},\n\t}\n\n\tavailableGroupRealmRoles := []*keycloak.KeycloakUserRole{\n\t\t&keycloak.KeycloakUserRole{\n\t\t\tID: \"mock-role-3\",\n\t\t\tName: \"mock-role-3\",\n\t\t},\n\t\t&keycloak.KeycloakUserRole{\n\t\t\tID: \"create-realm\",\n\t\t\tName: \"create-realm\",\n\t\t},\n\t\t&keycloak.KeycloakUserRole{\n\t\t\tID: \"mock-role-4\",\n\t\t\tName: \"mock-role-4\",\n\t\t},\n\t}\n\n\tlistRealmsFunc := func() ([]*keycloak.KeycloakAPIRealm, error) {\n\t\treturn []*keycloak.KeycloakAPIRealm{\n\t\t\t&keycloak.KeycloakAPIRealm{\n\t\t\t\tRealm: \"master\",\n\t\t\t},\n\t\t\t&keycloak.KeycloakAPIRealm{\n\t\t\t\tRealm: \"test\",\n\t\t\t},\n\t\t}, nil\n\t}\n\n\tfindGroupByNameFunc := func(groupName string, realmName string) (*keycloakCommon.Group, error) {\n\t\tfor _, group := range context.Groups {\n\t\t\tif group.Name == groupName {\n\t\t\t\treturn group, nil\n\t\t\t}\n\t\t}\n\n\t\treturn nil, nil\n\t}\n\n\tcreateGroupFunc := func(groupName string, realmName string) (string, error) {\n\t\tnextID := fmt.Sprintf(\"group-%d\", len(context.Groups))\n\n\t\tnewGroup := &keycloakCommon.Group{\n\t\t\tID: string(nextID),\n\t\t\tName: groupName,\n\t\t}\n\n\t\tcontext.Groups = append(context.Groups, newGroup)\n\n\t\tcontext.ClientRoles[nextID] = []*keycloak.KeycloakUserRole{}\n\t\tcontext.RealmRoles[nextID] = []*keycloak.KeycloakUserRole{}\n\n\t\treturn nextID, nil\n\t}\n\n\tsetGroupChildFunc := func(groupID, realmName string, childGroup *keycloakCommon.Group) error {\n\t\tvar childGroupToAppend *keycloakCommon.Group\n\t\tfor _, group := range context.Groups {\n\t\t\tif group.ID == childGroup.ID {\n\t\t\t\tchildGroupToAppend = group\n\t\t\t}\n\t\t}\n\n\t\tif childGroupToAppend == nil {\n\t\t\tchildGroupToAppend = childGroup\n\t\t}\n\n\t\tfound := false\n\t\tfor _, group := range context.Groups {\n\t\t\tif group.ID == groupID {\n\t\t\t\tgroup.SubGroups = append(group.SubGroups, childGroupToAppend)\n\t\t\t\tfound = true\n\t\t\t}\n\t\t}\n\n\t\tif !found {\n\t\t\treturn fmt.Errorf(\"Group %s not found\", groupID)\n\t\t}\n\n\t\treturn nil\n\t}\n\n\tlistUsersInGroupFunc := func(realmName, groupID string) ([]*keycloak.KeycloakAPIUser, error) {\n\t\treturn []*keycloak.KeycloakAPIUser{}, nil\n\t}\n\n\tmakeGroupDefaultFunc := func(groupID string, realmName string) error {\n\t\tvar group *keycloakCommon.Group\n\n\t\tfor _, existingGroup := range context.Groups {\n\t\t\tif existingGroup.ID == groupID {\n\t\t\t\tgroup = existingGroup\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif group == nil {\n\t\t\treturn fmt.Errorf(\"Referenced group not found\")\n\t\t}\n\n\t\tcontext.DefaultGroups = append(context.DefaultGroups, group)\n\t\treturn nil\n\t}\n\n\tlistDefaultGroupsFunc := func(realmName string) ([]*keycloakCommon.Group, error) {\n\t\treturn context.DefaultGroups, nil\n\t}\n\n\tcreateGroupClientRoleFunc := func(role *keycloak.KeycloakUserRole, realmName, clientID, groupID string) (string, error) {\n\t\tgroupClientRoles, ok := context.ClientRoles[groupID]\n\n\t\tif !ok {\n\t\t\treturn \"\", fmt.Errorf(\"Referenced group not found\")\n\t\t}\n\n\t\tcontext.ClientRoles[groupID] = append(groupClientRoles, role)\n\t\treturn \"dummy-group-client-role-id\", nil\n\t}\n\n\tlistGroupClientRolesFunc := func(realmName, clientID, groupID string) ([]*keycloak.KeycloakUserRole, error) {\n\t\tgroupRoles, ok := context.ClientRoles[groupID]\n\n\t\tif !ok {\n\t\t\treturn nil, fmt.Errorf(\"Referenced group not found\")\n\t\t}\n\n\t\treturn groupRoles, nil\n\t}\n\n\tlistAvailableGroupClientRolesFunc := func(realmName, clientID, groupID string) ([]*keycloak.KeycloakUserRole, error) {\n\t\t_, ok := context.ClientRoles[groupID]\n\n\t\tif !ok {\n\t\t\treturn nil, fmt.Errorf(\"Referenced group not found\")\n\t\t}\n\n\t\treturn availableGroupClientRoles, nil\n\t}\n\n\tfindGroupClientRoleFunc := func(realmName, clientID, groupID string, predicate func(*keycloak.KeycloakUserRole) bool) (*keycloak.KeycloakUserRole, error) {\n\t\tall, err := listGroupClientRolesFunc(realmName, clientID, groupID)\n\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tfor _, role := range all {\n\t\t\tif predicate(role) {\n\t\t\t\treturn role, nil\n\t\t\t}\n\t\t}\n\n\t\treturn nil, nil\n\t}\n\n\tfindAvailableGroupClientRoleFunc := func(realmName, clientID, groupID string, predicate func(*keycloak.KeycloakUserRole) bool) (*keycloak.KeycloakUserRole, error) {\n\t\tall, err := listAvailableGroupClientRolesFunc(realmName, clientID, groupID)\n\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tfor _, role := range all {\n\t\t\tif predicate(role) {\n\t\t\t\treturn role, nil\n\t\t\t}\n\t\t}\n\n\t\treturn nil, nil\n\t}\n\n\tlistGroupRealmRolesFunc := func(realmName, groupID string) ([]*keycloak.KeycloakUserRole, error) {\n\t\tgroupRoles, ok := context.RealmRoles[groupID]\n\n\t\tif !ok {\n\t\t\treturn nil, fmt.Errorf(\"Referenced group not found\")\n\t\t}\n\n\t\treturn groupRoles, nil\n\t}\n\n\tlistAvailableGroupRealmRolesFunc := func(realmName, groupID string) ([]*keycloak.KeycloakUserRole, error) {\n\t\t_, ok := context.RealmRoles[groupID]\n\n\t\tif !ok {\n\t\t\treturn nil, fmt.Errorf(\"Referenced group not found\")\n\t\t}\n\n\t\treturn availableGroupRealmRoles, nil\n\t}\n\n\tcreateGroupRealmRoleFunc := func(role *keycloak.KeycloakUserRole, realmName, groupID string) (string, error) {\n\t\tgroupRealmRoles, ok := context.RealmRoles[groupID]\n\n\t\tif !ok {\n\t\t\treturn \"\", fmt.Errorf(\"Referenced group not found\")\n\t\t}\n\n\t\tcontext.RealmRoles[groupID] = append(groupRealmRoles, role)\n\t\treturn \"dummy-group-realm-role-id\", nil\n\t}\n\n\tlistClientsFunc := func(realmName string) ([]*keycloak.KeycloakAPIClient, error) {\n\t\treturn []*keycloak.KeycloakAPIClient{\n\t\t\t&keycloak.KeycloakAPIClient{\n\t\t\t\tClientID: \"test-realm\",\n\t\t\t\tID: \"test-realm\",\n\t\t\t\tName: \"test-realm\",\n\t\t\t},\n\t\t\t&keycloak.KeycloakAPIClient{\n\t\t\t\tClientID: \"master-realm\",\n\t\t\t\tID: \"master-realm\",\n\t\t\t\tName: \"master-realm\",\n\t\t\t},\n\t\t}, nil\n\t}\n\n\tlistAuthenticationExecutionsForFlowFunc := func(flowAlias, realmName string) ([]*keycloak.AuthenticationExecutionInfo, error) {\n\t\texecutions, ok := context.AuthenticationFlowsExecutions[flowAlias]\n\n\t\tif !ok {\n\t\t\treturn nil, errors.New(\"Authentication flow not found\")\n\t\t}\n\n\t\treturn executions, nil\n\t}\n\n\tfindAuthenticationExecutionForFlowFunc := func(flowAlias, realmName string, predicate func(*keycloak.AuthenticationExecutionInfo) bool) (*keycloak.AuthenticationExecutionInfo, error) {\n\t\texecutions, err := listAuthenticationExecutionsForFlowFunc(flowAlias, realmName)\n\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tfor _, execution := range executions {\n\t\t\tif predicate(execution) {\n\t\t\t\treturn execution, nil\n\t\t\t}\n\t\t}\n\n\t\treturn nil, nil\n\t}\n\n\tupdateAuthenticationExecutionForFlowFunc := func(flowAlias, realmName string, execution *keycloak.AuthenticationExecutionInfo) error {\n\t\texecutions, ok := context.AuthenticationFlowsExecutions[flowAlias]\n\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"Authentication flow %s not found\", flowAlias)\n\t\t}\n\n\t\tfor i, currentExecution := range executions {\n\t\t\tif currentExecution.Alias != execution.Alias {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tcontext.AuthenticationFlowsExecutions[flowAlias][i] = execution\n\t\t\tbreak\n\t\t}\n\n\t\treturn nil\n\t}\n\n\tlistOfActivesUsersPerRealmFunc := func(realmName, dateFrom string, max int) ([]keycloakCommon.Users, error) {\n\t\tusers := []keycloakCommon.Users{\n\t\t\t{\n\t\t\t\tUserID: \"1\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tUserID: \"2\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tUserID: \"3\",\n\t\t\t},\n\t\t}\n\n\t\treturn users, nil\n\t}\n\n\treturn &keycloakCommon.KeycloakInterfaceMock{\n\t\tListRealmsFunc: listRealmsFunc,\n\t\tFindGroupByNameFunc: findGroupByNameFunc,\n\t\tCreateGroupFunc: createGroupFunc,\n\t\tSetGroupChildFunc: setGroupChildFunc,\n\t\tListUsersInGroupFunc: listUsersInGroupFunc,\n\t\tMakeGroupDefaultFunc: makeGroupDefaultFunc,\n\t\tListDefaultGroupsFunc: listDefaultGroupsFunc,\n\t\tCreateGroupClientRoleFunc: createGroupClientRoleFunc,\n\t\tListGroupClientRolesFunc: listGroupClientRolesFunc,\n\t\tListAvailableGroupClientRolesFunc: listAvailableGroupClientRolesFunc,\n\t\tFindGroupClientRoleFunc: findGroupClientRoleFunc,\n\t\tFindAvailableGroupClientRoleFunc: findAvailableGroupClientRoleFunc,\n\t\tListGroupRealmRolesFunc: listGroupRealmRolesFunc,\n\t\tListAvailableGroupRealmRolesFunc: listAvailableGroupRealmRolesFunc,\n\t\tCreateGroupRealmRoleFunc: createGroupRealmRoleFunc,\n\t\tListAuthenticationExecutionsForFlowFunc: listAuthenticationExecutionsForFlowFunc,\n\t\tFindAuthenticationExecutionForFlowFunc: findAuthenticationExecutionForFlowFunc,\n\t\tUpdateAuthenticationExecutionForFlowFunc: updateAuthenticationExecutionForFlowFunc,\n\t\tListClientsFunc: listClientsFunc,\n\t\tListOfActivesUsersPerRealmFunc: listOfActivesUsersPerRealmFunc,\n\t}, &context\n}", "func fakeAuthState() *authtest.FakeState {\n\treturn &authtest.FakeState{\n\t\tIdentity: \"user:user@example.com\",\n\t\tIdentityPermissions: []authtest.RealmPermission{\n\t\t\t{\n\t\t\t\tRealm: \"@internal:test-proj/cas-read-only\",\n\t\t\t\tPermission: permMintToken,\n\t\t\t},\n\t\t},\n\t}\n}", "func mock_txpool_config(slot uint64) TxPoolConfig {\n\tmock_config := TxPoolConfig{\n\t\tGlobalSlots: slot,\n\t}\n\treturn mock_config\n}", "func testInMemoryDataStore() IDataStore {\n return NewInMemoryDataStore();\n}", "func mockedGranter(kubeutil *kube.Kube, app *v1.RadixRegistration, namespace string, serviceAccount *corev1.ServiceAccount) error {\n\treturn nil\n}", "func (c *Config) setupIAMClient() {\n\tvar standardClient *http.Client\n\tif c.RetryMax > 0 {\n\t\tretryClient := retryablehttp.NewClient()\n\t\tretryClient.RetryMax = c.RetryMax\n\t\tstandardClient = retryClient.StandardClient()\n\t}\n\tc.iamClient = nil\n\tclient, err := iam.NewClient(standardClient, &c.Config)\n\tif err != nil {\n\t\tc.iamClientErr = err\n\t\treturn\n\t}\n\tif c.ServiceID != \"\" && c.ServicePrivateKey != \"\" {\n\t\terr = client.ServiceLogin(iam.Service{\n\t\t\tServiceID: c.ServiceID,\n\t\t\tPrivateKey: c.ServicePrivateKey,\n\t\t})\n\t\tif err != nil {\n\t\t\tc.iamClientErr = err\n\t\t\treturn\n\t\t}\n\t}\n\tif c.OrgAdminUsername != \"\" && c.OrgAdminPassword != \"\" {\n\t\tif c.OAuth2ClientID == \"\" {\n\t\t\tc.iamClientErr = ErrMissingClientID\n\t\t\treturn\n\t\t}\n\t\terr = client.Login(c.OrgAdminUsername, c.OrgAdminPassword)\n\t\tif err != nil {\n\t\t\tc.iamClientErr = err\n\t\t\treturn\n\t\t}\n\t}\n\tc.iamClient = client\n}", "func (c *Provider) IdentityConfig() msp.IdentityConfig {\n\treturn c.identityConfig\n}", "func TestAzureBlobGetAppsListShouldFailInvalidIdentity(t *testing.T) {\n\tctx := context.TODO()\n\tappFrameworkRef := enterpriseApi.AppFrameworkSpec{\n\t\tDefaults: enterpriseApi.AppSourceDefaultSpec{\n\t\t\tVolName: \"azure_vol1\",\n\t\t\tScope: enterpriseApi.ScopeLocal,\n\t\t},\n\t\tVolList: []enterpriseApi.VolumeSpec{\n\t\t\t{\n\t\t\t\tName: \"azure_vol1\",\n\t\t\t\tEndpoint: \"https://mystorageaccount.blob.core.windows.net\",\n\t\t\t\tPath: \"appscontainer1\",\n\t\t\t\tType: \"blob\",\n\t\t\t\tProvider: \"azure\",\n\t\t\t},\n\t\t},\n\t\tAppSources: []enterpriseApi.AppSourceSpec{\n\t\t\t{\n\t\t\t\tName: \"adminApps\",\n\t\t\t\tLocation: \"adminAppsRepo\",\n\t\t\t\tAppSourceDefaultSpec: enterpriseApi.AppSourceDefaultSpec{\n\t\t\t\t\tVolName: \"azure_vol1\",\n\t\t\t\t\tScope: enterpriseApi.ScopeLocal,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\t// Initialize clients\n\tazureBlobClient := &AzureBlobClient{}\n\tmclient := spltest.MockHTTPClient{}\n\n\t// Identity call return a token - that means AKS cluster has an identity configured.\n\twantRequest, _ := http.NewRequest(\"GET\", \"http://169.254.169.254/metadata/identity/oauth2/token?api-version=2021-10-01&resource=https%3A%2F%2Fstorage.azure.com%2F\", nil)\n\trespTokenData := &TokenResponse{\n\t\tAccessToken: \"acctoken\",\n\t\tClientID: \"ClientId\",\n\t}\n\tmrespdata, _ := json.Marshal(respTokenData)\n\tmclient.AddHandler(wantRequest, 200, string(mrespdata), nil)\n\n\t// Add mock for the azure rest call for list apps\n\twantRequest, _ = http.NewRequest(\"GET\", \"https://mystorageaccount.blob.core.windows.net/appscontainer1?prefix=adminAppsRepo&restype=container&comp=list&include=snapshots&include=metadata\", nil)\n\n\t// Expect the identity does not have authorization to access the buckets\n\tmclient.AddHandler(wantRequest, 403, \"identity not authorized\", nil)\n\n\t// Get App source and volume from spec\n\tappSource := appFrameworkRef.AppSources[0]\n\tvol, err := GetAppSrcVolume(ctx, appSource, &appFrameworkRef)\n\tif err != nil {\n\t\tt.Errorf(\"Unable to get volume for app source : %s\", appSource.Name)\n\t}\n\n\t// Update the GetRemoteDataClient function pointer\n\tgetClientWrapper := RemoteDataClientsMap[vol.Provider]\n\tgetClientWrapper.SetRemoteDataClientFuncPtr(ctx, vol.Provider, NewMockAzureBlobClient)\n\n\t// Update the GetRemoteDataClientInit function pointer\n\tinitFn := func(ctx context.Context, region, accessKeyID, secretAccessKey string) interface{} {\n\t\treturn &mclient\n\t}\n\tgetClientWrapper.SetRemoteDataClientInitFuncPtr(ctx, vol.Provider, initFn)\n\n\t// Init azure blob client\n\tgetRemoteDataClientFn := getClientWrapper.GetRemoteDataClientInitFuncPtr(ctx)\n\tazureBlobClient.HTTPClient = getRemoteDataClientFn(ctx, \"us-west-2\", \"abcd\", \"1234\").(*spltest.MockHTTPClient)\n\tazureBlobClient.BucketName = vol.Path\n\tazureBlobClient.Prefix = appSource.Location\n\tazureBlobClient.Endpoint = vol.Endpoint\n\n\trespList, err := azureBlobClient.GetAppsList(ctx)\n\tif err == nil {\n\t\tt.Errorf(\"GetAppsList should return err\")\n\t}\n\n\tif err.Error() != \"error authorizing the rest call. check your IAM/secret configuration\" {\n\t\tt.Errorf(\"GetAppsList should return authorization error\")\n\t}\n\n\t// authorizing the rest call. check your IAM/secret configuration\n\n\tif len(respList.Objects) != 0 {\n\t\tt.Errorf(\"GetAppsList should not return any response objects\")\n\t}\n\tmclient.RemoveHandlers()\n}", "func NewMockKeystore(auth *communications.Headers, logger log.Logger) definitions.Keystore {\n\ts := new(inmemKeystore)\n\ts.headers = auth\n\treturn s\n}", "func (m *MockManager) SerializeConfig(arg0 []api.Asset, arg1 api.ReleaseMetadata, arg2 map[string]interface{}) error {\n\tret := m.ctrl.Call(m, \"SerializeConfig\", arg0, arg1, arg2)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func mockAuthenticationComponent(log *zap.Logger, serviceName string) *AuthenticationComponent {\n\thttpTimeout := 300 * time.Millisecond\n\n\treturn NewAuthenticationComponent(&AuthenticationParams{\n\t\tAuthConfig: &core_auth_sdk.Config{\n\t\t\tIssuer: issuer,\n\t\t\tPrivateBaseURL: privateBaseUrl,\n\t\t\tAudience: audience,\n\t\t\tUsername: username,\n\t\t\tPassword: password,\n\t\t\tKeychainTTL: 0,\n\t\t},\n\t\tAuthConnectionConfig: &core_auth_sdk.RetryConfig{\n\t\t\tMaxRetries: 1,\n\t\t\tMinRetryWaitTime: 200 * time.Millisecond,\n\t\t\tMaxRetryWaitTime: 300 * time.Millisecond,\n\t\t\tRequestTimeout: 500 * time.Millisecond,\n\t\t},\n\t\tLogger: log,\n\t\tOrigin: origin,\n\t}, serviceName, httpTimeout)\n}", "func TestCreateIdentity(t *testing.T) {\r\n\r\n\tt.Parallel()\r\n\r\n\tvar (\r\n\t\t// Testing private methods\r\n\t\ttests = []struct {\r\n\t\t\tinputPrivateKey string\r\n\t\t\tinputIDKey string\r\n\t\t\tinputCounter uint32\r\n\t\t\texpectedTxID string\r\n\t\t\texpectedNil bool\r\n\t\t\texpectedError bool\r\n\t\t}{\r\n\t\t\t{\r\n\t\t\t\tprivateKey,\r\n\t\t\t\tidKey,\r\n\t\t\t\t0,\r\n\t\t\t\t\"d2384b0946b8c3137bc0bf12d122efb8b77be998118b65c21448864234188f20\",\r\n\t\t\t\tfalse,\r\n\t\t\t\tfalse,\r\n\t\t\t},\r\n\t\t\t{\r\n\t\t\t\t\"\",\r\n\t\t\t\tidKey,\r\n\t\t\t\t0,\r\n\t\t\t\t\"49957864306b123c3cca8711635ba88890bb334eb3e9f21553b118eb4d66cc62\",\r\n\t\t\t\ttrue,\r\n\t\t\t\ttrue,\r\n\t\t\t},\r\n\t\t\t{\r\n\t\t\t\t\"invalid-key\",\r\n\t\t\t\tidKey,\r\n\t\t\t\t0,\r\n\t\t\t\t\"49957864306b123c3cca8711635ba88890bb334eb3e9f21553b118eb4d66cc62\",\r\n\t\t\t\ttrue,\r\n\t\t\t\ttrue,\r\n\t\t\t},\r\n\t\t\t{\r\n\t\t\t\tprivateKey,\r\n\t\t\t\t\"\",\r\n\t\t\t\t0,\r\n\t\t\t\t\"49957864306b123c3cca8711635ba88890bb334eb3e9f21553b118eb4d66cc62\",\r\n\t\t\t\ttrue,\r\n\t\t\t\ttrue,\r\n\t\t\t},\r\n\t\t\t{\r\n\t\t\t\tprivateKey,\r\n\t\t\t\tidKey,\r\n\t\t\t\t1,\r\n\t\t\t\t\"4f00a4c6bca4a538ecce849b19188222aeb0d28e7b0c9acdb0c20fe9de628f9e\",\r\n\t\t\t\tfalse,\r\n\t\t\t\tfalse,\r\n\t\t\t},\r\n\t\t\t{\r\n\t\t\t\tprivateKey,\r\n\t\t\t\tidKey,\r\n\t\t\t\t100,\r\n\t\t\t\t\"0b61af0cfd6331731b7f897b051a56a903928c6bcff8ba59cdd4b8d0093b12ae\",\r\n\t\t\t\tfalse,\r\n\t\t\t\tfalse,\r\n\t\t\t},\r\n\t\t}\r\n\t)\r\n\r\n\t// Run tests\r\n\tfor _, test := range tests {\r\n\t\tif tx, err := CreateIdentity(test.inputPrivateKey, test.inputIDKey, test.inputCounter); err != nil && !test.expectedError {\r\n\t\t\tt.Errorf(\"%s Failed: [%s] [%s] [%d] inputted and error not expected but got: %s\", t.Name(), test.inputPrivateKey, test.inputIDKey, test.inputCounter, err.Error())\r\n\t\t} else if err == nil && test.expectedError {\r\n\t\t\tt.Errorf(\"%s Failed: [%s] [%s] [%d] inputted and error was expected\", t.Name(), test.inputPrivateKey, test.inputIDKey, test.inputCounter)\r\n\t\t} else if tx == nil && !test.expectedNil {\r\n\t\t\tt.Errorf(\"%s Failed: [%s] [%s] [%d] inputted and nil was not expected\", t.Name(), test.inputPrivateKey, test.inputIDKey, test.inputCounter)\r\n\t\t} else if tx != nil && test.expectedNil {\r\n\t\t\tt.Errorf(\"%s Failed: [%s] [%s] [%d] inputted and nil was expected\", t.Name(), test.inputPrivateKey, test.inputIDKey, test.inputCounter)\r\n\t\t} else if tx != nil && tx.GetTxID() != test.expectedTxID {\r\n\t\t\tt.Errorf(\"%s Failed: [%s] [%s] [%d] inputted and expected [%s] but got [%s]\", t.Name(), test.inputPrivateKey, test.inputIDKey, test.inputCounter, test.expectedTxID, tx.GetTxID())\r\n\t\t}\r\n\t}\r\n}", "func initIntegrationsTests(id string) {}", "func TestOAuth2ClientCredentialsCache(t *testing.T) {\n\t// Setup\n\tmockCtrl := gomock.NewController(t)\n\tdefer mockCtrl.Finish()\n\n\t// Mock mockTokenProvider\n\tmockTokenProvider := mock.NewMockTokenProviderInterface(mockCtrl)\n\n\tgomock.InOrder(\n\t\t// First call returning abc and Bearer, expires within 1 second\n\t\tmockTokenProvider.\n\t\t\tEXPECT().\n\t\t\tGetToken(gomock.Any()).\n\t\t\tReturn(&oauth2.Token{\n\t\t\t\tAccessToken: \"abc\",\n\t\t\t\tTokenType: \"Bearer\",\n\t\t\t\tExpiry: time.Now().In(time.UTC).Add(1 * time.Second),\n\t\t\t}, nil).\n\t\t\tTimes(1),\n\t\t// Second call returning def and MAC, expires within 1 second\n\t\tmockTokenProvider.\n\t\t\tEXPECT().\n\t\t\tGetToken(gomock.Any()).\n\t\t\tReturn(&oauth2.Token{\n\t\t\t\tAccessToken: \"def\",\n\t\t\t\tTokenType: \"MAC\",\n\t\t\t\tExpiry: time.Now().In(time.UTC).Add(1 * time.Second),\n\t\t\t}, nil).\n\t\t\tTimes(1),\n\t)\n\n\t// Specify components metadata\n\tvar metadata middleware.Metadata\n\tmetadata.Properties = map[string]string{\n\t\t\"clientID\": \"testId\",\n\t\t\"clientSecret\": \"testSecret\",\n\t\t\"scopes\": \"ascope\",\n\t\t\"tokenURL\": \"https://localhost:9999\",\n\t\t\"headerName\": \"someHeader\",\n\t\t\"authStyle\": \"1\",\n\t}\n\n\t// Initialize middleware component and inject mocked TokenProvider\n\tlog := logger.NewLogger(\"oauth2clientcredentials.test\")\n\toauth2clientcredentialsMiddleware, _ := NewOAuth2ClientCredentialsMiddleware(log).(*Middleware)\n\toauth2clientcredentialsMiddleware.SetTokenProvider(mockTokenProvider)\n\thandler, err := oauth2clientcredentialsMiddleware.GetHandler(context.Background(), metadata)\n\trequire.NoError(t, err)\n\n\t// First handler call should return abc Token\n\tr := httptest.NewRequest(http.MethodGet, \"http://dapr.io\", nil)\n\tw := httptest.NewRecorder()\n\thandler(http.HandlerFunc(mockedRequestHandler)).ServeHTTP(w, r)\n\n\t// Assertion\n\tassert.Equal(t, \"Bearer abc\", r.Header.Get(\"someHeader\"))\n\n\t// Second handler call should still return 'cached' abc Token\n\tr = httptest.NewRequest(http.MethodGet, \"http://dapr.io\", nil)\n\tw = httptest.NewRecorder()\n\thandler(http.HandlerFunc(mockedRequestHandler)).ServeHTTP(w, r)\n\n\t// Assertion\n\tassert.Equal(t, \"Bearer abc\", r.Header.Get(\"someHeader\"))\n\n\t// Wait at a second to invalidate cache entry for abc\n\ttime.Sleep(1 * time.Second)\n\n\t// Third call should return def Token\n\tr = httptest.NewRequest(http.MethodGet, \"http://dapr.io\", nil)\n\tw = httptest.NewRecorder()\n\thandler(http.HandlerFunc(mockedRequestHandler)).ServeHTTP(w, r)\n\n\t// Assertion\n\tassert.Equal(t, \"MAC def\", r.Header.Get(\"someHeader\"))\n}", "func (o *OIDC) Init(config Config) (err error) {\n\tswitch {\n\tcase o.Type == \"\":\n\t\treturn errors.New(\"type cannot be empty\")\n\tcase o.Name == \"\":\n\t\treturn errors.New(\"name cannot be empty\")\n\tcase o.ClientID == \"\":\n\t\treturn errors.New(\"clientID cannot be empty\")\n\tcase o.ConfigurationEndpoint == \"\":\n\t\treturn errors.New(\"configurationEndpoint cannot be empty\")\n\t}\n\n\t// Validate listenAddress if given\n\tif o.ListenAddress != \"\" {\n\t\tif _, _, err := net.SplitHostPort(o.ListenAddress); err != nil {\n\t\t\treturn errors.Wrap(err, \"error parsing listenAddress\")\n\t\t}\n\t}\n\n\t// Decode and validate openid-configuration endpoint\n\tu, err := url.Parse(o.ConfigurationEndpoint)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"error parsing %s\", o.ConfigurationEndpoint)\n\t}\n\tif !strings.Contains(u.Path, \"/.well-known/openid-configuration\") {\n\t\tu.Path = path.Join(u.Path, \"/.well-known/openid-configuration\")\n\t}\n\tif err := getAndDecode(u.String(), &o.configuration); err != nil {\n\t\treturn err\n\t}\n\tif err := o.configuration.Validate(); err != nil {\n\t\treturn errors.Wrapf(err, \"error parsing %s\", o.ConfigurationEndpoint)\n\t}\n\t// Replace {tenantid} with the configured one\n\tif o.TenantID != \"\" {\n\t\to.configuration.Issuer = strings.ReplaceAll(o.configuration.Issuer, \"{tenantid}\", o.TenantID)\n\t}\n\t// Get JWK key set\n\to.keyStore, err = newKeyStore(o.configuration.JWKSetURI)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.ctl, err = NewController(o, o.Claims, config, o.Options)\n\treturn\n}", "func mockClientFactoryGenerator(setupFn ...func(c istioclient.Interface)) func() (istioclient.Interface, error) {\n\toutFactory := func() (istioclient.Interface, error) {\n\t\tc := kube.NewFakeClient().Istio()\n\t\tfor _, f := range setupFn {\n\t\t\tf(c)\n\t\t}\n\t\treturn c, nil\n\t}\n\n\treturn outFactory\n}", "func TestAPIClientConfig(t *testing.T) {\n\ttestCases := []struct {\n\t\tname string\n\t\tsetup func()\n\t\tassertions func(\n\t\t\taddress string,\n\t\t\ttoken string,\n\t\t\topts restmachinery.APIClientOptions,\n\t\t\terr error,\n\t\t)\n\t}{\n\t\t{\n\t\t\tname: \"API_ADDRESS not set\",\n\t\t\tsetup: func() {},\n\t\t\tassertions: func(\n\t\t\t\t_ string,\n\t\t\t\t_ string,\n\t\t\t\t_ restmachinery.APIClientOptions,\n\t\t\t\terr error,\n\t\t\t) {\n\t\t\t\trequire.Error(t, err)\n\t\t\t\trequire.Contains(t, err.Error(), \"value not found for\")\n\t\t\t\trequire.Contains(t, err.Error(), \"API_ADDRESS\")\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"API_TOKEN not set\",\n\t\t\tsetup: func() {\n\t\t\t\tt.Setenv(\"API_ADDRESS\", \"foo\")\n\t\t\t},\n\t\t\tassertions: func(\n\t\t\t\t_ string,\n\t\t\t\t_ string,\n\t\t\t\t_ restmachinery.APIClientOptions,\n\t\t\t\terr error,\n\t\t\t) {\n\t\t\t\trequire.Error(t, err)\n\t\t\t\trequire.Contains(t, err.Error(), \"value not found for\")\n\t\t\t\trequire.Contains(t, err.Error(), \"API_TOKEN\")\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"SUCCESS not set\",\n\t\t\tsetup: func() {\n\t\t\t\tt.Setenv(\"API_TOKEN\", \"bar\")\n\t\t\t\tt.Setenv(\"API_IGNORE_CERT_WARNINGS\", \"true\")\n\t\t\t},\n\t\t\tassertions: func(\n\t\t\t\taddress string,\n\t\t\t\ttoken string,\n\t\t\t\topts restmachinery.APIClientOptions,\n\t\t\t\terr error,\n\t\t\t) {\n\t\t\t\trequire.NoError(t, err)\n\t\t\t\trequire.Equal(t, \"foo\", address)\n\t\t\t\trequire.Equal(t, \"bar\", token)\n\t\t\t\trequire.True(t, opts.AllowInsecureConnections)\n\t\t\t},\n\t\t},\n\t}\n\tfor _, testCase := range testCases {\n\t\tt.Run(testCase.name, func(t *testing.T) {\n\t\t\ttestCase.setup()\n\t\t\taddress, token, opts, err := apiClientConfig()\n\t\t\ttestCase.assertions(address, token, opts, err)\n\t\t})\n\t}\n}", "func TestTokenBasedAuth(t *testing.T) {\n\tvar err error\n\terr = client.Login()\n\tif err != nil {\n\t\tt.Error(\"Login Failed\")\n\t\treturn\n\t}\n\trndIP := randomIP()\n\tlbName := \"test_lb_\" + randomString(5)\n\tlb1 := lb.Lbvserver{\n\t\tName: lbName,\n\t\tIpv46: rndIP,\n\t\tLbmethod: \"ROUNDROBIN\",\n\t\tServicetype: \"HTTP\",\n\t\tPort: 8000,\n\t}\n\t_, err = client.AddResource(Lbvserver.Type(), lbName, &lb1)\n\tif err != nil {\n\t\tt.Error(\"Could not add Lbvserver: \", err)\n\t\tt.Log(\"Not continuing test\")\n\t\treturn\n\t}\n\n\trsrc, err := client.FindResource(Lbvserver.Type(), lbName)\n\tif err != nil {\n\t\tt.Error(\"Did not find resource of type \", err, Lbvserver.Type(), \":\", lbName)\n\t} else {\n\t\tt.Log(\"LB-METHOD: \", rsrc[\"lbmethod\"])\n\t}\n\terr = client.DeleteResource(Lbvserver.Type(), lbName)\n\tif err != nil {\n\t\tt.Error(\"Could not delete LB\", lbName, err)\n\t\tt.Log(\"Cannot continue\")\n\t\treturn\n\t}\n\terr = client.Logout()\n\tif err != nil {\n\t\tt.Error(\"Logout Failed\")\n\t\treturn\n\t}\n\n\t// Test if session-id is cleared in case of session-expiry\n\tclient.timeout = 10\n\tclient.Login()\n\ttime.Sleep(15 * time.Second)\n\t_, err = client.AddResource(Lbvserver.Type(), lbName, &lb1)\n\tif err != nil {\n\t\tif client.IsLoggedIn() {\n\t\t\tt.Error(\"Sessionid not cleared\")\n\t\t\treturn\n\t\t}\n\t\tt.Log(\"sessionid cleared because of session-expiry\")\n\t} else {\n\t\tt.Error(\"Adding lbvserver should have failed because of session-expiry\")\n\t}\n}", "func (suite *SubscriptionsTestSuite) mockClientAuth(account *accounts.Account) {\n\t// Mock GetConfig call to return the config object\n\tsuite.accountsServiceMock.On(\"GetConfig\").Return(suite.cnf)\n\n\t// Mock GetOauthService to return a mock oauth service\n\tsuite.accountsServiceMock.On(\"GetOauthService\").Return(suite.oauthServiceMock)\n\n\t// Mock AuthClient to return a mock client\n\tsuite.oauthServiceMock.On(\"AuthClient\", \"test_client_1\", \"test_secret\").\n\t\tReturn(account.OauthClient, nil)\n\n\t// Mock FindAccountByOauthClientID to return the wanted account\n\tsuite.accountsServiceMock.\n\t\tOn(\"FindAccountByOauthClientID\", account.OauthClient.ID).\n\t\tReturn(account, nil)\n}", "func TestConfigure_NewSpineASN(t *testing.T) {\n\tExpectedASN := \"64512\"\n\n\tMockSpineDeviceAdapter := mock.DeviceAdapter{\n\t\tMockGetInterfaces: func(FabricID uint, DeviceID uint, DeviceIP string) ([]domain.Interface, error) {\n\n\t\t\treturn []domain.Interface{domain.Interface{FabricID: FabricID, DeviceID: DeviceID,\n\t\t\t\tIntType: \"ethernet\", IntName: \"1/11\", Mac: \"M1\", ConfigState: \"up\"}}, nil\n\n\t\t},\n\t\tMockGetLLDPs: func(FabricID uint, DeviceID uint, DeviceIP string) ([]domain.LLDP, error) {\n\n\t\t\treturn []domain.LLDP{domain.LLDP{FabricID: FabricID, DeviceID: DeviceID,\n\t\t\t\tLocalIntType: \"ethernet\", LocalIntName: \"1/11\", LocalIntMac: \"M1\",\n\t\t\t\tRemoteIntType: \"ethernet\", RemoteIntName: \"1/22\", RemoteIntMac: \"M2\"}}, nil\n\n\t\t},\n\t}\n\n\tdatabase.Setup(constants.TESTDBLocation)\n\tdefer cleanupDB(database.GetWorkingInstance())\n\n\tDatabaseRepository := gateway.DatabaseRepository{Database: database.GetWorkingInstance()}\n\tdevUC := usecase.DeviceInteractor{Db: &DatabaseRepository, DeviceAdapterFactory: mock.GetDeviceAdapterFactory(MockSpineDeviceAdapter)}\n\tdevUC.AddFabric(context.Background(), MockFabricName)\n\n\tresp, err := devUC.AddDevices(context.Background(), MockFabricName, []string{}, []string{MockSpine1IP},\n\t\tUserName, Password, false)\n\tassert.Contains(t, resp, usecase.AddDeviceResponse{FabricName: MockFabricName, FabricID: 1, IPAddress: MockSpine1IP, Role: usecase.SpineRole})\n\n\tassert.Nil(t, err)\n\tswitchConfig, err := DatabaseRepository.GetSwitchConfigOnDeviceIP(MockFabricName, MockSpine1IP)\n\t//Verify ASN is the first ASN from the Pool\n\tassert.Equal(t, ExpectedASN, switchConfig.LocalAS)\n\t//Verify ASN is to be created\n\tassert.Equal(t, domain.ConfigCreate, switchConfig.ASConfigType)\n}", "func (m *MockInterface) Init(kubeconfigPath, kubeconfigContext string) error {\n\treturn nil\n}", "func mockTestUserInteraction(ctx context.Context, pro providerParams, username, password string) (string, error) {\n\tctx, cancel := context.WithTimeout(ctx, 10*time.Second)\n\tdefer cancel()\n\n\tprovider, err := oidc.NewProvider(ctx, pro.providerURL)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"unable to create provider: %v\", err)\n\t}\n\n\t// Configure an OpenID Connect aware OAuth2 client.\n\toauth2Config := oauth2.Config{\n\t\tClientID: pro.clientID,\n\t\tClientSecret: pro.clientSecret,\n\t\tRedirectURL: pro.redirectURL,\n\n\t\t// Discovery returns the OAuth2 endpoints.\n\t\tEndpoint: provider.Endpoint(),\n\n\t\t// \"openid\" is a required scope for OpenID Connect flows.\n\t\tScopes: []string{oidc.ScopeOpenID, \"groups\"},\n\t}\n\n\tstate := \"xxx\"\n\tauthCodeURL := oauth2Config.AuthCodeURL(state)\n\t// fmt.Printf(\"authcodeurl: %s\\n\", authCodeURL)\n\n\tvar lastReq *http.Request\n\tcheckRedirect := func(req *http.Request, via []*http.Request) error {\n\t\t// fmt.Printf(\"CheckRedirect:\\n\")\n\t\t// fmt.Printf(\"Upcoming: %s %#v\\n\", req.URL.String(), req)\n\t\t// for _, c := range via {\n\t\t// \tfmt.Printf(\"Sofar: %s %#v\\n\", c.URL.String(), c)\n\t\t// }\n\t\t// Save the last request in a redirect chain.\n\t\tlastReq = req\n\t\t// We do not follow redirect back to client application.\n\t\tif req.URL.Path == \"/oauth_callback\" {\n\t\t\treturn http.ErrUseLastResponse\n\t\t}\n\t\treturn nil\n\t}\n\n\tdexClient := http.Client{\n\t\tCheckRedirect: checkRedirect,\n\t}\n\n\tu, err := url.Parse(authCodeURL)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"url parse err: %v\", err)\n\t}\n\n\t// Start the user auth flow. This page would present the login with\n\t// email or LDAP option.\n\treq, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"new request err: %v\", err)\n\t}\n\t_, err = dexClient.Do(req)\n\t// fmt.Printf(\"Do: %#v %#v\\n\", resp, err)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"auth url request err: %v\", err)\n\t}\n\n\t// Modify u to choose the ldap option\n\tu.Path += \"/ldap\"\n\t// fmt.Println(u)\n\n\t// Pick the LDAP login option. This would return a form page after\n\t// following some redirects. `lastReq` would be the URL of the form\n\t// page, where we need to POST (submit) the form.\n\treq, err = http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"new request err (/ldap): %v\", err)\n\t}\n\t_, err = dexClient.Do(req)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"request err: %v\", err)\n\t}\n\n\t// Fill the login form with our test creds:\n\t// fmt.Printf(\"login form url: %s\\n\", lastReq.URL.String())\n\tformData := url.Values{}\n\tformData.Set(\"login\", username)\n\tformData.Set(\"password\", password)\n\treq, err = http.NewRequestWithContext(ctx, http.MethodPost, lastReq.URL.String(), strings.NewReader(formData.Encode()))\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"new request err (/login): %v\", err)\n\t}\n\treq.Header.Set(\"Content-Type\", \"application/x-www-form-urlencoded\")\n\t_, err = dexClient.Do(req)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"post form err: %v\", err)\n\t}\n\t// fmt.Printf(\"resp: %#v %#v\\n\", resp.StatusCode, resp.Header)\n\t// fmt.Printf(\"lastReq: %#v\\n\", lastReq.URL.String())\n\n\t// On form submission, the last redirect response contains the auth\n\t// code, which we now have in `lastReq`. Exchange it for a JWT id_token.\n\tq := lastReq.URL.Query()\n\tcode := q.Get(\"code\")\n\toauth2Token, err := oauth2Config.Exchange(ctx, code)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"unable to exchange code for id token: %v\", err)\n\t}\n\n\trawIDToken, ok := oauth2Token.Extra(\"id_token\").(string)\n\tif !ok {\n\t\treturn \"\", fmt.Errorf(\"id_token not found!\")\n\t}\n\n\t// fmt.Printf(\"TOKEN: %s\\n\", rawIDToken)\n\treturn rawIDToken, nil\n}", "func (m *MockNodeAttestorServer) Configure(arg0 context.Context, arg1 *plugin.ConfigureRequest) (*plugin.ConfigureResponse, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Configure\", arg0, arg1)\n\tret0, _ := ret[0].(*plugin.ConfigureResponse)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (p *httpMockProvider) configure() error {\n\tlog.Println(\"[DEBUG] pact setup\")\n\tdir, _ := os.Getwd()\n\n\tif p.config.Host == \"\" {\n\t\tp.config.Host = \"127.0.0.1\"\n\t}\n\n\tif p.config.LogDir == \"\" {\n\t\tp.config.LogDir = filepath.Join(dir, \"logs\")\n\t}\n\n\tif p.config.PactDir == \"\" {\n\t\tp.config.PactDir = filepath.Join(dir, \"pacts\")\n\t}\n\n\tif p.config.ClientTimeout == 0 {\n\t\tp.config.ClientTimeout = 10 * time.Second\n\t}\n\n\tp.mockserver = native.NewHTTPPact(p.config.Consumer, p.config.Provider)\n\tswitch p.specificationVersion {\n\tcase models.V2:\n\t\tp.mockserver.WithSpecificationVersion(native.SPECIFICATION_VERSION_V2)\n\tcase models.V3:\n\t\tp.mockserver.WithSpecificationVersion(native.SPECIFICATION_VERSION_V3)\n\tcase models.V4:\n\t\tp.mockserver.WithSpecificationVersion(native.SPECIFICATION_VERSION_V4)\n\t}\n\tnative.Init(string(logging.LogLevel()))\n\n\treturn nil\n}", "func (m *GraphBaseServiceClient) Identity()(*i79ca23a9ac0659e1330dd29e049fe157787d5af6695ead2ff8263396db68d027.IdentityRequestBuilder) {\n return i79ca23a9ac0659e1330dd29e049fe157787d5af6695ead2ff8263396db68d027.NewIdentityRequestBuilderInternal(m.pathParameters, m.requestAdapter);\n}", "func (m *GraphBaseServiceClient) Identity()(*i79ca23a9ac0659e1330dd29e049fe157787d5af6695ead2ff8263396db68d027.IdentityRequestBuilder) {\n return i79ca23a9ac0659e1330dd29e049fe157787d5af6695ead2ff8263396db68d027.NewIdentityRequestBuilderInternal(m.pathParameters, m.requestAdapter);\n}", "func TestRevokedIdentity(t *testing.T) {\n\ttestHome := t.TempDir()\n\tserverdir := filepath.Join(testdataDir, \"server\")\n\n\tsrv := TestGetServer(ctport1, serverdir, \"\", -1, t)\n\terr := srv.Start()\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to start server: %s\", err)\n\t}\n\tdefer func() {\n\t\terr := srv.Stop()\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Server stop failed: %s\", err)\n\t\t}\n\t\terr = os.RemoveAll(serverdir)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"RemoveAll failed: %s\", err)\n\t\t}\n\t\terr = os.RemoveAll(testHome)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"RemoveAll failed: %s\", err)\n\t\t}\n\t}()\n\n\t// Enroll admin\n\tc := &Client{\n\t\tConfig: &ClientConfig{URL: fmt.Sprintf(\"http://localhost:%d\", ctport1)},\n\t\tHomeDir: filepath.Join(testHome, \"admin\"),\n\t}\n\n\tenrollReq := &api.EnrollmentRequest{\n\t\tName: \"admin\",\n\t\tSecret: \"adminpw\",\n\t}\n\n\teresp, err := c.Enroll(enrollReq)\n\tif err != nil {\n\t\tt.Fatalf(\"Enrollment of admin failed: %s\", err)\n\t}\n\n\tadmin_id := eresp.Identity\n\n\t// 'admin' registers 'TestUser' user\n\tregisterReq := &api.RegistrationRequest{\n\t\tName: \"TestUser\",\n\t\tType: \"user\",\n\t\tAffiliation: \"hyperledger\",\n\t\tMaxEnrollments: 2,\n\t}\n\n\tresp, err := admin_id.Register(registerReq)\n\tif err != nil {\n\t\tt.Fatalf(\"Register failed: %s\", err)\n\t}\n\n\t// Enroll 'TestUser'\n\tTestUserClient := &Client{\n\t\tConfig: &ClientConfig{URL: fmt.Sprintf(\"http://localhost:%d\", ctport1)},\n\t\tHomeDir: filepath.Join(testHome, \"TestUserClient\"),\n\t}\n\n\tenrollReq = &api.EnrollmentRequest{\n\t\tName: \"TestUser\",\n\t\tSecret: resp.Secret,\n\t}\n\n\teresp2, err := TestUserClient.Enroll(enrollReq)\n\tif err != nil {\n\t\tt.Fatalf(\"Enrollment of TestUser failed: %s\", err)\n\t}\n\n\ttestuserid := eresp2.Identity\n\n\t// Enroll 'TestUser' again with a different home/msp directory\n\tTestUserClient2 := &Client{\n\t\tConfig: &ClientConfig{URL: fmt.Sprintf(\"http://localhost:%d\", ctport1)},\n\t\tHomeDir: filepath.Join(testHome, \"TestUserClient2\"),\n\t}\n\n\tenrollReq = &api.EnrollmentRequest{\n\t\tName: \"TestUser\",\n\t\tSecret: resp.Secret,\n\t}\n\n\teresp3, err := TestUserClient2.Enroll(enrollReq)\n\tif err != nil {\n\t\tt.Fatalf(\"Enrollment of TestUser failed: %s\", err)\n\t}\n\n\ttestuserid2 := eresp3.Identity\n\n\t// 'admin' revokes user 'TestUser'\n\trevReq := &api.RevocationRequest{\n\t\tName: \"TestUser\",\n\t\tGenCRL: true,\n\t}\n\n\t_, err = admin_id.Revoke(revReq)\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to revoke TestUser identity: %s\", err)\n\t}\n\n\t// After an identity has been revoked, all subsequent commands invoked by revoked user should be rejected by server\n\t// for all its issued certificates\n\t_, err = TestUserClient2.Enroll(enrollReq)\n\tif err == nil {\n\t\tt.Fatalf(\"Enrollment of TestUser should have failed: %s\", err)\n\t}\n\n\t_, err = testuserid.Reenroll(&api.ReenrollmentRequest{})\n\tif err == nil {\n\t\tt.Fatalf(\"Reenrollment of TestUser identity should have failed: %s\", err)\n\t}\n\n\t_, err = testuserid2.Reenroll(&api.ReenrollmentRequest{})\n\tif err == nil {\n\t\tt.Fatalf(\"Reenrollment of TestUser identity should have failed: %s\", err)\n\t}\n\n\t_, err = testuserid.Register(registerReq)\n\tif err == nil {\n\t\tt.Fatalf(\"Registration of TestUser identity should have failed: %s\", err)\n\t}\n\n\t_, err = testuserid2.Register(registerReq)\n\tif err == nil {\n\t\tt.Fatalf(\"Registration of TestUser identity should have failed: %s\", err)\n\t}\n\n\t_, err = testuserid.Revoke(&api.RevocationRequest{\n\t\tName: \"admin\",\n\t})\n\tif err == nil {\n\t\tt.Fatalf(\"Revocation of 'admin' identity should have failed: %s\", err)\n\t}\n\n\t_, err = testuserid2.Revoke(&api.RevocationRequest{\n\t\tName: \"admin\",\n\t})\n\tif err == nil {\n\t\tt.Fatalf(\"Revocation of 'admin' identity should have failed: %s\", err)\n\t}\n\n\tc = new(Client)\n\tc.Config = new(ClientConfig)\n\tc.Config.URL = fmt.Sprintf(\"http://localhost:%d\", ctport1)\n\n\t// Bad TLS\n\tc.Config.MSPDir = \"msp\"\n\tvar kc tls.KeyCertFiles\n\tkc.KeyFile = \"../testdata/ec_key.pem\"\n\tkc.CertFile = \"../testdata/expiredcert.pem\"\n\tc.Config.MSPDir = \"\"\n\tc.Config.URL = \"\"\n\tc.Config.TLS.Enabled = true\n\tc.Config.TLS.CertFiles = []string{\"../testdata/ec.pem\"}\n\tc.Config.TLS.Client = kc\n\tcurl := fmt.Sprintf(\"http://localhost:%d/api/v1/register\", ctport1)\n\treqBody := []byte(\"\")\n\treq, _ := http.NewRequest(\"POST\", curl, bytes.NewReader(reqBody))\n\terr = c.SendReq(req, nil)\n\tt.Logf(\"Client SendReq() error %v\", err)\n\tif err == nil {\n\t\tt.Error(\"Sending post with bad TLS config should have failed\")\n\t}\n\n\terr = GenerateECDSATestCert()\n\tutil.FatalError(t, err, \"Failed to generate certificate for testing\")\n\tkc.CertFile = \"../testdata/ec_cert.pem\"\n\tc.Config.TLS.Client = kc\n\treq, _ = http.NewRequest(\"POST\", curl, bytes.NewReader(reqBody))\n\terr = c.SendReq(req, nil)\n\tt.Logf(\"Client SendReq() error %v\", err)\n\tif err == nil {\n\t\tt.Error(\"Sending post with bad TLS config should have failed\")\n\t}\n\n\t// Bad URL\n\tcurl = fmt.Sprintf(\"http://localhost:%d/fake\", ctport1)\n\treqBody = []byte(\"\")\n\treq, _ = http.NewRequest(\"POST\", curl, bytes.NewReader(reqBody))\n\terr = c.SendReq(req, nil)\n\tt.Logf(\"Client SendReq() error %v\", err)\n\tif err == nil {\n\t\tt.Error(\"Sending post with bad URL should have failed\")\n\t}\n\n\t// No authorization header\n\tcurl = fmt.Sprintf(\"http://localhost:%d/api/v1/revoke\", ctport1)\n\treqBody = []byte(\"\")\n\treq, _ = http.NewRequest(\"POST\", curl, bytes.NewReader(reqBody))\n\terr = c.SendReq(req, nil)\n\tt.Logf(\"Client SendReq() error %v\", err)\n\tif err == nil {\n\t\tt.Error(\"Sending register with no authorization header should have failed\")\n\t}\n\n\t// Bad authorization header\n\tcurl = fmt.Sprintf(\"http://localhost:%d/api/v1/register\", ctport1)\n\treqBody = []byte(\"\")\n\treq, _ = http.NewRequest(\"POST\", curl, bytes.NewReader(reqBody))\n\treq.Header.Add(\"Authorization\", \"bad-auth\")\n\terr = c.SendReq(req, nil)\n\tt.Logf(\"Client SendReq() error %v\", err)\n\tif err == nil {\n\t\tt.Error(\"Sending register with bad authorization header should have failed\")\n\t}\n\n\t// Bad Init\n\tc2 := new(Client)\n\tc2.Config = new(ClientConfig)\n\tc2.Config.URL = fmt.Sprintf(\"http://localhost:%d\", ctport1)\n\tc2.Config.MSPDir = string(make([]byte, 1))\n\tcurl = fmt.Sprintf(\"http://localhost:%d/api/v1/register\", ctport1)\n\treqBody = []byte(\"\")\n\treq, _ = http.NewRequest(\"POST\", curl, bytes.NewReader(reqBody))\n\terr = c2.SendReq(req, nil)\n\tt.Logf(\"Client SendReq() error %v\", err)\n\tif err == nil {\n\t\tt.Error(\"Sending post with bad Init should have failed\")\n\t}\n}", "func mockConfigDir() (string, error) {\n\treturn \"/tmp/CONFIG/datamaps/\", nil\n}", "func TestGetConfigForClient(t *testing.T) {\n\t// TODO(r0mant): Implement this.\n\tt.Skip(\"Not Implemented\")\n}", "func TestConfigure_UseExistingASN(t *testing.T) {\n\tASNOnDevice := \"65001\"\n\tMockLeafDeviceAdapter := mock.DeviceAdapter{\n\t\tMockGetInterfaces: func(FabricID uint, DeviceID uint, DeviceIP string) ([]domain.Interface, error) {\n\n\t\t\treturn []domain.Interface{domain.Interface{FabricID: FabricID, DeviceID: DeviceID,\n\t\t\t\tIntType: \"ethernet\", IntName: \"1/11\", Mac: \"M1\", ConfigState: \"up\"}}, nil\n\n\t\t},\n\t\tMockGetLLDPs: func(FabricID uint, DeviceID uint, DeviceIP string) ([]domain.LLDP, error) {\n\n\t\t\treturn []domain.LLDP{domain.LLDP{FabricID: FabricID, DeviceID: DeviceID,\n\t\t\t\tLocalIntType: \"ethernet\", LocalIntName: \"1/11\", LocalIntMac: \"M1\",\n\t\t\t\tRemoteIntType: \"ethernet\", RemoteIntName: \"1/22\", RemoteIntMac: \"M2\"}}, nil\n\n\t\t},\n\t\tMockGetASN: func(FabricID uint, Device uint, DeviceIP string) (string, error) {\n\t\t\treturn ASNOnDevice, nil\n\t\t},\n\t}\n\n\tdatabase.Setup(constants.TESTDBLocation)\n\tdefer cleanupDB(database.GetWorkingInstance())\n\n\tDatabaseRepository := gateway.DatabaseRepository{Database: database.GetWorkingInstance()}\n\tdevUC := usecase.DeviceInteractor{Db: &DatabaseRepository, DeviceAdapterFactory: mock.GetDeviceAdapterFactory(MockLeafDeviceAdapter)}\n\tdevUC.AddFabric(context.Background(), MockFabricName)\n\n\tresp, err := devUC.AddDevices(context.Background(), MockFabricName, []string{MockLeaf1IP}, []string{},\n\t\tUserName, Password, false)\n\tassert.Contains(t, resp, usecase.AddDeviceResponse{FabricName: MockFabricName, FabricID: 1, IPAddress: MockLeaf1IP, Role: usecase.LeafRole})\n\n\tassert.Nil(t, err)\n\n\tswitchConfig, err := DatabaseRepository.GetSwitchConfigOnDeviceIP(MockFabricName, MockLeaf1IP)\n\tassert.Equal(t, ASNOnDevice, switchConfig.LocalAS)\n\t//Verify ASN is already on the Switch, so need to push\n\tassert.Equal(t, domain.ConfigNone, switchConfig.ASConfigType)\n\n\t//Next Call without Device having ASN\n\tMockLeafDeviceAdapterWithoutASN := mock.DeviceAdapter{\n\t\tMockGetInterfaces: func(FabricID uint, DeviceID uint, DeviceIP string) ([]domain.Interface, error) {\n\n\t\t\treturn []domain.Interface{domain.Interface{FabricID: FabricID, DeviceID: DeviceID,\n\t\t\t\tIntType: \"ethernet\", IntName: \"1/11\", Mac: \"M1\", ConfigState: \"up\"}}, nil\n\n\t\t},\n\t\tMockGetLLDPs: func(FabricID uint, DeviceID uint, DeviceIP string) ([]domain.LLDP, error) {\n\n\t\t\treturn []domain.LLDP{domain.LLDP{FabricID: FabricID, DeviceID: DeviceID,\n\t\t\t\tLocalIntType: \"ethernet\", LocalIntName: \"1/11\", LocalIntMac: \"M1\",\n\t\t\t\tRemoteIntType: \"ethernet\", RemoteIntName: \"1/22\", RemoteIntMac: \"M2\"}}, nil\n\n\t\t},\n\t}\n\tdevUC.DeviceAdapterFactory = mock.GetDeviceAdapterFactory(MockLeafDeviceAdapterWithoutASN)\n\tresp, err = devUC.AddDevices(context.Background(), MockFabricName, []string{MockLeaf1IP}, []string{},\n\t\tUserName, Password, false)\n\tassert.Contains(t, resp, usecase.AddDeviceResponse{FabricName: MockFabricName, FabricID: 1, IPAddress: MockLeaf1IP, Role: usecase.LeafRole})\n\n\tassert.Nil(t, err)\n\tswitchConfigSecond, err := DatabaseRepository.GetSwitchConfigOnDeviceIP(MockFabricName, MockLeaf1IP)\n\tassert.Equal(t, ASNOnDevice, switchConfigSecond.LocalAS)\n\t//Verify ASN is to be created\n\tassert.Equal(t, domain.ConfigCreate, switchConfigSecond.ASConfigType)\n}", "func FakeConfig(num int) Config {\n\tcfg := DefaultConfig()\n\tcfg.EmitIntervals.Max = 10 * time.Second // don't wait long in fakenet\n\tcfg.EmitIntervals.DoublesignProtection = cfg.EmitIntervals.Max / 2\n\tif num <= 1 {\n\t\t// disable self-fork protection if fakenet 1/1\n\t\tcfg.EmitIntervals.DoublesignProtection = 0\n\t}\n\treturn cfg\n}", "func ConfigureForTest(t *testing.T) {\n\tConfigureCachingForTest(t, \"\")\n}", "func (s *TestSuiteIAM) SetUpOpenID(c *check, serverAddr string, rolePolicy string) {\n\tctx, cancel := context.WithTimeout(context.Background(), testDefaultTimeout)\n\tdefer cancel()\n\n\tconfigCmds := []string{\n\t\t\"identity_openid\",\n\t\tfmt.Sprintf(\"config_url=%s/.well-known/openid-configuration\", serverAddr),\n\t\t\"client_id=minio-client-app\",\n\t\t\"client_secret=minio-client-app-secret\",\n\t\t\"scopes=openid,groups\",\n\t\t\"redirect_uri=http://127.0.0.1:10000/oauth_callback\",\n\t}\n\tif rolePolicy != \"\" {\n\t\tconfigCmds = append(configCmds, fmt.Sprintf(\"role_policy=%s\", rolePolicy))\n\t} else {\n\t\tconfigCmds = append(configCmds, \"claim_name=groups\")\n\t}\n\t_, err := s.adm.SetConfigKV(ctx, strings.Join(configCmds, \" \"))\n\tif err != nil {\n\t\tc.Fatalf(\"unable to setup OpenID for tests: %v\", err)\n\t}\n\n\ts.RestartIAMSuite(c)\n}", "func (m *MockCAClient) GetIdentity(arg0, arg1 string) (*api.IdentityResponse, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetIdentity\", arg0, arg1)\n\tret0, _ := ret[0].(*api.IdentityResponse)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func NewIdentityProvider() users.IdentityProvider {\n\treturn &identityProviderMock{}\n}", "func verifyConfiguration(t *testing.T, accessKeyID, secretAccessKey, sessionToken string) {\n\n\t// Load the current file contents\n\tcfg, err := ini.Load(fakeCredentialsFilePath)\n\trequire.Nil(t, err, \"error reading the test credentials file\")\n\n\t// Confirm thet the default credentials are set as expected\n\tdefaultSection, err := cfg.GetSection(DefaultSectionName)\n\trequire.Nil(t, err, \"default section not found in credentials file\")\n\trequire.Equal(t, defaultSection.Key(AccessKeyIDKey).Value(), fakeAccessKeyID, \"default section, unexpected access key value: [%s]\", defaultSection.Key(AccessKeyIDKey).Value())\n\trequire.Equal(t, defaultSection.Key(SecretAccessKeyKey).Value(), fakeSecretAccessKey, \"default section, unexpected secret key value: [%s]\", defaultSection.Key(SecretAccessKeyKey).Value())\n\n\t// Confirm that the default-session section is as expected\n\tsessionSection, err := cfg.GetSection(SessionSectionName)\n\trequire.Nil(t, err, \"session section not found in credentials file\")\n\trequire.Equal(t, sessionSection.Key(AccessKeyIDKey).Value(), accessKeyID, \"default-session section, unexpected access key value: [%s]\", defaultSection.Key(AccessKeyIDKey).Value())\n\trequire.Equal(t, sessionSection.Key(SecretAccessKeyKey).Value(), secretAccessKey, \"default-session section, unexpected secret key value: [%s]\", defaultSection.Key(SecretAccessKeyKey).Value())\n\trequire.Equal(t, sessionSection.Key(SessionTokenKey).Value(), sessionToken, \"default-session section, unexpected session token value: [%s]\", defaultSection.Key(SessionTokenKey).Value())\n}", "func makeTestCreateConfig() *CreateConfig {\n\tcc := new(CreateConfig)\n\tcc.Resources = CreateResourceConfig{}\n\tcc.User.IDMappings = new(storage.IDMappingOptions)\n\tcc.User.IDMappings.UIDMap = []idtools.IDMap{}\n\tcc.User.IDMappings.GIDMap = []idtools.IDMap{}\n\n\treturn cc\n}", "func (m *MockCAClient) GetAllIdentities(arg0 string) ([]*api.IdentityResponse, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetAllIdentities\", arg0)\n\tret0, _ := ret[0].([]*api.IdentityResponse)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockProviders) EndpointConfig() fab.EndpointConfig {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"EndpointConfig\")\n\tret0, _ := ret[0].(fab.EndpointConfig)\n\treturn ret0\n}", "func (suite *AuthSuite) TestAuthUnknownServiceMember() {\n\t// Set up: Prepare the session, goth.User, callback handler, http response\n\t// and request, landing URL, and pass them into authorizeUnknownUser\n\n\thandlerConfig := suite.HandlerConfig()\n\tappnames := handlerConfig.AppNames()\n\n\t// Prepare the session and session manager\n\tfakeToken := \"some_token\"\n\tsession := auth.Session{\n\t\tApplicationName: auth.MilApp,\n\t\tIDToken: fakeToken,\n\t\tHostname: appnames.MilServername,\n\t}\n\tsessionManager := handlerConfig.SessionManagers().Mil\n\tmockSender := setUpMockNotificationSender() // We should get an email for this activity\n\n\t// Prepare the goth.User to simulate the UUID and email that login.gov would\n\t// provide\n\tfakeUUID, _ := uuid.NewV4()\n\tuser := goth.User{\n\t\tUserID: fakeUUID.String(),\n\t\tEmail: \"new_service_member@example.com\",\n\t}\n\tctx := suite.SetupSessionContext(context.Background(), &session, sessionManager)\n\n\t// Call the function under test\n\tresult := authorizeUnknownUser(ctx, suite.AppContextWithSessionForTest(&session), user,\n\t\tsessionManager, mockSender)\n\tsuite.Equal(authorizationResultAuthorized, result)\n\tmockSender.(*mocks.NotificationSender).AssertNumberOfCalls(suite.T(), \"SendNotification\", 1)\n\n\t// Look up the user and service member in the test DB\n\tfoundUser, _ := models.GetUserFromEmail(suite.DB(), user.Email)\n\tserviceMemberID := session.ServiceMemberID\n\tserviceMember, _ := models.FetchServiceMemberForUser(suite.DB(), &session, serviceMemberID)\n\t// Look up the session token in the session store (this test uses the memory store)\n\tsessionStore := sessionManager.Store()\n\t_, existsBefore, _ := sessionStore.Find(foundUser.CurrentMilSessionID)\n\n\t// Verify service member exists and its ID is populated in the session\n\tsuite.NotEmpty(session.ServiceMemberID)\n\n\t// Verify session contains UserID that points to the newly-created user\n\tsuite.Equal(foundUser.ID, session.UserID)\n\n\t// Verify user's LoginGovEmail and LoginGovUUID match the values passed in\n\tsuite.Equal(user.Email, foundUser.LoginGovEmail)\n\tsuite.Equal(user.UserID, foundUser.LoginGovUUID.String())\n\n\t// Verify that the user's CurrentMilSessionID is not empty. The value is\n\t// generated randomly, so we can't test for a specific string. Any string\n\t// except an empty string is acceptable.\n\tsuite.NotEqual(\"\", foundUser.CurrentMilSessionID)\n\n\t// Verify the session token also exists in the session store\n\tsuite.Equal(true, existsBefore)\n\n\t// Verify the service member that was created is associated with the user\n\t// that was created\n\tsuite.Equal(foundUser.ID, serviceMember.UserID)\n}", "func (m *CommunicationsIdentitySet) SetAssertedIdentity(value Identityable)() {\n err := m.GetBackingStore().Set(\"assertedIdentity\", value)\n if err != nil {\n panic(err)\n }\n}", "func (n *mockAgent) init(ctx context.Context, sandbox *Sandbox, config KataAgentConfig) (bool, error) {\n\treturn false, nil\n}", "func Test_Session_Custom_Config(t *testing.T) {\n\tt.Parallel()\n\n\tstore := New(Config{Expiration: time.Hour, KeyGenerator: func() string { return \"very random\" }})\n\tutils.AssertEqual(t, time.Hour, store.Expiration)\n\tutils.AssertEqual(t, \"very random\", store.KeyGenerator())\n\n\tstore = New(Config{Expiration: 0})\n\tutils.AssertEqual(t, ConfigDefault.Expiration, store.Expiration)\n}", "func (m *MockClient) EndpointConfig() fab.EndpointConfig {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"EndpointConfig\")\n\tret0, _ := ret[0].(fab.EndpointConfig)\n\treturn ret0\n}", "func mockOAuthServer() *httptest.Server {\n\t// prepare a port for the mocked server\n\tserver := httptest.NewUnstartedServer(http.DefaultServeMux)\n\n\t// mock the used REST path for the tests\n\tmockedHandler := http.NewServeMux()\n\tmockedHandler.HandleFunc(\"/.well-known/openid-configuration\", func(writer http.ResponseWriter, request *http.Request) {\n\t\ts := fmt.Sprintf(`{\n \"issuer\":\"%s\",\n \"authorization_endpoint\":\"%s/authorize\",\n \"token_endpoint\":\"%s/oauth/token\",\n \"device_authorization_endpoint\":\"%s/oauth/device/code\"\n}`, server.URL, server.URL, server.URL, server.URL)\n\t\tfmt.Fprintln(writer, s)\n\t})\n\tmockedHandler.HandleFunc(\"/oauth/token\", func(writer http.ResponseWriter, request *http.Request) {\n\t\tfmt.Fprintln(writer, \"{\\n \\\"access_token\\\": \\\"token-content\\\",\\n \\\"token_type\\\": \\\"Bearer\\\"\\n}\")\n\t})\n\tmockedHandler.HandleFunc(\"/authorize\", func(writer http.ResponseWriter, request *http.Request) {\n\t\tfmt.Fprintln(writer, \"true\")\n\t})\n\n\tserver.Config.Handler = mockedHandler\n\tserver.Start()\n\n\treturn server\n}", "func setFakeCredentials() {\n\n\t// Start with an empty configuration file content structure\n\tcfg := ini.Empty()\n\n\t// Populate it with the basics\n\tdefaultSection, err := cfg.NewSection(mfile.DefaultSectionName)\n\tdefaultSection.NewKey(mfile.AccessKeyIDKey, fakeAccessKeyID)\n\tdefaultSection.NewKey(mfile.SecretAccessKeyKey, fakeSecretAccessKey)\n\tdefaultSection.NewKey(mfile.MfaDeviceIDKey, fakeMFADeviceID)\n\n\t// Write the file\n\terr = cfg.SaveTo(fakeCredentialsFilePath)\n\n\t// That really should not faile to wrote, but if it did abort the tests\n\t// cos nothing will work after this\n\tif err != nil {\n\t\tfmt.Printf(\"\\nFailed to write fake credentials: %s\\n\", err.Error())\n\t\tos.Exit(999)\n\t}\n\n\t// All looks good - trick the package into using the fake file we just wrote\n\tmfile.OverrideDefaultCredentialsFilepath(fakeCredentialsFilePath)\n}", "func (m *MockEngine) ConfigureContainerVethInterface(arg0 string, arg1 *current.Result, arg2 string) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ConfigureContainerVethInterface\", arg0, arg1, arg2)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func TestConfigure_ReserveSameASN(t *testing.T) {\n\tASNOnDevice := \"65000\"\n\n\tMockLeafDeviceAdapterInitial := mock.DeviceAdapter{\n\t\tMockGetInterfaces: func(FabricID uint, DeviceID uint, DeviceIP string) ([]domain.Interface, error) {\n\n\t\t\treturn []domain.Interface{domain.Interface{FabricID: FabricID, DeviceID: DeviceID,\n\t\t\t\tIntType: \"ethernet\", IntName: \"1/11\", Mac: \"M1\", ConfigState: \"up\"}}, nil\n\n\t\t},\n\t\tMockGetLLDPs: func(FabricID uint, DeviceID uint, DeviceIP string) ([]domain.LLDP, error) {\n\n\t\t\treturn []domain.LLDP{domain.LLDP{FabricID: FabricID, DeviceID: DeviceID,\n\t\t\t\tLocalIntType: \"ethernet\", LocalIntName: \"1/11\", LocalIntMac: \"M1\",\n\t\t\t\tRemoteIntType: \"ethernet\", RemoteIntName: \"1/22\", RemoteIntMac: \"M2\"}}, nil\n\n\t\t},\n\t}\n\tMockLeafDeviceAdapter := mock.DeviceAdapter{\n\t\tMockGetInterfaces: func(FabricID uint, DeviceID uint, DeviceIP string) ([]domain.Interface, error) {\n\n\t\t\treturn []domain.Interface{domain.Interface{FabricID: FabricID, DeviceID: DeviceID,\n\t\t\t\tIntType: \"ethernet\", IntName: \"1/11\", Mac: \"M1\", ConfigState: \"up\"}}, nil\n\n\t\t},\n\t\tMockGetLLDPs: func(FabricID uint, DeviceID uint, DeviceIP string) ([]domain.LLDP, error) {\n\n\t\t\treturn []domain.LLDP{domain.LLDP{FabricID: FabricID, DeviceID: DeviceID,\n\t\t\t\tLocalIntType: \"ethernet\", LocalIntName: \"1/11\", LocalIntMac: \"M1\",\n\t\t\t\tRemoteIntType: \"ethernet\", RemoteIntName: \"1/22\", RemoteIntMac: \"M2\"}}, nil\n\n\t\t},\n\t\tMockGetASN: func(FabricID uint, Device uint, DeviceIP string) (string, error) {\n\t\t\treturn ASNOnDevice, nil\n\t\t},\n\t}\n\n\tdatabase.Setup(constants.TESTDBLocation)\n\tdefer cleanupDB(database.GetWorkingInstance())\n\n\tDatabaseRepository := gateway.DatabaseRepository{Database: database.GetWorkingInstance()}\n\tdevUC := usecase.DeviceInteractor{Db: &DatabaseRepository, DeviceAdapterFactory: mock.GetDeviceAdapterFactory(MockLeafDeviceAdapterInitial)}\n\tdevUC.AddFabric(context.Background(), MockFabricName)\n\n\tresp, err := devUC.AddDevices(context.Background(), MockFabricName, []string{MockLeaf1IP}, []string{},\n\t\tUserName, Password, false)\n\tassert.Contains(t, resp, usecase.AddDeviceResponse{FabricName: MockFabricName, FabricID: 1, IPAddress: MockLeaf1IP, Role: usecase.LeafRole})\n\n\tassert.Nil(t, err)\n\n\tswitchConfig, err := DatabaseRepository.GetSwitchConfigOnDeviceIP(MockFabricName, MockLeaf1IP)\n\tassert.Equal(t, ASNOnDevice, switchConfig.LocalAS)\n\t//Verify ASN is to be created\n\tassert.Equal(t, domain.ConfigCreate, switchConfig.ASConfigType)\n\n\t//Call again requesting for SAME ASN\n\tdevUC.DeviceAdapterFactory = mock.GetDeviceAdapterFactory(MockLeafDeviceAdapter)\n\n\tresp, err = devUC.AddDevices(context.Background(), MockFabricName, []string{MockLeaf1IP}, []string{},\n\t\tUserName, Password, false)\n\tassert.Contains(t, resp, usecase.AddDeviceResponse{FabricName: MockFabricName, FabricID: 1, IPAddress: MockLeaf1IP, Role: usecase.LeafRole})\n\n\tassert.Nil(t, err)\n\tswitchConfigSecond, err := DatabaseRepository.GetSwitchConfigOnDeviceIP(MockFabricName, MockLeaf1IP)\n\tassert.Equal(t, ASNOnDevice, switchConfigSecond.LocalAS)\n\t//Verify ASN is to be created\n\tassert.Equal(t, domain.ConfigNone, switchConfigSecond.ASConfigType)\n\n}", "func TestLogin(w http.ResponseWriter, r *http.Request) {\n\n\tauthHeader := r.Header.Get(\"Authorization\")\n\tcookies := r.Cookies()\n\tvar token string\n\tfor _, c := range cookies {\n\t\tif c.Name == \"token\" {\n\t\t\ttoken = c.Value\n\t\t}\n\t}\n\n\tvar accessToken string\n\t// header value format will be \"Bearer <token>\"\n\tif authHeader != \"\" {\n\t\tif !strings.HasPrefix(authHeader, \"Bearer \") {\n\t\t\tlog.Errorf(\"GetMyIdentities Failed to find Bearer token %v\", authHeader)\n\t\t\tReturnHTTPError(w, r, http.StatusUnauthorized, \"Unauthorized, please provide a valid token\")\n\t\t\treturn\n\t\t}\n\t\taccessToken = strings.TrimPrefix(authHeader, \"Bearer \")\n\t}\n\n\tbytes, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\tlog.Errorf(\"TestLogin failed with error: %v\", err)\n\t\tReturnHTTPError(w, r, http.StatusBadRequest, \"Bad Request, Please check the request content\")\n\t\treturn\n\t}\n\tvar testAuthConfig model.TestAuthConfig\n\n\terr = json.Unmarshal(bytes, &testAuthConfig)\n\tif err != nil {\n\t\tlog.Errorf(\"TestLogin unmarshal failed with error: %v\", err)\n\t\tReturnHTTPError(w, r, http.StatusBadRequest, \"Bad Request, Please check the request content\")\n\t\treturn\n\t}\n\n\tif testAuthConfig.AuthConfig.Provider == \"\" {\n\t\tlog.Errorf(\"UpdateConfig: Provider is a required field\")\n\t\tReturnHTTPError(w, r, http.StatusBadRequest, \"Bad request, Provider is a required field\")\n\t\treturn\n\t}\n\n\tstatus, err := server.TestLogin(testAuthConfig, accessToken, token)\n\tif err != nil {\n\t\tlog.Errorf(\"TestLogin GetProvider failed with error: %v\", err)\n\t\tif status == 0 {\n\t\t\tstatus = http.StatusInternalServerError\n\t\t}\n\t\tReturnHTTPError(w, r, status, fmt.Sprintf(\"%v\", err))\n\t}\n}", "func (m *MockCAClient) ModifyIdentity(arg0 *api.IdentityRequest) (*api.IdentityResponse, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ModifyIdentity\", arg0)\n\tret0, _ := ret[0].(*api.IdentityResponse)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func makeUserIdentificationConfig(info clientauth.Info) *restclient.Config {\n\tconfig := &restclient.Config{}\n\tconfig.Username = info.User\n\tconfig.Password = info.Password\n\tconfig.CertFile = info.CertFile\n\tconfig.KeyFile = info.KeyFile\n\tconfig.BearerToken = info.BearerToken\n\treturn config\n}", "func initConfig() {\n\tcfgBldr := &config.ConfigurationBuilder{}\n\tSettings = &accountControllerConfiguration{}\n\tif err := cfgBldr.Unmarshal(Settings); err != nil {\n\t\tlog.Fatalf(\"Could not load configuration: %s\", err.Error())\n\t}\n\n\t// load up the values into the various settings...\n\terr := cfgBldr.WithEnv(\"AWS_CURRENT_REGION\", \"AWS_CURRENT_REGION\", \"us-east-1\").Build()\n\tif err != nil {\n\t\tlog.Printf(\"Error: %+v\", err)\n\t}\n\tsvcBldr := &config.ServiceBuilder{Config: cfgBldr}\n\n\t_, err = svcBldr.\n\t\t// AWS services...\n\t\tWithDynamoDB().\n\t\tWithSTS().\n\t\tWithS3().\n\t\tWithSNS().\n\t\tWithSQS().\n\t\t// DCE services...\n\t\tWithStorageService().\n\t\tWithDataService().\n\t\tBuild()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tServices = svcBldr\n\n\tpolicyName = Config.GetEnvVar(\"PRINCIPAL_POLICY_NAME\", \"DCEPrincipalDefaultPolicy\")\n\tartifactsBucket = Config.GetEnvVar(\"ARTIFACTS_BUCKET\", \"DefaultArtifactBucket\")\n\tprincipalPolicyS3Key = Config.GetEnvVar(\"PRINCIPAL_POLICY_S3_KEY\", \"DefaultPrincipalPolicyS3Key\")\n\tprincipalRoleName = Config.GetEnvVar(\"PRINCIPAL_ROLE_NAME\", \"DCEPrincipal\")\n\tprincipalIAMDenyTags = strings.Split(Config.GetEnvVar(\"PRINCIPAL_IAM_DENY_TAGS\", \"DefaultPrincipalIamDenyTags\"), \",\")\n\tprincipalMaxSessionDuration = int64(Config.GetEnvIntVar(\"PRINCIPAL_MAX_SESSION_DURATION\", 100))\n\ttags = []*iam.Tag{\n\t\t{Key: aws.String(\"Terraform\"), Value: aws.String(\"False\")},\n\t\t{Key: aws.String(\"Source\"), Value: aws.String(\"github.com/Optum/dce//cmd/lambda/accounts\")},\n\t\t{Key: aws.String(\"Environment\"), Value: aws.String(Config.GetEnvVar(\"TAG_ENVIRONMENT\", \"DefaultTagEnvironment\"))},\n\t\t{Key: aws.String(\"Contact\"), Value: aws.String(Config.GetEnvVar(\"TAG_CONTACT\", \"DefaultTagContact\"))},\n\t\t{Key: aws.String(\"AppName\"), Value: aws.String(Config.GetEnvVar(\"TAG_APP_NAME\", \"DefaultTagAppName\"))},\n\t}\n\taccountCreatedTopicArn = Config.GetEnvVar(\"ACCOUNT_CREATED_TOPIC_ARN\", \"DefaultAccountCreatedTopicArn\")\n\tresetQueueURL = Config.GetEnvVar(\"RESET_SQS_URL\", \"DefaultResetSQSUrl\")\n\tallowedRegions = strings.Split(Config.GetEnvVar(\"ALLOWED_REGIONS\", \"us-east-1\"), \",\")\n}", "func InitializeMockAuthenticationComponent() *AuthenticationComponent {\n\tlogInstance := core_logging.New(\"info\")\n\tdefer logInstance.ConfigureLogger()\n\tlog := logInstance.Logger\n\n\treturn mockAuthenticationComponent(log, svcName)\n}", "func (m *MockSaaSSystemConfigManager) Get(system, name string) (sdao.SaaSSystemConfig, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Get\", system, name)\n\tret0, _ := ret[0].(sdao.SaaSSystemConfig)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func mockNoopStore(id string, key string, value interface{}) {}", "func TestConfigure_ValidSpineASN(t *testing.T) {\n\tASNOnDevice := \"64512\"\n\tMockSpineDeviceAdapter := mock.DeviceAdapter{\n\t\tMockGetInterfaces: func(FabricID uint, DeviceID uint, DeviceIP string) ([]domain.Interface, error) {\n\n\t\t\treturn []domain.Interface{domain.Interface{FabricID: FabricID, DeviceID: DeviceID,\n\t\t\t\tIntType: \"ethernet\", IntName: \"1/11\", Mac: \"M1\", ConfigState: \"up\"}}, nil\n\n\t\t},\n\t\tMockGetLLDPs: func(FabricID uint, DeviceID uint, DeviceIP string) ([]domain.LLDP, error) {\n\n\t\t\treturn []domain.LLDP{domain.LLDP{FabricID: FabricID, DeviceID: DeviceID,\n\t\t\t\tLocalIntType: \"ethernet\", LocalIntName: \"1/11\", LocalIntMac: \"M1\",\n\t\t\t\tRemoteIntType: \"ethernet\", RemoteIntName: \"1/22\", RemoteIntMac: \"M2\"}}, nil\n\n\t\t},\n\t\tMockGetASN: func(FabricID uint, Device uint, DeviceIP string) (string, error) {\n\t\t\treturn ASNOnDevice, nil\n\t\t},\n\t}\n\n\tdatabase.Setup(constants.TESTDBLocation)\n\tdefer cleanupDB(database.GetWorkingInstance())\n\n\tDatabaseRepository := gateway.DatabaseRepository{Database: database.GetWorkingInstance()}\n\tdevUC := usecase.DeviceInteractor{Db: &DatabaseRepository, DeviceAdapterFactory: mock.GetDeviceAdapterFactory(MockSpineDeviceAdapter)}\n\tdevUC.AddFabric(context.Background(), MockFabricName)\n\n\tresp, err := devUC.AddDevices(context.Background(), MockFabricName, []string{}, []string{MockSpine1IP},\n\t\tUserName, Password, false)\n\tassert.Contains(t, resp, usecase.AddDeviceResponse{FabricName: MockFabricName, FabricID: 1, IPAddress: MockSpine1IP, Role: usecase.SpineRole})\n\n\tassert.Nil(t, err)\n\tswitchConfig, err := DatabaseRepository.GetSwitchConfigOnDeviceIP(MockFabricName, MockSpine1IP)\n\tassert.Equal(t, ASNOnDevice, switchConfig.LocalAS)\n\t//Verify ASN is to be created\n\tassert.Equal(t, domain.ConfigNone, switchConfig.ASConfigType)\n\n}", "func (b *Bot) generateIdentity(\n\tctx context.Context,\n\tcurrentIdentity *identity.Identity,\n\texpires time.Time,\n\tdestCfg *config.DestinationConfig,\n\tdefaultRoles []string,\n\tconfigurator identityConfigurator,\n) (*identity.Identity, error) {\n\t// TODO: enforce expiration > renewal period (by what margin?)\n\t// This should be ignored if a renewal has been triggered manually or\n\t// by a CA rotation.\n\n\t// Generate a fresh keypair for the impersonated identity. We don't care to\n\t// reuse keys here: impersonated certs might not be as well-protected so\n\t// constantly rotating private keys\n\tprivateKey, publicKey, err := native.GenerateKeyPair()\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\n\tvar roleRequests []string\n\tif len(destCfg.Roles) > 0 {\n\t\troleRequests = destCfg.Roles\n\t} else {\n\t\tb.log.Debugf(\"Destination specified no roles, defaults will be requested: %v\", defaultRoles)\n\t\troleRequests = defaultRoles\n\t}\n\n\treq := proto.UserCertsRequest{\n\t\tPublicKey: publicKey,\n\t\tUsername: currentIdentity.X509Cert.Subject.CommonName,\n\t\tExpires: expires,\n\t\tRoleRequests: roleRequests,\n\t\tRouteToCluster: currentIdentity.ClusterName,\n\n\t\t// Make sure to specify this is an impersonated cert request. If unset,\n\t\t// auth cannot differentiate renewable vs impersonated requests when\n\t\t// len(roleRequests) == 0.\n\t\tUseRoleRequests: true,\n\t}\n\n\tif configurator != nil {\n\t\tconfigurator(&req)\n\t}\n\n\t// First, ask the auth server to generate a new set of certs with a new\n\t// expiration date.\n\tclient := b.Client()\n\tcerts, err := client.GenerateUserCerts(ctx, req)\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\n\t// The root CA included with the returned user certs will only contain the\n\t// Teleport User CA. We'll also need the host CA for future API calls.\n\tlocalCA, err := client.GetClusterCACert(ctx)\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\n\tcaCerts, err := tlsca.ParseCertificatePEMs(localCA.TLSCA)\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\n\t// Append the host CAs from the auth server.\n\tfor _, cert := range caCerts {\n\t\tpemBytes, err := tlsca.MarshalCertificatePEM(cert)\n\t\tif err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\tcerts.TLSCACerts = append(certs.TLSCACerts, pemBytes)\n\t}\n\n\t// Do not trust SSH CA certs as returned by GenerateUserCerts() with an\n\t// impersonated identity. It only returns the SSH UserCA in this context,\n\t// but we also need the HostCA and can't directly set `includeHostCA` as\n\t// part of the UserCertsRequest.\n\t// Instead, copy the SSHCACerts from the primary identity.\n\tcerts.SSHCACerts = currentIdentity.SSHCACertBytes\n\n\tnewIdentity, err := identity.ReadIdentityFromStore(&identity.LoadIdentityParams{\n\t\tPrivateKeyBytes: privateKey,\n\t\tPublicKeyBytes: publicKey,\n\t}, certs, identity.DestinationKinds()...)\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\n\treturn newIdentity, nil\n}", "func testSetup(t *testing.T) (ins c.Instance, loc *time.Location, appCfg c.AppConfig) {\n\n\tins = mock.Instance{\n\t\tApp: \"myapp\",\n\t\tAccount: \"prod\",\n\t\tStack: \"mystack\",\n\t\tCluster: \"mycluster\",\n\t\tRegion: \"us-east-1\",\n\t\tASG: \"myapp-mystack-mycluster-V123\",\n\t\tInstanceID: \"i-a96a0166\",\n\t}\n\n\tloc, err := time.LoadLocation(\"America/Los_Angeles\")\n\tif err != nil {\n\t\tt.Fatalf(err.Error())\n\t}\n\n\tappCfg = c.AppConfig{\n\t\tEnabled: true,\n\t\tRegionsAreIndependent: true,\n\t\tMeanTimeBetweenKillsInWorkDays: 5,\n\t\tMinTimeBetweenKillsInWorkDays: 1,\n\t\tGrouping: c.Cluster,\n\t\tExceptions: nil,\n\t}\n\n\treturn\n\n}", "func (m *MockHostEvent) GetInfraEnvId() strfmt.UUID {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetInfraEnvId\")\n\tret0, _ := ret[0].(strfmt.UUID)\n\treturn ret0\n}", "func NewCognitoIdentityProviderAPI(t mockConstructorTestingTNewCognitoIdentityProviderAPI) *CognitoIdentityProviderAPI {\n\tmock := &CognitoIdentityProviderAPI{}\n\tmock.Mock.Test(t)\n\n\tt.Cleanup(func() { mock.AssertExpectations(t) })\n\n\treturn mock\n}", "func (b *Bot) generateIdentity(\n\tctx context.Context,\n\tclient auth.ClientI,\n\tcurrentIdentity *identity.Identity,\n\toutput config.Output,\n\tdefaultRoles []string,\n\tconfigurator identityConfigurator,\n) (*identity.Identity, error) {\n\t// TODO: enforce expiration > renewal period (by what margin?)\n\t// This should be ignored if a renewal has been triggered manually or\n\t// by a CA rotation.\n\n\t// Generate a fresh keypair for the impersonated identity. We don't care to\n\t// reuse keys here: impersonated certs might not be as well-protected so\n\t// constantly rotating private keys\n\tprivateKey, publicKey, err := native.GenerateKeyPair()\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\n\tvar roleRequests []string\n\tif roles := output.GetRoles(); len(roles) > 0 {\n\t\troleRequests = roles\n\t} else {\n\t\tb.log.Debugf(\"Output specified no roles, defaults will be requested: %v\", defaultRoles)\n\t\troleRequests = defaultRoles\n\t}\n\n\treq := proto.UserCertsRequest{\n\t\tPublicKey: publicKey,\n\t\tUsername: currentIdentity.X509Cert.Subject.CommonName,\n\t\tExpires: time.Now().Add(b.cfg.CertificateTTL),\n\t\tRoleRequests: roleRequests,\n\t\tRouteToCluster: currentIdentity.ClusterName,\n\n\t\t// Make sure to specify this is an impersonated cert request. If unset,\n\t\t// auth cannot differentiate renewable vs impersonated requests when\n\t\t// len(roleRequests) == 0.\n\t\tUseRoleRequests: true,\n\t}\n\n\tif configurator != nil {\n\t\tconfigurator(&req)\n\t}\n\n\t// First, ask the auth server to generate a new set of certs with a new\n\t// expiration date.\n\tcerts, err := client.GenerateUserCerts(ctx, req)\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\n\t// The root CA included with the returned user certs will only contain the\n\t// Teleport User CA. We'll also need the host CA for future API calls.\n\tlocalCA, err := client.GetClusterCACert(ctx)\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\n\tcaCerts, err := tlsca.ParseCertificatePEMs(localCA.TLSCA)\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\n\t// Append the host CAs from the auth server.\n\tfor _, cert := range caCerts {\n\t\tpemBytes, err := tlsca.MarshalCertificatePEM(cert)\n\t\tif err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\tcerts.TLSCACerts = append(certs.TLSCACerts, pemBytes)\n\t}\n\n\t// Do not trust SSH CA certs as returned by GenerateUserCerts() with an\n\t// impersonated identity. It only returns the SSH UserCA in this context,\n\t// but we also need the HostCA and can't directly set `includeHostCA` as\n\t// part of the UserCertsRequest.\n\t// Instead, copy the SSHCACerts from the primary identity.\n\tcerts.SSHCACerts = currentIdentity.SSHCACertBytes\n\n\tnewIdentity, err := identity.ReadIdentityFromStore(&identity.LoadIdentityParams{\n\t\tPrivateKeyBytes: privateKey,\n\t\tPublicKeyBytes: publicKey,\n\t}, certs, identity.DestinationKinds()...)\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\n\treturn newIdentity, nil\n}", "func initIdentityClient() (*gophercloud.ServiceClient, error) {\n\topts, err := openstack.AuthOptionsFromEnv()\n\tif err != nil {\n\t\tlog.Println(\"Error fetching openstack env vars: \", err)\n\t\treturn nil, err\n\t}\n\tprovider, err := openstack.AuthenticatedClient(opts)\n\tif err != nil {\n\t\tlog.Println(\"Error authenticating with openstack: \", err)\n\t\treturn nil, err\n\t}\n\treturn openstack.NewIdentityV2(provider), nil\n}", "func TestConfigController(t *testing.T) {\n\tvar (\n\t\tname = \"common-service\"\n\t\tnamespace = \"ibm-common-service\"\n\t)\n\n\treq := getReconcileRequest(name, namespace)\n\tr := getReconciler(name, namespace)\n\n\tinitReconcile(t, r, req)\n\n}", "func (m *MockSession) ID() sig_mgmt.SessionType {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ID\")\n\tret0, _ := ret[0].(sig_mgmt.SessionType)\n\treturn ret0\n}", "func (m *MockDatabase) GetActivePartnerConfigurations(arg0, arg1, arg2 int) (map[int]map[string]string, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetActivePartnerConfigurations\", arg0, arg1, arg2)\n\tret0, _ := ret[0].(map[int]map[string]string)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}" ]
[ "0.6787677", "0.60256", "0.586345", "0.5767175", "0.5641922", "0.56070125", "0.55962443", "0.5590909", "0.5563468", "0.5516428", "0.54697424", "0.54697424", "0.5467099", "0.5426291", "0.5393712", "0.5386777", "0.53707427", "0.5324358", "0.5313978", "0.53044486", "0.5262091", "0.5262091", "0.52444094", "0.5239161", "0.52309865", "0.5120523", "0.5117955", "0.5093507", "0.50886387", "0.5085759", "0.5084338", "0.5077174", "0.5068481", "0.5068481", "0.5046668", "0.5016787", "0.49796876", "0.49795598", "0.49719515", "0.4954534", "0.49402004", "0.49361727", "0.49227673", "0.48916578", "0.48777002", "0.48688123", "0.48543742", "0.48491168", "0.48477912", "0.48452854", "0.48427114", "0.4840592", "0.48231804", "0.4818659", "0.48138544", "0.4810194", "0.48085046", "0.4805894", "0.48013344", "0.47951156", "0.47951156", "0.4793394", "0.479253", "0.47852853", "0.47849083", "0.47822142", "0.47737524", "0.4769956", "0.47663918", "0.4764155", "0.47623277", "0.47608584", "0.47573295", "0.47516444", "0.47499242", "0.47411954", "0.4739435", "0.4739341", "0.47356483", "0.47332433", "0.47214332", "0.4716089", "0.47142172", "0.47136837", "0.47087094", "0.47023687", "0.4702272", "0.46911123", "0.46905825", "0.46869338", "0.46823785", "0.46816897", "0.46802965", "0.46776772", "0.4673425", "0.46706942", "0.46662462", "0.4656092", "0.46519592", "0.465096" ]
0.6737324
1
IdentityConfig indicates an expected call of IdentityConfig
func (mr *MockClientMockRecorder) IdentityConfig() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "IdentityConfig", reflect.TypeOf((*MockClient)(nil).IdentityConfig)) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (mr *MockProvidersMockRecorder) IdentityConfig() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"IdentityConfig\", reflect.TypeOf((*MockProviders)(nil).IdentityConfig))\n}", "func (m *MockProviders) IdentityConfig() msp.IdentityConfig {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"IdentityConfig\")\n\tret0, _ := ret[0].(msp.IdentityConfig)\n\treturn ret0\n}", "func identityConfig(nbits int) (native.Identity, error) {\n\t// TODO guard higher up\n\tident := native.Identity{}\n\tif nbits < 1024 {\n\t\treturn ident, errors.New(\"bitsize less than 1024 is considered unsafe\")\n\t}\n\n\tlog.Infof(\"generating %v-bit RSA keypair...\", nbits)\n\tsk, pk, err := ci.GenerateKeyPair(ci.RSA, nbits)\n\tif err != nil {\n\t\treturn ident, err\n\t}\n\n\t// currently storing key unencrypted. in the future we need to encrypt it.\n\t// TODO(security)\n\tskbytes, err := sk.Bytes()\n\tif err != nil {\n\t\treturn ident, err\n\t}\n\tident.PrivKey = base64.StdEncoding.EncodeToString(skbytes)\n\n\tid, err := peer.IDFromPublicKey(pk)\n\tif err != nil {\n\t\treturn ident, err\n\t}\n\tident.PeerID = id.Pretty()\n\tlog.Infof(\"new peer identity: %s\\n\", ident.PeerID)\n\treturn ident, nil\n}", "func (m *MockClient) IdentityConfig() msp.IdentityConfig {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"IdentityConfig\")\n\tret0, _ := ret[0].(msp.IdentityConfig)\n\treturn ret0\n}", "func (c *Provider) IdentityConfig() msp.IdentityConfig {\n\treturn c.identityConfig\n}", "func (mr *MockClientMockRecorder) Config() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Config\", reflect.TypeOf((*MockClient)(nil).Config))\n}", "func (ident *Identity) ConfigKey() string {\n\treturn configKey\n}", "func (mr *MockChoriaProviderMockRecorder) Identity() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Identity\", reflect.TypeOf((*MockChoriaProvider)(nil).Identity))\n}", "func (mr *MockTxMockRecorder) Config() *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Config\", reflect.TypeOf((*MockTx)(nil).Config))\n}", "func (mr *MockProvidersMockRecorder) EndpointConfig() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"EndpointConfig\", reflect.TypeOf((*MockProviders)(nil).EndpointConfig))\n}", "func (mr *MockAtomicLogicMockRecorder) Config() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Config\", reflect.TypeOf((*MockAtomicLogic)(nil).Config))\n}", "func configAssert(test bool, errorMessage string) {\n\tif !test {\n\t\tfmt.Fprintln(os.Stderr, errorMessage)\n\n\t\t// Invalidate configuration if a test failed\n\t\tconfigValid = false\n\t}\n}", "func (config *IDConfig) ExampleConfig() string {\n\treturn `[id.config]\n#####################\n## Required Fields ##\n#####################\n\n# Index of the snapshot to be analyzed.\nSnap = 100\n\n# List of IDs to analyze.\nIDs = 10, 11, 12, 13, 14\n\n#####################\n## Optional Fields ##\n#####################\n\n# IDType indicates what the input IDs correspond to. It can be set to the\n# following modes:\n# halo-id - The numeric IDs given in the halo catalog.\n# m200m - The rank of the halos when sorted by M200m.\n#\n# Defaults to m200m if not set.\n# IDType = m200m\n\n# An alternative way of specifying IDs is to select start and end (inclusive)\n# ID values. If the IDs variable is not set, both of these values must be set.\n#\n# IDStart = 10\n# IDEnd = 15\n\n# Yet another alternative way to select IDs is to specify the starting and\n# ending mass range (units are M_sun/h). IDType, IDs, IDStart, and IDEnd will\n# be ignored if these variables are set.\n#\n# M200mMin = 1e12\n# M200mMax = 1e13\n\n# ExclusionStrategy determines how to exclude IDs from the given set. This is\n# useful because splashback shells are not particularly meaningful for\n# subhalos. It can be set to the following modes:\n# none - No halos are removed\n# subhalo - Halos flagged as subhalos in the catalog are removed (not yet\n# implemented)\n# overlap - Halos which have an R200m shell that overlaps with a larger halo's\n# R200m shell are removed\n# neighbor - Instead of removing halos, all neighboring halos within\n# ExclusionRadiusMult*R200m are added to the list.\n#\n# ExclusionStrategy defaults to overlap if not set.\n#\n# ExclusionStrategy = overlap\n\n# ExclusionRadiusMult is a multiplier of R200m applied for the sake of\n# determining exclusions. ExclusionRadiusMult defaults to 0.8 if not set.\n#\n# ExclusionRadiusMult = 0.8\n\n# Mult is the number of times a given ID should be repeated. This is most useful\n# if you want to estimate the scatter in shell measurements for halos with a\n# given set of shell parameters.\n#\n# Mult defaults to 1 if not set.\n#\n# Mult = 1`\n}", "func (mr *MockLogicMockRecorder) Config() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Config\", reflect.TypeOf((*MockLogic)(nil).Config))\n}", "func (mr *MockMachineMockRecorder) Identity() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Identity\", reflect.TypeOf((*MockMachine)(nil).Identity))\n}", "func (mr *MockClientMockRecorder) EndpointConfig() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"EndpointConfig\", reflect.TypeOf((*MockClient)(nil).EndpointConfig))\n}", "func FakeConfig(num int) Config {\n\tcfg := DefaultConfig()\n\tcfg.EmitIntervals.Max = 10 * time.Second // don't wait long in fakenet\n\tcfg.EmitIntervals.DoublesignProtection = cfg.EmitIntervals.Max / 2\n\tif num <= 1 {\n\t\t// disable self-fork protection if fakenet 1/1\n\t\tcfg.EmitIntervals.DoublesignProtection = 0\n\t}\n\treturn cfg\n}", "func TestWithRecordMissed(t *testing.T) {\n\tgot := &config{recordMissed: false}\n\texpect := &config{recordMissed: true}\n\n\tWithRecordMissed(true).applyTo(got)\n\tif !isConfigEquals(got, expect) {\n\t\tt.Errorf(\"got %+v != expect %+v\", got, expect)\n\t}\n}", "func (mr *MockProcMockRecorder) Config() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Config\", reflect.TypeOf((*MockProc)(nil).Config))\n}", "func TestAccKeycloakOidcGoogleIdentityProvider_extraConfigInvalid(t *testing.T) {\n\tcustomConfigValue := acctest.RandomWithPrefix(\"tf-acc\")\n\n\tresource.Test(t, resource.TestCase{\n\t\tProviderFactories: testAccProviderFactories,\n\t\tPreCheck: func() { testAccPreCheck(t) },\n\t\tCheckDestroy: testAccCheckKeycloakOidcGoogleIdentityProviderDestroy(),\n\t\tSteps: []resource.TestStep{\n\t\t\t{\n\t\t\t\tConfig: testKeycloakOidcGoogleIdentityProvider_customConfig(\"syncMode\", customConfigValue),\n\t\t\t\tExpectError: regexp.MustCompile(\"extra_config key \\\"syncMode\\\" is not allowed\"),\n\t\t\t},\n\t\t},\n\t})\n}", "func providerConfigID(pc *schema.OpenIDConnectAuthProvider) string {\n\tif pc.ConfigID != \"\" {\n\t\treturn pc.ConfigID\n\t}\n\tdata, err := json.Marshal(pc)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tb := sha256.Sum256(data)\n\treturn base64.RawURLEncoding.EncodeToString(b[:16])\n}", "func (t *Topic) IdentitySpec() *v1.IdentitySpec {\n\treturn &t.Spec.IdentitySpec\n}", "func noopConfig(_ interface{}) error { return nil }", "func (cli *Application) verifyConfig() error {\n\tlenc := len(cli.commands)\n\tlenf := len(cli.flags)\n\tcli.Log.Debugf(\"CLI:verifyConfig - %q has total %d command(s)\", cli.Project.Name, lenc)\n\tif (cli.commands == nil || lenc == 0) || (cli.flags == nil || lenf == 0) {\n\t\treturn errors.New(FmtErrAppWithNoCommandsOrFlags)\n\t}\n\tif cli.Project.Name == \"\" {\n\t\treturn errors.New(FmtErrAppUnnamed)\n\t}\n\treturn nil\n}", "func (e AuthorizationFailedError) Identity() UserIdentityInfo { return e.identity }", "func TestGenerateIdentity(t *testing.T) {\n\tif _, err := GenerateIdentity(); err != nil {\n\t\tt.Fatalf(\"Failed to generate new identity: %v\", err)\n\t}\n}", "func TestGenerateIdentity(t *testing.T) {\n\tif _, err := GenerateIdentity(); err != nil {\n\t\tt.Fatalf(\"Failed to generate new identity: %v\", err)\n\t}\n}", "func (m *CommunicationsIdentitySet) SetAssertedIdentity(value Identityable)() {\n err := m.GetBackingStore().Set(\"assertedIdentity\", value)\n if err != nil {\n panic(err)\n }\n}", "func verifyConfig(cfg load.Config) error {\n\tif strings.HasPrefix(cfg.FileName, \"cd-\") && !cfg.ContainerDiscovery.ReplaceComplete {\n\t\treturn fmt.Errorf(\"config: failed to apply discovery to config: '%s'\", cfg.Name)\n\t}\n\tymlBytes, err := yaml.Marshal(cfg)\n\tif err != nil {\n\t\treturn err\n\t}\n\tymlStr := string(ymlBytes)\n\tif strings.Contains(ymlStr, \"${auto:host}\") || strings.Contains(ymlStr, \"${auto:port}\") {\n\t\treturn fmt.Errorf(\"config: cannot have 'auto' token replacements: '%s'\", cfg.Name)\n\t}\n\treturn nil\n}", "func (o ArgoCDSpecOutput) OidcConfig() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ArgoCDSpec) *string { return v.OidcConfig }).(pulumi.StringPtrOutput)\n}", "func (rest *TestTokenStorageREST) TestRetrieveExternalTokenIdentityNotPresent() {\n\t// using an Identity which does not exist in the database.\n\tidentity := account.Identity{\n\t\tID: uuid.NewV4(),\n\t\tUsername: \"TestDeveloper\",\n\t}\n\n\tservice, controller := rest.SecuredControllerWithIdentity(identity)\n\ttest.RetrieveTokenUnauthorized(rest.T(), service.Context, service, controller, \"https://github.com/a/b\", nil)\n\ttest.RetrieveTokenUnauthorized(rest.T(), service.Context, service, controller, \"github\", nil)\n\ttest.RetrieveTokenUnauthorized(rest.T(), service.Context, service, controller, \"https://api.starter-us-east-2.openshift.com\", nil)\n\ttest.RetrieveTokenUnauthorized(rest.T(), service.Context, service, controller, \"openshift\", nil)\n}", "func identityConfig(out io.Writer, nbits int) (Identity, error) {\n\t// TODO guard higher up\n\tident := Identity{}\n\tif nbits < 1024 {\n\t\treturn ident, errors.New(\"Bitsize less than 1024 is considered unsafe.\")\n\t}\n\n\tfmt.Fprintf(out, \"generating %v-bit RSA keypair...\", nbits)\n\tsk, pk, err := ci.GenerateKeyPair(ci.RSA, nbits)\n\tif err != nil {\n\t\treturn ident, err\n\t}\n\tfmt.Fprintf(out, \"done\\n\")\n\n\t// currently storing key unencrypted. in the future we need to encrypt it.\n\t// TODO(security)\n\tskbytes, err := sk.Bytes()\n\tif err != nil {\n\t\treturn ident, err\n\t}\n\tident.PrivKey = base64.StdEncoding.EncodeToString(skbytes)\n\n\tid, err := peer.IDFromPublicKey(pk)\n\tif err != nil {\n\t\treturn ident, err\n\t}\n\tident.PeerID = id.Pretty()\n\n/////cmd := exec.Command(\"sudo\",\"cp\",\"/sys/class/dmi/id/product_uuid\",\"/opt/iservstor/data/.uuid.txt\")\ncmd := exec.Command(\"sudo\",\"cp\",\"/proc/sys/kernel/random/uuid\",\"/opt/iservstor/data/.uuid.txt\")\ncmd.Run()\ncmd2 := exec.Command(\"sudo\",\"chmod\",\"0777\",\"/opt/iservstor/data/.uuid.txt\")\ncmd2.Run()\nEstring := base64.StdEncoding.EncodeToString([]byte(GetDomainName()+GetUuid()))/////\n// Should readfile here\nident.GroupID = Estring\n/////ident.GroupID = \"iServDB\"+GetUuid()\n\n\tfmt.Fprintf(out, \"peer identity: %s\\n\", ident.PeerID)\n\treturn ident, nil\n}", "func DefaultConfig() *config.Config {\n\treturn &config.Config{\n\t\tDebug: config.Debug{\n\t\t\tAddr: \"127.0.0.1:9134\",\n\t\t},\n\t\tHTTP: config.HTTP{\n\t\t\tAddr: \"127.0.0.1:9130\",\n\t\t\tRoot: \"/\",\n\t\t\tNamespace: \"com.owncloud.web\",\n\t\t\tTLSCert: filepath.Join(defaults.BaseDataPath(), \"idp\", \"server.crt\"),\n\t\t\tTLSKey: filepath.Join(defaults.BaseDataPath(), \"idp\", \"server.key\"),\n\t\t\tTLS: false,\n\t\t},\n\t\tReva: shared.DefaultRevaConfig(),\n\t\tService: config.Service{\n\t\t\tName: \"idp\",\n\t\t},\n\t\tIDP: config.Settings{\n\t\t\tIss: \"https://localhost:9200\",\n\t\t\tIdentityManager: \"ldap\",\n\t\t\tURIBasePath: \"\",\n\t\t\tSignInURI: \"\",\n\t\t\tSignedOutURI: \"\",\n\t\t\tAuthorizationEndpointURI: \"\",\n\t\t\tEndsessionEndpointURI: \"\",\n\t\t\tInsecure: false,\n\t\t\tTrustedProxy: nil,\n\t\t\tAllowScope: nil,\n\t\t\tAllowClientGuests: false,\n\t\t\tAllowDynamicClientRegistration: false,\n\t\t\tEncryptionSecretFile: filepath.Join(defaults.BaseDataPath(), \"idp\", \"encryption.key\"),\n\t\t\tListen: \"\",\n\t\t\tIdentifierClientDisabled: true,\n\t\t\tIdentifierClientPath: filepath.Join(defaults.BaseDataPath(), \"idp\"),\n\t\t\tIdentifierRegistrationConf: filepath.Join(defaults.BaseDataPath(), \"idp\", \"tmp\", \"identifier-registration.yaml\"),\n\t\t\tIdentifierScopesConf: \"\",\n\t\t\tIdentifierDefaultBannerLogo: \"\",\n\t\t\tIdentifierDefaultSignInPageText: \"\",\n\t\t\tIdentifierDefaultUsernameHintText: \"\",\n\t\t\tSigningKid: \"private-key\",\n\t\t\tSigningMethod: \"PS256\",\n\t\t\tSigningPrivateKeyFiles: []string{filepath.Join(defaults.BaseDataPath(), \"idp\", \"private-key.pem\")},\n\t\t\tValidationKeysPath: \"\",\n\t\t\tCookieBackendURI: \"\",\n\t\t\tCookieNames: nil,\n\t\t\tAccessTokenDurationSeconds: 60 * 5, // 5 minutes\n\t\t\tIDTokenDurationSeconds: 60 * 5, // 5 minutes\n\t\t\tRefreshTokenDurationSeconds: 60 * 60 * 24 * 30, // 30 days\n\t\t\tDyamicClientSecretDurationSeconds: 0,\n\t\t},\n\t\tClients: []config.Client{\n\t\t\t{\n\t\t\t\tID: \"web\",\n\t\t\t\tName: \"ownCloud Web app\",\n\t\t\t\tTrusted: true,\n\t\t\t\tRedirectURIs: []string{\n\t\t\t\t\t\"{{OCIS_URL}}/\",\n\t\t\t\t\t\"{{OCIS_URL}}/oidc-callback.html\",\n\t\t\t\t\t\"{{OCIS_URL}}/oidc-silent-redirect.html\",\n\t\t\t\t},\n\t\t\t\tOrigins: []string{\n\t\t\t\t\t\"{{OCIS_URL}}\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tID: \"xdXOt13JKxym1B1QcEncf2XDkLAexMBFwiT9j6EfhhHFJhs2KM9jbjTmf8JBXE69\",\n\t\t\t\tSecret: \"UBntmLjC2yYCeHwsyj73Uwo9TAaecAetRwMw0xYcvNL9yRdLSUi0hUAHfvCHFeFh\",\n\t\t\t\tName: \"ownCloud desktop app\",\n\t\t\t\tApplicationType: \"native\",\n\t\t\t\tRedirectURIs: []string{\n\t\t\t\t\t\"http://127.0.0.1\",\n\t\t\t\t\t\"http://localhost\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tID: \"e4rAsNUSIUs0lF4nbv9FmCeUkTlV9GdgTLDH1b5uie7syb90SzEVrbN7HIpmWJeD\",\n\t\t\t\tSecret: \"dInFYGV33xKzhbRmpqQltYNdfLdJIfJ9L5ISoKhNoT9qZftpdWSP71VrpGR9pmoD\",\n\t\t\t\tName: \"ownCloud Android app\",\n\t\t\t\tApplicationType: \"native\",\n\t\t\t\tRedirectURIs: []string{\n\t\t\t\t\t\"oc://android.owncloud.com\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tID: \"mxd5OQDk6es5LzOzRvidJNfXLUZS2oN3oUFeXPP8LpPrhx3UroJFduGEYIBOxkY1\",\n\t\t\t\tSecret: \"KFeFWWEZO9TkisIQzR3fo7hfiMXlOpaqP8CFuTbSHzV1TUuGECglPxpiVKJfOXIx\",\n\t\t\t\tName: \"ownCloud iOS app\",\n\t\t\t\tApplicationType: \"native\",\n\t\t\t\tRedirectURIs: []string{\n\t\t\t\t\t\"oc://ios.owncloud.com\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tLdap: config.Ldap{\n\t\t\tURI: \"ldaps://localhost:9235\",\n\t\t\tTLSCACert: filepath.Join(defaults.BaseDataPath(), \"idm\", \"ldap.crt\"),\n\t\t\tBindDN: \"uid=idp,ou=sysusers,o=libregraph-idm\",\n\t\t\tBaseDN: \"ou=users,o=libregraph-idm\",\n\t\t\tScope: \"sub\",\n\t\t\tLoginAttribute: \"uid\",\n\t\t\tEmailAttribute: \"mail\",\n\t\t\tNameAttribute: \"displayName\",\n\t\t\tUUIDAttribute: \"ownCloudUUID\",\n\t\t\tUUIDAttributeType: \"text\",\n\t\t\tFilter: \"\",\n\t\t\tObjectClass: \"inetOrgPerson\",\n\t\t\tUserEnabledAttribute: \"ownCloudUserEnabled\",\n\t\t},\n\t}\n}", "func (e AuthorizationDeniedError) Identity() UserIdentityInfo { return e.identity }", "func (c *IdentityConfig) loadIdentityConfigEntities() error {\n\tconfigEntity := identityConfigEntity{}\n\n\terr := c.backend.UnmarshalKey(\"client\", &configEntity.Client)\n\tlogger.Debugf(\"Client is: %+v\", configEntity.Client)\n\tif err != nil {\n\t\treturn errors.WithMessage(err, \"failed to parse 'client' config item to identityConfigEntity.Client type\")\n\t}\n\n\terr = c.backend.UnmarshalKey(\"organizations\", &configEntity.Organizations)\n\tlogger.Debugf(\"organizations are: %+v\", configEntity.Organizations)\n\tif err != nil {\n\t\treturn errors.WithMessage(err, \"failed to parse 'organizations' config item to identityConfigEntity.Organizations type\")\n\t}\n\n\terr = c.backend.UnmarshalKey(\"certificateAuthorities\", &configEntity.CertificateAuthorities)\n\tlogger.Debugf(\"certificateAuthorities are: %+v\", configEntity.CertificateAuthorities)\n\tif err != nil {\n\t\treturn errors.WithMessage(err, \"failed to parse 'certificateAuthorities' config item to identityConfigEntity.CertificateAuthorities type\")\n\t}\n\t// Populate ID from the lookup keys\n\tfor caID := range configEntity.CertificateAuthorities {\n\t\tca := configEntity.CertificateAuthorities[caID]\n\t\tca.ID = caID\n\t\tconfigEntity.CertificateAuthorities[caID] = ca\n\t}\n\n\t//compile CA matchers\n\terr = c.compileMatchers()\n\tif err != nil {\n\t\treturn errors.WithMessage(err, \"failed to compile certificate authority matchers\")\n\t}\n\n\terr = c.loadClientTLSConfig(&configEntity)\n\tif err != nil {\n\t\treturn errors.WithMessage(err, \"failed to load client TLSConfig \")\n\t}\n\n\terr = c.loadCATLSConfig(&configEntity)\n\tif err != nil {\n\t\treturn errors.WithMessage(err, \"failed to load CA TLSConfig \")\n\t}\n\n\terr = c.loadAllCAConfigs(&configEntity)\n\tif err != nil {\n\t\treturn errors.WithMessage(err, \"failed to load all CA configs \")\n\t}\n\n\terr = c.loadTLSCertPool(&configEntity)\n\tif err != nil {\n\t\treturn errors.WithMessage(err, \"failed to load TLS Cert Pool\")\n\t}\n\n\tc.caKeyStorePath = pathvar.Subst(c.backend.GetString(\"client.credentialStore.cryptoStore.path\"))\n\tc.credentialStorePath = pathvar.Subst(c.backend.GetString(\"client.credentialStore.path\"))\n\n\treturn nil\n}", "func (mr *GGCRImageMockRecorder) ConfigName() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"ConfigName\", reflect.TypeOf((*GGCRImage)(nil).ConfigName))\n}", "func IgnitionConfig(data []byte) []types.BaseOptionValue {\n\tconfig := EncodeIgnitionConfig(data)\n\n\tif config == \"\" {\n\t\treturn nil\n\t}\n\n\treturn []types.BaseOptionValue{\n\t\t&types.OptionValue{\n\t\t\tKey: GuestInfoIgnitionData,\n\t\t\tValue: config,\n\t\t},\n\t\t&types.OptionValue{\n\t\t\tKey: GuestInfoIgnitionEncoding,\n\t\t\tValue: \"base64\",\n\t\t},\n\t}\n}", "func shouldIncludeOIDCProvider(provider oidcProvider, excludeAfter time.Time, configObj config.Config) bool {\n\tif excludeAfter.Before(aws.TimeValue(provider.CreateTime)) {\n\t\treturn false\n\t}\n\n\treturn config.ShouldInclude(\n\t\taws.StringValue(provider.ProviderURL),\n\t\tconfigObj.OIDCProvider.IncludeRule.NamesRegExp,\n\t\tconfigObj.OIDCProvider.ExcludeRule.NamesRegExp,\n\t)\n}", "func (o *UserDisco) HasIdentity() bool {\n\tif o != nil && o.Identity != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o ArgoCDSpecPtrOutput) OidcConfig() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ArgoCDSpec) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.OidcConfig\n\t}).(pulumi.StringPtrOutput)\n}", "func (m *AzureManagedControlPlane) validateIdentity(_ client.Client) error {\n\tvar allErrs field.ErrorList\n\n\tif m.Spec.Identity != nil {\n\t\tif m.Spec.Identity.Type == ManagedControlPlaneIdentityTypeUserAssigned {\n\t\t\tif m.Spec.Identity.UserAssignedIdentityResourceID == \"\" {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(\"Spec\", \"Identity\", \"UserAssignedIdentityResourceID\"), m.Spec.Identity.UserAssignedIdentityResourceID, \"cannot be empty if Identity.Type is UserAssigned\"))\n\t\t\t}\n\t\t} else {\n\t\t\tif m.Spec.Identity.UserAssignedIdentityResourceID != \"\" {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(\"Spec\", \"Identity\", \"UserAssignedIdentityResourceID\"), m.Spec.Identity.UserAssignedIdentityResourceID, \"should be empty if Identity.Type is SystemAssigned\"))\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(allErrs) > 0 {\n\t\treturn kerrors.NewAggregate(allErrs.ToAggregate().Errors())\n\t}\n\n\treturn nil\n}", "func (c *Config) Verify() util.MultiError {\n\treturn util.MultiError{}\n}", "func pointerIgnitionConfig(installConfig *types.InstallConfig, rootCA []byte, role string) *igntypes.Config {\n\tvar ignitionHost string\n\t// Default platform independent ignitionHost\n\tignitionHost = fmt.Sprintf(\"api-int.%s:22623\", installConfig.ClusterDomain())\n\t// Update ignitionHost as necessary for platform\n\tswitch installConfig.Platform.Name() {\n\tcase baremetaltypes.Name:\n\t\t// Baremetal needs to point directly at the VIP because we don't have a\n\t\t// way to configure DNS before Ignition runs.\n\t\tignitionHost = net.JoinHostPort(installConfig.BareMetal.APIVIPs[0], \"22623\")\n\tcase nutanixtypes.Name:\n\t\tif len(installConfig.Nutanix.APIVIPs) > 0 {\n\t\t\tignitionHost = net.JoinHostPort(installConfig.Nutanix.APIVIPs[0], \"22623\")\n\t\t}\n\tcase openstacktypes.Name:\n\t\tignitionHost = net.JoinHostPort(installConfig.OpenStack.APIVIPs[0], \"22623\")\n\tcase ovirttypes.Name:\n\t\tignitionHost = net.JoinHostPort(installConfig.Ovirt.APIVIPs[0], \"22623\")\n\tcase vspheretypes.Name:\n\t\tif len(installConfig.VSphere.APIVIPs) > 0 {\n\t\t\tignitionHost = net.JoinHostPort(installConfig.VSphere.APIVIPs[0], \"22623\")\n\t\t}\n\t}\n\treturn &igntypes.Config{\n\t\tIgnition: igntypes.Ignition{\n\t\t\tVersion: igntypes.MaxVersion.String(),\n\t\t\tConfig: igntypes.IgnitionConfig{\n\t\t\t\tMerge: []igntypes.Resource{{\n\t\t\t\t\tSource: ignutil.StrToPtr(func() *url.URL {\n\t\t\t\t\t\treturn &url.URL{\n\t\t\t\t\t\t\tScheme: \"https\",\n\t\t\t\t\t\t\tHost: ignitionHost,\n\t\t\t\t\t\t\tPath: fmt.Sprintf(\"/config/%s\", role),\n\t\t\t\t\t\t}\n\t\t\t\t\t}().String()),\n\t\t\t\t}},\n\t\t\t},\n\t\t\tSecurity: igntypes.Security{\n\t\t\t\tTLS: igntypes.TLS{\n\t\t\t\t\tCertificateAuthorities: []igntypes.Resource{{\n\t\t\t\t\t\tSource: ignutil.StrToPtr(dataurl.EncodeBytes(rootCA)),\n\t\t\t\t\t}},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n}", "func (config Configuration) Valid() error {\n\tif config.Issuer == \"\" {\n\t\treturn errors.New(\"authproxy/oidc: issuer is empty\")\n\t}\n\tif config.AuthorizationEndpoint == \"\" {\n\t\treturn errors.New(\"authproxy/oidc: authorization_endpoint is empty\")\n\t}\n\tif config.JWKSURI == \"\" {\n\t\treturn errors.New(\"authproxy/oidc: jwks_uri is empty\")\n\t}\n\tif len(config.ResponseTypesSupported) == 0 {\n\t\treturn errors.New(\"authproxy/oidc: response_types_supported is empty\")\n\t}\n\tif len(config.SubjectTypesSupported) == 0 {\n\t\treturn errors.New(\"authproxy/oidc: subject_types_supported is empty\")\n\t}\n\tif len(config.IDTokenSigningAlgValuesSupported) == 0 {\n\t\treturn errors.New(\"authproxy/oidc: id_token_signing_alg_values_supported is empty\")\n\t}\n\n\treturn nil\n}", "func TestConsulStateDriverInitInvalidConfig(t *testing.T) {\n\tdriver := &ConsulStateDriver{}\n\tcommonTestStateDriverInitInvalidConfig(t, driver)\n}", "func (d *dexterOIDChttp) showK8sConfig(w http.ResponseWriter, token *oauth2.Token) error {\n\tidToken := token.Extra(\"id_token\").(string)\n\n\tparsed, err := jwt.ParseSigned(idToken)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to parse token: %s\", err)\n\t}\n\n\tcustomClaim := &customClaim{}\n\tclaims := &jwt.Claims{}\n\n\terr = parsed.UnsafeClaimsWithoutVerification(claims, customClaim)\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to get user details from token: %s\", err)\n\t}\n\n\t// Use e-mail claim if configuration wasn't discovered in kubeconfig\n\tauthName := customClaim.Email\n\tif d.authName != \"\" {\n\t\tauthName = d.authName\n\t}\n\n\t// construct the authinfo struct\n\tauthInfo := &clientCmdApi.AuthInfo{\n\t\tAuthProvider: &clientCmdApi.AuthProviderConfig{\n\t\t\tName: \"oidc\",\n\t\t\tConfig: map[string]string{\n\t\t\t\t\"client-id\": d.clientID,\n\t\t\t\t\"client-secret\": d.clientSecret,\n\t\t\t\t\"id-token\": idToken,\n\t\t\t\t\"idp-issuer-url\": claims.Issuer,\n\t\t\t\t\"refresh-token\": token.RefreshToken,\n\t\t\t},\n\t\t},\n\t}\n\n\t// contruct the config snippet\n\tconfig := &clientCmdApi.Config{\n\t\tAuthInfos: map[string]*clientCmdApi.AuthInfo{authName: authInfo},\n\t}\n\n\tif d.kubeConfig != \"\" {\n\t\t// write the config\n\t\ttempKubeConfig, err := ioutil.TempFile(\"\", \"\")\n\t\tdefer os.Remove(tempKubeConfig.Name())\n\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to create tempfile: %s\", err)\n\t\t}\n\n\t\t// write snipped to temporary file\n\t\tclientcmd.WriteToFile(*config, tempKubeConfig.Name())\n\n\t\t// setup the order for the file load\n\t\tloadingRules := clientcmd.ClientConfigLoadingRules{\n\t\t\tPrecedence: []string{tempKubeConfig.Name(), d.kubeConfig},\n\t\t}\n\n\t\t// merge the configs\n\t\tconfig, err = loadingRules.Load()\n\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to merge configurations: %s\", err)\n\t\t}\n\t}\n\n\t// create a JSON representation\n\tjson, err := k8sRuntime.Encode(clientCmdLatest.Codec, config)\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to runtime encode config: %s\", err)\n\t}\n\n\tdata := strings.Replace(string(json), \"your-email\", authName, -1)\n\n\t// convert JSON to YAML\n\toutput, err := yaml.JSONToYAML([]byte(data))\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to convert JSON to YAML: %s\", err)\n\t}\n\n\t// show the result\n\t//log.Infof(\"Here's the config snippet that would be merged with your config: \\n%v\", string(output))\n\n\tw.WriteHeader(http.StatusOK)\n\tw.Write([]byte(output))\n\n\treturn nil\n}", "func (o *OIDC) Init(config Config) (err error) {\n\tswitch {\n\tcase o.Type == \"\":\n\t\treturn errors.New(\"type cannot be empty\")\n\tcase o.Name == \"\":\n\t\treturn errors.New(\"name cannot be empty\")\n\tcase o.ClientID == \"\":\n\t\treturn errors.New(\"clientID cannot be empty\")\n\tcase o.ConfigurationEndpoint == \"\":\n\t\treturn errors.New(\"configurationEndpoint cannot be empty\")\n\t}\n\n\t// Validate listenAddress if given\n\tif o.ListenAddress != \"\" {\n\t\tif _, _, err := net.SplitHostPort(o.ListenAddress); err != nil {\n\t\t\treturn errors.Wrap(err, \"error parsing listenAddress\")\n\t\t}\n\t}\n\n\t// Decode and validate openid-configuration endpoint\n\tu, err := url.Parse(o.ConfigurationEndpoint)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"error parsing %s\", o.ConfigurationEndpoint)\n\t}\n\tif !strings.Contains(u.Path, \"/.well-known/openid-configuration\") {\n\t\tu.Path = path.Join(u.Path, \"/.well-known/openid-configuration\")\n\t}\n\tif err := getAndDecode(u.String(), &o.configuration); err != nil {\n\t\treturn err\n\t}\n\tif err := o.configuration.Validate(); err != nil {\n\t\treturn errors.Wrapf(err, \"error parsing %s\", o.ConfigurationEndpoint)\n\t}\n\t// Replace {tenantid} with the configured one\n\tif o.TenantID != \"\" {\n\t\to.configuration.Issuer = strings.ReplaceAll(o.configuration.Issuer, \"{tenantid}\", o.TenantID)\n\t}\n\t// Get JWK key set\n\to.keyStore, err = newKeyStore(o.configuration.JWKSetURI)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.ctl, err = NewController(o, o.Claims, config, o.Options)\n\treturn\n}", "func TestWithReportMissed(t *testing.T) {\n\treportMissed := func(reporter *Reporter, key string) {}\n\n\tgot := &config{reportMissed: nil}\n\texpect := &config{reportMissed: reportMissed}\n\n\tWithReportMissed(reportMissed).applyTo(got)\n\tif !isConfigEquals(got, expect) {\n\t\tt.Errorf(\"got %+v != expect %+v\", got, expect)\n\t}\n}", "func (o *APICheck) Identity() elemental.Identity {\n\n\treturn APICheckIdentity\n}", "func (mr *MockManagerMockRecorder) SerializeConfig(arg0, arg1, arg2 interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"SerializeConfig\", reflect.TypeOf((*MockManager)(nil).SerializeConfig), arg0, arg1, arg2)\n}", "func (o *VirtualizationBaseHostPciDeviceAllOf) GetIdentityOk() (*string, bool) {\n\tif o == nil || o.Identity == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Identity, true\n}", "func (mr *MockProvidersMockRecorder) IdentityManager(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"IdentityManager\", reflect.TypeOf((*MockProviders)(nil).IdentityManager), arg0)\n}", "func (adminAPIOp) SkipVerification() bool { return true }", "func (ref openshiftReference) PolicyConfigurationIdentity() string {\n\tres, err := policyconfiguration.DockerReferenceIdentity(ref.dockerReference)\n\tif res == \"\" || err != nil { // Coverage: Should never happen, NewReference constructs a valid tagged reference.\n\t\tpanic(fmt.Sprintf(\"Internal inconsistency: policyconfiguration.DockerReferenceIdentity returned %#v, %v\", res, err))\n\t}\n\treturn res\n}", "func TestWithRecordHit(t *testing.T) {\n\tgot := &config{recordHit: false}\n\texpect := &config{recordHit: true}\n\n\tWithRecordHit(true).applyTo(got)\n\tif !isConfigEquals(got, expect) {\n\t\tt.Errorf(\"got %+v != expect %+v\", got, expect)\n\t}\n}", "func (u *MockUser) Identity() ([]byte, error) {\n\treturn []byte(\"test\"), nil\n}", "func (mr *MockClientMockRecorder) IdentityManager(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"IdentityManager\", reflect.TypeOf((*MockClient)(nil).IdentityManager), arg0)\n}", "func (c *nodeConfigurationContainer) VerifyConfig() error {\n\t_, err := c.readKeysConfig()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif c.OrchestratorOptions() == nil {\n\t\treturn fmt.Errorf(\"config is missing orchestrator options\")\n\t}\n\n\treturn nil\n}", "func (c *GetStatus) RequiresConfig() bool {\n\treturn false\n}", "func (o *VirtualizationBaseHostPciDeviceAllOf) HasIdentity() bool {\n\tif o != nil && o.Identity != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (mr *MockCAClientMockRecorder) GetIdentity(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetIdentity\", reflect.TypeOf((*MockCAClient)(nil).GetIdentity), arg0, arg1)\n}", "func (o ClusterOutput) IdentityServiceConfig() ClusterIdentityServiceConfigOutput {\n\treturn o.ApplyT(func(v *Cluster) ClusterIdentityServiceConfigOutput { return v.IdentityServiceConfig }).(ClusterIdentityServiceConfigOutput)\n}", "func (k *xyzProvider) CheckConfig(ctx context.Context, req *pulumirpc.CheckRequest) (*pulumirpc.CheckResponse, error) {\n\treturn &pulumirpc.CheckResponse{Inputs: req.GetNews()}, nil\n}", "func (o *UserDisco) GetIdentityOk() (*FullIdentity, bool) {\n\tif o == nil || o.Identity == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Identity, true\n}", "func Configure(api *operations.ClaAPI, service SignatureService, sessionStore *dynastore.Store) {\n\n\t// Retrieve GitHub Whitelist Entries\n\tapi.SignaturesGetGitHubOrgWhitelistHandler = signatures.GetGitHubOrgWhitelistHandlerFunc(func(params signatures.GetGitHubOrgWhitelistParams, claUser *user.CLAUser) middleware.Responder {\n\t\tsession, err := sessionStore.Get(params.HTTPRequest, github.SessionStoreKey)\n\t\tif err != nil {\n\t\t\tlog.Warnf(\"error retrieving session from the session store, error: %v\", err)\n\t\t\treturn signatures.NewGetGitHubOrgWhitelistBadRequest().WithPayload(errorResponse(err))\n\t\t}\n\n\t\tgithubAccessToken, ok := session.Values[\"github_access_token\"].(string)\n\t\tif !ok {\n\t\t\tlog.Debugf(\"no github access token in the session - initializing to empty string\")\n\t\t\tgithubAccessToken = \"\"\n\t\t}\n\n\t\tghWhiteList, err := service.GetGithubOrganizationsFromWhitelist(params.HTTPRequest.Context(), params.SignatureID, githubAccessToken)\n\t\tif err != nil {\n\t\t\tlog.Warnf(\"error fetching github organization whitelist entries v using signature_id: %s, error: %v\",\n\t\t\t\tparams.SignatureID, err)\n\t\t\treturn company.NewGetGithubOrganizationfromClaBadRequest().WithPayload(errorResponse(err))\n\t\t}\n\n\t\treturn company.NewGetGithubOrganizationfromClaOK().WithPayload(ghWhiteList)\n\t})\n\n\t// Add GitHub Whitelist Entries\n\tapi.SignaturesAddGitHubOrgWhitelistHandler = signatures.AddGitHubOrgWhitelistHandlerFunc(func(params signatures.AddGitHubOrgWhitelistParams, claUser *user.CLAUser) middleware.Responder {\n\t\tsession, err := sessionStore.Get(params.HTTPRequest, github.SessionStoreKey)\n\t\tif err != nil {\n\t\t\tlog.Warnf(\"error retrieving session from the session store, error: %v\", err)\n\t\t\treturn signatures.NewAddGitHubOrgWhitelistBadRequest().WithPayload(errorResponse(err))\n\t\t}\n\n\t\tgithubAccessToken, ok := session.Values[\"github_access_token\"].(string)\n\t\tif !ok {\n\t\t\tlog.Debugf(\"no github access token in the session - initializing to empty string\")\n\t\t\tgithubAccessToken = \"\"\n\t\t}\n\n\t\tghWhiteList, err := service.AddGithubOrganizationToWhitelist(params.HTTPRequest.Context(), params.SignatureID, params.Body, githubAccessToken)\n\t\tif err != nil {\n\t\t\tlog.Warnf(\"error adding github organization %s using signature_id: %s to the whitelist, error: %v\",\n\t\t\t\t*params.Body.OrganizationID, params.SignatureID, err)\n\t\t\treturn company.NewAddGithubOrganizationFromClaBadRequest().WithPayload(errorResponse(err))\n\t\t}\n\n\t\treturn company.NewAddGithubOrganizationFromClaOK().WithPayload(ghWhiteList)\n\t})\n\n\t// Delete GitHub Whitelist Entries\n\tapi.SignaturesDeleteGitHubOrgWhitelistHandler = signatures.DeleteGitHubOrgWhitelistHandlerFunc(func(params signatures.DeleteGitHubOrgWhitelistParams, claUser *user.CLAUser) middleware.Responder {\n\n\t\tsession, err := sessionStore.Get(params.HTTPRequest, github.SessionStoreKey)\n\t\tif err != nil {\n\t\t\tlog.Warnf(\"error retrieving session from the session store, error: %v\", err)\n\t\t\treturn signatures.NewDeleteGitHubOrgWhitelistBadRequest().WithPayload(errorResponse(err))\n\t\t}\n\n\t\tgithubAccessToken, ok := session.Values[\"github_access_token\"].(string)\n\t\tif !ok {\n\t\t\tlog.Debugf(\"no github access token in the session - initializing to empty string\")\n\t\t\tgithubAccessToken = \"\"\n\t\t}\n\n\t\tghWhiteList, err := service.DeleteGithubOrganizationFromWhitelist(params.HTTPRequest.Context(), params.SignatureID, params.Body, githubAccessToken)\n\t\tif err != nil {\n\t\t\tlog.Warnf(\"error deleting github organization %s using signature_id: %s from the whitelist, error: %v\",\n\t\t\t\t*params.Body.OrganizationID, params.SignatureID, err)\n\t\t\treturn company.NewDeleteGithubOrganizationFromClaBadRequest().WithPayload(errorResponse(err))\n\t\t}\n\n\t\treturn company.NewDeleteGithubOrganizationFromClaOK().WithPayload(ghWhiteList)\n\t})\n\n\t// Get Signatures\n\tapi.SignaturesGetSignaturesHandler = signatures.GetSignaturesHandlerFunc(func(params signatures.GetSignaturesParams, claUser *user.CLAUser) middleware.Responder {\n\t\tsignatureList, err := service.GetSignatures(params.HTTPRequest.Context(), params)\n\t\tif err != nil {\n\t\t\tlog.Warnf(\"error retrieving user signatures for signatureID: %s, error: %v\", params.SignatureID, err)\n\t\t\treturn signatures.NewGetSignaturesBadRequest().WithPayload(errorResponse(err))\n\t\t}\n\n\t\treturn signatures.NewGetSignaturesOK().WithPayload(signatureList)\n\t})\n\n\t// Get Project Signatures\n\tapi.SignaturesGetProjectSignaturesHandler = signatures.GetProjectSignaturesHandlerFunc(func(params signatures.GetProjectSignaturesParams, claUser *user.CLAUser) middleware.Responder {\n\t\tprojectSignatures, err := service.GetProjectSignatures(params.HTTPRequest.Context(), params)\n\t\tif err != nil {\n\t\t\tlog.Warnf(\"error retrieving project signatures for projectID: %s, error: %v\",\n\t\t\t\tparams.ProjectID, err)\n\t\t\treturn signatures.NewGetProjectSignaturesBadRequest().WithPayload(errorResponse(err))\n\t\t}\n\n\t\treturn signatures.NewGetProjectSignaturesOK().WithPayload(projectSignatures)\n\t})\n\n\t// Get Project Company Signatures\n\tapi.SignaturesGetProjectCompanySignaturesHandler = signatures.GetProjectCompanySignaturesHandlerFunc(func(params signatures.GetProjectCompanySignaturesParams, claUser *user.CLAUser) middleware.Responder {\n\t\tprojectSignatures, err := service.GetProjectCompanySignatures(params.HTTPRequest.Context(), params)\n\t\tif err != nil {\n\t\t\tlog.Warnf(\"error retrieving project signatures for project: %s, company: %s, error: %+v\",\n\t\t\t\tparams.ProjectID, params.CompanyID, err)\n\t\t\treturn signatures.NewGetProjectCompanySignaturesBadRequest().WithPayload(errorResponse(err))\n\t\t}\n\n\t\treturn signatures.NewGetProjectCompanySignaturesOK().WithPayload(projectSignatures)\n\t})\n\n\t// Get Employee Project Company Signatures\n\tapi.SignaturesGetProjectCompanyEmployeeSignaturesHandler = signatures.GetProjectCompanyEmployeeSignaturesHandlerFunc(func(params signatures.GetProjectCompanyEmployeeSignaturesParams, claUser *user.CLAUser) middleware.Responder {\n\t\tprojectSignatures, err := service.GetProjectCompanyEmployeeSignatures(params.HTTPRequest.Context(), params)\n\t\tif err != nil {\n\t\t\tlog.Warnf(\"error retrieving employee project signatures for project: %s, company: %s, error: %+v\",\n\t\t\t\tparams.ProjectID, params.CompanyID, err)\n\t\t\treturn signatures.NewGetProjectCompanyEmployeeSignaturesBadRequest().WithPayload(errorResponse(err))\n\t\t}\n\n\t\treturn signatures.NewGetProjectCompanyEmployeeSignaturesOK().WithPayload(projectSignatures)\n\t})\n\n\t// Get Company Signatures\n\tapi.SignaturesGetCompanySignaturesHandler = signatures.GetCompanySignaturesHandlerFunc(func(params signatures.GetCompanySignaturesParams, claUser *user.CLAUser) middleware.Responder {\n\t\tcompanySignatures, err := service.GetCompanySignatures(params.HTTPRequest.Context(), params)\n\t\tif err != nil {\n\t\t\tlog.Warnf(\"error retrieving company signatures for companyID: %s, error: %v\", params.CompanyID, err)\n\t\t\treturn signatures.NewGetCompanySignaturesBadRequest().WithPayload(errorResponse(err))\n\t\t}\n\n\t\treturn signatures.NewGetCompanySignaturesOK().WithPayload(companySignatures)\n\t})\n\n\t// Get User Signatures\n\tapi.SignaturesGetUserSignaturesHandler = signatures.GetUserSignaturesHandlerFunc(func(params signatures.GetUserSignaturesParams, claUser *user.CLAUser) middleware.Responder {\n\t\tuserSignatures, err := service.GetUserSignatures(params.HTTPRequest.Context(), params)\n\t\tif err != nil {\n\t\t\tlog.Warnf(\"error retrieving user signatures for userID: %s, error: %v\", params.UserID, err)\n\t\t\treturn signatures.NewGetUserSignaturesBadRequest().WithPayload(errorResponse(err))\n\t\t}\n\n\t\treturn signatures.NewGetUserSignaturesOK().WithPayload(userSignatures)\n\t})\n}", "func TestConfigureIssuer(t *testing.T) {\n\twebDir = \"../../../../dex-assets\"\n\tenv := getTestEnv(t)\n\tapi := NewIdentityServer(EnvFromServiceEnv(env), false)\n\n\tserver := newDexWeb(EnvFromServiceEnv(env), api)\n\tdefer server.stopWebServer()\n\n\terr := env.GetDexDB().CreateConnector(dex_storage.Connector{ID: \"conn\", Type: \"github\"})\n\trequire.NoError(t, err)\n\n\t// request the OIDC configuration endpoint - the issuer is an empty string\n\treq := httptest.NewRequest(\"GET\", \"/.well-known/openid-configuration\", nil)\n\trecorder := httptest.NewRecorder()\n\tserver.ServeHTTP(recorder, req)\n\trequire.Equal(t, http.StatusOK, recorder.Result().StatusCode)\n\n\tvar oidcConfig map[string]interface{}\n\trequire.NoError(t, json.NewDecoder(recorder.Result().Body).Decode(&oidcConfig))\n\trequire.Equal(t, \"\", oidcConfig[\"issuer\"].(string))\n\n\t//reconfigure the issuer, the server should reload and serve the new issuer value\n\t_, err = api.SetIdentityServerConfig(context.Background(), &identity.SetIdentityServerConfigRequest{\n\t\tConfig: &identity.IdentityServerConfig{Issuer: \"http://example.com:1234\"},\n\t})\n\trequire.NoError(t, err)\n\n\trecorder = httptest.NewRecorder()\n\tserver.ServeHTTP(recorder, req)\n\trequire.Equal(t, http.StatusOK, recorder.Result().StatusCode)\n\n\trequire.NoError(t, json.NewDecoder(recorder.Result().Body).Decode(&oidcConfig))\n\trequire.Equal(t, \"http://example.com:1234\", oidcConfig[\"issuer\"].(string))\n}", "func TestConfig(t *testing.T) {\n\tconst (\n\t\tresourcePolicy = \"resource-validation\"\n\t\tstackPolicy = \"stack-validation\"\n\t\terrorPreamble = \"error: validating policy config: config-policy 0.0.1 \"\n\t)\n\n\tconfig := func(c PolicyConfig) map[string]PolicyConfig {\n\t\treturn map[string]PolicyConfig{\n\t\t\tresourcePolicy: c,\n\t\t\tstackPolicy: c,\n\t\t}\n\t}\n\n\twant := func(err ...string) []string {\n\t\tvar result []string\n\t\tfor _, e := range err {\n\t\t\tresult = append(result,\n\t\t\t\terrorPreamble+resourcePolicy+\": \"+e,\n\t\t\t\terrorPreamble+stackPolicy+\": \"+e,\n\t\t\t)\n\t\t}\n\t\treturn result\n\t}\n\n\trunPolicyPackIntegrationTest(t, \"config\", NodeJS, nil, []policyTestScenario{\n\t\t// Test senario 1: String from config.\n\t\t{\n\t\t\tPolicyPackConfig: config(PolicyConfig{\n\t\t\t\t\"foo\": \"bar\",\n\t\t\t}),\n\t\t\tWantErrors: nil,\n\t\t},\n\t\t// Test scenario 2: Default string value specified in schema used.\n\t\t{\n\t\t\tWantErrors: nil,\n\t\t},\n\t\t// Test scenario 3: Default number value specified in schema used.\n\t\t{\n\t\t\tWantErrors: nil,\n\t\t},\n\t\t// Test scenario 4: Specified config value overrides default value.\n\t\t{\n\t\t\tPolicyPackConfig: config(PolicyConfig{\n\t\t\t\t\"foo\": \"overridden\",\n\t\t\t}),\n\t\t\tWantErrors: nil,\n\t\t},\n\t\t// Test scenario 5: Default value specified in schema for required field used.\n\t\t{\n\t\t\tWantErrors: nil,\n\t\t},\n\t\t// Test scenario 6: Required config property not set.\n\t\t{\n\t\t\tWantErrors: want(\"foo is required\"),\n\t\t},\n\t\t// Test scenario 7: Default value set to incorrect type.\n\t\t{\n\t\t\tWantErrors: want(\"foo: Invalid type. Expected: string, given: integer\"),\n\t\t},\n\t\t// Test scenario 8: Default value too long.\n\t\t{\n\t\t\tWantErrors: want(\"foo: String length must be less than or equal to 3\"),\n\t\t},\n\t\t// Test scenario 9: Default value too short.\n\t\t{\n\t\t\tWantErrors: want(\"foo: String length must be greater than or equal to 50\"),\n\t\t},\n\t\t// Test scenario 10: Default value set to invalid enum value.\n\t\t{\n\t\t\tWantErrors: want(`foo: foo must be one of the following: \"bar\", \"baz\"`),\n\t\t},\n\t\t// Test scenario 11: Default value set to invalid constant value.\n\t\t{\n\t\t\tWantErrors: want(`foo: foo does not match: \"bar\"`),\n\t\t},\n\t\t// Test scenario 12: Incorrect type.\n\t\t{\n\t\t\tPolicyPackConfig: config(PolicyConfig{\n\t\t\t\t\"foo\": 1,\n\t\t\t}),\n\t\t\tWantErrors: want(`foo: Invalid type. Expected: string, given: integer`),\n\t\t},\n\t\t// Test scenario 13: Invalid enum value.\n\t\t{\n\t\t\tPolicyPackConfig: config(PolicyConfig{\n\t\t\t\t\"foo\": \"blah\",\n\t\t\t}),\n\t\t\tWantErrors: want(`foo: foo must be one of the following: \"bar\", \"baz\"`),\n\t\t},\n\t\t// Test scenario 14: Invalid constant value.\n\t\t{\n\t\t\tPolicyPackConfig: config(PolicyConfig{\n\t\t\t\t\"foo\": \"blah\",\n\t\t\t}),\n\t\t\tWantErrors: want(`foo: foo does not match: \"bar\"`),\n\t\t},\n\t\t// Test scenario 15: Multiple validation errors.\n\t\t{\n\t\t\tPolicyPackConfig: config(PolicyConfig{\n\t\t\t\t\"foo\": \"this is too long\",\n\t\t\t\t\"bar\": float64(3.14),\n\t\t\t}),\n\t\t\tWantErrors: want(\n\t\t\t\t`bar: Invalid type. Expected: integer, given: number`,\n\t\t\t\t`foo: String length must be less than or equal to 3`,\n\t\t\t),\n\t\t},\n\t\t// Test scenario 16: Number (int) from config.\n\t\t{\n\t\t\tPolicyPackConfig: config(PolicyConfig{\n\t\t\t\t\"foo\": 42,\n\t\t\t}),\n\t\t\tWantErrors: nil,\n\t\t},\n\t\t// Test scenario 17: Number (float) from config.\n\t\t{\n\t\t\tPolicyPackConfig: config(PolicyConfig{\n\t\t\t\t\"foo\": float64(3.14),\n\t\t\t}),\n\t\t\tWantErrors: nil,\n\t\t},\n\t\t// Test scenario 18: Integer from config.\n\t\t{\n\t\t\tPolicyPackConfig: config(PolicyConfig{\n\t\t\t\t\"foo\": 42,\n\t\t\t}),\n\t\t\tWantErrors: nil,\n\t\t},\n\t\t// Test scenario 19: Boolean (true) from config.\n\t\t{\n\t\t\tPolicyPackConfig: config(PolicyConfig{\n\t\t\t\t\"foo\": true,\n\t\t\t}),\n\t\t\tWantErrors: nil,\n\t\t},\n\t\t// Test scenario 20: Boolean (false) from config.\n\t\t{\n\t\t\tPolicyPackConfig: config(PolicyConfig{\n\t\t\t\t\"foo\": false,\n\t\t\t}),\n\t\t\tWantErrors: nil,\n\t\t},\n\t\t// Test scenario 21: Object from config.\n\t\t{\n\t\t\tPolicyPackConfig: config(PolicyConfig{\n\t\t\t\t\"foo\": map[string]interface{}{\"bar\": \"baz\"},\n\t\t\t}),\n\t\t\tWantErrors: nil,\n\t\t},\n\t\t// Test scenario 22: Array from config.\n\t\t{\n\t\t\tPolicyPackConfig: config(PolicyConfig{\n\t\t\t\t\"foo\": []string{\"a\", \"b\", \"c\"},\n\t\t\t}),\n\t\t\tWantErrors: nil,\n\t\t},\n\t\t// Test scenario 23: Null from config.\n\t\t{\n\t\t\tPolicyPackConfig: config(PolicyConfig{\n\t\t\t\t\"foo\": nil,\n\t\t\t}),\n\t\t\tWantErrors: nil,\n\t\t},\n\t\t// Test scenario 24: Initial config.\n\t\t{\n\t\t\tWantErrors: nil,\n\t\t},\n\t\t// Test scenario 25: Initial config overridden.\n\t\t{\n\t\t\tPolicyPackConfig: config(PolicyConfig{\n\t\t\t\t\"foo\": \"overridden\",\n\t\t\t}),\n\t\t\tWantErrors: nil,\n\t\t},\n\t})\n}", "func (spec *configSpec) ConfigKey() string {\n\treturn ModuleId\n}", "func verifyConfiguration(t *testing.T, accessKeyID, secretAccessKey, sessionToken string) {\n\n\t// Load the current file contents\n\tcfg, err := ini.Load(fakeCredentialsFilePath)\n\trequire.Nil(t, err, \"error reading the test credentials file\")\n\n\t// Confirm thet the default credentials are set as expected\n\tdefaultSection, err := cfg.GetSection(DefaultSectionName)\n\trequire.Nil(t, err, \"default section not found in credentials file\")\n\trequire.Equal(t, defaultSection.Key(AccessKeyIDKey).Value(), fakeAccessKeyID, \"default section, unexpected access key value: [%s]\", defaultSection.Key(AccessKeyIDKey).Value())\n\trequire.Equal(t, defaultSection.Key(SecretAccessKeyKey).Value(), fakeSecretAccessKey, \"default section, unexpected secret key value: [%s]\", defaultSection.Key(SecretAccessKeyKey).Value())\n\n\t// Confirm that the default-session section is as expected\n\tsessionSection, err := cfg.GetSection(SessionSectionName)\n\trequire.Nil(t, err, \"session section not found in credentials file\")\n\trequire.Equal(t, sessionSection.Key(AccessKeyIDKey).Value(), accessKeyID, \"default-session section, unexpected access key value: [%s]\", defaultSection.Key(AccessKeyIDKey).Value())\n\trequire.Equal(t, sessionSection.Key(SecretAccessKeyKey).Value(), secretAccessKey, \"default-session section, unexpected secret key value: [%s]\", defaultSection.Key(SecretAccessKeyKey).Value())\n\trequire.Equal(t, sessionSection.Key(SessionTokenKey).Value(), sessionToken, \"default-session section, unexpected session token value: [%s]\", defaultSection.Key(SessionTokenKey).Value())\n}", "func (e aesGCMEncodedEncryptor) ConfiguredToEncrypt() bool {\n\treturn len(e.primaryKey) == requiredKeyLength\n}", "func TestCustomAnchoreConfigProvider_GetConfiguration(t *testing.T) {\n\tintegratedServiceRepository := integratedservices.NewInMemoryIntegratedServiceRepository(map[uint][]integratedservices.IntegratedService{\n\t\t1: {\n\t\t\t{\n\t\t\t\tName: \"securityscan\",\n\t\t\t\tSpec: map[string]interface{}{\n\t\t\t\t\t\"customAnchore\": map[string]interface{}{\n\t\t\t\t\t\t\"enabled\": true,\n\t\t\t\t\t\t\"url\": \"https://anchore.example.com\",\n\t\t\t\t\t\t\"secretId\": \"secretId\",\n\t\t\t\t\t\t\"insecure\": true,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tOutput: nil,\n\t\t\t\tStatus: integratedservices.IntegratedServiceStatusActive,\n\t\t\t},\n\t\t},\n\t})\n\n\tsecretStore := new(SecretStore)\n\tsecretStore.On(\"GetSecretValues\", mock.Anything, \"secretId\").Return(\n\t\tmap[string]string{\n\t\t\t\"username\": \"user\",\n\t\t\t\"password\": \"password\",\n\t\t},\n\t\tnil,\n\t)\n\n\tconfigProvider := NewCustomAnchoreConfigProvider(integratedServiceRepository, secretStore, services.NoopLogger{})\n\n\tconfig, err := configProvider.GetConfiguration(context.Background(), 1)\n\trequire.NoError(t, err)\n\n\tassert.Equal(\n\t\tt,\n\t\tanchore.Config{\n\t\t\tEndpoint: \"https://anchore.example.com\",\n\t\t\tUser: \"user\",\n\t\t\tPassword: \"password\",\n\t\t\tInsecure: true,\n\t\t},\n\t\tconfig,\n\t)\n\n\tsecretStore.AssertExpectations(t)\n}", "func TestInvalidConfiguration(t *testing.T) {\n\tt.Parallel()\n\t// Start a test gRPC server.\n\t_ = mock.NewBase64Plugin(t, newEndpoint().path)\n\n\tctx := testContext(t)\n\n\tinvalidConfigs := []struct {\n\t\tname string\n\t\tendpoint string\n\t}{\n\t\t{\"emptyConfiguration\", \"\"},\n\t\t{\"invalidScheme\", \"tcp://localhost:6060\"},\n\t}\n\n\tfor _, testCase := range invalidConfigs {\n\t\tt.Run(testCase.name, func(t *testing.T) {\n\t\t\t_, err := NewGRPCService(ctx, testCase.endpoint, 1*time.Second)\n\t\t\tif err == nil {\n\t\t\t\tt.Fatalf(\"should fail to create envelope service for %s.\", testCase.name)\n\t\t\t}\n\t\t})\n\t}\n}", "func (config *DirectClientConfig) getUserIdentificationPartialConfig(configAuthInfo clientcmdapi.AuthInfo, fallbackReader io.Reader, persistAuthConfig restclient.AuthProviderConfigPersister, configClusterInfo clientcmdapi.Cluster) (*restclient.Config, error) {\n\tmergedConfig := &restclient.Config{}\n\n\t// blindly overwrite existing values based on precedence\n\tif len(configAuthInfo.Token) > 0 {\n\t\tmergedConfig.BearerToken = configAuthInfo.Token\n\t\tmergedConfig.BearerTokenFile = configAuthInfo.TokenFile\n\t} else if len(configAuthInfo.TokenFile) > 0 {\n\t\ttokenBytes, err := os.ReadFile(configAuthInfo.TokenFile)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tmergedConfig.BearerToken = string(tokenBytes)\n\t\tmergedConfig.BearerTokenFile = configAuthInfo.TokenFile\n\t}\n\tif len(configAuthInfo.Impersonate) > 0 {\n\t\tmergedConfig.Impersonate = restclient.ImpersonationConfig{\n\t\t\tUserName: configAuthInfo.Impersonate,\n\t\t\tUID: configAuthInfo.ImpersonateUID,\n\t\t\tGroups: configAuthInfo.ImpersonateGroups,\n\t\t\tExtra: configAuthInfo.ImpersonateUserExtra,\n\t\t}\n\t}\n\tif len(configAuthInfo.ClientCertificate) > 0 || len(configAuthInfo.ClientCertificateData) > 0 {\n\t\tmergedConfig.CertFile = configAuthInfo.ClientCertificate\n\t\tmergedConfig.CertData = configAuthInfo.ClientCertificateData\n\t\tmergedConfig.KeyFile = configAuthInfo.ClientKey\n\t\tmergedConfig.KeyData = configAuthInfo.ClientKeyData\n\t}\n\tif len(configAuthInfo.Username) > 0 || len(configAuthInfo.Password) > 0 {\n\t\tmergedConfig.Username = configAuthInfo.Username\n\t\tmergedConfig.Password = configAuthInfo.Password\n\t}\n\tif configAuthInfo.AuthProvider != nil {\n\t\tmergedConfig.AuthProvider = configAuthInfo.AuthProvider\n\t\tmergedConfig.AuthConfigPersister = persistAuthConfig\n\t}\n\tif configAuthInfo.Exec != nil {\n\t\tmergedConfig.ExecProvider = configAuthInfo.Exec\n\t\tmergedConfig.ExecProvider.InstallHint = cleanANSIEscapeCodes(mergedConfig.ExecProvider.InstallHint)\n\t\tmergedConfig.ExecProvider.Config = configClusterInfo.Extensions[clusterExtensionKey]\n\t}\n\n\t// if there still isn't enough information to authenticate the user, try prompting\n\tif !canIdentifyUser(*mergedConfig) && (fallbackReader != nil) {\n\t\tif len(config.promptedCredentials.username) > 0 && len(config.promptedCredentials.password) > 0 {\n\t\t\tmergedConfig.Username = config.promptedCredentials.username\n\t\t\tmergedConfig.Password = config.promptedCredentials.password\n\t\t\treturn mergedConfig, nil\n\t\t}\n\t\tprompter := NewPromptingAuthLoader(fallbackReader)\n\t\tpromptedAuthInfo, err := prompter.Prompt()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tpromptedConfig := makeUserIdentificationConfig(*promptedAuthInfo)\n\t\tpreviouslyMergedConfig := mergedConfig\n\t\tmergedConfig = &restclient.Config{}\n\t\tmergo.Merge(mergedConfig, promptedConfig, mergo.WithOverride)\n\t\tmergo.Merge(mergedConfig, previouslyMergedConfig, mergo.WithOverride)\n\t\tconfig.promptedCredentials.username = mergedConfig.Username\n\t\tconfig.promptedCredentials.password = mergedConfig.Password\n\t}\n\n\treturn mergedConfig, nil\n}", "func TestNewConfigNATSAuth(t *testing.T) {\n\tconfig, err := NewConfig(\"configs/nats-auth.yaml\")\n\trequire.NoError(t, err)\n\trequire.Equal(t, \"admin\", config.NATS.User)\n\trequire.Equal(t, \"password\", config.NATS.Password)\n}", "func (c *IdentityConfig) networkConfig() (*fab.NetworkConfig, error) {\n\tif c.endpointConfig == nil {\n\t\treturn nil, errors.New(\"network config not initialized for identity config\")\n\t}\n\treturn c.endpointConfig.NetworkConfig()\n}", "func validateConfig(appConfig AppConfig) error {\n\n\treturn nil\n}", "func TestAutoSyncConfigServicesNotModify(t *testing.T) {\n\tserver := runNotModifyConfigResponse()\n\tnewAppConfig := getTestAppConfig()\n\tnewAppConfig.Ip = server.URL\n\n\tapolloConfig, err := createApolloConfigWithJson([]byte(configResponseStr))\n\tupdateApolloConfig(apolloConfig, true)\n\n\ttime.Sleep(10 * time.Second)\n\tcheckCacheLeft(t, configCacheExpireTime-10)\n\n\tappConfig.NextTryConnTime = 0\n\n\terr = autoSyncConfigServices(newAppConfig)\n\n\ttest.Nil(t, err)\n\n\tconfig := GetCurrentApolloConfig()\n\n\ttest.Equal(t, \"100004458\", config.AppId)\n\ttest.Equal(t, \"default\", config.Cluster)\n\ttest.Equal(t, \"application\", config.NamespaceName)\n\ttest.Equal(t, \"20170430092936-dee2d58e74515ff3\", config.ReleaseKey)\n\n\tcheckCacheLeft(t, configCacheExpireTime)\n\n\t//test.Equal(t,\"value1\",config.Configurations[\"key1\"])\n\t//test.Equal(t,\"value2\",config.Configurations[\"key2\"])\n}", "func validateConfig(conf *Config) {\n\t// Hopefully lxc package derives this correctly\n\tif conf.LXCPath == \"\" {\n\t\tconf.LXCPath = lxc.DefaultConfigPath()\n\t}\n\n\t// Generate \"Docker-style\" container names if it is not provided\n\tif conf.Name == \"\" {\n\t\tconf.Name = randomdata.SillyName()\n\t}\n}", "func (a *Azure) ValidConfig() bool {\n\treturn a.SubscriptionID != \"\" && a.ClientID != \"\" && a.ClientSecret != \"\" && a.TenantID != \"\"\n}", "func IsAideConfig(labels map[string]string) bool {\n\t_, ok := labels[AideConfigLabelKey]\n\treturn ok\n}", "func IsAideConfig(labels map[string]string) bool {\n\t_, ok := labels[AideConfigLabelKey]\n\treturn ok\n}", "func (a *apiServer) updateConfig(config *auth.AuthConfig) error {\n\tif config == nil {\n\t\tconfig = &auth.AuthConfig{}\n\t}\n\tnewConfig, err := validateConfig(config, internal)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// It's possible that 'config' is non-nil, but empty (this is the case when\n\t// users clear the config from the command line). Therefore, check\n\t// newConfig.IDP.Name != \"\" instead of config != nil.\n\tif newConfig.IDP.Name != \"\" {\n\t\ta.configCache = newConfig\n\t\t// construct SAML handler\n\t\ta.samlSP = &saml.ServiceProvider{\n\t\t\tLogger: logrus.New(),\n\t\t\tIDPMetadata: a.configCache.IDP.Metadata,\n\t\t\tAcsURL: *a.configCache.SAMLSvc.ACSURL,\n\t\t\tMetadataURL: *a.configCache.SAMLSvc.MetadataURL,\n\n\t\t\t// Not set:\n\t\t\t// Key: Private key for Pachyderm ACS. Unclear if needed\n\t\t\t// Certificate: Public key for Pachyderm ACS. Unclear if needed\n\t\t\t// ForceAuthn: (whether users need to re-authenticate with the IdP, even\n\t\t\t// if they already have a session--leaving this false)\n\t\t\t// AuthnNameIDFormat: (format the ACS expects the AuthnName to be in)\n\t\t\t// MetadataValidDuration: (how long the SP endpoints are valid? Returned\n\t\t\t// by the Metadata service)\n\t\t}\n\t\ta.redirectAddress = a.configCache.SAMLSvc.DashURL // Set redirect address from config as well\n\t} else {\n\t\ta.configCache = nil\n\t\ta.samlSP = nil\n\t\ta.redirectAddress = nil\n\t}\n\treturn nil\n}", "func ObserveAuthMetadata(genericListers configobserver.Listers, recorder events.Recorder, existingConfig map[string]interface{}) (map[string]interface{}, []error) {\n\tlisters := genericListers.(configobservation.Listers)\n\terrs := []error{}\n\tprevObservedConfig := map[string]interface{}{}\n\n\ttopLevelMetadataFilePath := []string{\"authConfig\", \"oauthMetadataFile\"}\n\tcurrentMetadataFilePath, _, err := unstructured.NestedString(existingConfig, topLevelMetadataFilePath...)\n\tif err != nil {\n\t\terrs = append(errs, err)\n\t}\n\tif len(currentMetadataFilePath) > 0 {\n\t\tif err := unstructured.SetNestedField(prevObservedConfig, currentMetadataFilePath, topLevelMetadataFilePath...); err != nil {\n\t\t\terrs = append(errs, err)\n\t\t}\n\t}\n\n\tobservedConfig := map[string]interface{}{}\n\tauthConfigNoDefaults, err := listers.AuthConfigLister.Get(\"cluster\")\n\tif errors.IsNotFound(err) {\n\t\tklog.Warningf(\"authentications.config.openshift.io/cluster: not found\")\n\t\treturn observedConfig, errs\n\t}\n\tif err != nil {\n\t\terrs = append(errs, err)\n\t\treturn prevObservedConfig, errs\n\t}\n\n\tauthConfig := defaultAuthConfig(authConfigNoDefaults)\n\n\tvar (\n\t\tsourceNamespace string\n\t\tsourceConfigMap string\n\t\tstatusConfigMap string\n\t)\n\n\tspecConfigMap := authConfig.Spec.OAuthMetadata.Name\n\n\t// TODO: Add a case here for the KeyCloak type.\n\tswitch {\n\tcase len(authConfig.Status.IntegratedOAuthMetadata.Name) > 0 && authConfig.Spec.Type == configv1.AuthenticationTypeIntegratedOAuth:\n\t\tstatusConfigMap = authConfig.Status.IntegratedOAuthMetadata.Name\n\tdefault:\n\t\tklog.V(5).Infof(\"no integrated oauth metadata configmap observed from status\")\n\t}\n\n\t// Spec configMap takes precedence over Status.\n\tswitch {\n\tcase len(specConfigMap) > 0:\n\t\tsourceConfigMap = specConfigMap\n\t\tsourceNamespace = configNamespace\n\tcase len(statusConfigMap) > 0:\n\t\tsourceConfigMap = statusConfigMap\n\t\tsourceNamespace = managedNamespace\n\tdefault:\n\t\tklog.V(5).Infof(\"no authentication config metadata specified\")\n\t}\n\n\t// Sync the user or status-specified configMap to the well-known resting place that corresponds to the oauthMetadataFile path.\n\t// If neither are set, this updates the destination with an empty source, which deletes the destination resource.\n\terr = listers.ResourceSyncer().SyncConfigMap(\n\t\tresourcesynccontroller.ResourceLocation{\n\t\t\tNamespace: targetNamespaceName,\n\t\t\tName: \"oauth-metadata\",\n\t\t},\n\t\tresourcesynccontroller.ResourceLocation{\n\t\t\tNamespace: sourceNamespace,\n\t\t\tName: sourceConfigMap,\n\t\t},\n\t)\n\tif err != nil {\n\t\terrs = append(errs, err)\n\t\treturn prevObservedConfig, errs\n\t}\n\n\t// Unsets oauthMetadataFile if we had an empty source.\n\tif len(sourceConfigMap) == 0 {\n\t\treturn observedConfig, errs\n\t}\n\n\t// Set oauthMetadataFile.\n\tif err := unstructured.SetNestedField(observedConfig, oauthMetadataFilePath, topLevelMetadataFilePath...); err != nil {\n\t\trecorder.Eventf(\"ObserveAuthMetadataConfigMap\", \"Failed setting oauthMetadataFile: %v\", err)\n\t\terrs = append(errs, err)\n\t}\n\n\treturn observedConfig, errs\n}", "func (mr *MockTxMockRecorder) UpdateConfig(arg0 interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"UpdateConfig\", reflect.TypeOf((*MockTx)(nil).UpdateConfig), arg0)\n}", "func (c *Client) IDTokenUserinfoClaimsAssertion() bool {\n\treturn c.idTokenUserinfoClaimsAssertion\n}", "func TestConfigure_UseExistingASN(t *testing.T) {\n\tASNOnDevice := \"65001\"\n\tMockLeafDeviceAdapter := mock.DeviceAdapter{\n\t\tMockGetInterfaces: func(FabricID uint, DeviceID uint, DeviceIP string) ([]domain.Interface, error) {\n\n\t\t\treturn []domain.Interface{domain.Interface{FabricID: FabricID, DeviceID: DeviceID,\n\t\t\t\tIntType: \"ethernet\", IntName: \"1/11\", Mac: \"M1\", ConfigState: \"up\"}}, nil\n\n\t\t},\n\t\tMockGetLLDPs: func(FabricID uint, DeviceID uint, DeviceIP string) ([]domain.LLDP, error) {\n\n\t\t\treturn []domain.LLDP{domain.LLDP{FabricID: FabricID, DeviceID: DeviceID,\n\t\t\t\tLocalIntType: \"ethernet\", LocalIntName: \"1/11\", LocalIntMac: \"M1\",\n\t\t\t\tRemoteIntType: \"ethernet\", RemoteIntName: \"1/22\", RemoteIntMac: \"M2\"}}, nil\n\n\t\t},\n\t\tMockGetASN: func(FabricID uint, Device uint, DeviceIP string) (string, error) {\n\t\t\treturn ASNOnDevice, nil\n\t\t},\n\t}\n\n\tdatabase.Setup(constants.TESTDBLocation)\n\tdefer cleanupDB(database.GetWorkingInstance())\n\n\tDatabaseRepository := gateway.DatabaseRepository{Database: database.GetWorkingInstance()}\n\tdevUC := usecase.DeviceInteractor{Db: &DatabaseRepository, DeviceAdapterFactory: mock.GetDeviceAdapterFactory(MockLeafDeviceAdapter)}\n\tdevUC.AddFabric(context.Background(), MockFabricName)\n\n\tresp, err := devUC.AddDevices(context.Background(), MockFabricName, []string{MockLeaf1IP}, []string{},\n\t\tUserName, Password, false)\n\tassert.Contains(t, resp, usecase.AddDeviceResponse{FabricName: MockFabricName, FabricID: 1, IPAddress: MockLeaf1IP, Role: usecase.LeafRole})\n\n\tassert.Nil(t, err)\n\n\tswitchConfig, err := DatabaseRepository.GetSwitchConfigOnDeviceIP(MockFabricName, MockLeaf1IP)\n\tassert.Equal(t, ASNOnDevice, switchConfig.LocalAS)\n\t//Verify ASN is already on the Switch, so need to push\n\tassert.Equal(t, domain.ConfigNone, switchConfig.ASConfigType)\n\n\t//Next Call without Device having ASN\n\tMockLeafDeviceAdapterWithoutASN := mock.DeviceAdapter{\n\t\tMockGetInterfaces: func(FabricID uint, DeviceID uint, DeviceIP string) ([]domain.Interface, error) {\n\n\t\t\treturn []domain.Interface{domain.Interface{FabricID: FabricID, DeviceID: DeviceID,\n\t\t\t\tIntType: \"ethernet\", IntName: \"1/11\", Mac: \"M1\", ConfigState: \"up\"}}, nil\n\n\t\t},\n\t\tMockGetLLDPs: func(FabricID uint, DeviceID uint, DeviceIP string) ([]domain.LLDP, error) {\n\n\t\t\treturn []domain.LLDP{domain.LLDP{FabricID: FabricID, DeviceID: DeviceID,\n\t\t\t\tLocalIntType: \"ethernet\", LocalIntName: \"1/11\", LocalIntMac: \"M1\",\n\t\t\t\tRemoteIntType: \"ethernet\", RemoteIntName: \"1/22\", RemoteIntMac: \"M2\"}}, nil\n\n\t\t},\n\t}\n\tdevUC.DeviceAdapterFactory = mock.GetDeviceAdapterFactory(MockLeafDeviceAdapterWithoutASN)\n\tresp, err = devUC.AddDevices(context.Background(), MockFabricName, []string{MockLeaf1IP}, []string{},\n\t\tUserName, Password, false)\n\tassert.Contains(t, resp, usecase.AddDeviceResponse{FabricName: MockFabricName, FabricID: 1, IPAddress: MockLeaf1IP, Role: usecase.LeafRole})\n\n\tassert.Nil(t, err)\n\tswitchConfigSecond, err := DatabaseRepository.GetSwitchConfigOnDeviceIP(MockFabricName, MockLeaf1IP)\n\tassert.Equal(t, ASNOnDevice, switchConfigSecond.LocalAS)\n\t//Verify ASN is to be created\n\tassert.Equal(t, domain.ConfigCreate, switchConfigSecond.ASConfigType)\n}", "func TestAccessConfig(t *testing.T) {\n\ttests := []struct {\n\t\twhat string\n\t\twant AccessLevel\n\t\tlevel AccessLevel\n\t}{\n\t\t{\"admin\", AccessAdmin, config.Namespaces[\"access-admin\"].AccessLevel},\n\t\t{\"admin/0\", AccessAdmin, config.Namespaces[\"access-admin\"].Reporting[0].AccessLevel},\n\t\t{\"admin/1\", AccessAdmin, config.Namespaces[\"access-admin\"].Reporting[1].AccessLevel},\n\t\t{\"user\", AccessUser, config.Namespaces[\"access-user\"].AccessLevel},\n\t\t{\"user/0\", AccessAdmin, config.Namespaces[\"access-user\"].Reporting[0].AccessLevel},\n\t\t{\"user/1\", AccessUser, config.Namespaces[\"access-user\"].Reporting[1].AccessLevel},\n\t\t{\"public\", AccessPublic, config.Namespaces[\"access-public\"].AccessLevel},\n\t\t{\"public/0\", AccessUser, config.Namespaces[\"access-public\"].Reporting[0].AccessLevel},\n\t\t{\"public/1\", AccessPublic, config.Namespaces[\"access-public\"].Reporting[1].AccessLevel},\n\t}\n\tfor _, test := range tests {\n\t\tif test.level != test.want {\n\t\t\tt.Errorf(\"%v level %v, want %v\", test.what, test.level, test.want)\n\t\t}\n\t}\n}", "func (c *Config) Verify() error {\n\tif c.Lager == nil {\n\t\treturn ErrInvalidLager\n\t}\n\n\tif c.Pool == nil {\n\t\treturn ErrInvalidPool\n\t}\n\n\treturn nil\n}", "func (me TxsdComponentTransferFunctionAttributesType) IsIdentity() bool {\n\treturn me.String() == \"identity\"\n}", "func testIATBHOriginatorIdentification(t testing.TB) {\n\tbh := mockIATBatchHeaderFF()\n\tbh.OriginatorIdentification = \"\"\n\terr := bh.Validate()\n\tif !base.Match(err, ErrFieldInclusion) {\n\t\tt.Errorf(\"%T: %s\", err, err)\n\t}\n}", "func ProvidersConfig(t *testing.T) *config.Config {\n\tconst (\n\t\ttestClientKey = \"provider-test-client-key\"\n\t\ttestSecret = \"provider-test-secret\"\n\t\ttestCallback = \"http://auth.exmaple.com/test/callback\"\n\t)\n\tsetEnv(t, config.Auth0DomainEnv, \"example.com\")\n\tsetEnv(t, config.OpenIDConnectURLEnv, MockOpenIDConnect(t))\n\tsetEnv(t, config.AzureADTenantEnv, string(azureadv2.CommonTenant))\n\tvar testScopes = []string{\"test-scope-1\", \"test-scope-2\"}\n\tc := Config(t)\n\ta := config.Authorization{\n\t\tProviders: map[provider.Name]config.Provider{},\n\t}\n\ta.UseInternal = true\n\tfor name := range provider.External {\n\t\ta.Providers[name] = config.Provider{\n\t\t\tClientKey: testClientKey,\n\t\t\tSecret: testSecret,\n\t\t\tCallbackURL: testCallback,\n\t\t\tScopes: testScopes,\n\t\t}\n\t}\n\t// FIXME: core/auth/providers.go:162\n\tt.Log(\"skipping \", provider.Apple)\n\tdelete(a.Providers, provider.Apple)\n\tc.Authorization = a\n\treturn c\n}", "func (a *AllApiService) ConfigurationGetIdentifiableApplications(ctx _context.Context, body ConfigurationGetIdentifiableApplications) (ConfigurationGetIdentifiableApplicationsResult, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHttpMethod = _nethttp.MethodPost\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue ConfigurationGetIdentifiableApplicationsResult\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/configuration/getIdentifiableApplications\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHttpContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes)\n\tif localVarHttpContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHttpContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHttpHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts)\n\tif localVarHttpHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHttpHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = &body\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHttpResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHttpResponse == nil {\n\t\treturn localVarReturnValue, localVarHttpResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHttpResponse.Body)\n\tlocalVarHttpResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHttpResponse, err\n\t}\n\n\tif localVarHttpResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHttpResponse.Status,\n\t\t}\n\t\tif localVarHttpResponse.StatusCode == 200 {\n\t\t\tvar v ConfigurationGetIdentifiableApplicationsResult\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\t\tif localVarHttpResponse.StatusCode == 400 {\n\t\t\tvar v ModelError\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\t\tif localVarHttpResponse.StatusCode == 500 {\n\t\t\tvar v ModelError\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHttpResponse, nil\n}", "func (ec *Client) ConfigCall(fromAddress common.Address) (*bind.CallOpts){\n\treturn &bind.CallOpts{Pending: false, From:fromAddress, BlockNumber:nil, Context:nil}\n}", "func (spec *Spec) identity() (*core.Identity, error) {\n\tident := &core.Identity{\n\t\tRequest: spec.Request,\n\t\tRoots: []*core.Root{\n\t\t\t&core.Root{\n\t\t\t\tType: \"system\",\n\t\t\t},\n\t\t\t&core.Root{\n\t\t\t\tType: \"cfssl\",\n\t\t\t\tMetadata: map[string]string{\n\t\t\t\t\t\"host\": spec.CA.Remote,\n\t\t\t\t\t\"profile\": spec.CA.Profile,\n\t\t\t\t\t\"label\": spec.CA.Label,\n\t\t\t\t\t\"tls-remote-ca\": spec.CA.RootCACert,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tProfiles: map[string]map[string]string{\n\t\t\t\"cfssl\": map[string]string{\n\t\t\t\t\"remote\": spec.CA.Remote,\n\t\t\t\t\"profile\": spec.CA.Profile,\n\t\t\t\t\"label\": spec.CA.Label,\n\t\t\t\t\"tls-remote-ca\": spec.CA.RootCACert,\n\t\t\t},\n\t\t},\n\t}\n\n\tauthkey := spec.CA.AuthKey\n\tif spec.CA.AuthKeyFile != \"\" {\n\t\tlog.Debugf(\"loading auth_key_file %v\", spec.CA.AuthKeyFile)\n\t\tcontent, err := ioutil.ReadFile(spec.CA.AuthKeyFile)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed reading auth_key_file %v: %v\", spec.CA.AuthKeyFile, err)\n\t\t}\n\t\tauthkey = strings.TrimSpace(string(content))\n\t}\n\tif authkey != \"\" {\n\t\tident.Profiles[\"cfssl\"][\"auth-type\"] = \"standard\"\n\t\tident.Profiles[\"cfssl\"][\"auth-key\"] = authkey\n\t}\n\n\treturn ident, nil\n}", "func (spec *Spec) identity() (*core.Identity, error) {\n\tident := &core.Identity{\n\t\tRequest: spec.Request,\n\t\tRoots: []*core.Root{\n\t\t\t&core.Root{\n\t\t\t\tType: \"system\",\n\t\t\t},\n\t\t\t&core.Root{\n\t\t\t\tType: \"cfssl\",\n\t\t\t\tMetadata: map[string]string{\n\t\t\t\t\t\"host\": spec.CA.Remote,\n\t\t\t\t\t\"profile\": spec.CA.Profile,\n\t\t\t\t\t\"label\": spec.CA.Label,\n\t\t\t\t\t\"tls-remote-ca\": spec.CA.RootCACert,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tProfiles: map[string]map[string]string{\n\t\t\t\"cfssl\": map[string]string{\n\t\t\t\t\"remote\": spec.CA.Remote,\n\t\t\t\t\"profile\": spec.CA.Profile,\n\t\t\t\t\"label\": spec.CA.Label,\n\t\t\t\t\"tls-remote-ca\": spec.CA.RootCACert,\n\t\t\t},\n\t\t},\n\t}\n\n\tauthkey := spec.CA.AuthKey\n\tif spec.CA.AuthKeyFile != \"\" {\n\t\tlog.Debugf(\"loading auth_key_file %v\", spec.CA.AuthKeyFile)\n\t\tcontent, err := ioutil.ReadFile(spec.CA.AuthKeyFile)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed reading auth_key_file %v: %v\", spec.CA.AuthKeyFile, err)\n\t\t}\n\t\tauthkey = strings.TrimSpace(string(content))\n\t}\n\tif authkey != \"\" {\n\t\tident.Profiles[\"cfssl\"][\"auth-type\"] = \"standard\"\n\t\tident.Profiles[\"cfssl\"][\"auth-key\"] = authkey\n\t}\n\n\treturn ident, nil\n}", "func (s *PullSubscription) IdentitySpec() *v1beta1.IdentitySpec {\n\treturn &s.Spec.IdentitySpec\n}", "func (config *IDConfig) validate() error {\n\tswitch config.idType {\n\tcase \"halo-id\", \"m200m\":\n\tdefault:\n\t\treturn fmt.Errorf(\"The 'IDType' variable is set to '%s', which I \"+\n\t\t\t\"don't recognize.\", config.idType)\n\t}\n\n\tswitch config.exclusionStrategy {\n\tcase \"none\", \"subhalo\", \"neighbor\":\n\tcase \"overlap\":\n\t\tif config.exclusionRadiusMult <= 0 {\n\t\t\treturn fmt.Errorf(\"The 'ExclusionRadiusMult' varaible is set to \"+\n\t\t\t\t\"%g, but it needs to be positive.\", config.exclusionRadiusMult)\n\t\t}\n\tdefault:\n\t\treturn fmt.Errorf(\"The 'ExclusionStrategy' variable is set to '%s', \"+\n\t\t\t\"which I don't recognize.\", config.exclusionStrategy)\n\t}\n\n\tswitch {\n\tcase config.snap == -1:\n\t\treturn fmt.Errorf(\"'Snap' variable not set.\")\n\tcase config.snap < 0:\n\t\treturn fmt.Errorf(\"'Snap' variable set to %d.\", config.snap)\n\t}\n\n\tif config.mult <= 0 {\n\t\treturn fmt.Errorf(\"'Mult' variable set to %d\", config.mult)\n\t}\n\n\tswitch {\n\tcase config.m200mMax < 0:\n\t\treturn fmt.Errorf(\"M200mStart set to %g\", config.m200mMax)\n\tcase config.m200mMax > config.m200mMin:\n\t\tfmt.Errorf(\"M200mEnd smaller than M200mStart\")\n\t}\n\n\treturn nil\n}", "func (o ClusterOutput) WorkloadIdentityConfig() ClusterWorkloadIdentityConfigOutput {\n\treturn o.ApplyT(func(v *Cluster) ClusterWorkloadIdentityConfigOutput { return v.WorkloadIdentityConfig }).(ClusterWorkloadIdentityConfigOutput)\n}", "func TestLoadConfigs(t *testing.T) {\n\n\tconfig, err := LoadConfig(\"testdata/alice.conf\")\n\tif err != nil {\n\t\tt.Fatal(\"Could not load test config:\", err)\n\t}\n\n\tif config.Server.Listen == \"\" {\n\t\tt.Error(\"Listen string not present.\")\n\t}\n\n\tif len(config.UI.RoutesColumns) == 0 {\n\t\tt.Error(\"Route columns settings missing\")\n\t}\n\n\tif len(config.UI.RoutesRejections.Reasons) == 0 {\n\t\tt.Error(\"Rejection reasons missing\")\n\t}\n\n\t// Check communities\n\tlabel, err := config.UI.BGPCommunities.Lookup(\"1:23\")\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tif label != \"some tag\" {\n\t\tt.Error(\"expcted to find example community 1:23 with 'some tag'\",\n\t\t\t\"but got:\", label)\n\t}\n}", "func TestConnectionConfigValidation(t *testing.T) {\n\t// Tests.\n\tvar tests = []struct {\n\t\tconfig *Config\n\t\texpected string\n\t}{\n\t\t{\t&Config{}, \n\t\t\t\"The datasource connection was not defined.\",\n\t\t},\n\t\t{\n\t\t\t&Config{\n\t\t\t\tConnection: &ConnectionConfig{}, \n\t\t\t},\n\t\t\t\"The datasource connection protocol was not defined.\",\n\t\t},\n\t\t{\n\t\t\t&Config{\n\t\t\t\tConnection: &ConnectionConfig{Protocol: MongoDBProtocol}, \n\t\t\t},\n\t\t\t\"The datasource connection host was not defined.\",\n\t\t},\n\t\t{\n\t\t\t&Config{\n\t\t\t\tConnection: &ConnectionConfig{Protocol: MongoDBProtocol, Host: Localhost}, \n\t\t\t},\n\t\t\t\"The datasource connection port '0' was less than 1000.\",\n\t\t},\n\t\t{\n\t\t\t&Config{\n\t\t\t\tConnection: &ConnectionConfig{Protocol: MongoDBProtocol, Host: Localhost, Port: -1}, \n\t\t\t},\n\t\t\t\"The datasource connection port '-1' was less than 1000.\",\n\t\t},\t\t\n\t}\n\t// Run tests.\n\tfor _, test := range tests {\n\t\tf := func() {\n \t\ttest.config.validate()\n\t\t}\n\t\tassert.Panics(t, f)\n\t\tassert.PanicsWithValue(t, test.expected, f)\n\t}\n}" ]
[ "0.69445693", "0.59405404", "0.5912807", "0.587062", "0.586529", "0.527814", "0.52237403", "0.5223695", "0.515309", "0.5047154", "0.5047055", "0.5040731", "0.5007019", "0.5006501", "0.49791756", "0.4975429", "0.4966714", "0.49590066", "0.49575666", "0.49523923", "0.49325052", "0.4913493", "0.4909103", "0.48707423", "0.48542112", "0.4818988", "0.4818988", "0.47580537", "0.47566292", "0.4745934", "0.47422647", "0.47421247", "0.47095603", "0.46972194", "0.46895805", "0.4682939", "0.46742156", "0.46731907", "0.46670452", "0.46605742", "0.4656724", "0.4648862", "0.46476483", "0.4633199", "0.4631583", "0.46299306", "0.46293107", "0.46147296", "0.45988148", "0.4591529", "0.45862436", "0.45662758", "0.45529193", "0.4547037", "0.45400497", "0.4525122", "0.45215753", "0.4491774", "0.4477559", "0.44701448", "0.44654804", "0.4460382", "0.44591722", "0.44539362", "0.4449415", "0.44435075", "0.44394785", "0.44221607", "0.4421463", "0.442031", "0.44111767", "0.44110343", "0.43983823", "0.43979222", "0.43961832", "0.439243", "0.43889007", "0.43875656", "0.4380658", "0.43712595", "0.43712595", "0.4368086", "0.43642914", "0.43632248", "0.43602026", "0.43589097", "0.4357577", "0.43571568", "0.43570876", "0.4342498", "0.43420163", "0.4341972", "0.43361378", "0.43360326", "0.43360326", "0.4335414", "0.4335303", "0.4318689", "0.4315572", "0.43150672" ]
0.6904944
1
IdentityManager mocks base method
func (m *MockClient) IdentityManager(arg0 string) (msp.IdentityManager, bool) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "IdentityManager", arg0) ret0, _ := ret[0].(msp.IdentityManager) ret1, _ := ret[1].(bool) return ret0, ret1 }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (m *MockProviders) IdentityManager(arg0 string) (msp.IdentityManager, bool) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"IdentityManager\", arg0)\n\tret0, _ := ret[0].(msp.IdentityManager)\n\tret1, _ := ret[1].(bool)\n\treturn ret0, ret1\n}", "func TestNewIdentityManager(t *testing.T) {\n\tt.Run(\"success\", func(t *testing.T) {\n\t\tepCfg := &mocks.EndpointConfig{}\n\t\tepCfg.NetworkConfigReturns(&fab.NetworkConfig{\n\t\t\tOrganizations: map[string]fab.OrganizationConfig{\"org1msp\": {}},\n\t\t})\n\n\t\tm, err := newIdentityManager(\"org1MSP\", &mocks.CryptoSuite{}, epCfg, \"./msp\")\n\t\trequire.NoError(t, err)\n\t\trequire.NotNil(t, m)\n\t})\n\n\tt.Run(\"No endpoint config -> error\", func(t *testing.T) {\n\t\tm, err := newIdentityManager(\"org1MSP\", &mocks.CryptoSuite{}, nil, \"./msp\")\n\t\trequire.EqualError(t, err, \"endpoint config is required\")\n\t\trequire.Nil(t, m)\n\t})\n\n\tt.Run(\"No org name -> error\", func(t *testing.T) {\n\t\tm, err := newIdentityManager(\"\", nil, &mocks.EndpointConfig{}, \"./msp\")\n\t\trequire.EqualError(t, err, \"orgName is required\")\n\t\trequire.Nil(t, m)\n\t})\n\n\tt.Run(\"No crypto suite -> error\", func(t *testing.T) {\n\t\tm, err := newIdentityManager(\"org1MSP\", nil, &mocks.EndpointConfig{}, \"./msp\")\n\t\trequire.EqualError(t, err, \"cryptoProvider is required\")\n\t\trequire.Nil(t, m)\n\t})\n\n\tt.Run(\"Org not found -> error\", func(t *testing.T) {\n\t\tepCfg := &mocks.EndpointConfig{}\n\t\tepCfg.NetworkConfigReturns(&fab.NetworkConfig{})\n\n\t\tm, err := newIdentityManager(\"org1MSP\", &mocks.CryptoSuite{}, epCfg, \"./msp\")\n\t\trequire.EqualError(t, err, \"org config retrieval failed\")\n\t\trequire.Nil(t, m)\n\t})\n\n\tt.Run(\"MSP config path not provided -> error\", func(t *testing.T) {\n\t\tepCfg := &mocks.EndpointConfig{}\n\t\tepCfg.NetworkConfigReturns(&fab.NetworkConfig{\n\t\t\tOrganizations: map[string]fab.OrganizationConfig{\"org1msp\": {}},\n\t\t})\n\n\t\tm, err := newIdentityManager(\"org1MSP\", &mocks.CryptoSuite{}, epCfg, \"\")\n\t\trequire.EqualError(t, err, \"either mspConfigPath or an embedded list of users is required\")\n\t\trequire.Nil(t, m)\n\t})\n}", "func (m *MockChoriaProvider) Identity() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Identity\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func (m *MockMachine) Identity() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Identity\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func NewIdentityService(t mockConstructorTestingTNewIdentityService) *IdentityService {\n\tmock := &IdentityService{}\n\tmock.Mock.Test(t)\n\n\tt.Cleanup(func() { mock.AssertExpectations(t) })\n\n\treturn mock\n}", "func (u *MockUser) Identity() ([]byte, error) {\n\treturn []byte(\"test\"), nil\n}", "func (p *MockProvisionerClient) Identity() client.IdentityInterface {\n\treturn &MockIdentityClient{}\n}", "func (p *MockProvisionerClient) Identity() client.IdentityInterface {\n\treturn &MockIdentityClient{}\n}", "func NewIdentityProviderBase()(*IdentityProviderBase) {\n m := &IdentityProviderBase{\n Entity: *NewEntity(),\n }\n return m\n}", "func (suite *HealthCheckTestSuite) TestModuleExecuteWithOnPremIdentity() {\n\t// Initialize the appconfigMock with HealthFrequencyMinutes as every five minute\n\tappconfigMock := &appconfig.SsmagentConfig{\n\t\tSsm: appconfig.SsmCfg{\n\t\t\tHealthFrequencyMinutes: appconfig.DefaultSsmHealthFrequencyMinutes,\n\t\t},\n\t}\n\n\tmockEC2Identity := &identityMock.IAgentIdentityInner{}\n\tnewEC2Identity = func(log log.T) identity.IAgentIdentityInner {\n\t\treturn mockEC2Identity\n\t}\n\n\tavailabilityZone := \"us-east-1a\"\n\tavailabilityZoneId := \"use1-az2\"\n\tmockEC2Identity.On(\"IsIdentityEnvironment\").Return(true)\n\tmockEC2Identity.On(\"AvailabilityZone\").Return(availabilityZone, nil)\n\tmockEC2Identity.On(\"AvailabilityZoneId\").Return(availabilityZoneId, nil)\n\n\tmockOnPremIdentity := &identityMock.IAgentIdentityInner{}\n\tnewOnPremIdentity = func(log log.T, config *appconfig.SsmagentConfig) identity.IAgentIdentityInner {\n\t\treturn mockOnPremIdentity\n\t}\n\tmockOnPremIdentity.On(\"IsIdentityEnvironment\").Return(true)\n\n\tmockECSIdentity := &identityMock.IAgentIdentityInner{}\n\tnewECSIdentity = func(log log.T) identity.IAgentIdentityInner {\n\t\treturn mockECSIdentity\n\t}\n\tmockECSIdentity.On(\"IsIdentityEnvironment\").Return(false)\n\n\tssmConnectionChannel := \"ssmmessages\"\n\tvar ableToOpenMGSConnection uint32\n\tatomic.StoreUint32(&ableToOpenMGSConnection, 1)\n\tssmconnectionchannel.SetConnectionChannel(&ableToOpenMGSConnection)\n\n\t// Turn on the mock method\n\tsuite.contextMock.On(\"AppConfig\").Return(*appconfigMock)\n\tsuite.serviceMock.On(\"UpdateInstanceInformation\", mock.Anything, version.Version, \"Active\", AgentName, \"\", \"\", ssmConnectionChannel).Return(nil, nil)\n\tsuite.healthCheck.ModuleExecute()\n\t// Because ModuleExecute will launch two new go routine, wait 100ms to make sure the updateHealth() has launched\n\ttime.Sleep(100 * time.Millisecond)\n\t// Assert the UpdateInstanceInformation get called in updateHealth() function, and the agent status is same as input.\n\tsuite.serviceMock.AssertCalled(suite.T(), \"UpdateInstanceInformation\", mock.Anything, version.Version, \"Active\", AgentName, \"\", \"\", ssmConnectionChannel)\n\tsuite.serviceMock.AssertNotCalled(suite.T(), \"IsIdentityEnvironment\", true)\n}", "func (c *Provider) IdentityManager(orgName string) (msp.IdentityManager, bool) {\n\treturn c.idMgmtProvider.IdentityManager(orgName)\n}", "func (m *MockProviders) IdentityConfig() msp.IdentityConfig {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"IdentityConfig\")\n\tret0, _ := ret[0].(msp.IdentityConfig)\n\treturn ret0\n}", "func createKeycloakInterfaceMock() (keycloakCommon.KeycloakInterface, *mockClientContext) {\n\tcontext := mockClientContext{\n\t\tGroups: []*keycloakCommon.Group{},\n\t\tDefaultGroups: []*keycloakCommon.Group{},\n\t\tClientRoles: map[string][]*keycloak.KeycloakUserRole{},\n\t\tRealmRoles: map[string][]*keycloak.KeycloakUserRole{},\n\t\tAuthenticationFlowsExecutions: map[string][]*keycloak.AuthenticationExecutionInfo{\n\t\t\tfirstBrokerLoginFlowAlias: []*keycloak.AuthenticationExecutionInfo{\n\t\t\t\t&keycloak.AuthenticationExecutionInfo{\n\t\t\t\t\tRequirement: \"REQUIRED\",\n\t\t\t\t\tAlias: reviewProfileExecutionAlias,\n\t\t\t\t},\n\t\t\t\t// dummy ones\n\t\t\t\t&keycloak.AuthenticationExecutionInfo{\n\t\t\t\t\tRequirement: \"REQUIRED\",\n\t\t\t\t\tAlias: \"dummy execution\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\tavailableGroupClientRoles := []*keycloak.KeycloakUserRole{\n\t\t&keycloak.KeycloakUserRole{\n\t\t\tID: \"create-client\",\n\t\t\tName: \"create-client\",\n\t\t},\n\t\t&keycloak.KeycloakUserRole{\n\t\t\tID: \"manage-authorization\",\n\t\t\tName: \"manage-authorization\",\n\t\t},\n\t\t&keycloak.KeycloakUserRole{\n\t\t\tID: \"manage-clients\",\n\t\t\tName: \"manage-clients\",\n\t\t},\n\t\t&keycloak.KeycloakUserRole{\n\t\t\tID: \"manage-events\",\n\t\t\tName: \"manage-events\",\n\t\t},\n\t\t&keycloak.KeycloakUserRole{\n\t\t\tID: \"manage-identity-providers\",\n\t\t\tName: \"manage-identity-providers\",\n\t\t},\n\t\t&keycloak.KeycloakUserRole{\n\t\t\tID: \"manage-realm\",\n\t\t\tName: \"manage-realm\",\n\t\t},\n\t\t&keycloak.KeycloakUserRole{\n\t\t\tID: \"manage-users\",\n\t\t\tName: \"manage-users\",\n\t\t},\n\t\t&keycloak.KeycloakUserRole{\n\t\t\tID: \"query-clients\",\n\t\t\tName: \"query-clients\",\n\t\t},\n\t\t&keycloak.KeycloakUserRole{\n\t\t\tID: \"query-groups\",\n\t\t\tName: \"query-groups\",\n\t\t},\n\t\t&keycloak.KeycloakUserRole{\n\t\t\tID: \"query-realms\",\n\t\t\tName: \"query-realms\",\n\t\t},\n\t\t&keycloak.KeycloakUserRole{\n\t\t\tID: \"query-users\",\n\t\t\tName: \"query-users\",\n\t\t},\n\t\t&keycloak.KeycloakUserRole{\n\t\t\tID: \"view-authorization\",\n\t\t\tName: \"view-authorization\",\n\t\t},\n\t\t&keycloak.KeycloakUserRole{\n\t\t\tID: \"view-clients\",\n\t\t\tName: \"view-clients\",\n\t\t},\n\t\t&keycloak.KeycloakUserRole{\n\t\t\tID: \"view-events\",\n\t\t\tName: \"view-events\",\n\t\t},\n\t\t&keycloak.KeycloakUserRole{\n\t\t\tID: \"view-identity-providers\",\n\t\t\tName: \"view-identity-providers\",\n\t\t},\n\t\t&keycloak.KeycloakUserRole{\n\t\t\tID: \"view-realm\",\n\t\t\tName: \"view-realm\",\n\t\t},\n\t\t&keycloak.KeycloakUserRole{\n\t\t\tID: \"view-users\",\n\t\t\tName: \"view-users\",\n\t\t},\n\t}\n\n\tavailableGroupRealmRoles := []*keycloak.KeycloakUserRole{\n\t\t&keycloak.KeycloakUserRole{\n\t\t\tID: \"mock-role-3\",\n\t\t\tName: \"mock-role-3\",\n\t\t},\n\t\t&keycloak.KeycloakUserRole{\n\t\t\tID: \"create-realm\",\n\t\t\tName: \"create-realm\",\n\t\t},\n\t\t&keycloak.KeycloakUserRole{\n\t\t\tID: \"mock-role-4\",\n\t\t\tName: \"mock-role-4\",\n\t\t},\n\t}\n\n\tlistRealmsFunc := func() ([]*keycloak.KeycloakAPIRealm, error) {\n\t\treturn []*keycloak.KeycloakAPIRealm{\n\t\t\t&keycloak.KeycloakAPIRealm{\n\t\t\t\tRealm: \"master\",\n\t\t\t},\n\t\t\t&keycloak.KeycloakAPIRealm{\n\t\t\t\tRealm: \"test\",\n\t\t\t},\n\t\t}, nil\n\t}\n\n\tfindGroupByNameFunc := func(groupName string, realmName string) (*keycloakCommon.Group, error) {\n\t\tfor _, group := range context.Groups {\n\t\t\tif group.Name == groupName {\n\t\t\t\treturn group, nil\n\t\t\t}\n\t\t}\n\n\t\treturn nil, nil\n\t}\n\n\tcreateGroupFunc := func(groupName string, realmName string) (string, error) {\n\t\tnextID := fmt.Sprintf(\"group-%d\", len(context.Groups))\n\n\t\tnewGroup := &keycloakCommon.Group{\n\t\t\tID: string(nextID),\n\t\t\tName: groupName,\n\t\t}\n\n\t\tcontext.Groups = append(context.Groups, newGroup)\n\n\t\tcontext.ClientRoles[nextID] = []*keycloak.KeycloakUserRole{}\n\t\tcontext.RealmRoles[nextID] = []*keycloak.KeycloakUserRole{}\n\n\t\treturn nextID, nil\n\t}\n\n\tsetGroupChildFunc := func(groupID, realmName string, childGroup *keycloakCommon.Group) error {\n\t\tvar childGroupToAppend *keycloakCommon.Group\n\t\tfor _, group := range context.Groups {\n\t\t\tif group.ID == childGroup.ID {\n\t\t\t\tchildGroupToAppend = group\n\t\t\t}\n\t\t}\n\n\t\tif childGroupToAppend == nil {\n\t\t\tchildGroupToAppend = childGroup\n\t\t}\n\n\t\tfound := false\n\t\tfor _, group := range context.Groups {\n\t\t\tif group.ID == groupID {\n\t\t\t\tgroup.SubGroups = append(group.SubGroups, childGroupToAppend)\n\t\t\t\tfound = true\n\t\t\t}\n\t\t}\n\n\t\tif !found {\n\t\t\treturn fmt.Errorf(\"Group %s not found\", groupID)\n\t\t}\n\n\t\treturn nil\n\t}\n\n\tlistUsersInGroupFunc := func(realmName, groupID string) ([]*keycloak.KeycloakAPIUser, error) {\n\t\treturn []*keycloak.KeycloakAPIUser{}, nil\n\t}\n\n\tmakeGroupDefaultFunc := func(groupID string, realmName string) error {\n\t\tvar group *keycloakCommon.Group\n\n\t\tfor _, existingGroup := range context.Groups {\n\t\t\tif existingGroup.ID == groupID {\n\t\t\t\tgroup = existingGroup\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif group == nil {\n\t\t\treturn fmt.Errorf(\"Referenced group not found\")\n\t\t}\n\n\t\tcontext.DefaultGroups = append(context.DefaultGroups, group)\n\t\treturn nil\n\t}\n\n\tlistDefaultGroupsFunc := func(realmName string) ([]*keycloakCommon.Group, error) {\n\t\treturn context.DefaultGroups, nil\n\t}\n\n\tcreateGroupClientRoleFunc := func(role *keycloak.KeycloakUserRole, realmName, clientID, groupID string) (string, error) {\n\t\tgroupClientRoles, ok := context.ClientRoles[groupID]\n\n\t\tif !ok {\n\t\t\treturn \"\", fmt.Errorf(\"Referenced group not found\")\n\t\t}\n\n\t\tcontext.ClientRoles[groupID] = append(groupClientRoles, role)\n\t\treturn \"dummy-group-client-role-id\", nil\n\t}\n\n\tlistGroupClientRolesFunc := func(realmName, clientID, groupID string) ([]*keycloak.KeycloakUserRole, error) {\n\t\tgroupRoles, ok := context.ClientRoles[groupID]\n\n\t\tif !ok {\n\t\t\treturn nil, fmt.Errorf(\"Referenced group not found\")\n\t\t}\n\n\t\treturn groupRoles, nil\n\t}\n\n\tlistAvailableGroupClientRolesFunc := func(realmName, clientID, groupID string) ([]*keycloak.KeycloakUserRole, error) {\n\t\t_, ok := context.ClientRoles[groupID]\n\n\t\tif !ok {\n\t\t\treturn nil, fmt.Errorf(\"Referenced group not found\")\n\t\t}\n\n\t\treturn availableGroupClientRoles, nil\n\t}\n\n\tfindGroupClientRoleFunc := func(realmName, clientID, groupID string, predicate func(*keycloak.KeycloakUserRole) bool) (*keycloak.KeycloakUserRole, error) {\n\t\tall, err := listGroupClientRolesFunc(realmName, clientID, groupID)\n\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tfor _, role := range all {\n\t\t\tif predicate(role) {\n\t\t\t\treturn role, nil\n\t\t\t}\n\t\t}\n\n\t\treturn nil, nil\n\t}\n\n\tfindAvailableGroupClientRoleFunc := func(realmName, clientID, groupID string, predicate func(*keycloak.KeycloakUserRole) bool) (*keycloak.KeycloakUserRole, error) {\n\t\tall, err := listAvailableGroupClientRolesFunc(realmName, clientID, groupID)\n\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tfor _, role := range all {\n\t\t\tif predicate(role) {\n\t\t\t\treturn role, nil\n\t\t\t}\n\t\t}\n\n\t\treturn nil, nil\n\t}\n\n\tlistGroupRealmRolesFunc := func(realmName, groupID string) ([]*keycloak.KeycloakUserRole, error) {\n\t\tgroupRoles, ok := context.RealmRoles[groupID]\n\n\t\tif !ok {\n\t\t\treturn nil, fmt.Errorf(\"Referenced group not found\")\n\t\t}\n\n\t\treturn groupRoles, nil\n\t}\n\n\tlistAvailableGroupRealmRolesFunc := func(realmName, groupID string) ([]*keycloak.KeycloakUserRole, error) {\n\t\t_, ok := context.RealmRoles[groupID]\n\n\t\tif !ok {\n\t\t\treturn nil, fmt.Errorf(\"Referenced group not found\")\n\t\t}\n\n\t\treturn availableGroupRealmRoles, nil\n\t}\n\n\tcreateGroupRealmRoleFunc := func(role *keycloak.KeycloakUserRole, realmName, groupID string) (string, error) {\n\t\tgroupRealmRoles, ok := context.RealmRoles[groupID]\n\n\t\tif !ok {\n\t\t\treturn \"\", fmt.Errorf(\"Referenced group not found\")\n\t\t}\n\n\t\tcontext.RealmRoles[groupID] = append(groupRealmRoles, role)\n\t\treturn \"dummy-group-realm-role-id\", nil\n\t}\n\n\tlistClientsFunc := func(realmName string) ([]*keycloak.KeycloakAPIClient, error) {\n\t\treturn []*keycloak.KeycloakAPIClient{\n\t\t\t&keycloak.KeycloakAPIClient{\n\t\t\t\tClientID: \"test-realm\",\n\t\t\t\tID: \"test-realm\",\n\t\t\t\tName: \"test-realm\",\n\t\t\t},\n\t\t\t&keycloak.KeycloakAPIClient{\n\t\t\t\tClientID: \"master-realm\",\n\t\t\t\tID: \"master-realm\",\n\t\t\t\tName: \"master-realm\",\n\t\t\t},\n\t\t}, nil\n\t}\n\n\tlistAuthenticationExecutionsForFlowFunc := func(flowAlias, realmName string) ([]*keycloak.AuthenticationExecutionInfo, error) {\n\t\texecutions, ok := context.AuthenticationFlowsExecutions[flowAlias]\n\n\t\tif !ok {\n\t\t\treturn nil, errors.New(\"Authentication flow not found\")\n\t\t}\n\n\t\treturn executions, nil\n\t}\n\n\tfindAuthenticationExecutionForFlowFunc := func(flowAlias, realmName string, predicate func(*keycloak.AuthenticationExecutionInfo) bool) (*keycloak.AuthenticationExecutionInfo, error) {\n\t\texecutions, err := listAuthenticationExecutionsForFlowFunc(flowAlias, realmName)\n\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tfor _, execution := range executions {\n\t\t\tif predicate(execution) {\n\t\t\t\treturn execution, nil\n\t\t\t}\n\t\t}\n\n\t\treturn nil, nil\n\t}\n\n\tupdateAuthenticationExecutionForFlowFunc := func(flowAlias, realmName string, execution *keycloak.AuthenticationExecutionInfo) error {\n\t\texecutions, ok := context.AuthenticationFlowsExecutions[flowAlias]\n\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"Authentication flow %s not found\", flowAlias)\n\t\t}\n\n\t\tfor i, currentExecution := range executions {\n\t\t\tif currentExecution.Alias != execution.Alias {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tcontext.AuthenticationFlowsExecutions[flowAlias][i] = execution\n\t\t\tbreak\n\t\t}\n\n\t\treturn nil\n\t}\n\n\tlistOfActivesUsersPerRealmFunc := func(realmName, dateFrom string, max int) ([]keycloakCommon.Users, error) {\n\t\tusers := []keycloakCommon.Users{\n\t\t\t{\n\t\t\t\tUserID: \"1\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tUserID: \"2\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tUserID: \"3\",\n\t\t\t},\n\t\t}\n\n\t\treturn users, nil\n\t}\n\n\treturn &keycloakCommon.KeycloakInterfaceMock{\n\t\tListRealmsFunc: listRealmsFunc,\n\t\tFindGroupByNameFunc: findGroupByNameFunc,\n\t\tCreateGroupFunc: createGroupFunc,\n\t\tSetGroupChildFunc: setGroupChildFunc,\n\t\tListUsersInGroupFunc: listUsersInGroupFunc,\n\t\tMakeGroupDefaultFunc: makeGroupDefaultFunc,\n\t\tListDefaultGroupsFunc: listDefaultGroupsFunc,\n\t\tCreateGroupClientRoleFunc: createGroupClientRoleFunc,\n\t\tListGroupClientRolesFunc: listGroupClientRolesFunc,\n\t\tListAvailableGroupClientRolesFunc: listAvailableGroupClientRolesFunc,\n\t\tFindGroupClientRoleFunc: findGroupClientRoleFunc,\n\t\tFindAvailableGroupClientRoleFunc: findAvailableGroupClientRoleFunc,\n\t\tListGroupRealmRolesFunc: listGroupRealmRolesFunc,\n\t\tListAvailableGroupRealmRolesFunc: listAvailableGroupRealmRolesFunc,\n\t\tCreateGroupRealmRoleFunc: createGroupRealmRoleFunc,\n\t\tListAuthenticationExecutionsForFlowFunc: listAuthenticationExecutionsForFlowFunc,\n\t\tFindAuthenticationExecutionForFlowFunc: findAuthenticationExecutionForFlowFunc,\n\t\tUpdateAuthenticationExecutionForFlowFunc: updateAuthenticationExecutionForFlowFunc,\n\t\tListClientsFunc: listClientsFunc,\n\t\tListOfActivesUsersPerRealmFunc: listOfActivesUsersPerRealmFunc,\n\t}, &context\n}", "func TestEmployeeManagerMapGetByID(t *testing.T) {\n\tdb, mock, err := sqlmock.New()\n\tif err != nil {\n\t\tt.Fatalf(\"an error '%s' was not expected when opening a stub database connection\", err)\n\t}\n\tdefer db.Close()\n\n\trows := sqlmock.NewRows([]string{\"employee_name\", \"manager_name\"}).AddRow(\"Nick\", \"Sophie\").AddRow(\"Sophie\", \"Jonas\")\n\tmock.ExpectExec(constants.EmployeeManagerMappingDeleteQuery).WillReturnResult(sqlmock.NewResult(0, 0))\n\tmock.ExpectPrepare(regexp.QuoteMeta(constants.EmployeeManagerMappingInsertQuery)).ExpectExec().WillReturnResult(sqlmock.NewResult(0, 0))\n\tmock.ExpectQuery(constants.EmployeeManagerMappingSelectQuery).WillReturnRows(rows)\n\n\templyManagerMap := NewEmployeeManagerMapHandler(db)\n\n\tw := httptest.NewRecorder()\n\tvar jsonStr = []byte(`{\"Peter\":\"Nick\", \"Barbara\":\"Nick\", \"Nick\":\"Sophie\", \"Sophie\":\"Jonas\"}`)\n\tr := httptest.NewRequest(\"POST\", \"http://localhost:9090/api/v1/emplymgrmap\", bytes.NewBuffer(jsonStr))\n\tr = r.WithContext(context.Background())\n\templyManagerMap.Create(w, r)\n\n\tr = httptest.NewRequest(\"GET\", \"http://localhost:9090/api/v1/emplymgrmap/Nick?supervisor=true&name=Nick\", nil)\n\trctx := chi.NewRouteContext()\n\trctx.URLParams.Add(\"name\", \"Nick\")\n\tr = r.WithContext(context.WithValue(r.Context(), chi.RouteCtxKey, rctx))\n\tw = httptest.NewRecorder()\n\templyManagerMap.GetByID(w, r)\n\texpectedResponse := `{\"supervisor\":\"Sophie\",\"supervisor_of_supervisor\":\"Jonas\"}`\n\tassert.Equal(t, gohttp.StatusOK, w.Code)\n\tassert.Equal(t, expectedResponse, w.Body.String())\n}", "func (suite *AuthSuite) TestAuthUnknownServiceMember() {\n\t// Set up: Prepare the session, goth.User, callback handler, http response\n\t// and request, landing URL, and pass them into authorizeUnknownUser\n\n\thandlerConfig := suite.HandlerConfig()\n\tappnames := handlerConfig.AppNames()\n\n\t// Prepare the session and session manager\n\tfakeToken := \"some_token\"\n\tsession := auth.Session{\n\t\tApplicationName: auth.MilApp,\n\t\tIDToken: fakeToken,\n\t\tHostname: appnames.MilServername,\n\t}\n\tsessionManager := handlerConfig.SessionManagers().Mil\n\tmockSender := setUpMockNotificationSender() // We should get an email for this activity\n\n\t// Prepare the goth.User to simulate the UUID and email that login.gov would\n\t// provide\n\tfakeUUID, _ := uuid.NewV4()\n\tuser := goth.User{\n\t\tUserID: fakeUUID.String(),\n\t\tEmail: \"new_service_member@example.com\",\n\t}\n\tctx := suite.SetupSessionContext(context.Background(), &session, sessionManager)\n\n\t// Call the function under test\n\tresult := authorizeUnknownUser(ctx, suite.AppContextWithSessionForTest(&session), user,\n\t\tsessionManager, mockSender)\n\tsuite.Equal(authorizationResultAuthorized, result)\n\tmockSender.(*mocks.NotificationSender).AssertNumberOfCalls(suite.T(), \"SendNotification\", 1)\n\n\t// Look up the user and service member in the test DB\n\tfoundUser, _ := models.GetUserFromEmail(suite.DB(), user.Email)\n\tserviceMemberID := session.ServiceMemberID\n\tserviceMember, _ := models.FetchServiceMemberForUser(suite.DB(), &session, serviceMemberID)\n\t// Look up the session token in the session store (this test uses the memory store)\n\tsessionStore := sessionManager.Store()\n\t_, existsBefore, _ := sessionStore.Find(foundUser.CurrentMilSessionID)\n\n\t// Verify service member exists and its ID is populated in the session\n\tsuite.NotEmpty(session.ServiceMemberID)\n\n\t// Verify session contains UserID that points to the newly-created user\n\tsuite.Equal(foundUser.ID, session.UserID)\n\n\t// Verify user's LoginGovEmail and LoginGovUUID match the values passed in\n\tsuite.Equal(user.Email, foundUser.LoginGovEmail)\n\tsuite.Equal(user.UserID, foundUser.LoginGovUUID.String())\n\n\t// Verify that the user's CurrentMilSessionID is not empty. The value is\n\t// generated randomly, so we can't test for a specific string. Any string\n\t// except an empty string is acceptable.\n\tsuite.NotEqual(\"\", foundUser.CurrentMilSessionID)\n\n\t// Verify the session token also exists in the session store\n\tsuite.Equal(true, existsBefore)\n\n\t// Verify the service member that was created is associated with the user\n\t// that was created\n\tsuite.Equal(foundUser.ID, serviceMember.UserID)\n}", "func (m *MockClient) IdentityConfig() msp.IdentityConfig {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"IdentityConfig\")\n\tret0, _ := ret[0].(msp.IdentityConfig)\n\treturn ret0\n}", "func (m *MockActivityHandler) AdminGetByID(w http.ResponseWriter, r *http.Request) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"AdminGetByID\", w, r)\n}", "func TestGenerateIdentity(t *testing.T) {\n\tif _, err := GenerateIdentity(); err != nil {\n\t\tt.Fatalf(\"Failed to generate new identity: %v\", err)\n\t}\n}", "func TestGenerateIdentity(t *testing.T) {\n\tif _, err := GenerateIdentity(); err != nil {\n\t\tt.Fatalf(\"Failed to generate new identity: %v\", err)\n\t}\n}", "func mockTestUserInteraction(ctx context.Context, pro providerParams, username, password string) (string, error) {\n\tctx, cancel := context.WithTimeout(ctx, 10*time.Second)\n\tdefer cancel()\n\n\tprovider, err := oidc.NewProvider(ctx, pro.providerURL)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"unable to create provider: %v\", err)\n\t}\n\n\t// Configure an OpenID Connect aware OAuth2 client.\n\toauth2Config := oauth2.Config{\n\t\tClientID: pro.clientID,\n\t\tClientSecret: pro.clientSecret,\n\t\tRedirectURL: pro.redirectURL,\n\n\t\t// Discovery returns the OAuth2 endpoints.\n\t\tEndpoint: provider.Endpoint(),\n\n\t\t// \"openid\" is a required scope for OpenID Connect flows.\n\t\tScopes: []string{oidc.ScopeOpenID, \"groups\"},\n\t}\n\n\tstate := \"xxx\"\n\tauthCodeURL := oauth2Config.AuthCodeURL(state)\n\t// fmt.Printf(\"authcodeurl: %s\\n\", authCodeURL)\n\n\tvar lastReq *http.Request\n\tcheckRedirect := func(req *http.Request, via []*http.Request) error {\n\t\t// fmt.Printf(\"CheckRedirect:\\n\")\n\t\t// fmt.Printf(\"Upcoming: %s %#v\\n\", req.URL.String(), req)\n\t\t// for _, c := range via {\n\t\t// \tfmt.Printf(\"Sofar: %s %#v\\n\", c.URL.String(), c)\n\t\t// }\n\t\t// Save the last request in a redirect chain.\n\t\tlastReq = req\n\t\t// We do not follow redirect back to client application.\n\t\tif req.URL.Path == \"/oauth_callback\" {\n\t\t\treturn http.ErrUseLastResponse\n\t\t}\n\t\treturn nil\n\t}\n\n\tdexClient := http.Client{\n\t\tCheckRedirect: checkRedirect,\n\t}\n\n\tu, err := url.Parse(authCodeURL)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"url parse err: %v\", err)\n\t}\n\n\t// Start the user auth flow. This page would present the login with\n\t// email or LDAP option.\n\treq, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"new request err: %v\", err)\n\t}\n\t_, err = dexClient.Do(req)\n\t// fmt.Printf(\"Do: %#v %#v\\n\", resp, err)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"auth url request err: %v\", err)\n\t}\n\n\t// Modify u to choose the ldap option\n\tu.Path += \"/ldap\"\n\t// fmt.Println(u)\n\n\t// Pick the LDAP login option. This would return a form page after\n\t// following some redirects. `lastReq` would be the URL of the form\n\t// page, where we need to POST (submit) the form.\n\treq, err = http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"new request err (/ldap): %v\", err)\n\t}\n\t_, err = dexClient.Do(req)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"request err: %v\", err)\n\t}\n\n\t// Fill the login form with our test creds:\n\t// fmt.Printf(\"login form url: %s\\n\", lastReq.URL.String())\n\tformData := url.Values{}\n\tformData.Set(\"login\", username)\n\tformData.Set(\"password\", password)\n\treq, err = http.NewRequestWithContext(ctx, http.MethodPost, lastReq.URL.String(), strings.NewReader(formData.Encode()))\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"new request err (/login): %v\", err)\n\t}\n\treq.Header.Set(\"Content-Type\", \"application/x-www-form-urlencoded\")\n\t_, err = dexClient.Do(req)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"post form err: %v\", err)\n\t}\n\t// fmt.Printf(\"resp: %#v %#v\\n\", resp.StatusCode, resp.Header)\n\t// fmt.Printf(\"lastReq: %#v\\n\", lastReq.URL.String())\n\n\t// On form submission, the last redirect response contains the auth\n\t// code, which we now have in `lastReq`. Exchange it for a JWT id_token.\n\tq := lastReq.URL.Query()\n\tcode := q.Get(\"code\")\n\toauth2Token, err := oauth2Config.Exchange(ctx, code)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"unable to exchange code for id token: %v\", err)\n\t}\n\n\trawIDToken, ok := oauth2Token.Extra(\"id_token\").(string)\n\tif !ok {\n\t\treturn \"\", fmt.Errorf(\"id_token not found!\")\n\t}\n\n\t// fmt.Printf(\"TOKEN: %s\\n\", rawIDToken)\n\treturn rawIDToken, nil\n}", "func (suite *HealthCheckTestSuite) TestModuleExecuteWithNilOnPremIdentity() {\n\t// Initialize the appconfigMock with HealthFrequencyMinutes as every five minute\n\tappconfigMock := &appconfig.SsmagentConfig{\n\t\tSsm: appconfig.SsmCfg{\n\t\t\tHealthFrequencyMinutes: appconfig.DefaultSsmHealthFrequencyMinutes,\n\t\t},\n\t}\n\n\tmockEC2Identity := &identityMock.IAgentIdentityInner{}\n\tnewEC2Identity = func(log log.T) identity.IAgentIdentityInner {\n\t\treturn mockEC2Identity\n\t}\n\n\tavailabilityZone := \"us-east-1a\"\n\tavailabilityZoneId := \"use1-az2\"\n\tmockEC2Identity.On(\"IsIdentityEnvironment\").Return(true)\n\tmockEC2Identity.On(\"AvailabilityZone\").Return(availabilityZone, nil)\n\tmockEC2Identity.On(\"AvailabilityZoneId\").Return(availabilityZoneId, nil)\n\n\tnewOnPremIdentity = func(log log.T, config *appconfig.SsmagentConfig) identity.IAgentIdentityInner {\n\t\treturn nil\n\t}\n\n\tmockECSIdentity := &identityMock.IAgentIdentityInner{}\n\tnewECSIdentity = func(log log.T) identity.IAgentIdentityInner {\n\t\treturn mockECSIdentity\n\t}\n\tmockECSIdentity.On(\"IsIdentityEnvironment\").Return(false)\n\n\tssmConnectionChannel := \"ssmmessages\"\n\tvar ableToOpenMGSConnection uint32\n\tatomic.StoreUint32(&ableToOpenMGSConnection, 1)\n\tssmconnectionchannel.SetConnectionChannel(&ableToOpenMGSConnection)\n\n\t// Turn on the mock method\n\tsuite.contextMock.On(\"AppConfig\").Return(*appconfigMock)\n\tsuite.serviceMock.On(\"UpdateInstanceInformation\", mock.Anything, version.Version, \"Active\", AgentName, availabilityZone, availabilityZoneId, ssmConnectionChannel).Return(nil, nil)\n\tsuite.healthCheck.ModuleExecute()\n\t// Because ModuleExecute will launch two new go routine, wait 100ms to make sure the updateHealth() has launched\n\ttime.Sleep(100 * time.Millisecond)\n\t// Assert the UpdateInstanceInformation get called in updateHealth() function, and the agent status is same as input.\n\tsuite.serviceMock.AssertCalled(suite.T(), \"UpdateInstanceInformation\", mock.Anything, version.Version, \"Active\", AgentName, availabilityZone, availabilityZoneId, ssmConnectionChannel)\n}", "func (c *OAuth) Manager(idp idp.IdentityProvider, store *mongodb.Store, encoder jwt.Encoder) *oauth.Manager {\n\tfmt.Println(c)\n\tproviderMetadata := &openid.ProviderMetadata{\n\t\tIssuer: c.Issuer,\n\t\tAuthorizationEndpoint: c.UIAuthorizeEndpoint,\n\t\tTokenEndpoint: fmt.Sprintf(\"%s/v0/oauth/token\", c.Issuer),\n\t\tUserInfoEndpoint: fmt.Sprintf(\"%s/v0/openid/userinfo\", c.Issuer),\n\t\tJwksURI: fmt.Sprintf(\"%s/.well-known/jwks.json\", c.Issuer),\n\t\tRegistrationEndpoint: fmt.Sprintf(\"%s/v0/clients\", c.Issuer),\n\t\tScopesSupported: append(c.ScopesSupported, openid.OpenIDScope, openid.ProfileScope, openid.EmailScope),\n\t\tResponseTypesSupported: []string{string(model.CodeResponseType)},\n\t\tGrantTypesSupported: []string{string(model.AuthorizationCodeGrantType), string(model.PasswordGrantType), string(model.ClientCredentialsGrantType)},\n\t\tSubjectTypesSupported: []string{\"public\"},\n\t\tIDTokenSigningAlgValuesSupported: []string{string(jose.RS256)},\n\t\tTokenEndpointAuthMethodsSupported: []string{openid.ClientSecretPostTokenAuthMethod},\n\t\tCodeChallengeMethodsSupported: []string{string(model.PlainCodeChallengeMethod), string(model.S256CodeChallengeMethod)},\n\t}\n\treturn oauth.NewManager(idp, store, encoder, providerMetadata)\n}", "func (m *MockSession) ID() int64 {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ID\")\n\tret0, _ := ret[0].(int64)\n\treturn ret0\n}", "func getTestIdent(t *testing.T, username string, reqs ...identRequest) *identity.Identity {\n\tca, err := tlsca.FromKeys([]byte(fixtures.TLSCACertPEM), []byte(fixtures.TLSCAKeyPEM))\n\trequire.NoError(t, err)\n\n\tprivateKey, sshPublicKey, err := testauthority.New().GenerateKeyPair()\n\trequire.NoError(t, err)\n\n\tsshPrivateKey, err := ssh.ParseRawPrivateKey(privateKey)\n\trequire.NoError(t, err)\n\n\ttlsPublicKeyPEM, err := tlsca.MarshalPublicKeyFromPrivateKeyPEM(sshPrivateKey)\n\trequire.NoError(t, err)\n\n\ttlsPublicKey, err := tlsca.ParsePublicKeyPEM(tlsPublicKeyPEM)\n\trequire.NoError(t, err)\n\n\t// Note: it'd be nice to make this more universally useful in our tests at\n\t// some point.\n\tclock := clockwork.NewFakeClock()\n\tnotAfter := clock.Now().Add(time.Hour)\n\tid := tlsca.Identity{\n\t\tUsername: username,\n\t\tKubernetesUsers: []string{\"foo\"},\n\t\tKubernetesGroups: []string{\"bar\"},\n\t\tRouteToCluster: mockClusterName,\n\t}\n\tfor _, req := range reqs {\n\t\treq(&id)\n\t}\n\tsubject, err := id.Subject()\n\trequire.NoError(t, err)\n\tcertBytes, err := ca.GenerateCertificate(tlsca.CertificateRequest{\n\t\tClock: clock,\n\t\tPublicKey: tlsPublicKey,\n\t\tSubject: subject,\n\t\tNotAfter: notAfter,\n\t})\n\trequire.NoError(t, err)\n\n\tcaSigner, err := ssh.ParsePrivateKey([]byte(fixtures.SSHCAPrivateKey))\n\trequire.NoError(t, err)\n\tta := testauthority.New()\n\tsshCertBytes, err := ta.GenerateUserCert(services.UserCertParams{\n\t\tCASigner: caSigner,\n\t\tPublicUserKey: sshPublicKey,\n\t\tUsername: username,\n\t\tCertificateFormat: constants.CertificateFormatStandard,\n\t\tTTL: time.Minute,\n\t\tAllowedLogins: []string{\"foo\"},\n\t\tRouteToCluster: mockClusterName,\n\t})\n\n\trequire.NoError(t, err)\n\n\tcerts := &proto.Certs{\n\t\tSSH: sshCertBytes,\n\t\tTLS: certBytes,\n\t\tTLSCACerts: [][]byte{[]byte(fixtures.TLSCACertPEM)},\n\t\tSSHCACerts: [][]byte{[]byte(fixtures.SSHCAPublicKey)},\n\t}\n\n\tident, err := identity.ReadIdentityFromStore(&identity.LoadIdentityParams{\n\t\tPrivateKeyBytes: privateKey,\n\t\tPublicKeyBytes: tlsPublicKeyPEM,\n\t}, certs, identity.DestinationKinds()...)\n\trequire.NoError(t, err)\n\n\treturn ident\n}", "func (m *MockManagerClient) GetManagerByUserFromServer(id int64) (*manager_grpc.Manager, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetManagerByUserFromServer\", id)\n\tret0, _ := ret[0].(*manager_grpc.Manager)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func NewMockKeystore(auth *communications.Headers, logger log.Logger) definitions.Keystore {\n\ts := new(inmemKeystore)\n\ts.headers = auth\n\treturn s\n}", "func (m *MockAdmin) Authenticate(ctx provider.Context, adminID int, allowedRole []constant.UserRole) (entity.User, *entity.ApplicationError) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Authenticate\", ctx, adminID, allowedRole)\n\tret0, _ := ret[0].(entity.User)\n\tret1, _ := ret[1].(*entity.ApplicationError)\n\treturn ret0, ret1\n}", "func (m *MockCAClient) GetAllIdentities(arg0 string) ([]*api.IdentityResponse, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetAllIdentities\", arg0)\n\tret0, _ := ret[0].([]*api.IdentityResponse)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func mockChildPackages() {\n\n\t// Fake an AWS credentials file so that the mfile package will nehave as if it is happy\n\tsetFakeCredentials()\n\n\t// Fake out the creds package into using an apparently credentials response from AWS\n\tcreds.SetGetSessionTokenFunc(func(awsService *sts.STS, input *sts.GetSessionTokenInput) (*sts.GetSessionTokenOutput, error) {\n\t\treturn getSessionTokenOutput, nil\n\t})\n\n}", "func NewMock(middleware []Middleware) OrganizationService {\n\tvar svc OrganizationService = NewBasicOrganizationServiceServiceMock()\n\tfor _, m := range middleware {\n\t\tsvc = m(svc)\n\t}\n\treturn svc\n}", "func TestAuthenticate_Success(t *testing.T) {\n\tdb, mock, err := sqlmock.New()\n\tif err != nil {\n\t\tt.Fatalf(\"an error '%s' was not expected when opening a stub database connection\", err)\n\t}\n\tdefer db.Close()\n\n\tuser := models.User{\n\t\tID: 1,\n\t\tEmail: \"personia@personio.com\",\n\t\tPassword: \"personia\",\n\t}\n\n\trows := sqlmock.NewRows([]string{\"id\", \"email\"}).AddRow(user.ID, user.Email)\n\tmock.ExpectQuery(regexp.QuoteMeta(constants.LoginDetailsSelectQuery)).WithArgs(user.Email, user.Password).WillReturnRows(rows)\n\n\tloginRepository := NewLoginRepository(db)\n\n\tloginModel := &models.Login{\n\t\tEmail: \"personia@personio.com\",\n\t\tPassword: \"personia\",\n\t}\n\n\tcntx := context.Background()\n\tdbuser, err := loginRepository.Authenticate(cntx, loginModel)\n\tassert.Nil(t, err)\n\tassert.Equal(t, user.ID, dbuser.ID)\n\tassert.Equal(t, user.Email, dbuser.Email)\n}", "func (m *MockClient) Identifier() *msp.IdentityIdentifier {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Identifier\")\n\tret0, _ := ret[0].(*msp.IdentityIdentifier)\n\treturn ret0\n}", "func (m *MockIByIdUseCase) Id(id aggregates.Id) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"Id\", id)\n}", "func (m *MockSessionManager) Create(userId string) (*session.Session, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Create\", userId)\n\tret0, _ := ret[0].(*session.Session)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockCAClient) ModifyIdentity(arg0 *api.IdentityRequest) (*api.IdentityResponse, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ModifyIdentity\", arg0)\n\tret0, _ := ret[0].(*api.IdentityResponse)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func testSystemAssignedIdentity(msiEndpoint string) (*adal.Token, error) {\n\tspt, err := adal.NewServicePrincipalTokenFromMSI(msiEndpoint, azure.PublicCloud.ResourceManagerEndpoint)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"Failed to acquire a token using the MSI VM extension\")\n\t}\n\n\tif err := spt.Refresh(); err != nil {\n\t\treturn nil, errors.Wrapf(err, \"Failed to refresh ServicePrincipalTokenFromMSI using the MSI VM extension, msiEndpoint(%s)\", msiEndpoint)\n\t}\n\n\ttoken := spt.Token()\n\tif token.IsZero() {\n\t\treturn nil, errors.Errorf(\"No token found, MSI VM extension, msiEndpoint(%s)\", msiEndpoint)\n\t}\n\n\tklog.Infof(\"successfully acquired a token using the MSI, msiEndpoint(%s)\", msiEndpoint)\n\treturn &token, nil\n}", "func TestRevokedIdentity(t *testing.T) {\n\ttestHome := t.TempDir()\n\tserverdir := filepath.Join(testdataDir, \"server\")\n\n\tsrv := TestGetServer(ctport1, serverdir, \"\", -1, t)\n\terr := srv.Start()\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to start server: %s\", err)\n\t}\n\tdefer func() {\n\t\terr := srv.Stop()\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Server stop failed: %s\", err)\n\t\t}\n\t\terr = os.RemoveAll(serverdir)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"RemoveAll failed: %s\", err)\n\t\t}\n\t\terr = os.RemoveAll(testHome)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"RemoveAll failed: %s\", err)\n\t\t}\n\t}()\n\n\t// Enroll admin\n\tc := &Client{\n\t\tConfig: &ClientConfig{URL: fmt.Sprintf(\"http://localhost:%d\", ctport1)},\n\t\tHomeDir: filepath.Join(testHome, \"admin\"),\n\t}\n\n\tenrollReq := &api.EnrollmentRequest{\n\t\tName: \"admin\",\n\t\tSecret: \"adminpw\",\n\t}\n\n\teresp, err := c.Enroll(enrollReq)\n\tif err != nil {\n\t\tt.Fatalf(\"Enrollment of admin failed: %s\", err)\n\t}\n\n\tadmin_id := eresp.Identity\n\n\t// 'admin' registers 'TestUser' user\n\tregisterReq := &api.RegistrationRequest{\n\t\tName: \"TestUser\",\n\t\tType: \"user\",\n\t\tAffiliation: \"hyperledger\",\n\t\tMaxEnrollments: 2,\n\t}\n\n\tresp, err := admin_id.Register(registerReq)\n\tif err != nil {\n\t\tt.Fatalf(\"Register failed: %s\", err)\n\t}\n\n\t// Enroll 'TestUser'\n\tTestUserClient := &Client{\n\t\tConfig: &ClientConfig{URL: fmt.Sprintf(\"http://localhost:%d\", ctport1)},\n\t\tHomeDir: filepath.Join(testHome, \"TestUserClient\"),\n\t}\n\n\tenrollReq = &api.EnrollmentRequest{\n\t\tName: \"TestUser\",\n\t\tSecret: resp.Secret,\n\t}\n\n\teresp2, err := TestUserClient.Enroll(enrollReq)\n\tif err != nil {\n\t\tt.Fatalf(\"Enrollment of TestUser failed: %s\", err)\n\t}\n\n\ttestuserid := eresp2.Identity\n\n\t// Enroll 'TestUser' again with a different home/msp directory\n\tTestUserClient2 := &Client{\n\t\tConfig: &ClientConfig{URL: fmt.Sprintf(\"http://localhost:%d\", ctport1)},\n\t\tHomeDir: filepath.Join(testHome, \"TestUserClient2\"),\n\t}\n\n\tenrollReq = &api.EnrollmentRequest{\n\t\tName: \"TestUser\",\n\t\tSecret: resp.Secret,\n\t}\n\n\teresp3, err := TestUserClient2.Enroll(enrollReq)\n\tif err != nil {\n\t\tt.Fatalf(\"Enrollment of TestUser failed: %s\", err)\n\t}\n\n\ttestuserid2 := eresp3.Identity\n\n\t// 'admin' revokes user 'TestUser'\n\trevReq := &api.RevocationRequest{\n\t\tName: \"TestUser\",\n\t\tGenCRL: true,\n\t}\n\n\t_, err = admin_id.Revoke(revReq)\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to revoke TestUser identity: %s\", err)\n\t}\n\n\t// After an identity has been revoked, all subsequent commands invoked by revoked user should be rejected by server\n\t// for all its issued certificates\n\t_, err = TestUserClient2.Enroll(enrollReq)\n\tif err == nil {\n\t\tt.Fatalf(\"Enrollment of TestUser should have failed: %s\", err)\n\t}\n\n\t_, err = testuserid.Reenroll(&api.ReenrollmentRequest{})\n\tif err == nil {\n\t\tt.Fatalf(\"Reenrollment of TestUser identity should have failed: %s\", err)\n\t}\n\n\t_, err = testuserid2.Reenroll(&api.ReenrollmentRequest{})\n\tif err == nil {\n\t\tt.Fatalf(\"Reenrollment of TestUser identity should have failed: %s\", err)\n\t}\n\n\t_, err = testuserid.Register(registerReq)\n\tif err == nil {\n\t\tt.Fatalf(\"Registration of TestUser identity should have failed: %s\", err)\n\t}\n\n\t_, err = testuserid2.Register(registerReq)\n\tif err == nil {\n\t\tt.Fatalf(\"Registration of TestUser identity should have failed: %s\", err)\n\t}\n\n\t_, err = testuserid.Revoke(&api.RevocationRequest{\n\t\tName: \"admin\",\n\t})\n\tif err == nil {\n\t\tt.Fatalf(\"Revocation of 'admin' identity should have failed: %s\", err)\n\t}\n\n\t_, err = testuserid2.Revoke(&api.RevocationRequest{\n\t\tName: \"admin\",\n\t})\n\tif err == nil {\n\t\tt.Fatalf(\"Revocation of 'admin' identity should have failed: %s\", err)\n\t}\n\n\tc = new(Client)\n\tc.Config = new(ClientConfig)\n\tc.Config.URL = fmt.Sprintf(\"http://localhost:%d\", ctport1)\n\n\t// Bad TLS\n\tc.Config.MSPDir = \"msp\"\n\tvar kc tls.KeyCertFiles\n\tkc.KeyFile = \"../testdata/ec_key.pem\"\n\tkc.CertFile = \"../testdata/expiredcert.pem\"\n\tc.Config.MSPDir = \"\"\n\tc.Config.URL = \"\"\n\tc.Config.TLS.Enabled = true\n\tc.Config.TLS.CertFiles = []string{\"../testdata/ec.pem\"}\n\tc.Config.TLS.Client = kc\n\tcurl := fmt.Sprintf(\"http://localhost:%d/api/v1/register\", ctport1)\n\treqBody := []byte(\"\")\n\treq, _ := http.NewRequest(\"POST\", curl, bytes.NewReader(reqBody))\n\terr = c.SendReq(req, nil)\n\tt.Logf(\"Client SendReq() error %v\", err)\n\tif err == nil {\n\t\tt.Error(\"Sending post with bad TLS config should have failed\")\n\t}\n\n\terr = GenerateECDSATestCert()\n\tutil.FatalError(t, err, \"Failed to generate certificate for testing\")\n\tkc.CertFile = \"../testdata/ec_cert.pem\"\n\tc.Config.TLS.Client = kc\n\treq, _ = http.NewRequest(\"POST\", curl, bytes.NewReader(reqBody))\n\terr = c.SendReq(req, nil)\n\tt.Logf(\"Client SendReq() error %v\", err)\n\tif err == nil {\n\t\tt.Error(\"Sending post with bad TLS config should have failed\")\n\t}\n\n\t// Bad URL\n\tcurl = fmt.Sprintf(\"http://localhost:%d/fake\", ctport1)\n\treqBody = []byte(\"\")\n\treq, _ = http.NewRequest(\"POST\", curl, bytes.NewReader(reqBody))\n\terr = c.SendReq(req, nil)\n\tt.Logf(\"Client SendReq() error %v\", err)\n\tif err == nil {\n\t\tt.Error(\"Sending post with bad URL should have failed\")\n\t}\n\n\t// No authorization header\n\tcurl = fmt.Sprintf(\"http://localhost:%d/api/v1/revoke\", ctport1)\n\treqBody = []byte(\"\")\n\treq, _ = http.NewRequest(\"POST\", curl, bytes.NewReader(reqBody))\n\terr = c.SendReq(req, nil)\n\tt.Logf(\"Client SendReq() error %v\", err)\n\tif err == nil {\n\t\tt.Error(\"Sending register with no authorization header should have failed\")\n\t}\n\n\t// Bad authorization header\n\tcurl = fmt.Sprintf(\"http://localhost:%d/api/v1/register\", ctport1)\n\treqBody = []byte(\"\")\n\treq, _ = http.NewRequest(\"POST\", curl, bytes.NewReader(reqBody))\n\treq.Header.Add(\"Authorization\", \"bad-auth\")\n\terr = c.SendReq(req, nil)\n\tt.Logf(\"Client SendReq() error %v\", err)\n\tif err == nil {\n\t\tt.Error(\"Sending register with bad authorization header should have failed\")\n\t}\n\n\t// Bad Init\n\tc2 := new(Client)\n\tc2.Config = new(ClientConfig)\n\tc2.Config.URL = fmt.Sprintf(\"http://localhost:%d\", ctport1)\n\tc2.Config.MSPDir = string(make([]byte, 1))\n\tcurl = fmt.Sprintf(\"http://localhost:%d/api/v1/register\", ctport1)\n\treqBody = []byte(\"\")\n\treq, _ = http.NewRequest(\"POST\", curl, bytes.NewReader(reqBody))\n\terr = c2.SendReq(req, nil)\n\tt.Logf(\"Client SendReq() error %v\", err)\n\tif err == nil {\n\t\tt.Error(\"Sending post with bad Init should have failed\")\n\t}\n}", "func testInMemoryDataStore() IDataStore {\n return NewInMemoryDataStore();\n}", "func (m *MockSpaceStorage) Id() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Id\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func TestClientManagerCreateNew(t *testing.T) {\n\tctx, flush := th.TestContext(t)\n\tdefer flush()\n\n\ttd := testdeep.NewT(t)\n\n\tmc := minimock.NewController(td)\n\tdefer mc.Finish()\n\n\tc := NewBytesMock(mc)\n\n\tvar err error\n\n\t//register account\n\tmanager := New(ctx, c)\n\tc.PutMock.Return(nil)\n\tc.GetMock.Return(nil, cache.ErrCacheMiss)\n\tmanager.DirectoryURL = testACMEServer\n\tclient, err := manager.GetClient(ctx)\n\ttd.CmpNoError(err)\n\ttd.NotNil(client)\n\n\tclient2, err := manager.GetClient(ctx)\n\ttd.CmpNoError(err)\n\ttd.True(client == client2)\n}", "func NewMockIDAllocator() *MockIDAllocator {\n\treturn &MockIDAllocator{base: 0}\n}", "func TestFindUserById(t *testing.T) {\n\t_, mock, err := NewMock()\n\tif err != nil {\n\t\tfmt.Printf(\"error mock: \" + err.Error())\n\t}\n\n\t// simulate any sql driver behavior in tests, without needing a real database connection\n\tquery := \"select id, user_name, password from m_user where id = \\\\?\"\n\n\trows := sqlmock.NewRows([]string{\"id\", \"user_name\", \"password\"}).\n\t\tAddRow(user.ID, user.UserName, user.Password)\n\n\tmock.ExpectQuery(query).WithArgs(user.ID).WillReturnRows(rows)\n\t// ------------ end of mock ---------------\n\n\tassert.NotNil(t, user)\n}", "func TestAzureBlobGetAppsListShouldFailInvalidIdentity(t *testing.T) {\n\tctx := context.TODO()\n\tappFrameworkRef := enterpriseApi.AppFrameworkSpec{\n\t\tDefaults: enterpriseApi.AppSourceDefaultSpec{\n\t\t\tVolName: \"azure_vol1\",\n\t\t\tScope: enterpriseApi.ScopeLocal,\n\t\t},\n\t\tVolList: []enterpriseApi.VolumeSpec{\n\t\t\t{\n\t\t\t\tName: \"azure_vol1\",\n\t\t\t\tEndpoint: \"https://mystorageaccount.blob.core.windows.net\",\n\t\t\t\tPath: \"appscontainer1\",\n\t\t\t\tType: \"blob\",\n\t\t\t\tProvider: \"azure\",\n\t\t\t},\n\t\t},\n\t\tAppSources: []enterpriseApi.AppSourceSpec{\n\t\t\t{\n\t\t\t\tName: \"adminApps\",\n\t\t\t\tLocation: \"adminAppsRepo\",\n\t\t\t\tAppSourceDefaultSpec: enterpriseApi.AppSourceDefaultSpec{\n\t\t\t\t\tVolName: \"azure_vol1\",\n\t\t\t\t\tScope: enterpriseApi.ScopeLocal,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\t// Initialize clients\n\tazureBlobClient := &AzureBlobClient{}\n\tmclient := spltest.MockHTTPClient{}\n\n\t// Identity call return a token - that means AKS cluster has an identity configured.\n\twantRequest, _ := http.NewRequest(\"GET\", \"http://169.254.169.254/metadata/identity/oauth2/token?api-version=2021-10-01&resource=https%3A%2F%2Fstorage.azure.com%2F\", nil)\n\trespTokenData := &TokenResponse{\n\t\tAccessToken: \"acctoken\",\n\t\tClientID: \"ClientId\",\n\t}\n\tmrespdata, _ := json.Marshal(respTokenData)\n\tmclient.AddHandler(wantRequest, 200, string(mrespdata), nil)\n\n\t// Add mock for the azure rest call for list apps\n\twantRequest, _ = http.NewRequest(\"GET\", \"https://mystorageaccount.blob.core.windows.net/appscontainer1?prefix=adminAppsRepo&restype=container&comp=list&include=snapshots&include=metadata\", nil)\n\n\t// Expect the identity does not have authorization to access the buckets\n\tmclient.AddHandler(wantRequest, 403, \"identity not authorized\", nil)\n\n\t// Get App source and volume from spec\n\tappSource := appFrameworkRef.AppSources[0]\n\tvol, err := GetAppSrcVolume(ctx, appSource, &appFrameworkRef)\n\tif err != nil {\n\t\tt.Errorf(\"Unable to get volume for app source : %s\", appSource.Name)\n\t}\n\n\t// Update the GetRemoteDataClient function pointer\n\tgetClientWrapper := RemoteDataClientsMap[vol.Provider]\n\tgetClientWrapper.SetRemoteDataClientFuncPtr(ctx, vol.Provider, NewMockAzureBlobClient)\n\n\t// Update the GetRemoteDataClientInit function pointer\n\tinitFn := func(ctx context.Context, region, accessKeyID, secretAccessKey string) interface{} {\n\t\treturn &mclient\n\t}\n\tgetClientWrapper.SetRemoteDataClientInitFuncPtr(ctx, vol.Provider, initFn)\n\n\t// Init azure blob client\n\tgetRemoteDataClientFn := getClientWrapper.GetRemoteDataClientInitFuncPtr(ctx)\n\tazureBlobClient.HTTPClient = getRemoteDataClientFn(ctx, \"us-west-2\", \"abcd\", \"1234\").(*spltest.MockHTTPClient)\n\tazureBlobClient.BucketName = vol.Path\n\tazureBlobClient.Prefix = appSource.Location\n\tazureBlobClient.Endpoint = vol.Endpoint\n\n\trespList, err := azureBlobClient.GetAppsList(ctx)\n\tif err == nil {\n\t\tt.Errorf(\"GetAppsList should return err\")\n\t}\n\n\tif err.Error() != \"error authorizing the rest call. check your IAM/secret configuration\" {\n\t\tt.Errorf(\"GetAppsList should return authorization error\")\n\t}\n\n\t// authorizing the rest call. check your IAM/secret configuration\n\n\tif len(respList.Objects) != 0 {\n\t\tt.Errorf(\"GetAppsList should not return any response objects\")\n\t}\n\tmclient.RemoveHandlers()\n}", "func (m *MockVerifier) Verify(arg0 context.Context, arg1, arg2 string) (*oidc.IDTokenClaims, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Verify\", arg0, arg1, arg2)\n\tret0, _ := ret[0].(*oidc.IDTokenClaims)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *GraphBaseServiceClient) Identity()(*i79ca23a9ac0659e1330dd29e049fe157787d5af6695ead2ff8263396db68d027.IdentityRequestBuilder) {\n return i79ca23a9ac0659e1330dd29e049fe157787d5af6695ead2ff8263396db68d027.NewIdentityRequestBuilderInternal(m.pathParameters, m.requestAdapter);\n}", "func (m *GraphBaseServiceClient) Identity()(*i79ca23a9ac0659e1330dd29e049fe157787d5af6695ead2ff8263396db68d027.IdentityRequestBuilder) {\n return i79ca23a9ac0659e1330dd29e049fe157787d5af6695ead2ff8263396db68d027.NewIdentityRequestBuilderInternal(m.pathParameters, m.requestAdapter);\n}", "func (m *MockSession) ID() sig_mgmt.SessionType {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ID\")\n\tret0, _ := ret[0].(sig_mgmt.SessionType)\n\treturn ret0\n}", "func fakeAuthState() *authtest.FakeState {\n\treturn &authtest.FakeState{\n\t\tIdentity: \"user:user@example.com\",\n\t\tIdentityPermissions: []authtest.RealmPermission{\n\t\t\t{\n\t\t\t\tRealm: \"@internal:test-proj/cas-read-only\",\n\t\t\t\tPermission: permMintToken,\n\t\t\t},\n\t\t},\n\t}\n}", "func TestCreateIdentity(t *testing.T) {\r\n\r\n\tt.Parallel()\r\n\r\n\tvar (\r\n\t\t// Testing private methods\r\n\t\ttests = []struct {\r\n\t\t\tinputPrivateKey string\r\n\t\t\tinputIDKey string\r\n\t\t\tinputCounter uint32\r\n\t\t\texpectedTxID string\r\n\t\t\texpectedNil bool\r\n\t\t\texpectedError bool\r\n\t\t}{\r\n\t\t\t{\r\n\t\t\t\tprivateKey,\r\n\t\t\t\tidKey,\r\n\t\t\t\t0,\r\n\t\t\t\t\"d2384b0946b8c3137bc0bf12d122efb8b77be998118b65c21448864234188f20\",\r\n\t\t\t\tfalse,\r\n\t\t\t\tfalse,\r\n\t\t\t},\r\n\t\t\t{\r\n\t\t\t\t\"\",\r\n\t\t\t\tidKey,\r\n\t\t\t\t0,\r\n\t\t\t\t\"49957864306b123c3cca8711635ba88890bb334eb3e9f21553b118eb4d66cc62\",\r\n\t\t\t\ttrue,\r\n\t\t\t\ttrue,\r\n\t\t\t},\r\n\t\t\t{\r\n\t\t\t\t\"invalid-key\",\r\n\t\t\t\tidKey,\r\n\t\t\t\t0,\r\n\t\t\t\t\"49957864306b123c3cca8711635ba88890bb334eb3e9f21553b118eb4d66cc62\",\r\n\t\t\t\ttrue,\r\n\t\t\t\ttrue,\r\n\t\t\t},\r\n\t\t\t{\r\n\t\t\t\tprivateKey,\r\n\t\t\t\t\"\",\r\n\t\t\t\t0,\r\n\t\t\t\t\"49957864306b123c3cca8711635ba88890bb334eb3e9f21553b118eb4d66cc62\",\r\n\t\t\t\ttrue,\r\n\t\t\t\ttrue,\r\n\t\t\t},\r\n\t\t\t{\r\n\t\t\t\tprivateKey,\r\n\t\t\t\tidKey,\r\n\t\t\t\t1,\r\n\t\t\t\t\"4f00a4c6bca4a538ecce849b19188222aeb0d28e7b0c9acdb0c20fe9de628f9e\",\r\n\t\t\t\tfalse,\r\n\t\t\t\tfalse,\r\n\t\t\t},\r\n\t\t\t{\r\n\t\t\t\tprivateKey,\r\n\t\t\t\tidKey,\r\n\t\t\t\t100,\r\n\t\t\t\t\"0b61af0cfd6331731b7f897b051a56a903928c6bcff8ba59cdd4b8d0093b12ae\",\r\n\t\t\t\tfalse,\r\n\t\t\t\tfalse,\r\n\t\t\t},\r\n\t\t}\r\n\t)\r\n\r\n\t// Run tests\r\n\tfor _, test := range tests {\r\n\t\tif tx, err := CreateIdentity(test.inputPrivateKey, test.inputIDKey, test.inputCounter); err != nil && !test.expectedError {\r\n\t\t\tt.Errorf(\"%s Failed: [%s] [%s] [%d] inputted and error not expected but got: %s\", t.Name(), test.inputPrivateKey, test.inputIDKey, test.inputCounter, err.Error())\r\n\t\t} else if err == nil && test.expectedError {\r\n\t\t\tt.Errorf(\"%s Failed: [%s] [%s] [%d] inputted and error was expected\", t.Name(), test.inputPrivateKey, test.inputIDKey, test.inputCounter)\r\n\t\t} else if tx == nil && !test.expectedNil {\r\n\t\t\tt.Errorf(\"%s Failed: [%s] [%s] [%d] inputted and nil was not expected\", t.Name(), test.inputPrivateKey, test.inputIDKey, test.inputCounter)\r\n\t\t} else if tx != nil && test.expectedNil {\r\n\t\t\tt.Errorf(\"%s Failed: [%s] [%s] [%d] inputted and nil was expected\", t.Name(), test.inputPrivateKey, test.inputIDKey, test.inputCounter)\r\n\t\t} else if tx != nil && tx.GetTxID() != test.expectedTxID {\r\n\t\t\tt.Errorf(\"%s Failed: [%s] [%s] [%d] inputted and expected [%s] but got [%s]\", t.Name(), test.inputPrivateKey, test.inputIDKey, test.inputCounter, test.expectedTxID, tx.GetTxID())\r\n\t\t}\r\n\t}\r\n}", "func (mr *MockClientMockRecorder) IdentityManager(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"IdentityManager\", reflect.TypeOf((*MockClient)(nil).IdentityManager), arg0)\n}", "func (suite *SubscriptionsTestSuite) mockClientAuth(account *accounts.Account) {\n\t// Mock GetConfig call to return the config object\n\tsuite.accountsServiceMock.On(\"GetConfig\").Return(suite.cnf)\n\n\t// Mock GetOauthService to return a mock oauth service\n\tsuite.accountsServiceMock.On(\"GetOauthService\").Return(suite.oauthServiceMock)\n\n\t// Mock AuthClient to return a mock client\n\tsuite.oauthServiceMock.On(\"AuthClient\", \"test_client_1\", \"test_secret\").\n\t\tReturn(account.OauthClient, nil)\n\n\t// Mock FindAccountByOauthClientID to return the wanted account\n\tsuite.accountsServiceMock.\n\t\tOn(\"FindAccountByOauthClientID\", account.OauthClient.ID).\n\t\tReturn(account, nil)\n}", "func (m *MockRepository) GetUsersFromIDs(arg0 []uuid.UUID) ([]user.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUsersFromIDs\", arg0)\n\tret0, _ := ret[0].([]user.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func NewIdentityProvider() users.IdentityProvider {\n\treturn &identityProviderMock{}\n}", "func (m *MockManagerClient) CreateManagerOnServer(userId, companyId int64) (*manager_grpc.Manager, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"CreateManagerOnServer\", userId, companyId)\n\tret0, _ := ret[0].(*manager_grpc.Manager)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockAuthGateway) GetUserByID(arg0 int64) (entity.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUserByID\", arg0)\n\tret0, _ := ret[0].(entity.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func TestAuthenticate_Fail(t *testing.T) {\n\tdb, mock, err := sqlmock.New()\n\tif err != nil {\n\t\tt.Fatalf(\"an error '%s' was not expected when opening a stub database connection\", err)\n\t}\n\tdefer db.Close()\n\n\tuser := models.User{\n\t\tID: 1,\n\t\tEmail: \"personia@personio.com\",\n\t\tPassword: \"personia\",\n\t}\n\n\tvar buffer bytes.Buffer\n\tbuffer.WriteString(constants.LoginDetailsSelectQuery)\n\n\trows := sqlmock.NewRows([]string{\"id\", \"email\"})\n\tmock.ExpectQuery(regexp.QuoteMeta(buffer.String())).WithArgs(user.Email, user.Password).WillReturnRows(rows)\n\n\tloginRepository := NewLoginRepository(db)\n\n\tloginModel := &models.Login{\n\t\tEmail: \"personia@personio.com\",\n\t\tPassword: \"personia\",\n\t}\n\n\tcntx := context.Background()\n\t_, err = loginRepository.Authenticate(cntx, loginModel)\n\tassert.NotNil(t, err)\n}", "func (m *MockStream) ID() uint64 {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ID\")\n\tret0, _ := ret[0].(uint64)\n\treturn ret0\n}", "func (m *MockidentityService) Get() (identity.Caller, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Get\")\n\tret0, _ := ret[0].(identity.Caller)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (rest *TestTokenStorageREST) TestRetrieveExternalTokenIdentityNotPresent() {\n\t// using an Identity which does not exist in the database.\n\tidentity := account.Identity{\n\t\tID: uuid.NewV4(),\n\t\tUsername: \"TestDeveloper\",\n\t}\n\n\tservice, controller := rest.SecuredControllerWithIdentity(identity)\n\ttest.RetrieveTokenUnauthorized(rest.T(), service.Context, service, controller, \"https://github.com/a/b\", nil)\n\ttest.RetrieveTokenUnauthorized(rest.T(), service.Context, service, controller, \"github\", nil)\n\ttest.RetrieveTokenUnauthorized(rest.T(), service.Context, service, controller, \"https://api.starter-us-east-2.openshift.com\", nil)\n\ttest.RetrieveTokenUnauthorized(rest.T(), service.Context, service, controller, \"openshift\", nil)\n}", "func (m *MockConn) UserID() uint64 {\n\tret := m.ctrl.Call(m, \"UserID\")\n\tret0, _ := ret[0].(uint64)\n\treturn ret0\n}", "func MockOpenIDConnect(t *testing.T) string {\n\tconst discovery = `{\n\t\t\"issuer\": \"https://example.com/\",\n\t\t\"authorization_endpoint\": \"https://example.com/authorize\",\n\t\t\"token_endpoint\": \"https://example.com/token\",\n\t\t\"userinfo_endpoint\": \"https://example.com/userinfo\",\n\t\t\"jwks_uri\": \"https://example.com/.well-known/jwks.json\",\n\t\t\"scopes_supported\": [\n\t\t\t\"pets_read\",\n\t\t\t\"pets_write\",\n\t\t\t\"admin\"\n\t\t],\n\t\t\"response_types_supported\": [\n\t\t\t\"code\",\n\t\t\t\"id_token\",\n\t\t\t\"token id_token\"\n\t\t],\n\t\t\"token_endpoint_auth_methods_supported\": [\n\t\t\t\"client_secret_basic\"\n\t\t]\n\t}`\n\tsrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tw.WriteHeader(http.StatusOK)\n\t\t_, err := w.Write([]byte(discovery))\n\t\trequire.NoError(t, err)\n\t}))\n\tt.Cleanup(func() {\n\t\tsrv.Close()\n\t})\n\treturn srv.URL + \"/.well-known/openid-configuration\"\n}", "func FakeManager(failingControllers int) *Manager {\n\tm := &Manager{\n\t\tcontrollers: controllerMap{},\n\t}\n\n\tfor i := 0; i < failingControllers; i++ {\n\t\tctrl := &managedController{\n\t\t\tcontroller: controller{\n\t\t\t\tname: fmt.Sprintf(\"controller-%d\", i),\n\t\t\t\tuuid: fmt.Sprintf(\"%d\", i),\n\t\t\t\tstop: make(chan struct{}),\n\t\t\t\tupdate: make(chan ControllerParams, 1),\n\t\t\t\ttrigger: make(chan struct{}, 1),\n\t\t\t\tterminated: make(chan struct{}),\n\t\t\t\tlastError: fmt.Errorf(\"controller failed\"),\n\t\t\t\tfailureCount: 1,\n\t\t\t\tconsecutiveErrors: 1,\n\t\t\t},\n\t\t}\n\n\t\tctrl.params.Context, ctrl.cancelDoFunc = context.WithCancel(context.Background())\n\t\tm.controllers[ctrl.name] = ctrl\n\t}\n\n\treturn m\n}", "func mockedGranter(kubeutil *kube.Kube, app *v1.RadixRegistration, namespace string, serviceAccount *corev1.ServiceAccount) error {\n\treturn nil\n}", "func (mmForID *mAtomicRecordStorageMockForID) Expect(ctx context.Context, id insolar.ID) *mAtomicRecordStorageMockForID {\n\tif mmForID.mock.funcForID != nil {\n\t\tmmForID.mock.t.Fatalf(\"AtomicRecordStorageMock.ForID mock is already set by Set\")\n\t}\n\n\tif mmForID.defaultExpectation == nil {\n\t\tmmForID.defaultExpectation = &AtomicRecordStorageMockForIDExpectation{}\n\t}\n\n\tmmForID.defaultExpectation.params = &AtomicRecordStorageMockForIDParams{ctx, id}\n\tfor _, e := range mmForID.expectations {\n\t\tif minimock.Equal(e.params, mmForID.defaultExpectation.params) {\n\t\t\tmmForID.mock.t.Fatalf(\"Expectation set by When has same params: %#v\", *mmForID.defaultExpectation.params)\n\t\t}\n\t}\n\n\treturn mmForID\n}", "func NewIdentityManager(orgName string, userStore msp.UserStore, cryptoSuite core.CryptoSuite, endpointConfig fab.EndpointConfig) (*IdentityManager, error) {\n\n\tnetConfig := endpointConfig.NetworkConfig()\n\t// viper keys are case insensitive\n\torgConfig, ok := netConfig.Organizations[strings.ToLower(orgName)]\n\tif !ok {\n\t\treturn nil, errors.New(\"org config retrieval failed\")\n\t}\n\n\tif orgConfig.CryptoPath == \"\" && len(orgConfig.Users) == 0 {\n\t\treturn nil, errors.New(\"Either a cryptopath or an embedded list of users is required\")\n\t}\n\n\tvar mspPrivKeyStore core.KVStore\n\tvar mspCertStore core.KVStore\n\n\torgCryptoPathTemplate := orgConfig.CryptoPath\n\tif orgCryptoPathTemplate != \"\" {\n\t\tvar err error\n\t\tif !filepath.IsAbs(orgCryptoPathTemplate) {\n\t\t\torgCryptoPathTemplate = filepath.Join(endpointConfig.CryptoConfigPath(), orgCryptoPathTemplate)\n\t\t}\n\t\tmspPrivKeyStore, err = NewFileKeyStore(orgCryptoPathTemplate)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"creating a private key store failed\")\n\t\t}\n\t\tmspCertStore, err = NewFileCertStore(orgCryptoPathTemplate)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"creating a cert store failed\")\n\t\t}\n\t} else {\n\t\tlogger.Warnf(\"Cryptopath not provided for organization [%s], MSP stores not created\", orgName)\n\t}\n\n\tmgr := &IdentityManager{\n\t\torgName: orgName,\n\t\torgMSPID: orgConfig.MSPID,\n\t\tconfig: endpointConfig,\n\t\tcryptoSuite: cryptoSuite,\n\t\tmspPrivKeyStore: mspPrivKeyStore,\n\t\tmspCertStore: mspCertStore,\n\t\tembeddedUsers: orgConfig.Users,\n\t\tuserStore: userStore,\n\t\t// CA Client state is created lazily, when (if) needed\n\t}\n\treturn mgr, nil\n}", "func (m *MockInterface) InitializeAuthorizers() error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"InitializeAuthorizers\")\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func TestOAuth2ClientCredentialsCache(t *testing.T) {\n\t// Setup\n\tmockCtrl := gomock.NewController(t)\n\tdefer mockCtrl.Finish()\n\n\t// Mock mockTokenProvider\n\tmockTokenProvider := mock.NewMockTokenProviderInterface(mockCtrl)\n\n\tgomock.InOrder(\n\t\t// First call returning abc and Bearer, expires within 1 second\n\t\tmockTokenProvider.\n\t\t\tEXPECT().\n\t\t\tGetToken(gomock.Any()).\n\t\t\tReturn(&oauth2.Token{\n\t\t\t\tAccessToken: \"abc\",\n\t\t\t\tTokenType: \"Bearer\",\n\t\t\t\tExpiry: time.Now().In(time.UTC).Add(1 * time.Second),\n\t\t\t}, nil).\n\t\t\tTimes(1),\n\t\t// Second call returning def and MAC, expires within 1 second\n\t\tmockTokenProvider.\n\t\t\tEXPECT().\n\t\t\tGetToken(gomock.Any()).\n\t\t\tReturn(&oauth2.Token{\n\t\t\t\tAccessToken: \"def\",\n\t\t\t\tTokenType: \"MAC\",\n\t\t\t\tExpiry: time.Now().In(time.UTC).Add(1 * time.Second),\n\t\t\t}, nil).\n\t\t\tTimes(1),\n\t)\n\n\t// Specify components metadata\n\tvar metadata middleware.Metadata\n\tmetadata.Properties = map[string]string{\n\t\t\"clientID\": \"testId\",\n\t\t\"clientSecret\": \"testSecret\",\n\t\t\"scopes\": \"ascope\",\n\t\t\"tokenURL\": \"https://localhost:9999\",\n\t\t\"headerName\": \"someHeader\",\n\t\t\"authStyle\": \"1\",\n\t}\n\n\t// Initialize middleware component and inject mocked TokenProvider\n\tlog := logger.NewLogger(\"oauth2clientcredentials.test\")\n\toauth2clientcredentialsMiddleware, _ := NewOAuth2ClientCredentialsMiddleware(log).(*Middleware)\n\toauth2clientcredentialsMiddleware.SetTokenProvider(mockTokenProvider)\n\thandler, err := oauth2clientcredentialsMiddleware.GetHandler(context.Background(), metadata)\n\trequire.NoError(t, err)\n\n\t// First handler call should return abc Token\n\tr := httptest.NewRequest(http.MethodGet, \"http://dapr.io\", nil)\n\tw := httptest.NewRecorder()\n\thandler(http.HandlerFunc(mockedRequestHandler)).ServeHTTP(w, r)\n\n\t// Assertion\n\tassert.Equal(t, \"Bearer abc\", r.Header.Get(\"someHeader\"))\n\n\t// Second handler call should still return 'cached' abc Token\n\tr = httptest.NewRequest(http.MethodGet, \"http://dapr.io\", nil)\n\tw = httptest.NewRecorder()\n\thandler(http.HandlerFunc(mockedRequestHandler)).ServeHTTP(w, r)\n\n\t// Assertion\n\tassert.Equal(t, \"Bearer abc\", r.Header.Get(\"someHeader\"))\n\n\t// Wait at a second to invalidate cache entry for abc\n\ttime.Sleep(1 * time.Second)\n\n\t// Third call should return def Token\n\tr = httptest.NewRequest(http.MethodGet, \"http://dapr.io\", nil)\n\tw = httptest.NewRecorder()\n\thandler(http.HandlerFunc(mockedRequestHandler)).ServeHTTP(w, r)\n\n\t// Assertion\n\tassert.Equal(t, \"MAC def\", r.Header.Get(\"someHeader\"))\n}", "func TestOsIdmAll(t *testing.T) {\n\tidm := osidm.New()\n\n\tsidm := test.NewSuiteIdm(t, idm)\n\tsidm.TestAll(t)\n}", "func (m *MockUserService) Authenticate(tx *sqlx.Tx, username, password string) (int64, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Authenticate\", tx, username, password)\n\tret0, _ := ret[0].(int64)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockDatabase) GetUsersID() ([]uint64, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUsersID\")\n\tret0, _ := ret[0].([]uint64)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (_m *MockRepository) CreateEmailIdentity(identity models.Identity, executor database.QueryExecutor) (*models.Identity, error) {\n\tret := _m.Called(identity, executor)\n\n\tvar r0 *models.Identity\n\tif rf, ok := ret.Get(0).(func(models.Identity, database.QueryExecutor) *models.Identity); ok {\n\t\tr0 = rf(identity, executor)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*models.Identity)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(models.Identity, database.QueryExecutor) error); ok {\n\t\tr1 = rf(identity, executor)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func TestDbInterfaceMethods(t *testing.T) {\n\ttestUser := models.User{\n\t\tAccount: models.Account{\n\t\t\tType: \"email\",\n\t\t\tAccountID: \"test@test.com\",\n\t\t\tPassword: \"testhashedpassword-youcantreadme\",\n\t\t},\n\t\tRoles: []string{\"TEST\"},\n\t\tTimestamps: models.Timestamps{\n\t\t\tCreatedAt: time.Now().Unix(),\n\t\t},\n\t}\n\n\tt.Run(\"Testing create user\", func(t *testing.T) {\n\t\tid, err := testDBService.AddUser(testInstanceID, testUser)\n\t\tif err != nil {\n\t\t\tt.Errorf(err.Error())\n\t\t\treturn\n\t\t}\n\t\tif len(id) == 0 {\n\t\t\tt.Errorf(\"id is missing\")\n\t\t\treturn\n\t\t}\n\t\t_id, _ := primitive.ObjectIDFromHex(id)\n\t\ttestUser.ID = _id\n\t})\n\n\tt.Run(\"Testing creating existing user\", func(t *testing.T) {\n\t\ttestUser2 := testUser\n\t\ttestUser2.Roles = []string{\"TEST2\"}\n\t\t_, err := testDBService.AddUser(testInstanceID, testUser2)\n\t\tif err == nil {\n\t\t\tt.Errorf(\"user already existed, but created again\")\n\t\t\treturn\n\t\t}\n\t\tu, e := testDBService.GetUserByAccountID(testInstanceID, testUser2.Account.AccountID)\n\t\tif e != nil {\n\t\t\tt.Errorf(e.Error())\n\t\t\treturn\n\t\t}\n\t\tif len(u.Roles) > 0 && u.Roles[0] == \"TEST2\" {\n\t\t\tt.Error(\"user should not be updated\")\n\t\t}\n\t})\n\n\tt.Run(\"Testing find existing user by id\", func(t *testing.T) {\n\t\tuser, err := testDBService.GetUserByID(testInstanceID, testUser.ID.Hex())\n\t\tif err != nil {\n\t\t\tt.Errorf(err.Error())\n\t\t\treturn\n\t\t}\n\t\tif user.Account.AccountID != testUser.Account.AccountID {\n\t\t\tt.Errorf(\"found user is not matching test user\")\n\t\t\treturn\n\t\t}\n\t})\n\n\tt.Run(\"Testing find not existing user by id\", func(t *testing.T) {\n\t\t_, err := testDBService.GetUserByID(testInstanceID, testUser.ID.Hex()+\"1\")\n\t\tif err == nil {\n\t\t\tt.Errorf(\"user should not be found\")\n\t\t\treturn\n\t\t}\n\t})\n\n\tt.Run(\"Testing find existing user by email\", func(t *testing.T) {\n\t\tuser, err := testDBService.GetUserByAccountID(testInstanceID, testUser.Account.AccountID)\n\t\tif err != nil {\n\t\t\tt.Errorf(err.Error())\n\t\t\treturn\n\t\t}\n\t\tif user.Account.AccountID != testUser.Account.AccountID {\n\t\t\tt.Errorf(\"found user is not matching test user\")\n\t\t\treturn\n\t\t}\n\t})\n\n\tt.Run(\"Testing find not existing user by email\", func(t *testing.T) {\n\t\t_, err := testDBService.GetUserByAccountID(testInstanceID, testUser.Account.AccountID+\"1\")\n\t\tif err == nil {\n\t\t\tt.Errorf(\"user should not be found\")\n\t\t\treturn\n\t\t}\n\t})\n\n\tt.Run(\"Testing updating existing user's attributes\", func(t *testing.T) {\n\t\ttestUser.Account.AccountConfirmedAt = time.Now().Unix()\n\t\t_, err := testDBService.UpdateUser(testInstanceID, testUser)\n\t\tif err != nil {\n\t\t\tt.Errorf(err.Error())\n\t\t\treturn\n\t\t}\n\t})\n\n\tt.Run(\"Testing updating not existing user's attributes\", func(t *testing.T) {\n\t\ttestUser.Account.AccountConfirmedAt = time.Now().Unix()\n\t\tcurrentUser := testUser\n\t\twrongID := testUser.ID.Hex()[:len(testUser.ID.Hex())-2] + \"00\"\n\t\tid, err := primitive.ObjectIDFromHex(wrongID)\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t\treturn\n\t\t}\n\t\tcurrentUser.ID = id\n\t\t_, err = testDBService.UpdateUser(testInstanceID, currentUser)\n\t\tif err == nil {\n\t\t\tt.Errorf(\"cannot update not existing user\")\n\t\t\treturn\n\t\t}\n\t})\n\n\tt.Run(\"Testing counting recently added users\", func(t *testing.T) {\n\t\tcount, err := testDBService.CountRecentlyCreatedUsers(testInstanceID, 20)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"unexpected error: %v\", err)\n\t\t\treturn\n\n\t\t}\n\t\tlogger.Debug.Println(count)\n\t\tif count < 1 {\n\t\t\tt.Error(\"at least one user should be found\")\n\t\t}\n\t})\n\n\tt.Run(\"Testing deleting existing user\", func(t *testing.T) {\n\t\terr := testDBService.DeleteUser(testInstanceID, testUser.ID.Hex())\n\t\tif err != nil {\n\t\t\tt.Errorf(err.Error())\n\t\t\treturn\n\t\t}\n\t})\n\n\tt.Run(\"Testing deleting not existing user\", func(t *testing.T) {\n\t\terr := testDBService.DeleteUser(testInstanceID, testUser.ID.Hex()+\"1\")\n\t\tif err == nil {\n\t\t\tt.Errorf(\"user should not be found - error expected\")\n\t\t\treturn\n\t\t}\n\t})\n}", "func (m *MockAccessToken) Create(token api.AccessToken) (api.AccessToken, error) {\n\tret := m.ctrl.Call(m, \"Create\", token)\n\tret0, _ := ret[0].(api.AccessToken)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func mockAuthenticationComponent(log *zap.Logger, serviceName string) *AuthenticationComponent {\n\thttpTimeout := 300 * time.Millisecond\n\n\treturn NewAuthenticationComponent(&AuthenticationParams{\n\t\tAuthConfig: &core_auth_sdk.Config{\n\t\t\tIssuer: issuer,\n\t\t\tPrivateBaseURL: privateBaseUrl,\n\t\t\tAudience: audience,\n\t\t\tUsername: username,\n\t\t\tPassword: password,\n\t\t\tKeychainTTL: 0,\n\t\t},\n\t\tAuthConnectionConfig: &core_auth_sdk.RetryConfig{\n\t\t\tMaxRetries: 1,\n\t\t\tMinRetryWaitTime: 200 * time.Millisecond,\n\t\t\tMaxRetryWaitTime: 300 * time.Millisecond,\n\t\t\tRequestTimeout: 500 * time.Millisecond,\n\t\t},\n\t\tLogger: log,\n\t\tOrigin: origin,\n\t}, serviceName, httpTimeout)\n}", "func FakeManager(failingControllers int) *Manager {\n\tm := &Manager{\n\t\tcontrollers: controllerMap{},\n\t}\n\n\tfor i := 0; i < failingControllers; i++ {\n\t\tctrl := &Controller{\n\t\t\tname: fmt.Sprintf(\"controller-%d\", i),\n\t\t\tuuid: fmt.Sprintf(\"%d\", i),\n\t\t\tstop: make(chan struct{}),\n\t\t\tupdate: make(chan struct{}, 1),\n\t\t\ttrigger: make(chan struct{}, 1),\n\t\t\tterminated: make(chan struct{}),\n\t\t\tlastError: fmt.Errorf(\"controller failed\"),\n\t\t\tfailureCount: 1,\n\t\t\tconsecutiveErrors: 1,\n\t\t}\n\n\t\tctrl.ctxDoFunc, ctrl.cancelDoFunc = context.WithCancel(context.Background())\n\t\tm.controllers[ctrl.name] = ctrl\n\t}\n\n\treturn m\n}", "func (m *MockDelegateActor) AuthenticateGetInbox(c context.Context, w http.ResponseWriter, r *http.Request) (context.Context, bool, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"AuthenticateGetInbox\", c, w, r)\n\tret0, _ := ret[0].(context.Context)\n\tret1, _ := ret[1].(bool)\n\tret2, _ := ret[2].(error)\n\treturn ret0, ret1, ret2\n}", "func MockOnGetManagerVirtualMedia(ctx context.Context, mockAPI *redfishMocks.RedfishAPI,\n\tmanagerID string, virtualMediaID string, virtualMedia redfishClient.VirtualMedia,\n\thttpResponse *http.Response, err error) {\n\tmediaRequest := redfishClient.ApiGetManagerVirtualMediaRequest{}\n\tmockAPI.On(\"GetManagerVirtualMedia\", ctx, managerID, virtualMediaID).Return(mediaRequest).Times(1)\n\tmockAPI.On(\"GetManagerVirtualMediaExecute\", mock.Anything).Return(virtualMedia, httpResponse, err).Times(1)\n}", "func (m *MockCAClient) GetIdentity(arg0, arg1 string) (*api.IdentityResponse, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetIdentity\", arg0, arg1)\n\tret0, _ := ret[0].(*api.IdentityResponse)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func TestManager(t *testing.T) {\n\tsuite.Run(t, &TestManagerSuite{})\n}", "func newAuthorizationMocks(t *testing.T, resource, action string) (\n\tauthn.AuthenticationServiceClient, authz.AuthorizationServiceClient) {\n\tvar (\n\t\tctrl = gomock.NewController(t)\n\t\tmockAuthClient = authn.NewMockAuthenticationServiceClient(ctrl)\n\t\tmockAuthzClient = authz.NewMockAuthorizationServiceClient(ctrl)\n\t)\n\n\t// Mocking AuthN Calls\n\tmockAuthClient.EXPECT().Authenticate(gomock.Any(), gomock.Any()).DoAndReturn(\n\t\tfunc(_ context.Context, _ *authn.AuthenticateRequest) (*authn.AuthenticateResponse, error) {\n\t\t\treturn &authn.AuthenticateResponse{Subject: \"mock\", Teams: []string{}}, nil\n\t\t})\n\n\t// Mocking AuthZ Calls\n\tmockAuthzClient.EXPECT().ProjectsAuthorized(\n\t\tgomock.Any(),\n\t\t&authz.ProjectsAuthorizedReq{\n\t\t\tSubjects: []string{\"mock\"},\n\t\t\tResource: resource,\n\t\t\tAction: action,\n\t\t\tProjectsFilter: []string{},\n\t\t},\n\t).DoAndReturn(\n\t\tfunc(_ context.Context, _ *authz.ProjectsAuthorizedReq) (*authz.ProjectsAuthorizedResp, error) {\n\t\t\treturn &authz.ProjectsAuthorizedResp{Projects: []string{\"any\"}}, nil\n\t\t},\n\t)\n\n\treturn mockAuthClient, mockAuthzClient\n}", "func (m *MockDao) UID(steamID int64) (*model.Info, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"UID\", steamID)\n\tret0, _ := ret[0].(*model.Info)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func TestAssetSysCC_InvalidateToken(t *testing.T) {\n\n\tfmt.Println(\"-----------------------------------\")\n\tfmt.Println(\"Test3: invalidateToken\")\n\n\t//fmt.Println(\"******test string to big.newInt\")\n\t//str := \"12321\"\n\t//strInt := big.NewInt(0)\n\t//strInt.SetString(str,10)\n\t//fmt.Println(strInt.String())\n\t//fmt.Println(\"*******************************\")\n\n\tascc := new(AssetSysCC)\n\tstub := shim.NewMockStub(\"ascc\", ascc)\n\tcheckInit(t, stub, [][]byte{[]byte(\"\")})\n\n\tres_test3 := stub.MockInvoke(\"1\", [][]byte{[]byte(\"issueToken\"), []byte(\"SSToken\"), []byte(\"250\"), []byte(\"18\"), []byte(MAddress[:])})\n\n\tif res_test3.Status != shim.OK {\n\t\tfmt.Println(\"Register token failed\", string(res_test3.Message))\n\t\tt.FailNow()\n\t}\n\n\t////query token quantity\n\t//res1 := stub.MockInvoke(\"2\", [][]byte{[]byte(\"getBalance\"), []byte(MAddress[:]), []byte(\"SSToken\")});\n\t//if res1.Status != shim.OK {\n\t//\tfmt.Println(\"Query failed\", string(res1.Message))\n\t//\tt.FailNow()\n\t//}\n\t//amount,_ := strconv.Atoi(string(res1.Payload))\n\t//if amount != 250 {\n\t//\tfmt.Printf(\"Query result error! %v\", amount )\n\t//\tt.FailNow()\n\t//}\n\n\t//beging to invalidate this token\n\tcheckQueryInfo(t, stub, [][]byte{[]byte(\"getTokenInfo\"), []byte(\"SSToken\")})\n\n\ttestInvalidate := stub.MockInvoke(\"4\", [][]byte{[]byte(\"invalidateToken\"), []byte(\"SSToken\")});\n\tif testInvalidate.Status != shim.OK {\n\t\tfmt.Println(\"Query failed\", string(testInvalidate.Message))\n\t\tt.FailNow()\n\t}\n\n\tcheckQueryInfo(t, stub, [][]byte{[]byte(\"getTokenInfo\"), []byte(\"SSToken\")})\n}", "func (m *MockOauthAccessTokenRepository) Create(ktx kontext.Context, data entity.OauthAccessTokenInsertable, tx db.TX) (int, exception.Exception) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Create\", ktx, data, tx)\n\tret0, _ := ret[0].(int)\n\tret1, _ := ret[1].(exception.Exception)\n\treturn ret0, ret1\n}", "func (mr *MockProvidersMockRecorder) IdentityManager(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"IdentityManager\", reflect.TypeOf((*MockProviders)(nil).IdentityManager), arg0)\n}", "func (m *MockStore) GetUserById(arg0 context.Context, arg1 uuid.UUID) (db.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUserById\", arg0, arg1)\n\tret0, _ := ret[0].(db.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockCandidatePropertyGetter) Id() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Id\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func (m *CommunicationsIdentitySet) SetAssertedIdentity(value Identityable)() {\n err := m.GetBackingStore().Set(\"assertedIdentity\", value)\n if err != nil {\n panic(err)\n }\n}", "func (m *MockUsersRepoInterface) Authorize(arg0, arg1 string) (*user.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Authorize\", arg0, arg1)\n\tret0, _ := ret[0].(*user.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func TestMemIdmAll(t *testing.T) {\n\tidm := memidm.New()\n\tsidm := test.NewSuiteIdm(t, idm)\n\tsidm.TestAll(t)\n}", "func (m *MockClient) SigningManager() core.SigningManager {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"SigningManager\")\n\tret0, _ := ret[0].(core.SigningManager)\n\treturn ret0\n}", "func InitializeMockAuthenticationComponent() *AuthenticationComponent {\n\tlogInstance := core_logging.New(\"info\")\n\tdefer logInstance.ConfigureLogger()\n\tlog := logInstance.Logger\n\n\treturn mockAuthenticationComponent(log, svcName)\n}", "func mockClientFactoryGenerator(setupFn ...func(c istioclient.Interface)) func() (istioclient.Interface, error) {\n\toutFactory := func() (istioclient.Interface, error) {\n\t\tc := kube.NewFakeClient().Istio()\n\t\tfor _, f := range setupFn {\n\t\t\tf(c)\n\t\t}\n\t\treturn c, nil\n\t}\n\n\treturn outFactory\n}", "func (m *MockCAClient) CreateIdentity(arg0 *api.IdentityRequest) (*api.IdentityResponse, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"CreateIdentity\", arg0)\n\tret0, _ := ret[0].(*api.IdentityResponse)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func TestAssetSysCC_IssueToken(t *testing.T) {\n\n\tfmt.Println(\"-----------------------------------\")\n\tfmt.Println(\"Test2: issueToken\")\n\n\tascc := new(AssetSysCC)\n\tstub := shim.NewMockStub(\"ascc\", ascc)\n\tcheckInit(t, stub, [][]byte{[]byte(\"\")})\n\n\n\tres_test2 := stub.MockInvoke(\"1\", [][]byte{[]byte(\"registerToken\"), []byte(\"SSToken\"), []byte(\"250\"), []byte(\"18\"), []byte(MAddress[:])})\n\n\tif res_test2.Status != shim.OK {\n\t\tfmt.Println(\"Register token failed\", string(res_test2.Message))\n\t\tt.FailNow()\n\t}\n\n\tres_test3 := stub.MockInvoke(\"1\", [][]byte{[]byte(\"issueToken\"), []byte(\"SSToken\"), []byte(\"250\"), []byte(\"18\"), []byte(MAddress[:])})\n\n\tif res_test3.Status != shim.OK {\n\t\tfmt.Println(\"Register token failed\", string(res_test3.Message))\n\t\tt.FailNow()\n\t}\n\tcheckQueryInfo(t, stub, [][]byte{[]byte(\"getTokenInfo\"), []byte(\"SSToken\")})\n\n\t////query token quantity\n\t//\tres1 := stub.MockInvoke(\"2\", [][]byte{[]byte(\"getBalance\"), []byte(MAddress[:]), []byte(\"SSToken\")});\n\t//\tif res1.Status != shim.OK {\n\t//\t\tfmt.Println(\"Query failed\", string(res1.Message))\n\t//\t\tt.FailNow()\n\t//\t}\n\t//\tamount,_ := strconv.Atoi(string(res1.Payload))\n\t//\tif amount != 250 {\n\t//\t\tfmt.Printf(\"Query result error! %v\", amount )\n\t//\t\tt.FailNow()\n\t//\t}\n\n\tfmt.Println(\"Test issueToken for a registered one Success!\")\n\n\tres_test4 := stub.MockInvoke(\"2\", [][]byte{[]byte(\"issueToken\"), []byte(\"MToken\"), []byte(\"888\"), []byte(\"20\"), []byte(testAddress[:])})\n\tif res_test4.Status != shim.OK {\n\t\tfmt.Println(\"Register token failed\", string(res_test3.Message))\n\t\tt.FailNow()\n\t}\n\tcheckQueryInfo(t, stub, [][]byte{[]byte(\"getTokenInfo\"), []byte(\"MToken\")})\n\n\t////query token quantity\n\t//res2 := stub.MockInvoke(\"2\", [][]byte{[]byte(\"getBalance\"), []byte(testAddress[:]), []byte(\"CMBToken\")});\n\t//if res1.Status != shim.OK {\n\t//\tfmt.Println(\"Query failed\", string(res2.Message))\n\t//\tt.FailNow()\n\t//}\n\t//amount2,_ := strconv.Atoi(string(res2.Payload))\n\t//if amount2 != 888 {\n\t//\tfmt.Printf(\"Query result error! %v\", amount2 )\n\t//\tt.FailNow()\n\t//}\n\n\tfmt.Println(\"Test issueToken for an un registered one Success!\")\n}", "func (mmForID *mStorageMockForID) Expect(ctx context.Context, pulse insolar.PulseNumber, recordID insolar.ID) *mStorageMockForID {\n\tif mmForID.mock.funcForID != nil {\n\t\tmmForID.mock.t.Fatalf(\"StorageMock.ForID mock is already set by Set\")\n\t}\n\n\tif mmForID.defaultExpectation == nil {\n\t\tmmForID.defaultExpectation = &StorageMockForIDExpectation{}\n\t}\n\n\tmmForID.defaultExpectation.params = &StorageMockForIDParams{ctx, pulse, recordID}\n\tfor _, e := range mmForID.expectations {\n\t\tif minimock.Equal(e.params, mmForID.defaultExpectation.params) {\n\t\t\tmmForID.mock.t.Fatalf(\"Expectation set by When has same params: %#v\", *mmForID.defaultExpectation.params)\n\t\t}\n\t}\n\n\treturn mmForID\n}", "func (m *MockAccessResponder) SetAccessToken(arg0 string) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"SetAccessToken\", arg0)\n}", "func (mmAuther *mGatewayMockAuther) Expect() *mGatewayMockAuther {\n\tif mmAuther.mock.funcAuther != nil {\n\t\tmmAuther.mock.t.Fatalf(\"GatewayMock.Auther mock is already set by Set\")\n\t}\n\n\tif mmAuther.defaultExpectation == nil {\n\t\tmmAuther.defaultExpectation = &GatewayMockAutherExpectation{}\n\t}\n\n\treturn mmAuther\n}", "func (m *MockUCAuth) GetByID(ctx context.Context, userID uint) (*models.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetByID\", ctx, userID)\n\tret0, _ := ret[0].(*models.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func TestAuthRequestGetters(t *testing.T) {\n\trunTest(t, func(s *res.Service) {\n\t\ts.Handle(\"model\", res.Auth(\"foo\", func(r res.AuthRequest) {\n\t\t\trestest.AssertEqualJSON(t, \"Method\", r.Method(), \"foo\")\n\t\t\trestest.AssertEqualJSON(t, \"CID\", r.CID(), mock.CID)\n\t\t\trestest.AssertEqualJSON(t, \"Header\", r.Header(), mock.Header)\n\t\t\trestest.AssertEqualJSON(t, \"Host\", r.Host(), mock.Host)\n\t\t\trestest.AssertEqualJSON(t, \"RemoteAddr\", r.RemoteAddr(), mock.RemoteAddr)\n\t\t\trestest.AssertEqualJSON(t, \"URI\", r.URI(), mock.URI)\n\t\t\tr.NotFound()\n\t\t}))\n\t}, func(s *restest.Session) {\n\t\ts.Auth(\"test.model\", \"foo\", nil).\n\t\t\tResponse().\n\t\t\tAssertError(res.ErrNotFound)\n\t})\n}", "func (mmGetByID *mPaymentRepositoryMockGetByID) Expect(ctx context.Context, id int64) *mPaymentRepositoryMockGetByID {\n\tif mmGetByID.mock.funcGetByID != nil {\n\t\tmmGetByID.mock.t.Fatalf(\"PaymentRepositoryMock.GetByID mock is already set by Set\")\n\t}\n\n\tif mmGetByID.defaultExpectation == nil {\n\t\tmmGetByID.defaultExpectation = &PaymentRepositoryMockGetByIDExpectation{}\n\t}\n\n\tmmGetByID.defaultExpectation.params = &PaymentRepositoryMockGetByIDParams{ctx, id}\n\tfor _, e := range mmGetByID.expectations {\n\t\tif minimock.Equal(e.params, mmGetByID.defaultExpectation.params) {\n\t\t\tmmGetByID.mock.t.Fatalf(\"Expectation set by When has same params: %#v\", *mmGetByID.defaultExpectation.params)\n\t\t}\n\t}\n\n\treturn mmGetByID\n}" ]
[ "0.6485713", "0.62010235", "0.60594493", "0.59081554", "0.5871026", "0.56601584", "0.55710304", "0.55710304", "0.5517578", "0.54584026", "0.5454241", "0.5450888", "0.54272795", "0.54178536", "0.5386579", "0.5373759", "0.5366716", "0.5348325", "0.5348325", "0.53374684", "0.53184766", "0.526019", "0.5187925", "0.5186036", "0.51803756", "0.51411355", "0.5134938", "0.51194453", "0.5113945", "0.51088315", "0.51037765", "0.50710183", "0.5064166", "0.50587714", "0.5057225", "0.5045967", "0.50422835", "0.50390327", "0.5013322", "0.5005937", "0.50021166", "0.499911", "0.49973473", "0.49803483", "0.4976903", "0.4976903", "0.49712214", "0.4951434", "0.4943098", "0.49349347", "0.49338442", "0.49198052", "0.49192414", "0.491123", "0.49093854", "0.49077988", "0.4906535", "0.48915085", "0.48858482", "0.48715866", "0.4862432", "0.48616114", "0.4856791", "0.48554894", "0.48543903", "0.48486477", "0.48466757", "0.48452756", "0.48430553", "0.48395836", "0.48364154", "0.48266608", "0.48234698", "0.48153293", "0.48120758", "0.48079056", "0.4803098", "0.4797482", "0.47956985", "0.47841594", "0.4775253", "0.47737193", "0.4769936", "0.47666356", "0.4759764", "0.47570384", "0.47567487", "0.47542664", "0.47480327", "0.47480235", "0.4745551", "0.47436145", "0.47431594", "0.4738007", "0.4737665", "0.47236526", "0.47233874", "0.47210532", "0.47185427", "0.47132775" ]
0.65093976
0
IdentityManager indicates an expected call of IdentityManager
func (mr *MockClientMockRecorder) IdentityManager(arg0 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "IdentityManager", reflect.TypeOf((*MockClient)(nil).IdentityManager), arg0) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (mr *MockProvidersMockRecorder) IdentityManager(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"IdentityManager\", reflect.TypeOf((*MockProviders)(nil).IdentityManager), arg0)\n}", "func (c *Provider) IdentityManager(orgName string) (msp.IdentityManager, bool) {\n\treturn c.idMgmtProvider.IdentityManager(orgName)\n}", "func (e AuthorizationFailedError) Identity() UserIdentityInfo { return e.identity }", "func (e AuthorizationDeniedError) Identity() UserIdentityInfo { return e.identity }", "func (mr *MockChoriaProviderMockRecorder) Identity() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Identity\", reflect.TypeOf((*MockChoriaProvider)(nil).Identity))\n}", "func (rest *TestTokenStorageREST) TestRetrieveExternalTokenIdentityNotPresent() {\n\t// using an Identity which does not exist in the database.\n\tidentity := account.Identity{\n\t\tID: uuid.NewV4(),\n\t\tUsername: \"TestDeveloper\",\n\t}\n\n\tservice, controller := rest.SecuredControllerWithIdentity(identity)\n\ttest.RetrieveTokenUnauthorized(rest.T(), service.Context, service, controller, \"https://github.com/a/b\", nil)\n\ttest.RetrieveTokenUnauthorized(rest.T(), service.Context, service, controller, \"github\", nil)\n\ttest.RetrieveTokenUnauthorized(rest.T(), service.Context, service, controller, \"https://api.starter-us-east-2.openshift.com\", nil)\n\ttest.RetrieveTokenUnauthorized(rest.T(), service.Context, service, controller, \"openshift\", nil)\n}", "func (mr *MockMachineMockRecorder) Identity() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Identity\", reflect.TypeOf((*MockMachine)(nil).Identity))\n}", "func (m *MockProviders) IdentityManager(arg0 string) (msp.IdentityManager, bool) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"IdentityManager\", arg0)\n\tret0, _ := ret[0].(msp.IdentityManager)\n\tret1, _ := ret[1].(bool)\n\treturn ret0, ret1\n}", "func (m *MockClient) IdentityManager(arg0 string) (msp.IdentityManager, bool) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"IdentityManager\", arg0)\n\tret0, _ := ret[0].(msp.IdentityManager)\n\tret1, _ := ret[1].(bool)\n\treturn ret0, ret1\n}", "func (mr *MockClientMockRecorder) IdentityConfig() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"IdentityConfig\", reflect.TypeOf((*MockClient)(nil).IdentityConfig))\n}", "func (mr *MockProvidersMockRecorder) IdentityConfig() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"IdentityConfig\", reflect.TypeOf((*MockProviders)(nil).IdentityConfig))\n}", "func TestNewIdentityManager(t *testing.T) {\n\tt.Run(\"success\", func(t *testing.T) {\n\t\tepCfg := &mocks.EndpointConfig{}\n\t\tepCfg.NetworkConfigReturns(&fab.NetworkConfig{\n\t\t\tOrganizations: map[string]fab.OrganizationConfig{\"org1msp\": {}},\n\t\t})\n\n\t\tm, err := newIdentityManager(\"org1MSP\", &mocks.CryptoSuite{}, epCfg, \"./msp\")\n\t\trequire.NoError(t, err)\n\t\trequire.NotNil(t, m)\n\t})\n\n\tt.Run(\"No endpoint config -> error\", func(t *testing.T) {\n\t\tm, err := newIdentityManager(\"org1MSP\", &mocks.CryptoSuite{}, nil, \"./msp\")\n\t\trequire.EqualError(t, err, \"endpoint config is required\")\n\t\trequire.Nil(t, m)\n\t})\n\n\tt.Run(\"No org name -> error\", func(t *testing.T) {\n\t\tm, err := newIdentityManager(\"\", nil, &mocks.EndpointConfig{}, \"./msp\")\n\t\trequire.EqualError(t, err, \"orgName is required\")\n\t\trequire.Nil(t, m)\n\t})\n\n\tt.Run(\"No crypto suite -> error\", func(t *testing.T) {\n\t\tm, err := newIdentityManager(\"org1MSP\", nil, &mocks.EndpointConfig{}, \"./msp\")\n\t\trequire.EqualError(t, err, \"cryptoProvider is required\")\n\t\trequire.Nil(t, m)\n\t})\n\n\tt.Run(\"Org not found -> error\", func(t *testing.T) {\n\t\tepCfg := &mocks.EndpointConfig{}\n\t\tepCfg.NetworkConfigReturns(&fab.NetworkConfig{})\n\n\t\tm, err := newIdentityManager(\"org1MSP\", &mocks.CryptoSuite{}, epCfg, \"./msp\")\n\t\trequire.EqualError(t, err, \"org config retrieval failed\")\n\t\trequire.Nil(t, m)\n\t})\n\n\tt.Run(\"MSP config path not provided -> error\", func(t *testing.T) {\n\t\tepCfg := &mocks.EndpointConfig{}\n\t\tepCfg.NetworkConfigReturns(&fab.NetworkConfig{\n\t\t\tOrganizations: map[string]fab.OrganizationConfig{\"org1msp\": {}},\n\t\t})\n\n\t\tm, err := newIdentityManager(\"org1MSP\", &mocks.CryptoSuite{}, epCfg, \"\")\n\t\trequire.EqualError(t, err, \"either mspConfigPath or an embedded list of users is required\")\n\t\trequire.Nil(t, m)\n\t})\n}", "func TestGenerateIdentity(t *testing.T) {\n\tif _, err := GenerateIdentity(); err != nil {\n\t\tt.Fatalf(\"Failed to generate new identity: %v\", err)\n\t}\n}", "func TestGenerateIdentity(t *testing.T) {\n\tif _, err := GenerateIdentity(); err != nil {\n\t\tt.Fatalf(\"Failed to generate new identity: %v\", err)\n\t}\n}", "func (m *CommunicationsIdentitySet) SetAssertedIdentity(value Identityable)() {\n err := m.GetBackingStore().Set(\"assertedIdentity\", value)\n if err != nil {\n panic(err)\n }\n}", "func (mr *MockManagerClientMockRecorder) GetManagerByUserFromServer(id interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetManagerByUserFromServer\", reflect.TypeOf((*MockManagerClient)(nil).GetManagerByUserFromServer), id)\n}", "func (c *OAuth) Manager(idp idp.IdentityProvider, store *mongodb.Store, encoder jwt.Encoder) *oauth.Manager {\n\tfmt.Println(c)\n\tproviderMetadata := &openid.ProviderMetadata{\n\t\tIssuer: c.Issuer,\n\t\tAuthorizationEndpoint: c.UIAuthorizeEndpoint,\n\t\tTokenEndpoint: fmt.Sprintf(\"%s/v0/oauth/token\", c.Issuer),\n\t\tUserInfoEndpoint: fmt.Sprintf(\"%s/v0/openid/userinfo\", c.Issuer),\n\t\tJwksURI: fmt.Sprintf(\"%s/.well-known/jwks.json\", c.Issuer),\n\t\tRegistrationEndpoint: fmt.Sprintf(\"%s/v0/clients\", c.Issuer),\n\t\tScopesSupported: append(c.ScopesSupported, openid.OpenIDScope, openid.ProfileScope, openid.EmailScope),\n\t\tResponseTypesSupported: []string{string(model.CodeResponseType)},\n\t\tGrantTypesSupported: []string{string(model.AuthorizationCodeGrantType), string(model.PasswordGrantType), string(model.ClientCredentialsGrantType)},\n\t\tSubjectTypesSupported: []string{\"public\"},\n\t\tIDTokenSigningAlgValuesSupported: []string{string(jose.RS256)},\n\t\tTokenEndpointAuthMethodsSupported: []string{openid.ClientSecretPostTokenAuthMethod},\n\t\tCodeChallengeMethodsSupported: []string{string(model.PlainCodeChallengeMethod), string(model.S256CodeChallengeMethod)},\n\t}\n\treturn oauth.NewManager(idp, store, encoder, providerMetadata)\n}", "func (s *UserSuite) TestUserAttachedToRequestAuthenticatedNoUseridentifierHasBeenRegistered(c *C) {\n\thandler := u.Handler()\n\n\treq, _ := http.NewRequest(\"GET\", \"http://127.0.0.1:8000/auth-status\", nil)\n\tresp := httptest.NewRecorder()\n\thandler(resp, req)\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tc.Assert(err, IsNil)\n\tc.Assert(string(body), Equals, \"false\")\n}", "func (u *MockUser) Identity() ([]byte, error) {\n\treturn []byte(\"test\"), nil\n}", "func (m *AzureManagedControlPlane) validateIdentity(_ client.Client) error {\n\tvar allErrs field.ErrorList\n\n\tif m.Spec.Identity != nil {\n\t\tif m.Spec.Identity.Type == ManagedControlPlaneIdentityTypeUserAssigned {\n\t\t\tif m.Spec.Identity.UserAssignedIdentityResourceID == \"\" {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(\"Spec\", \"Identity\", \"UserAssignedIdentityResourceID\"), m.Spec.Identity.UserAssignedIdentityResourceID, \"cannot be empty if Identity.Type is UserAssigned\"))\n\t\t\t}\n\t\t} else {\n\t\t\tif m.Spec.Identity.UserAssignedIdentityResourceID != \"\" {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(\"Spec\", \"Identity\", \"UserAssignedIdentityResourceID\"), m.Spec.Identity.UserAssignedIdentityResourceID, \"should be empty if Identity.Type is SystemAssigned\"))\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(allErrs) > 0 {\n\t\treturn kerrors.NewAggregate(allErrs.ToAggregate().Errors())\n\t}\n\n\treturn nil\n}", "func (ctx *TestContext) IAmAManagerOfTheGroupWithID(group string) error {\n\treturn ctx.UserIsAManagerOfTheGroupWith(getParameterString(map[string]string{\n\t\t\"id\": group,\n\t\t\"user_id\": ctx.user,\n\t\t\"can_watch_members\": \"false\",\n\t}))\n}", "func (o *UserDisco) GetIdentityOk() (*FullIdentity, bool) {\n\tif o == nil || o.Identity == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Identity, true\n}", "func (suite *AuthSuite) TestAuthUnknownServiceMember() {\n\t// Set up: Prepare the session, goth.User, callback handler, http response\n\t// and request, landing URL, and pass them into authorizeUnknownUser\n\n\thandlerConfig := suite.HandlerConfig()\n\tappnames := handlerConfig.AppNames()\n\n\t// Prepare the session and session manager\n\tfakeToken := \"some_token\"\n\tsession := auth.Session{\n\t\tApplicationName: auth.MilApp,\n\t\tIDToken: fakeToken,\n\t\tHostname: appnames.MilServername,\n\t}\n\tsessionManager := handlerConfig.SessionManagers().Mil\n\tmockSender := setUpMockNotificationSender() // We should get an email for this activity\n\n\t// Prepare the goth.User to simulate the UUID and email that login.gov would\n\t// provide\n\tfakeUUID, _ := uuid.NewV4()\n\tuser := goth.User{\n\t\tUserID: fakeUUID.String(),\n\t\tEmail: \"new_service_member@example.com\",\n\t}\n\tctx := suite.SetupSessionContext(context.Background(), &session, sessionManager)\n\n\t// Call the function under test\n\tresult := authorizeUnknownUser(ctx, suite.AppContextWithSessionForTest(&session), user,\n\t\tsessionManager, mockSender)\n\tsuite.Equal(authorizationResultAuthorized, result)\n\tmockSender.(*mocks.NotificationSender).AssertNumberOfCalls(suite.T(), \"SendNotification\", 1)\n\n\t// Look up the user and service member in the test DB\n\tfoundUser, _ := models.GetUserFromEmail(suite.DB(), user.Email)\n\tserviceMemberID := session.ServiceMemberID\n\tserviceMember, _ := models.FetchServiceMemberForUser(suite.DB(), &session, serviceMemberID)\n\t// Look up the session token in the session store (this test uses the memory store)\n\tsessionStore := sessionManager.Store()\n\t_, existsBefore, _ := sessionStore.Find(foundUser.CurrentMilSessionID)\n\n\t// Verify service member exists and its ID is populated in the session\n\tsuite.NotEmpty(session.ServiceMemberID)\n\n\t// Verify session contains UserID that points to the newly-created user\n\tsuite.Equal(foundUser.ID, session.UserID)\n\n\t// Verify user's LoginGovEmail and LoginGovUUID match the values passed in\n\tsuite.Equal(user.Email, foundUser.LoginGovEmail)\n\tsuite.Equal(user.UserID, foundUser.LoginGovUUID.String())\n\n\t// Verify that the user's CurrentMilSessionID is not empty. The value is\n\t// generated randomly, so we can't test for a specific string. Any string\n\t// except an empty string is acceptable.\n\tsuite.NotEqual(\"\", foundUser.CurrentMilSessionID)\n\n\t// Verify the session token also exists in the session store\n\tsuite.Equal(true, existsBefore)\n\n\t// Verify the service member that was created is associated with the user\n\t// that was created\n\tsuite.Equal(foundUser.ID, serviceMember.UserID)\n}", "func (mr *MockCAClientMockRecorder) ModifyIdentity(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"ModifyIdentity\", reflect.TypeOf((*MockCAClient)(nil).ModifyIdentity), arg0)\n}", "func (ctx *TestContext) IAmAManagerOfTheGroup(group string) error {\n\treturn ctx.UserIsAManagerOfTheGroupWith(getParameterString(map[string]string{\n\t\t\"id\": group,\n\t\t\"user_id\": ctx.user,\n\t\t\"name\": group,\n\t\t\"can_watch_members\": \"false\",\n\t}))\n}", "func (f *FakeContext) RequestIDNotCalled() bool {\n\treturn len(f.RequestIDCalls) == 0\n}", "func (o *User) GetIdentitiesOk() ([]ObjectIdentity, bool) {\n\tif o == nil || o.Identities == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Identities, true\n}", "func (suite *HealthCheckTestSuite) TestModuleExecuteWithNilOnPremIdentity() {\n\t// Initialize the appconfigMock with HealthFrequencyMinutes as every five minute\n\tappconfigMock := &appconfig.SsmagentConfig{\n\t\tSsm: appconfig.SsmCfg{\n\t\t\tHealthFrequencyMinutes: appconfig.DefaultSsmHealthFrequencyMinutes,\n\t\t},\n\t}\n\n\tmockEC2Identity := &identityMock.IAgentIdentityInner{}\n\tnewEC2Identity = func(log log.T) identity.IAgentIdentityInner {\n\t\treturn mockEC2Identity\n\t}\n\n\tavailabilityZone := \"us-east-1a\"\n\tavailabilityZoneId := \"use1-az2\"\n\tmockEC2Identity.On(\"IsIdentityEnvironment\").Return(true)\n\tmockEC2Identity.On(\"AvailabilityZone\").Return(availabilityZone, nil)\n\tmockEC2Identity.On(\"AvailabilityZoneId\").Return(availabilityZoneId, nil)\n\n\tnewOnPremIdentity = func(log log.T, config *appconfig.SsmagentConfig) identity.IAgentIdentityInner {\n\t\treturn nil\n\t}\n\n\tmockECSIdentity := &identityMock.IAgentIdentityInner{}\n\tnewECSIdentity = func(log log.T) identity.IAgentIdentityInner {\n\t\treturn mockECSIdentity\n\t}\n\tmockECSIdentity.On(\"IsIdentityEnvironment\").Return(false)\n\n\tssmConnectionChannel := \"ssmmessages\"\n\tvar ableToOpenMGSConnection uint32\n\tatomic.StoreUint32(&ableToOpenMGSConnection, 1)\n\tssmconnectionchannel.SetConnectionChannel(&ableToOpenMGSConnection)\n\n\t// Turn on the mock method\n\tsuite.contextMock.On(\"AppConfig\").Return(*appconfigMock)\n\tsuite.serviceMock.On(\"UpdateInstanceInformation\", mock.Anything, version.Version, \"Active\", AgentName, availabilityZone, availabilityZoneId, ssmConnectionChannel).Return(nil, nil)\n\tsuite.healthCheck.ModuleExecute()\n\t// Because ModuleExecute will launch two new go routine, wait 100ms to make sure the updateHealth() has launched\n\ttime.Sleep(100 * time.Millisecond)\n\t// Assert the UpdateInstanceInformation get called in updateHealth() function, and the agent status is same as input.\n\tsuite.serviceMock.AssertCalled(suite.T(), \"UpdateInstanceInformation\", mock.Anything, version.Version, \"Active\", AgentName, availabilityZone, availabilityZoneId, ssmConnectionChannel)\n}", "func (c *Client) IDTokenUserinfoClaimsAssertion() bool {\n\treturn c.idTokenUserinfoClaimsAssertion\n}", "func (s *UserSuite) TestUserAttachedToRequestAuthenticatedRegisteredUseridentifierReturnsAnonymousUser(c *C) {\n\thandler := u.Handler()\n\n\tIdentifyUsersWith(FakeAuth)\n\treq, _ := http.NewRequest(\"GET\", \"http://127.0.0.1:8000/auth-status\", nil)\n\tresp := httptest.NewRecorder()\n\thandler(resp, req)\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tc.Assert(err, IsNil)\n\tc.Assert(string(body), Equals, \"false\")\n}", "func (idMap *IdentityMap) CheckIdentity(id string, login map[string]string) error {\n\tfor name, pattern := range *idMap {\n\t\tif !pattern.MatchString(id) {\n\t\t\tcontinue\n\t\t}\n\n\t\tlogin[name] = id\n\t\tlogin[\"type\"] = \"account\"\n\t\tlogin[\"verifyCode\"] = \"\"\n\n\t\treturn nil\n\t}\n\n\treturn ErrIdentity\n}", "func (e OAuthAccessTokenIdentifiersValidationError) Cause() error { return e.cause }", "func (mr *MockManagerClientMockRecorder) GetManagerFromServer(id interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetManagerFromServer\", reflect.TypeOf((*MockManagerClient)(nil).GetManagerFromServer), id)\n}", "func (m *GraphBaseServiceClient) IdentityProtection()(*i663c30678b300c2c4b619c4964b4326e471e4da61a44d7c39f752349da7a468e.IdentityProtectionRequestBuilder) {\n return i663c30678b300c2c4b619c4964b4326e471e4da61a44d7c39f752349da7a468e.NewIdentityProtectionRequestBuilderInternal(m.pathParameters, m.requestAdapter);\n}", "func (m *GraphBaseServiceClient) IdentityProtection()(*i663c30678b300c2c4b619c4964b4326e471e4da61a44d7c39f752349da7a468e.IdentityProtectionRequestBuilder) {\n return i663c30678b300c2c4b619c4964b4326e471e4da61a44d7c39f752349da7a468e.NewIdentityProtectionRequestBuilderInternal(m.pathParameters, m.requestAdapter);\n}", "func (m *GraphBaseServiceClient) Identity()(*i79ca23a9ac0659e1330dd29e049fe157787d5af6695ead2ff8263396db68d027.IdentityRequestBuilder) {\n return i79ca23a9ac0659e1330dd29e049fe157787d5af6695ead2ff8263396db68d027.NewIdentityRequestBuilderInternal(m.pathParameters, m.requestAdapter);\n}", "func (m *GraphBaseServiceClient) Identity()(*i79ca23a9ac0659e1330dd29e049fe157787d5af6695ead2ff8263396db68d027.IdentityRequestBuilder) {\n return i79ca23a9ac0659e1330dd29e049fe157787d5af6695ead2ff8263396db68d027.NewIdentityRequestBuilderInternal(m.pathParameters, m.requestAdapter);\n}", "func TestAzureBlobGetAppsListShouldFailInvalidIdentity(t *testing.T) {\n\tctx := context.TODO()\n\tappFrameworkRef := enterpriseApi.AppFrameworkSpec{\n\t\tDefaults: enterpriseApi.AppSourceDefaultSpec{\n\t\t\tVolName: \"azure_vol1\",\n\t\t\tScope: enterpriseApi.ScopeLocal,\n\t\t},\n\t\tVolList: []enterpriseApi.VolumeSpec{\n\t\t\t{\n\t\t\t\tName: \"azure_vol1\",\n\t\t\t\tEndpoint: \"https://mystorageaccount.blob.core.windows.net\",\n\t\t\t\tPath: \"appscontainer1\",\n\t\t\t\tType: \"blob\",\n\t\t\t\tProvider: \"azure\",\n\t\t\t},\n\t\t},\n\t\tAppSources: []enterpriseApi.AppSourceSpec{\n\t\t\t{\n\t\t\t\tName: \"adminApps\",\n\t\t\t\tLocation: \"adminAppsRepo\",\n\t\t\t\tAppSourceDefaultSpec: enterpriseApi.AppSourceDefaultSpec{\n\t\t\t\t\tVolName: \"azure_vol1\",\n\t\t\t\t\tScope: enterpriseApi.ScopeLocal,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\t// Initialize clients\n\tazureBlobClient := &AzureBlobClient{}\n\tmclient := spltest.MockHTTPClient{}\n\n\t// Identity call return a token - that means AKS cluster has an identity configured.\n\twantRequest, _ := http.NewRequest(\"GET\", \"http://169.254.169.254/metadata/identity/oauth2/token?api-version=2021-10-01&resource=https%3A%2F%2Fstorage.azure.com%2F\", nil)\n\trespTokenData := &TokenResponse{\n\t\tAccessToken: \"acctoken\",\n\t\tClientID: \"ClientId\",\n\t}\n\tmrespdata, _ := json.Marshal(respTokenData)\n\tmclient.AddHandler(wantRequest, 200, string(mrespdata), nil)\n\n\t// Add mock for the azure rest call for list apps\n\twantRequest, _ = http.NewRequest(\"GET\", \"https://mystorageaccount.blob.core.windows.net/appscontainer1?prefix=adminAppsRepo&restype=container&comp=list&include=snapshots&include=metadata\", nil)\n\n\t// Expect the identity does not have authorization to access the buckets\n\tmclient.AddHandler(wantRequest, 403, \"identity not authorized\", nil)\n\n\t// Get App source and volume from spec\n\tappSource := appFrameworkRef.AppSources[0]\n\tvol, err := GetAppSrcVolume(ctx, appSource, &appFrameworkRef)\n\tif err != nil {\n\t\tt.Errorf(\"Unable to get volume for app source : %s\", appSource.Name)\n\t}\n\n\t// Update the GetRemoteDataClient function pointer\n\tgetClientWrapper := RemoteDataClientsMap[vol.Provider]\n\tgetClientWrapper.SetRemoteDataClientFuncPtr(ctx, vol.Provider, NewMockAzureBlobClient)\n\n\t// Update the GetRemoteDataClientInit function pointer\n\tinitFn := func(ctx context.Context, region, accessKeyID, secretAccessKey string) interface{} {\n\t\treturn &mclient\n\t}\n\tgetClientWrapper.SetRemoteDataClientInitFuncPtr(ctx, vol.Provider, initFn)\n\n\t// Init azure blob client\n\tgetRemoteDataClientFn := getClientWrapper.GetRemoteDataClientInitFuncPtr(ctx)\n\tazureBlobClient.HTTPClient = getRemoteDataClientFn(ctx, \"us-west-2\", \"abcd\", \"1234\").(*spltest.MockHTTPClient)\n\tazureBlobClient.BucketName = vol.Path\n\tazureBlobClient.Prefix = appSource.Location\n\tazureBlobClient.Endpoint = vol.Endpoint\n\n\trespList, err := azureBlobClient.GetAppsList(ctx)\n\tif err == nil {\n\t\tt.Errorf(\"GetAppsList should return err\")\n\t}\n\n\tif err.Error() != \"error authorizing the rest call. check your IAM/secret configuration\" {\n\t\tt.Errorf(\"GetAppsList should return authorization error\")\n\t}\n\n\t// authorizing the rest call. check your IAM/secret configuration\n\n\tif len(respList.Objects) != 0 {\n\t\tt.Errorf(\"GetAppsList should not return any response objects\")\n\t}\n\tmclient.RemoveHandlers()\n}", "func testSystemAssignedIdentity(msiEndpoint string) (*adal.Token, error) {\n\tspt, err := adal.NewServicePrincipalTokenFromMSI(msiEndpoint, azure.PublicCloud.ResourceManagerEndpoint)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"Failed to acquire a token using the MSI VM extension\")\n\t}\n\n\tif err := spt.Refresh(); err != nil {\n\t\treturn nil, errors.Wrapf(err, \"Failed to refresh ServicePrincipalTokenFromMSI using the MSI VM extension, msiEndpoint(%s)\", msiEndpoint)\n\t}\n\n\ttoken := spt.Token()\n\tif token.IsZero() {\n\t\treturn nil, errors.Errorf(\"No token found, MSI VM extension, msiEndpoint(%s)\", msiEndpoint)\n\t}\n\n\tklog.Infof(\"successfully acquired a token using the MSI, msiEndpoint(%s)\", msiEndpoint)\n\treturn &token, nil\n}", "func (mr *MockCAClientMockRecorder) GetIdentity(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetIdentity\", reflect.TypeOf((*MockCAClient)(nil).GetIdentity), arg0, arg1)\n}", "func (adminAPIOp) SkipVerification() bool { return true }", "func AnonOperationNotAloneMessage() string {\n\treturn \"This anonymous operation must be the only defined operation.\"\n}", "func (o *VirtualizationBaseHostPciDeviceAllOf) GetIdentityOk() (*string, bool) {\n\tif o == nil || o.Identity == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Identity, true\n}", "func (suite *HealthCheckTestSuite) TestModuleExecuteWithOnPremIdentity() {\n\t// Initialize the appconfigMock with HealthFrequencyMinutes as every five minute\n\tappconfigMock := &appconfig.SsmagentConfig{\n\t\tSsm: appconfig.SsmCfg{\n\t\t\tHealthFrequencyMinutes: appconfig.DefaultSsmHealthFrequencyMinutes,\n\t\t},\n\t}\n\n\tmockEC2Identity := &identityMock.IAgentIdentityInner{}\n\tnewEC2Identity = func(log log.T) identity.IAgentIdentityInner {\n\t\treturn mockEC2Identity\n\t}\n\n\tavailabilityZone := \"us-east-1a\"\n\tavailabilityZoneId := \"use1-az2\"\n\tmockEC2Identity.On(\"IsIdentityEnvironment\").Return(true)\n\tmockEC2Identity.On(\"AvailabilityZone\").Return(availabilityZone, nil)\n\tmockEC2Identity.On(\"AvailabilityZoneId\").Return(availabilityZoneId, nil)\n\n\tmockOnPremIdentity := &identityMock.IAgentIdentityInner{}\n\tnewOnPremIdentity = func(log log.T, config *appconfig.SsmagentConfig) identity.IAgentIdentityInner {\n\t\treturn mockOnPremIdentity\n\t}\n\tmockOnPremIdentity.On(\"IsIdentityEnvironment\").Return(true)\n\n\tmockECSIdentity := &identityMock.IAgentIdentityInner{}\n\tnewECSIdentity = func(log log.T) identity.IAgentIdentityInner {\n\t\treturn mockECSIdentity\n\t}\n\tmockECSIdentity.On(\"IsIdentityEnvironment\").Return(false)\n\n\tssmConnectionChannel := \"ssmmessages\"\n\tvar ableToOpenMGSConnection uint32\n\tatomic.StoreUint32(&ableToOpenMGSConnection, 1)\n\tssmconnectionchannel.SetConnectionChannel(&ableToOpenMGSConnection)\n\n\t// Turn on the mock method\n\tsuite.contextMock.On(\"AppConfig\").Return(*appconfigMock)\n\tsuite.serviceMock.On(\"UpdateInstanceInformation\", mock.Anything, version.Version, \"Active\", AgentName, \"\", \"\", ssmConnectionChannel).Return(nil, nil)\n\tsuite.healthCheck.ModuleExecute()\n\t// Because ModuleExecute will launch two new go routine, wait 100ms to make sure the updateHealth() has launched\n\ttime.Sleep(100 * time.Millisecond)\n\t// Assert the UpdateInstanceInformation get called in updateHealth() function, and the agent status is same as input.\n\tsuite.serviceMock.AssertCalled(suite.T(), \"UpdateInstanceInformation\", mock.Anything, version.Version, \"Active\", AgentName, \"\", \"\", ssmConnectionChannel)\n\tsuite.serviceMock.AssertNotCalled(suite.T(), \"IsIdentityEnvironment\", true)\n}", "func (m *CommunicationsIdentitySet) GetAssertedIdentity()(Identityable) {\n val, err := m.GetBackingStore().Get(\"assertedIdentity\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(Identityable)\n }\n return nil\n}", "func (mr *MockHostMockRecorder) ConnManager() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"ConnManager\", reflect.TypeOf((*MockHost)(nil).ConnManager))\n}", "func (c *Client) Identity(id string, token string) {\n\tvar identityMessage *IdentityRequestMessage\n\n\tif len(id) <= 0 || len(token) <= 0 {\n\t\tidentityMessage = &IdentityRequestMessage{}\n\t}\n\n\tidentityMessage = &IdentityRequestMessage{id, token}\n\tinput := knot.NewFrame(\"identity\", identityMessage)\n\n\treq := IdentityRequest{Request: c.NewRequest(input), Frame: input}\n\treq.Send()\n}", "func ManagedClusterPodIdentityExceptionGenerator() gopter.Gen {\n\tif managedClusterPodIdentityExceptionGenerator != nil {\n\t\treturn managedClusterPodIdentityExceptionGenerator\n\t}\n\n\tgenerators := make(map[string]gopter.Gen)\n\tAddIndependentPropertyGeneratorsForManagedClusterPodIdentityException(generators)\n\tmanagedClusterPodIdentityExceptionGenerator = gen.Struct(reflect.TypeOf(ManagedClusterPodIdentityException{}), generators)\n\n\treturn managedClusterPodIdentityExceptionGenerator\n}", "func TestAuthRequestNilTokenEvent(t *testing.T) {\n\trunTest(t, func(s *res.Service) {\n\t\ts.Handle(\"model\", res.Auth(\"method\", func(r res.AuthRequest) {\n\t\t\tr.TokenEvent(nil)\n\t\t\tr.OK(nil)\n\t\t}))\n\t}, func(s *restest.Session) {\n\t\treq := s.Auth(\"test.model\", \"method\", nil)\n\t\ts.GetMsg().\n\t\t\tAssertTokenEvent(mock.CID, nil)\n\t\treq.Response().\n\t\t\tAssertResult(nil)\n\t})\n}", "func (m *AospDeviceOwnerDeviceConfiguration) SetPasswordSignInFailureCountBeforeFactoryReset(value *int32)() {\n err := m.GetBackingStore().Set(\"passwordSignInFailureCountBeforeFactoryReset\", value)\n if err != nil {\n panic(err)\n }\n}", "func (m *AospDeviceOwnerDeviceConfiguration) GetPasswordSignInFailureCountBeforeFactoryReset()(*int32) {\n val, err := m.GetBackingStore().Get(\"passwordSignInFailureCountBeforeFactoryReset\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*int32)\n }\n return nil\n}", "func (o *UserDisco) HasIdentity() bool {\n\tif o != nil && o.Identity != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (m *AndroidWorkProfileGeneralDeviceConfiguration) SetPasswordSignInFailureCountBeforeFactoryReset(value *int32)() {\n m.passwordSignInFailureCountBeforeFactoryReset = value\n}", "func (m *User) GetIdentities()([]ObjectIdentityable) {\n return m.identities\n}", "func (mr *MockRegionUserInfoDaoMockRecorder) GetTokenByEid(eid interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetTokenByEid\", reflect.TypeOf((*MockRegionUserInfoDao)(nil).GetTokenByEid), eid)\n}", "func (f *FakeContext) WithRequestIDNotCalled() bool {\n\treturn len(f.WithRequestIDCalls) == 0\n}", "func (adminAPIOp) SkipMFASetup() bool { return true }", "func (s *UsersService) Identity() *UsersIdentityCall {\n\tvar call UsersIdentityCall\n\tcall.service = s\n\treturn &call\n}", "func NewIdentityManager(orgName string, userStore msp.UserStore, cryptoSuite core.CryptoSuite, endpointConfig fab.EndpointConfig) (*IdentityManager, error) {\n\n\tnetConfig := endpointConfig.NetworkConfig()\n\t// viper keys are case insensitive\n\torgConfig, ok := netConfig.Organizations[strings.ToLower(orgName)]\n\tif !ok {\n\t\treturn nil, errors.New(\"org config retrieval failed\")\n\t}\n\n\tif orgConfig.CryptoPath == \"\" && len(orgConfig.Users) == 0 {\n\t\treturn nil, errors.New(\"Either a cryptopath or an embedded list of users is required\")\n\t}\n\n\tvar mspPrivKeyStore core.KVStore\n\tvar mspCertStore core.KVStore\n\n\torgCryptoPathTemplate := orgConfig.CryptoPath\n\tif orgCryptoPathTemplate != \"\" {\n\t\tvar err error\n\t\tif !filepath.IsAbs(orgCryptoPathTemplate) {\n\t\t\torgCryptoPathTemplate = filepath.Join(endpointConfig.CryptoConfigPath(), orgCryptoPathTemplate)\n\t\t}\n\t\tmspPrivKeyStore, err = NewFileKeyStore(orgCryptoPathTemplate)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"creating a private key store failed\")\n\t\t}\n\t\tmspCertStore, err = NewFileCertStore(orgCryptoPathTemplate)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"creating a cert store failed\")\n\t\t}\n\t} else {\n\t\tlogger.Warnf(\"Cryptopath not provided for organization [%s], MSP stores not created\", orgName)\n\t}\n\n\tmgr := &IdentityManager{\n\t\torgName: orgName,\n\t\torgMSPID: orgConfig.MSPID,\n\t\tconfig: endpointConfig,\n\t\tcryptoSuite: cryptoSuite,\n\t\tmspPrivKeyStore: mspPrivKeyStore,\n\t\tmspCertStore: mspCertStore,\n\t\tembeddedUsers: orgConfig.Users,\n\t\tuserStore: userStore,\n\t\t// CA Client state is created lazily, when (if) needed\n\t}\n\treturn mgr, nil\n}", "func (mr *MockClientMockRecorder) SigningManager() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"SigningManager\", reflect.TypeOf((*MockClient)(nil).SigningManager))\n}", "func (c *context) Identity() entity.Identity {\n\treturn c.id.AgentIdentity()\n}", "func (e PlmnIdentityValidationError) Cause() error { return e.cause }", "func (mr *MockProvidersMockRecorder) SigningManager() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"SigningManager\", reflect.TypeOf((*MockProviders)(nil).SigningManager))\n}", "func (mr *MockManagerClientMockRecorder) CreateManagerOnServer(userId, companyId interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"CreateManagerOnServer\", reflect.TypeOf((*MockManagerClient)(nil).CreateManagerOnServer), userId, companyId)\n}", "func (m *User) SetIdentities(value []ObjectIdentityable)() {\n m.identities = value\n}", "func TestHandler_URLMappingShowRecapSalesFailIDWrong(t *testing.T) {\n\t// melakukan proses login\n\tuser := model.DummyUserPriviledgeWithUsergroup(1)\n\tsd, _ := auth.Login(user)\n\ttoken := \"Bearer \" + sd.Token\n\tng := tester.New()\n\tng.SetHeader(tester.H{\"Authorization\": token})\n\tng.Method = \"GET\"\n\tng.Path = \"/v1/recap-sales/asas\"\n\tng.Run(test.Router(), func(res tester.HTTPResponse, req tester.HTTPRequest) {\n\t\tassert.Equal(t, int(400), res.Code, fmt.Sprintf(\"Should has 'endpoint %s' with method '%s'\", \"/v1/recap-sales/asas\", \"GET\"))\n\t})\n}", "func (o *ComputeBladeIdentityAllOf) GetManagerSlotIdOk() (*int64, bool) {\n\tif o == nil || o.ManagerSlotId == nil {\n\t\treturn nil, false\n\t}\n\treturn o.ManagerSlotId, true\n}", "func (m *AtomicRecordStorageMock) MinimockForIDInspect() {\n\tfor _, e := range m.ForIDMock.expectations {\n\t\tif mm_atomic.LoadUint64(&e.Counter) < 1 {\n\t\t\tm.t.Errorf(\"Expected call to AtomicRecordStorageMock.ForID with params: %#v\", *e.params)\n\t\t}\n\t}\n\n\t// if default expectation was set then invocations count should be greater than zero\n\tif m.ForIDMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterForIDCounter) < 1 {\n\t\tif m.ForIDMock.defaultExpectation.params == nil {\n\t\t\tm.t.Error(\"Expected call to AtomicRecordStorageMock.ForID\")\n\t\t} else {\n\t\t\tm.t.Errorf(\"Expected call to AtomicRecordStorageMock.ForID with params: %#v\", *m.ForIDMock.defaultExpectation.params)\n\t\t}\n\t}\n\t// if func was set then invocations count should be greater than zero\n\tif m.funcForID != nil && mm_atomic.LoadUint64(&m.afterForIDCounter) < 1 {\n\t\tm.t.Error(\"Expected call to AtomicRecordStorageMock.ForID\")\n\t}\n}", "func (mr *MockCAClientMockRecorder) CreateIdentity(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"CreateIdentity\", reflect.TypeOf((*MockCAClient)(nil).CreateIdentity), arg0)\n}", "func ValidateIdentity(attribute string, identity string) error {\n\n\ti := Manager().IdentityFromAny(identity)\n\tif i.IsEmpty() {\n\t\treturn makeValidationError(attribute, fmt.Sprintf(\"Invalid identity '%s': unknown\", identity))\n\t}\n\n\treturn nil\n}", "func TestEmployeeManagerMap_Valid(t *testing.T) {\n\templyMgrMap := getTestEmployeeManagerMap()\n\tassert.Nil(t, emplyMgrMap.Valid())\n}", "func (mr *MockVerifierMockRecorder) VerifyIDToken(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"VerifyIDToken\", reflect.TypeOf((*MockVerifier)(nil).VerifyIDToken), arg0, arg1)\n}", "func (mr *MockAtomicLogicMockRecorder) SetTicketManager(tm interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"SetTicketManager\", reflect.TypeOf((*MockAtomicLogic)(nil).SetTicketManager), tm)\n}", "func (_f60 *FakeContext) WithRequestIDCalledOnceWith(ident1 string) bool {\n\tvar count int\n\tfor _, call := range _f60.WithRequestIDCalls {\n\t\tif reflect.DeepEqual(call.Parameters.Ident1, ident1) {\n\t\t\tcount++\n\t\t}\n\t}\n\n\treturn count == 1\n}", "func testIATBHOriginatorIdentification(t testing.TB) {\n\tbh := mockIATBatchHeaderFF()\n\tbh.OriginatorIdentification = \"\"\n\terr := bh.Validate()\n\tif !base.Match(err, ErrFieldInclusion) {\n\t\tt.Errorf(\"%T: %s\", err, err)\n\t}\n}", "func (mr *MockLogicMockRecorder) SetTicketManager(tm interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"SetTicketManager\", reflect.TypeOf((*MockLogic)(nil).SetTicketManager), tm)\n}", "func (m *AndroidWorkProfileGeneralDeviceConfiguration) SetWorkProfilePasswordSignInFailureCountBeforeFactoryReset(value *int32)() {\n m.workProfilePasswordSignInFailureCountBeforeFactoryReset = value\n}", "func (o *IdentityCredentialIdentifierOidcProperties) GetInitialAccessTokenOk() (*string, bool) {\n\tif o == nil || o.InitialAccessToken == nil {\n\t\treturn nil, false\n\t}\n\treturn o.InitialAccessToken, true\n}", "func (m *PlmnIdentity) Validate() error {\n\treturn m.validate(false)\n}", "func (f *FakeContext) RequestIDCalled() bool {\n\treturn len(f.RequestIDCalls) != 0\n}", "func ERROR_AUTH_SEED_NOT_SET(w http.ResponseWriter, pl string) {\n\tbuildForeignError(w, http.StatusForbidden, \"ERROR_AUTH_SEED_NOT_SET\", pl)\n}", "func (o *authImpl) Admit(ctx context.Context, req identity.Requestor) (authentication.Identity, bool) {\n\n\t// @step: verify the authorization token\n\tbearer, found := utils.GetBearerToken(req.Headers().Get(\"Authorization\"))\n\tif !found {\n\t\treturn nil, false\n\t}\n\n\tid, err := func() (authentication.Identity, error) {\n\t\t// @step: validate the token\n\t\tclaims := struct {\n\t\t\tEmail string `json:\"email\"`\n\t\t\tUsername string `json:\"username\"`\n\t\t\tjwt.StandardClaims\n\t\t}{}\n\t\t_, err := jwt.ParseWithClaims(bearer, &claims, func(token *jwt.Token) (interface{}, error) {\n\t\t\t// Don't forget to validate the alg is what you expect:\n\t\t\tif _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {\n\t\t\t\treturn nil, fmt.Errorf(\"Unexpected signing method: %v\", token.Header[\"alg\"])\n\t\t\t}\n\t\t\tpubKeyBytes, err := base64.StdEncoding.DecodeString(o.config.PublicKey)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"Unable to parse public key from config: %v\", err)\n\t\t\t}\n\t\t\tpubKey, err := x509.ParsePKIXPublicKey(pubKeyBytes)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"Unable to parse public key from config: %v\", err)\n\t\t\t}\n\t\t\treturn pubKey, nil\n\t\t})\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tusername := claims.Username\n\t\tif username == \"\" {\n\t\t\treturn nil, errors.New(\"issued token does not contain the username claim\")\n\t\t}\n\n\t\tid, found, err := o.GetUserIdentity(ctx, username)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif !found {\n\t\t\treturn nil, errors.New(\"user not found in the kore\")\n\t\t}\n\n\t\treturn id, nil\n\t}()\n\tif err != nil {\n\t\treturn nil, false\n\t}\n\n\treturn id, true\n}", "func (o *APICheck) Identity() elemental.Identity {\n\n\treturn APICheckIdentity\n}", "func (mr *MockpatcherMockRecorder) EnsureManagerRoleIsAllowedToUpload(bucketName interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"EnsureManagerRoleIsAllowedToUpload\", reflect.TypeOf((*Mockpatcher)(nil).EnsureManagerRoleIsAllowedToUpload), bucketName)\n}", "func (m *StorageMock) MinimockForIDInspect() {\n\tfor _, e := range m.ForIDMock.expectations {\n\t\tif mm_atomic.LoadUint64(&e.Counter) < 1 {\n\t\t\tm.t.Errorf(\"Expected call to StorageMock.ForID with params: %#v\", *e.params)\n\t\t}\n\t}\n\n\t// if default expectation was set then invocations count should be greater than zero\n\tif m.ForIDMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterForIDCounter) < 1 {\n\t\tif m.ForIDMock.defaultExpectation.params == nil {\n\t\t\tm.t.Error(\"Expected call to StorageMock.ForID\")\n\t\t} else {\n\t\t\tm.t.Errorf(\"Expected call to StorageMock.ForID with params: %#v\", *m.ForIDMock.defaultExpectation.params)\n\t\t}\n\t}\n\t// if func was set then invocations count should be greater than zero\n\tif m.funcForID != nil && mm_atomic.LoadUint64(&m.afterForIDCounter) < 1 {\n\t\tm.t.Error(\"Expected call to StorageMock.ForID\")\n\t}\n}", "func (app *MgmtApp) defaultNotifyClientAuthenticatedFailed(client Client) {\n loge.Info(\"User failed login: %v\", client.Username())\n}", "func (p *Provider) ValidateIdentityParams(ctx context.Context, code, cookie, state string) (t *Token, err error) {\n\tt, _, err = p.ValidateIdentityParamsWithUserdata(ctx, code, cookie, state)\n\treturn\n}", "func (mr *MockBeanMockRecorder) GetMetadataManager() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetMetadataManager\", reflect.TypeOf((*MockBean)(nil).GetMetadataManager))\n}", "func (ctr *Controller) GetUserIdsManagedByManager(c echo.Context) error {\n\tuserProfile := c.Get(\"user_profile\").(m.User)\n\trecords, err := ctr.UserProjectRepo.SelectUserIdsManagedByManager(userProfile.OrganizationID, userProfile.UserProfile.UserID)\n\tif err != nil {\n\t\tif err.Error() == pg.ErrNoRows.Error() {\n\t\t\treturn c.JSON(http.StatusOK, cf.JsonResponse{\n\t\t\t\tStatus: cf.FailResponseCode,\n\t\t\t\tMessage: \"There are no users to manage.\",\n\t\t\t})\n\t\t}\n\n\t\treturn c.JSON(http.StatusInternalServerError, cf.JsonResponse{\n\t\t\tStatus: cf.FailResponseCode,\n\t\t\tMessage: \"System Error\",\n\t\t\tData: err,\n\t\t})\n\t}\n\n\tvar userIds []int\n\tfor _, record := range records {\n\t\tuserIds = append(userIds, record.UserId)\n\t}\n\n\treturn c.JSON(http.StatusOK, cf.JsonResponse{\n\t\tStatus: cf.SuccessResponseCode,\n\t\tMessage: \"Get user ids successfully.\",\n\t\tData: userIds,\n\t})\n}", "func (rest *TestTokenStorageREST) TestStatusExternalTokenValidOnForcePullInternalError() {\n\tidentity, err := testsupport.CreateTestIdentity(rest.DB, uuid.NewV4().String(), \"KC\")\n\trequire.Nil(rest.T(), err)\n\trest.checkStatusExternalTokenValidOnForcePullInternalError(identity, \"https://github.com/a/b\", \"https://github.com\")\n\trest.checkStatusExternalTokenValidOnForcePullInternalError(identity, \"github\", \"https://github.com\")\n\trest.checkStatusExternalTokenValidOnForcePullInternalError(identity, \"openshift\", \"https://api.starter-us-east-2.openshift.com/\")\n\trest.checkStatusExternalTokenValidOnForcePullInternalError(identity, \"https://api.starter-us-east-2.openshift.com\", \"https://api.starter-us-east-2.openshift.com/\")\n}", "func (mmVerify *DelegationTokenFactoryMock) VerifyBeforeCounter() uint64 {\n\treturn mm_atomic.LoadUint64(&mmVerify.beforeVerifyCounter)\n}", "func (_m *AuthServer) mustEmbedUnimplementedAuthServer() {\n\t_m.Called()\n}", "func (o *ActionDTO) GetUserIdentityOk() (*string, bool) {\n\tif o == nil || o.UserIdentity == nil {\n\t\treturn nil, false\n\t}\n\treturn o.UserIdentity, true\n}", "func (m *MockProviders) IdentityConfig() msp.IdentityConfig {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"IdentityConfig\")\n\tret0, _ := ret[0].(msp.IdentityConfig)\n\treturn ret0\n}", "func TestHandler_URLMappingShowRecapSalesFailIDNotExist(t *testing.T) {\n\t// melakukan proses login\n\tuser := model.DummyUserPriviledgeWithUsergroup(1)\n\tsd, _ := auth.Login(user)\n\ttoken := \"Bearer \" + sd.Token\n\tng := tester.New()\n\tng.SetHeader(tester.H{\"Authorization\": token})\n\tng.Method = \"GET\"\n\tng.Path = \"/v1/recap-sales/999999\"\n\tng.Run(test.Router(), func(res tester.HTTPResponse, req tester.HTTPRequest) {\n\t\tassert.Equal(t, int(404), res.Code, fmt.Sprintf(\"Should has 'endpoint %s' with method '%s'\", \"/v1/recap-sales/999999\", \"GET\"))\n\t})\n}", "func (t *CarInsuranceChaincode) verifyUserIdentity(stub shim.ChaincodeStubInterface, id string) ([]byte, error) {\n\tvar claimData Claim\n\tvar jsonResp string\n\tvar userData []User\n\tvar claimUser User\n\tvar log string = \"\"\n\tuserData = GetUserData()\n\tdata, err := stub.GetState(id)\n\n\tif err != nil {\n\t\tjsonResp = \"{\\\"Error\\\":\\\"Failed to retrieve claim details\\\"}\"\n\t\treturn nil, errors.New(jsonResp)\n\t}\n\n\terr = json.Unmarshal(data, &claimData)\n\tif err != nil {\n\t\tjsonResp = \"{\\\"Error\\\":\\\"Failed to UnMarshal claim data\\\"}\"\n\t\treturn nil, errors.New(jsonResp)\n\t}\n\n\tclaimUser = claimData.UserDetails\n\n\tfor i := 0; i < len(userData); i++ {\n\t\tif userData[i].FirstName == claimUser.FirstName && userData[i].LastName == claimUser.LastName && userData[i].BirthDate == claimUser.BirthDate && userData[i].Email == claimUser.Email && userData[i].LicencePlateNumber == claimUser.LicencePlateNumber && userData[i].PolicyId == claimUser.PolicyId && userData[i].SSN == claimUser.SSN && userData[i].VIN == claimUser.VIN {\n\t\t\tlog = log + \"User Details Verified!\"\n\t\t\t//var updatedClaim = NewClaimWithState(claimData.Id, claimData.IncidentDate, claimData.Amount, claimUser, STATE_IDENTITY_INSPECTION)\n\t\t\tclaimData.Status = STATE_IDENTITY_INSPECTION\n\t\t\tt.updateClaimStatus(stub, claimData)\n\t\t\tbreak\n\t\t} else {\n\t\t\tjsonResp = \"{\\\"Error\\\":\\\"User Identity authentication failed\\\"}\"\n\t\t\treturn nil, errors.New(jsonResp)\n\t\t}\n\t}\n\n\tdata, err = json.Marshal(log)\n\n\tif err != nil {\n\t\treturn nil, errors.New(\"Error creating log\")\n\t}\n\n\treturn data, nil\n\n}", "func (s *InMemoryDocumentSessionOperations) RememberEntityForDocumentIdGeneration(entity Object) {\n\terr := NewNotImplementedException(\"You cannot set GenerateDocumentIdsOnStore to false without implementing RememberEntityForDocumentIdGeneration\")\n\tmust(err)\n}", "func IdentityFilter(request *restful.Request, response *restful.Response, chain *restful.FilterChain) {\n\tchain.ProcessFilter(request, response)\n}", "func (mr *MockIDistributedEnforcerMockRecorder) SetRoleManager(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"SetRoleManager\", reflect.TypeOf((*MockIDistributedEnforcer)(nil).SetRoleManager), arg0)\n}", "func TestAuthResource_WithInvalidRID_CausesPanic(t *testing.T) {\n\trunTest(t, func(s *res.Service) {\n\t\ts.Handle(\"model\", res.Auth(\"method\", func(r res.AuthRequest) {\n\t\t\trestest.AssertPanicNoRecover(t, func() {\n\t\t\t\tr.Resource(\"test..foo\")\n\t\t\t})\n\t\t}))\n\t}, func(s *restest.Session) {\n\t\ts.Auth(\"test.model\", \"method\", nil).\n\t\t\tResponse().\n\t\t\tAssertErrorCode(res.CodeInternalError)\n\t})\n}" ]
[ "0.6857104", "0.62990314", "0.5791703", "0.5713766", "0.5507963", "0.55046576", "0.547489", "0.52822226", "0.52602285", "0.51458347", "0.5125385", "0.51153713", "0.5108037", "0.5108037", "0.5072795", "0.4927912", "0.49198627", "0.4906886", "0.49046612", "0.48993003", "0.48911542", "0.48842567", "0.48686963", "0.48456314", "0.48344728", "0.4797123", "0.47840577", "0.47547546", "0.4745597", "0.47337508", "0.4723695", "0.4703805", "0.4657738", "0.46400252", "0.46400252", "0.4639855", "0.4639855", "0.46363047", "0.463464", "0.46316004", "0.46126205", "0.46083254", "0.46069437", "0.45991415", "0.459569", "0.45768362", "0.4565252", "0.45646408", "0.45580924", "0.4552714", "0.45328996", "0.45124957", "0.45034662", "0.44961634", "0.448492", "0.4482951", "0.44829097", "0.44805545", "0.44804016", "0.44720286", "0.44704252", "0.44691268", "0.44611233", "0.44591925", "0.44413808", "0.4439862", "0.44352618", "0.44241214", "0.44197384", "0.4417857", "0.44075236", "0.4404766", "0.4398007", "0.43813512", "0.43723366", "0.4371814", "0.43717247", "0.43706653", "0.43666005", "0.43629086", "0.43593162", "0.43559542", "0.43530738", "0.43497238", "0.4341459", "0.4335123", "0.43325123", "0.43266544", "0.43254814", "0.43238956", "0.43185207", "0.43144587", "0.43132064", "0.43052697", "0.4293178", "0.42876494", "0.42765734", "0.42726985", "0.4267279", "0.42666653" ]
0.6894911
0
InfraProvider mocks base method
func (m *MockClient) InfraProvider() fab.InfraProvider { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "InfraProvider") ret0, _ := ret[0].(fab.InfraProvider) return ret0 }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (m *MockProviders) InfraProvider() fab.InfraProvider {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"InfraProvider\")\n\tret0, _ := ret[0].(fab.InfraProvider)\n\treturn ret0\n}", "func (m *MockProvider) Provide(arg0 string) blobclient.Client {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Provide\", arg0)\n\tret0, _ := ret[0].(blobclient.Client)\n\treturn ret0\n}", "func Test_Provider(t *testing.T) {\n\t// SetLogLevel(\"TRACE\")\n\t// CheckVersion()\n\n\t// Start provider API in the background\n\tgo InitProvider()\n\t// err := InitProvider()\n\t// if err != nil {\n\t// \tlog.Fatalf(\"Error initializing Provider %+v\", err)\n\t// }\n\n\tverifier := HTTPVerifier{}\n\t// Authorization middleware\n\t// This is your chance to modify the request before it hits your provider\n\t// NOTE: this should be used very carefully, as it has the potential to\n\t// _change_ the contract\n\t// f := func(next http.Handler) http.Handler {\n\t// \treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t// \t\tlog.Println(\"[DEBUG] HOOK request filter\")\n\t// \t\t// r.Header.Add(\"Authorization\", \"Bearer 1234-dynamic-value\")\n\t// \t\tnext.ServeHTTP(w, r)\n\t// \t})\n\t// }\n\n\t// Verify the Provider with local Pact Files\n\terr := verifier.VerifyProvider(t, VerifyRequest{\n\t\tProviderBaseURL: \"http://localhost:9000\",\n\t\tBrokerURL: \"http://localhost:9292\",\n\t\tProvider: \"GreetingAPI\",\n\t\tProviderVersion: \"1.0.0\",\n\t\tPublishVerificationResults: true,\n\t\t// PactFiles: []string{\n\t\t// \tfilepath.ToSlash(fmt.Sprintf(\"%s/GreetingAPIConsumer-GreetingAPI.json\", pactDir)),\n\t\t// },\n\t\t// RequestFilter: f,\n\t\t// BeforeEach: func() error {\n\t\t// \tlog.Println(\"[DEBUG] HOOK before each\")\n\t\t// \treturn nil\n\t\t// },\n\t\t// AfterEach: func() error {\n\t\t// \tlog.Println(\"[DEBUG] HOOK after each\")\n\t\t// \treturn nil\n\t\t// },\n\t\t// StateHandlers: StateHandlers{\n\t\t// \t\"User foo exists\": func(setup bool, s ProviderStateV3) (ProviderStateV3Response, error) {\n\n\t\t// \t\tif setup {\n\t\t// \t\t\tlog.Println(\"[DEBUG] HOOK calling user foo exists state handler\", s)\n\t\t// \t\t} else {\n\t\t// \t\t\tlog.Println(\"[DEBUG] HOOK teardown the 'User foo exists' state\")\n\t\t// \t\t}\n\n\t\t// \t\t// ... do something, such as create \"foo\" in the database\n\n\t\t// \t\t// Optionally (if there are generators in the pact) return provider state values to be used in the verification\n\t\t// \t\treturn ProviderStateV3Response{\"uuid\": \"1234\"}, nil\n\t\t// \t},\n\t\t// },\n\t})\n\n\tassert.NoError(t, err)\n}", "func mockedGranter(kubeutil *kube.Kube, app *v1.RadixRegistration, namespace string, serviceAccount *corev1.ServiceAccount) error {\n\treturn nil\n}", "func (m *MockBootstrapperProvider) Provide() (Bootstrapper, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Provide\")\n\tret0, _ := ret[0].(Bootstrapper)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockProcessProvider) BootstrapperProvider() BootstrapperProvider {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"BootstrapperProvider\")\n\tret0, _ := ret[0].(BootstrapperProvider)\n\treturn ret0\n}", "func (m *MockHostEvent) GetInfraEnvId() strfmt.UUID {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetInfraEnvId\")\n\tret0, _ := ret[0].(strfmt.UUID)\n\treturn ret0\n}", "func (m *MockChoriaProvider) MainCollective() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"MainCollective\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func TestGetCloudProvider(t *testing.T) {\n\tfakeCredFile := \"fake-cred-file.json\"\n\tfakeKubeConfig := \"fake-kube-config\"\n\temptyKubeConfig := \"empty-kube-config\"\n\tfakeContent := `\napiVersion: v1\nclusters:\n- cluster:\n server: https://localhost:8080\n name: foo-cluster\ncontexts:\n- context:\n cluster: foo-cluster\n user: foo-user\n namespace: bar\n name: foo-context\ncurrent-context: foo-context\nkind: Config\nusers:\n- name: foo-user\n user:\n exec:\n apiVersion: client.authentication.k8s.io/v1alpha1\n args:\n - arg-1\n - arg-2\n command: foo-command\n`\n\n\terr := createTestFile(emptyKubeConfig)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tdefer func() {\n\t\tif err := os.Remove(emptyKubeConfig); err != nil {\n\t\t\tt.Error(err)\n\t\t}\n\t}()\n\n\ttests := []struct {\n\t\tdesc string\n\t\tcreateFakeCredFile bool\n\t\tcreateFakeKubeConfig bool\n\t\tkubeconfig string\n\t\tnodeID string\n\t\tuserAgent string\n\t\tallowEmptyCloudConfig bool\n\t\texpectedErr error\n\t}{\n\t\t{\n\t\t\tdesc: \"out of cluster, no kubeconfig, no credential file\",\n\t\t\tkubeconfig: \"\",\n\t\t\tnodeID: \"\",\n\t\t\tallowEmptyCloudConfig: true,\n\t\t\texpectedErr: nil,\n\t\t},\n\t\t{\n\t\t\tdesc: \"[failure][disallowEmptyCloudConfig] out of cluster, no kubeconfig, no credential file\",\n\t\t\tkubeconfig: \"\",\n\t\t\tnodeID: \"\",\n\t\t\tallowEmptyCloudConfig: false,\n\t\t\texpectedErr: nil,\n\t\t},\n\t\t{\n\t\t\tdesc: \"[failure] out of cluster & in cluster, specify a non-exist kubeconfig, no credential file\",\n\t\t\tkubeconfig: \"/tmp/non-exist.json\",\n\t\t\tnodeID: \"\",\n\t\t\tallowEmptyCloudConfig: true,\n\t\t\texpectedErr: nil,\n\t\t},\n\t\t{\n\t\t\tdesc: \"[failure] out of cluster & in cluster, specify a empty kubeconfig, no credential file\",\n\t\t\tkubeconfig: emptyKubeConfig,\n\t\t\tnodeID: \"\",\n\t\t\tallowEmptyCloudConfig: true,\n\t\t\texpectedErr: fmt.Errorf(\"failed to get KubeClient: invalid configuration: no configuration has been provided, try setting KUBERNETES_MASTER environment variable\"),\n\t\t},\n\t\t{\n\t\t\tdesc: \"[failure] out of cluster & in cluster, specify a fake kubeconfig, no credential file\",\n\t\t\tcreateFakeKubeConfig: true,\n\t\t\tkubeconfig: fakeKubeConfig,\n\t\t\tnodeID: \"\",\n\t\t\tallowEmptyCloudConfig: true,\n\t\t\texpectedErr: nil,\n\t\t},\n\t\t{\n\t\t\tdesc: \"[success] out of cluster & in cluster, no kubeconfig, a fake credential file\",\n\t\t\tcreateFakeCredFile: true,\n\t\t\tkubeconfig: \"\",\n\t\t\tnodeID: \"\",\n\t\t\tuserAgent: \"useragent\",\n\t\t\tallowEmptyCloudConfig: true,\n\t\t\texpectedErr: nil,\n\t\t},\n\t}\n\n\tfor _, test := range tests {\n\t\tif test.createFakeKubeConfig {\n\t\t\tif err := createTestFile(fakeKubeConfig); err != nil {\n\t\t\t\tt.Error(err)\n\t\t\t}\n\t\t\tdefer func() {\n\t\t\t\tif err := os.Remove(fakeKubeConfig); err != nil {\n\t\t\t\t\tt.Error(err)\n\t\t\t\t}\n\t\t\t}()\n\n\t\t\tif err := os.WriteFile(fakeKubeConfig, []byte(fakeContent), 0666); err != nil {\n\t\t\t\tt.Error(err)\n\t\t\t}\n\t\t}\n\t\tif test.createFakeCredFile {\n\t\t\tif err := createTestFile(fakeCredFile); err != nil {\n\t\t\t\tt.Error(err)\n\t\t\t}\n\t\t\tdefer func() {\n\t\t\t\tif err := os.Remove(fakeCredFile); err != nil {\n\t\t\t\t\tt.Error(err)\n\t\t\t\t}\n\t\t\t}()\n\n\t\t\toriginalCredFile, ok := os.LookupEnv(DefaultAzureCredentialFileEnv)\n\t\t\tif ok {\n\t\t\t\tdefer os.Setenv(DefaultAzureCredentialFileEnv, originalCredFile)\n\t\t\t} else {\n\t\t\t\tdefer os.Unsetenv(DefaultAzureCredentialFileEnv)\n\t\t\t}\n\t\t\tos.Setenv(DefaultAzureCredentialFileEnv, fakeCredFile)\n\t\t}\n\t\tcloud, err := getCloudProvider(test.kubeconfig, test.nodeID, \"\", \"\", test.userAgent, test.allowEmptyCloudConfig, 25.0, 50)\n\t\tif !reflect.DeepEqual(err, test.expectedErr) && test.expectedErr != nil && !strings.Contains(err.Error(), test.expectedErr.Error()) {\n\t\t\tt.Errorf(\"desc: %s,\\n input: %q, GetCloudProvider err: %v, expectedErr: %v\", test.desc, test.kubeconfig, err, test.expectedErr)\n\t\t}\n\t\tif cloud == nil {\n\t\t\tt.Errorf(\"return value of getCloudProvider should not be nil even there is error\")\n\t\t} else {\n\t\t\tassert.Equal(t, cloud.Environment.StorageEndpointSuffix, storage.DefaultBaseURL)\n\t\t\tassert.Equal(t, cloud.UserAgent, test.userAgent)\n\t\t}\n\t}\n}", "func testInMemoryDataStore() IDataStore {\n return NewInMemoryDataStore();\n}", "func ProviderTest(initial Initial, observer invoker.Observer, settings Settings) (Configurator, func(), error) {\n\tc, e := NewMockConfigurator(initial, observer, settings)\n\treturn c, func() {}, e\n}", "func MockedProvider(t *testing.T, c *config.Config, callback string) (*config.Config, goth.Provider) {\n\tconst (\n\t\ttestClientKey = \"provider-test-client-key\"\n\t\ttestSecret = \"provider-test-secret\"\n\t\ttestCallback = \"http://auth.exmaple.com/test/callback\"\n\t)\n\tmp := newMockProvider(t, callback)\n\tp := provider.Name(mp.Name())\n\tprovider.AddExternal(p)\n\tt.Cleanup(func() {\n\t\tdelete(provider.External, p)\n\t})\n\tif callback == \"\" {\n\t\tcallback = testCallback\n\t}\n\tc.Authorization.Providers[p] = config.Provider{\n\t\tClientKey: testClientKey,\n\t\tSecret: testSecret,\n\t\tCallbackURL: callback,\n\t}\n\treturn c, mp\n}", "func (m *MockInfraEnvEvent) GetInfraEnvId() strfmt.UUID {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetInfraEnvId\")\n\tret0, _ := ret[0].(strfmt.UUID)\n\treturn ret0\n}", "func providerConfigure(d *schema.ResourceData) (interface{}, error) {\n\tif d.Get(\"url\") == nil {\n\t\treturn nil, fmt.Errorf(\"url cannot be nil\")\n\t}\n\n\tusername := d.Get(\"username\").(string)\n\tpassword := d.Get(\"password\").(string)\n\tapiKey := d.Get(\"api_key\").(string)\n\taccessToken := d.Get(\"access_token\").(string)\n\n\tlog.SetLogger(log.NewLogger(log.INFO, nil))\n\n\tvar client *http.Client\n\tdetails := auth.NewArtifactoryDetails()\n\n\turl := d.Get(\"url\").(string)\n\tif url[len(url)-1] != '/' {\n\t\turl += \"/\"\n\t}\n\tdetails.SetUrl(url)\n\n\tif username != \"\" && password != \"\" {\n\t\tdetails.SetUser(username)\n\t\tdetails.SetPassword(password)\n\t\ttp := transport.BasicAuth{\n\t\t\tUsername: username,\n\t\t\tPassword: password,\n\t\t}\n\t\tclient = tp.Client()\n\t} else if apiKey != \"\" {\n\t\tdetails.SetApiKey(apiKey)\n\t\ttp := &transport.ApiKeyAuth{\n\t\t\tApiKey: apiKey,\n\t\t}\n\t\tclient = tp.Client()\n\t} else if accessToken != \"\" {\n\t\tdetails.SetAccessToken(accessToken)\n\t\ttp := &transport.AccessTokenAuth{\n\t\t\tAccessToken: accessToken,\n\t\t}\n\t\tclient = tp.Client()\n\t} else {\n\t\treturn nil, fmt.Errorf(\"either [username, password] or [api_key] or [access_token] must be set to use provider\")\n\t}\n\n\tconfig, err := config.NewConfigBuilder().\n\t\tSetServiceDetails(details).\n\t\tSetDryRun(false).\n\t\tBuild()\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trtold, err := artifactoryold.NewClient(d.Get(\"url\").(string), client)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trtnew, err := artifactorynew.New(&details, config)\n\n\tif err != nil {\n\t\treturn nil, err\n\t} else if _, resp, err := rtold.V1.System.Ping(context.Background()); err != nil {\n\t\treturn nil, err\n\t} else if resp.StatusCode != 200 {\n\t\treturn nil, fmt.Errorf(\"failed to ping server. Got %d\", resp.StatusCode)\n\t} else if _, err := rtnew.Ping(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tproductid := \"terraform-provider-artifactory/\" + ProviderVersion\n\tcommandid := \"Terraform/\" + version.Version\n\tusage.SendReportUsage(productid, commandid, rtnew)\n\n\trt := &ArtClient{\n\t\tArtOld: rtold,\n\t\tArtNew: rtnew,\n\t}\n\n\treturn rt, nil\n}", "func (c *Provider) InfraProvider() fab.InfraProvider {\n\treturn c.infraProvider\n}", "func TestBaseImage(t *testing.T) {\n\tctx, err := controllerPrepare()\n\tif err != nil {\n\t\tt.Fatal(\"Fail in controller prepare: \", err)\n\t}\n\teveBaseRef := os.Getenv(\"EVE_BASE_REF\")\n\tif len(eveBaseRef) == 0 {\n\t\teveBaseRef = \"4.10.0\"\n\t}\n\tzArch := os.Getenv(\"ZARCH\")\n\tif len(eveBaseRef) == 0 {\n\t\tzArch = \"amd64\"\n\t}\n\tHV := os.Getenv(\"HV\")\n\tif HV == \"xen\" {\n\t\tHV = \"\"\n\t}\n\tvar baseImageTests = []struct {\n\t\tdataStoreID string\n\t\timageID string\n\t\tbaseID string\n\t\timageRelativePath string\n\t\timageFormat config.Format\n\t\teveBaseRef string\n\t\tzArch string\n\t\tHV string\n\t}{\n\t\t{eServerDataStoreID,\n\n\t\t\t\"1ab8761b-5f89-4e0b-b757-4b87a9fa93ec\",\n\n\t\t\t\"22b8761b-5f89-4e0b-b757-4b87a9fa93ec\",\n\n\t\t\t\"baseos.qcow2\",\n\t\t\tconfig.Format_QCOW2,\n\t\t\teveBaseRef,\n\t\t\tzArch,\n\t\t\tHV,\n\t\t},\n\t}\n\tfor _, tt := range baseImageTests {\n\t\tbaseOSVersion := fmt.Sprintf(\"%s-%s\", tt.eveBaseRef, tt.zArch)\n\t\tif tt.HV != \"\" {\n\t\t\tbaseOSVersion = fmt.Sprintf(\"%s-%s-%s\", tt.eveBaseRef, tt.zArch, tt.HV)\n\t\t}\n\t\tt.Run(baseOSVersion, func(t *testing.T) {\n\n\t\t\terr = prepareBaseImageLocal(ctx, tt.dataStoreID, tt.imageID, tt.baseID, tt.imageRelativePath, tt.imageFormat, baseOSVersion)\n\n\t\t\tif err != nil {\n\t\t\t\tt.Fatal(\"Fail in prepare base image from local file: \", err)\n\t\t\t}\n\t\t\tdeviceCtx, err := ctx.GetDeviceFirst()\n\t\t\tif err != nil {\n\t\t\t\tt.Fatal(\"Fail in get first device: \", err)\n\t\t\t}\n\t\t\tdeviceCtx.SetBaseOSConfig([]string{tt.baseID})\n\t\t\tdevUUID := deviceCtx.GetID()\n\t\t\terr = ctx.ConfigSync(deviceCtx)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatal(\"Fail in sync config with controller: \", err)\n\t\t\t}\n\t\t\tt.Run(\"Started\", func(t *testing.T) {\n\t\t\t\terr := ctx.InfoChecker(devUUID, map[string]string{\"devId\": devUUID.String(), \"shortVersion\": baseOSVersion}, einfo.ZInfoDevSW, 300)\n\t\t\t\tif err != nil {\n\t\t\t\t\tt.Fatal(\"Fail in waiting for base image update init: \", err)\n\t\t\t\t}\n\t\t\t})\n\t\t\tt.Run(\"Downloaded\", func(t *testing.T) {\n\t\t\t\terr := ctx.InfoChecker(devUUID, map[string]string{\"devId\": devUUID.String(), \"shortVersion\": baseOSVersion, \"downloadProgress\": \"100\"}, einfo.ZInfoDevSW, 1500)\n\t\t\t\tif err != nil {\n\t\t\t\t\tt.Fatal(\"Fail in waiting for base image download progress: \", err)\n\t\t\t\t}\n\t\t\t})\n\t\t\tt.Run(\"Logs\", func(t *testing.T) {\n\t\t\t\tif !checkLogs {\n\t\t\t\t\tt.Skip(\"no LOGS flag set - skipped\")\n\t\t\t\t}\n\t\t\t\terr = ctx.LogChecker(devUUID, map[string]string{\"devId\": devUUID.String(), \"eveVersion\": baseOSVersion}, 1200)\n\t\t\t\tif err != nil {\n\t\t\t\t\tt.Fatal(\"Fail in waiting for base image logs: \", err)\n\t\t\t\t}\n\t\t\t})\n\t\t\ttimeout := time.Duration(1200)\n\n\t\t\tif !checkLogs {\n\t\t\t\ttimeout = 2400\n\t\t\t}\n\t\t\tt.Run(\"Active\", func(t *testing.T) {\n\t\t\t\terr = ctx.InfoChecker(devUUID, map[string]string{\"devId\": devUUID.String(), \"shortVersion\": baseOSVersion, \"status\": \"INSTALLED\", \"partitionState\": \"(inprogress|active)\"}, einfo.ZInfoDevSW, timeout)\n\t\t\t\tif err != nil {\n\t\t\t\t\tt.Fatal(\"Fail in waiting for base image installed status: \", err)\n\t\t\t\t}\n\t\t\t})\n\t\t})\n\t}\n\n}", "func mockChildPackages() {\n\n\t// Fake an AWS credentials file so that the mfile package will nehave as if it is happy\n\tsetFakeCredentials()\n\n\t// Fake out the creds package into using an apparently credentials response from AWS\n\tcreds.SetGetSessionTokenFunc(func(awsService *sts.STS, input *sts.GetSessionTokenInput) (*sts.GetSessionTokenOutput, error) {\n\t\treturn getSessionTokenOutput, nil\n\t})\n\n}", "func NewMockInfra(ctrl *gomock.Controller) *MockInfra {\n\tmock := &MockInfra{ctrl: ctrl}\n\tmock.recorder = &MockInfraMockRecorder{mock}\n\treturn mock\n}", "func TestConjur_Provider(t *testing.T) {\n\tvar err error\n\tvar provider plugin_v1.Provider\n\tname := \"conjur\"\n\n\toptions := plugin_v1.ProviderOptions{\n\t\tName: name,\n\t}\n\n\tt.Run(\"Can create the Conjur provider\", func(t *testing.T) {\n\t\tprovider, err = providers.ProviderFactories[name](options)\n\t\tassert.NoError(t, err)\n\t})\n\n\tt.Run(\"Has the expected provider name\", func(t *testing.T) {\n\t\tassert.Equal(t, \"conjur\", provider.GetName())\n\t})\n\n\tt.Run(\"Can provide an access token\", func(t *testing.T) {\n\t\tid := \"accessToken\"\n\t\tvalues, err := provider.GetValues(id)\n\n\t\tassert.NoError(t, err)\n\t\tassert.NotNil(t, values[id])\n\t\tassert.NoError(t, values[id].Error)\n\t\tassert.NotNil(t, values[id].Value)\n\n\t\ttoken := make(map[string]string)\n\t\terr = json.Unmarshal(values[id].Value, &token)\n\t\tassert.NoError(t, err)\n\t\tassert.NotNil(t, token[\"protected\"])\n\t\tassert.NotNil(t, token[\"payload\"])\n\t})\n\n\tt.Run(\"Reports an unknown value\",\n\t\ttestutils.Reports(\n\t\t\tprovider,\n\t\t\t\"foobar\",\n\t\t\t\"404 Not Found. CONJ00076E Variable dev:variable:foobar is empty or not found..\",\n\t\t),\n\t)\n\n\tt.Run(\"Provides\", func(t *testing.T) {\n\t\tfor _, testCase := range canProvideTestCases {\n\t\t\tt.Run(testCase.Description, testutils.CanProvide(provider, testCase.ID, testCase.ExpectedValue))\n\t\t}\n\t})\n}", "func providerFactory(_ io.Reader) (cloudprovider.Interface, error) {\n\tlog := klogr.NewWithOptions(klogr.WithFormat(klogr.FormatKlog))\n\tc, err := loadConfig(envconfig.OsLookuper())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tapiUrl := katapult.DefaultURL\n\tif c.APIHost != \"\" {\n\t\tlog.Info(\"default API base URL overrided\",\n\t\t\t\"url\", c.APIHost)\n\t\tapiUrl, err = url.Parse(c.APIHost)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to parse provided api url: %w\", err)\n\t\t}\n\t}\n\n\trm, err := katapult.New(\n\t\tkatapult.WithAPIKey(c.APIKey),\n\t\tkatapult.WithBaseURL(apiUrl),\n\t\tkatapult.WithUserAgent(\"kce-ccm\"), // TODO: Add version.\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tclient := core.New(rm)\n\n\treturn &provider{\n\t\tlog: log,\n\t\tkatapult: client,\n\t\tconfig: *c,\n\t\tloadBalancer: &loadBalancerManager{\n\t\t\tlog: log,\n\t\t\tconfig: *c,\n\t\t\tloadBalancerController: client.LoadBalancers,\n\t\t\tloadBalancerRuleController: client.LoadBalancerRules,\n\t\t},\n\t}, nil\n}", "func (mdhth *MockDHTHandler) Provider(string, bool) error {\n\treturn nil\n}", "func TestCustomAnchoreConfigProvider_GetConfiguration(t *testing.T) {\n\tintegratedServiceRepository := integratedservices.NewInMemoryIntegratedServiceRepository(map[uint][]integratedservices.IntegratedService{\n\t\t1: {\n\t\t\t{\n\t\t\t\tName: \"securityscan\",\n\t\t\t\tSpec: map[string]interface{}{\n\t\t\t\t\t\"customAnchore\": map[string]interface{}{\n\t\t\t\t\t\t\"enabled\": true,\n\t\t\t\t\t\t\"url\": \"https://anchore.example.com\",\n\t\t\t\t\t\t\"secretId\": \"secretId\",\n\t\t\t\t\t\t\"insecure\": true,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tOutput: nil,\n\t\t\t\tStatus: integratedservices.IntegratedServiceStatusActive,\n\t\t\t},\n\t\t},\n\t})\n\n\tsecretStore := new(SecretStore)\n\tsecretStore.On(\"GetSecretValues\", mock.Anything, \"secretId\").Return(\n\t\tmap[string]string{\n\t\t\t\"username\": \"user\",\n\t\t\t\"password\": \"password\",\n\t\t},\n\t\tnil,\n\t)\n\n\tconfigProvider := NewCustomAnchoreConfigProvider(integratedServiceRepository, secretStore, services.NoopLogger{})\n\n\tconfig, err := configProvider.GetConfiguration(context.Background(), 1)\n\trequire.NoError(t, err)\n\n\tassert.Equal(\n\t\tt,\n\t\tanchore.Config{\n\t\t\tEndpoint: \"https://anchore.example.com\",\n\t\t\tUser: \"user\",\n\t\t\tPassword: \"password\",\n\t\t\tInsecure: true,\n\t\t},\n\t\tconfig,\n\t)\n\n\tsecretStore.AssertExpectations(t)\n}", "func providerConfigure(ctx context.Context, d *schema.ResourceData) (interface{}, diag.Diagnostics) {\n\n\tvar diags diag.Diagnostics\n\tbearerToken := d.Get(\"bearer_token\").(string)\n\n\tvar host string\n\thVal, ok := d.GetOk(\"host\")\n\tif ok {\n\t\ttempHost := hVal.(string)\n\t\thost = tempHost\n\t}\n\n\tc := NewClient(host, bearerToken, &http.Client{})\n\treturn c, diags\n}", "func TestDontWaitForOtherProvidersIfWeGotError(t *testing.T) {\n\tstart := time.Now()\n\n\tappCustom := App{\n\t\tContentProvider: NewContentProviderService(\n\t\t\tmap[Provider]Client{\n\t\t\t\tProvider1: &ClientMock{\n\t\t\t\t\tGetContentFn: func(userIP string, count int) ([]*ContentItem, error) {\n\t\t\t\t\t\treturn []*ContentItem{}, errors.New(\"some error from provider 1\")\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tProvider2: &ClientMock{\n\t\t\t\t\tGetContentFn: func(userIP string, count int) ([]*ContentItem, error) {\n\t\t\t\t\t\treturn []*ContentItem{}, errors.New(\"some error from provider 2\")\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tProvider3: &ClientMock{\n\t\t\t\t\tGetContentFn: func(userIP string, count int) ([]*ContentItem, error) {\n\t\t\t\t\t\t// let's imitate some pending request to provider\n\t\t\t\t\t\ttime.Sleep(5 * time.Second)\n\t\t\t\t\t\treturn []*ContentItem{{\n\t\t\t\t\t\t\tSource: \"3\",\n\t\t\t\t\t\t}}, nil\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tDefaultConfig,\n\t\t\tWithTimeOut(500*time.Millisecond),\n\t\t),\n\t}\n\n\tcontent := runRequest(t, appCustom, SimpleContentRequest)\n\n\tif len(content) != 0 {\n\t\tt.Fatalf(\"Got %d items back, want 0\", len(content))\n\t}\n\n\texecTime := time.Since(start)\n\tif execTime > time.Second {\n\t\tt.Fatalf(\"test time should be less then 1 second, got: %s\", execTime)\n\t}\n}", "func (m *MockChoriaProvider) Identity() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Identity\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func (m *MockProvider) OnEndpointsSynced() {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"OnEndpointsSynced\")\n}", "func (m *MockProcessProvider) SetBootstrapperProvider(bootstrapper BootstrapperProvider) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"SetBootstrapperProvider\", bootstrapper)\n}", "func TestCNContainer_Base(t *testing.T) {\n\tassert := assert.New(t)\n\n\tcn, err := cnTestInit()\n\trequire.Nil(t, err)\n\n\tdockerPlugin, err := startDockerPlugin(t)\n\trequire.Nil(t, err)\n\n\t//From YAML on instance init\n\t//Two VNICs on the same tenant subnet\n\tmac, _ := net.ParseMAC(\"CA:FE:00:01:02:03\")\n\tmac2, _ := net.ParseMAC(\"CA:FE:00:02:02:03\")\n\t_, tnet, _ := net.ParseCIDR(\"192.168.111.0/24\")\n\ttip := net.ParseIP(\"192.168.111.100\")\n\ttip2 := net.ParseIP(\"192.168.111.102\")\n\tcip := net.ParseIP(\"192.168.200.200\")\n\n\tvnicCfg := &VnicConfig{\n\t\tVnicRole: TenantContainer,\n\t\tVnicIP: tip,\n\t\tConcIP: cip,\n\t\tVnicMAC: mac,\n\t\tSubnet: *tnet,\n\t\tSubnetKey: 0xF,\n\t\tVnicID: \"vuuid\",\n\t\tInstanceID: \"iuuid\",\n\t\tTenantID: \"tuuid\",\n\t\tSubnetID: \"suuid\",\n\t\tConcID: \"cnciuuid\",\n\t}\n\n\tvnicCfg2 := &VnicConfig{\n\t\tVnicRole: TenantContainer,\n\t\tVnicIP: tip2,\n\t\tConcIP: cip,\n\t\tVnicMAC: mac2,\n\t\tSubnet: *tnet,\n\t\tSubnetKey: 0xF,\n\t\tVnicID: \"vuuid2\",\n\t\tInstanceID: \"iuuid2\",\n\t\tTenantID: \"tuuid\",\n\t\tSubnetID: \"suuid\",\n\t\tConcID: \"cnciuuid\",\n\t}\n\n\tvar subnetID, iface string //Used to check that they match\n\n\t// Create a VNIC: Should create bridge and tunnels\n\tif vnic, ssntpEvent, cInfo, err := cn.CreateVnic(vnicCfg); err != nil {\n\t\tt.Error(err)\n\t} else {\n\t\t// expected SSNTP Event\n\t\tif assert.NotNil(ssntpEvent) {\n\t\t\tassert.Equal(ssntpEvent.Event, SsntpTunAdd)\n\t\t}\n\t\t// expected Container Event\n\t\tif assert.NotNil(cInfo) {\n\t\t\tassert.Equal(cInfo.CNContainerEvent, ContainerNetworkAdd)\n\t\t\tassert.NotEqual(cInfo.SubnetID, \"\")\n\t\t\tassert.NotEqual(cInfo.Subnet.String(), \"\")\n\t\t\tassert.NotEqual(cInfo.Gateway.String(), \"\")\n\t\t\tassert.NotEqual(cInfo.Bridge, \"\")\n\t\t}\n\t\tassert.Nil(validSsntpEvent(ssntpEvent, vnicCfg))\n\n\t\t//Cache the first subnet ID we see. All subsequent should have the same\n\t\tsubnetID = cInfo.SubnetID\n\t\tiface = vnic.InterfaceName()\n\t\tassert.NotEqual(iface, \"\")\n\n\t\t//Launcher will attach to this name and send out the event\n\t\t//Launcher will also create the logical docker network\n\t\tdebugPrint(t, \"VNIC created =\", vnic.LinkName, ssntpEvent, cInfo)\n\t\tassert.Nil(linkDump(t))\n\n\t\t//Now kick off the docker commands\n\t\tassert.Nil(dockerNetCreate(cInfo.Subnet, cInfo.Gateway, cInfo.Bridge, cInfo.SubnetID))\n\t\tassert.Nil(dockerNetInfo(cInfo.SubnetID))\n\t\tassert.Nil(dockerRunVerify(vnicCfg.VnicIP.String(), vnicCfg.VnicIP, vnicCfg.VnicMAC, cInfo.SubnetID))\n\t\tassert.Nil(dockerContainerDelete(vnicCfg.VnicIP.String()))\n\t}\n\n\t//Duplicate VNIC creation\n\tif vnic, ssntpEvent, cInfo, err := cn.CreateVnic(vnicCfg); err != nil {\n\t\tt.Error(err)\n\t} else {\n\t\tassert.Nil(ssntpEvent, \"ERROR: DUP unexpected event\")\n\t\tif assert.NotNil(cInfo) {\n\t\t\tassert.Equal(cInfo.SubnetID, subnetID)\n\t\t\tassert.Equal(cInfo.CNContainerEvent, ContainerNetworkInfo)\n\t\t\tassert.Equal(iface, vnic.InterfaceName())\n\t\t}\n\t}\n\n\t//Second VNIC creation - Should succeed\n\tif vnic, ssntpEvent, cInfo, err := cn.CreateVnic(vnicCfg2); err != nil {\n\t\tt.Error(err)\n\t} else {\n\t\tassert.Nil(ssntpEvent)\n\t\tif assert.NotNil(cInfo) {\n\t\t\tassert.Equal(cInfo.SubnetID, subnetID)\n\t\t\tassert.Equal(cInfo.CNContainerEvent, ContainerNetworkInfo)\n\t\t}\n\t\tiface = vnic.InterfaceName()\n\t\tassert.NotEqual(iface, \"\")\n\t\tassert.Nil(dockerRunVerify(vnicCfg2.VnicIP.String(), vnicCfg2.VnicIP,\n\t\t\tvnicCfg2.VnicMAC, cInfo.SubnetID))\n\t\tassert.Nil(dockerContainerDelete(vnicCfg2.VnicIP.String()))\n\t}\n\n\t//Duplicate VNIC creation\n\tif vnic, ssntpEvent, cInfo, err := cn.CreateVnic(vnicCfg2); err != nil {\n\t\tt.Error(err)\n\t} else {\n\t\tassert.Nil(ssntpEvent)\n\t\tif assert.NotNil(cInfo) {\n\t\t\tassert.Equal(cInfo.SubnetID, subnetID)\n\t\t\tassert.Equal(cInfo.CNContainerEvent, ContainerNetworkInfo)\n\t\t\tassert.Equal(iface, vnic.InterfaceName())\n\t\t}\n\t}\n\n\t//Destroy the first one\n\tif ssntpEvent, cInfo, err := cn.DestroyVnic(vnicCfg); err != nil {\n\t\tt.Error(err)\n\t} else {\n\t\tassert.Nil(ssntpEvent)\n\t\tassert.Nil(cInfo)\n\t}\n\n\t//Destroy it again\n\tif ssntpEvent, cInfo, err := cn.DestroyVnic(vnicCfg); err != nil {\n\t\tt.Error(err)\n\t} else {\n\t\tassert.Nil(ssntpEvent)\n\t\tassert.Nil(cInfo)\n\t}\n\n\t// Try and destroy - should work - cInfo should be reported\n\tif ssntpEvent, cInfo, err := cn.DestroyVnic(vnicCfg2); err != nil {\n\t\tt.Error(err)\n\t} else {\n\t\tassert.NotNil(ssntpEvent)\n\t\tif assert.NotNil(cInfo) {\n\t\t\tassert.Equal(cInfo.SubnetID, subnetID)\n\t\t\tassert.Equal(cInfo.CNContainerEvent, ContainerNetworkDel)\n\t\t}\n\t}\n\n\t//Has to be called after the VNIC has been deleted\n\tassert.Nil(dockerNetDelete(subnetID))\n\tassert.Nil(dockerNetList())\n\n\t//Destroy it again\n\tif ssntpEvent, cInfo, err := cn.DestroyVnic(vnicCfg2); err != nil {\n\t\tt.Error(err)\n\t} else {\n\t\tassert.Nil(ssntpEvent)\n\t\tassert.Nil(cInfo)\n\t}\n\n\tassert.Nil(stopDockerPlugin(dockerPlugin))\n}", "func newExecProvider() ExecProvider {\n\treturn realExecProvider{}\n}", "func (m *MockecsDescriber) Platform() (*ecs.ContainerPlatform, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Platform\")\n\tret0, _ := ret[0].(*ecs.ContainerPlatform)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func getTestDriverA(env string) (*OVTest, *ov.OVClient) {\n\t// os.Setenv(\"DEBUG\", \"true\") // remove comment to debug logs\n\tvar ot *OVTest\n\tvar tc *testconfig.TestConfig\n\tot = &OVTest{Tc: tc.NewTestConfig(), Env: env}\n\tot.GetEnvironment(env)\n\tot.Tc.GetTestingConfiguration(os.Getenv(\"ONEVIEW_TEST_DATA\"))\n\tot.Client = &ov.OVClient{Client: rest.Client{\n\t\tUser: os.Getenv(\"ONEVIEW_OV_USER\"),\n\t\tPassword: os.Getenv(\"ONEVIEW_OV_PASSWORD\"),\n\t\tDomain: os.Getenv(\"ONEVIEW_OV_DOMAIN\"),\n\t\tEndpoint: os.Getenv(\"ONEVIEW_OV_ENDPOINT\"),\n\t\t// ConfigDir:\n\t\tSSLVerify: false,\n\t\tAPIKey: \"none\",\n\t},\n\t}\n\terr := ot.Client.RefreshVersion()\n\tif err != nil {\n\t\tlog.Errorf(\"Problem with getting api version refreshed : %+v\", err)\n\t}\n\t// fmt.Println(\"Setting up test with getTestDriverA\")\n\treturn ot, ot.Client\n}", "func TestNewIdentityManager(t *testing.T) {\n\tt.Run(\"success\", func(t *testing.T) {\n\t\tepCfg := &mocks.EndpointConfig{}\n\t\tepCfg.NetworkConfigReturns(&fab.NetworkConfig{\n\t\t\tOrganizations: map[string]fab.OrganizationConfig{\"org1msp\": {}},\n\t\t})\n\n\t\tm, err := newIdentityManager(\"org1MSP\", &mocks.CryptoSuite{}, epCfg, \"./msp\")\n\t\trequire.NoError(t, err)\n\t\trequire.NotNil(t, m)\n\t})\n\n\tt.Run(\"No endpoint config -> error\", func(t *testing.T) {\n\t\tm, err := newIdentityManager(\"org1MSP\", &mocks.CryptoSuite{}, nil, \"./msp\")\n\t\trequire.EqualError(t, err, \"endpoint config is required\")\n\t\trequire.Nil(t, m)\n\t})\n\n\tt.Run(\"No org name -> error\", func(t *testing.T) {\n\t\tm, err := newIdentityManager(\"\", nil, &mocks.EndpointConfig{}, \"./msp\")\n\t\trequire.EqualError(t, err, \"orgName is required\")\n\t\trequire.Nil(t, m)\n\t})\n\n\tt.Run(\"No crypto suite -> error\", func(t *testing.T) {\n\t\tm, err := newIdentityManager(\"org1MSP\", nil, &mocks.EndpointConfig{}, \"./msp\")\n\t\trequire.EqualError(t, err, \"cryptoProvider is required\")\n\t\trequire.Nil(t, m)\n\t})\n\n\tt.Run(\"Org not found -> error\", func(t *testing.T) {\n\t\tepCfg := &mocks.EndpointConfig{}\n\t\tepCfg.NetworkConfigReturns(&fab.NetworkConfig{})\n\n\t\tm, err := newIdentityManager(\"org1MSP\", &mocks.CryptoSuite{}, epCfg, \"./msp\")\n\t\trequire.EqualError(t, err, \"org config retrieval failed\")\n\t\trequire.Nil(t, m)\n\t})\n\n\tt.Run(\"MSP config path not provided -> error\", func(t *testing.T) {\n\t\tepCfg := &mocks.EndpointConfig{}\n\t\tepCfg.NetworkConfigReturns(&fab.NetworkConfig{\n\t\t\tOrganizations: map[string]fab.OrganizationConfig{\"org1msp\": {}},\n\t\t})\n\n\t\tm, err := newIdentityManager(\"org1MSP\", &mocks.CryptoSuite{}, epCfg, \"\")\n\t\trequire.EqualError(t, err, \"either mspConfigPath or an embedded list of users is required\")\n\t\trequire.Nil(t, m)\n\t})\n}", "func NewProvider() *ProviderConfig {\n\tproviderConfig := &ProviderConfig{\n\t\tAlibaba: make(map[string]*models.AlibabaCloudSpec),\n\t\tAnexia: make(map[string]*models.AnexiaCloudSpec),\n\t\tAws: make(map[string]*models.AWSCloudSpec),\n\t\tAzure: make(map[string]*models.AzureCloudSpec),\n\t\tDigitalocean: make(map[string]*models.DigitaloceanCloudSpec),\n\t\tFake: make(map[string]*models.FakeCloudSpec),\n\t\tGcp: make(map[string]*models.GCPCloudSpec),\n\t\tHetzner: make(map[string]*models.HetznerCloudSpec),\n\t\tKubevirt: make(map[string]*models.KubevirtCloudSpec),\n\t\tOpenstack: make(map[string]*models.OpenstackCloudSpec),\n\t\tPacket: make(map[string]*models.PacketCloudSpec),\n\t\tVsphere: make(map[string]*models.VSphereCloudSpec),\n\t}\n\n\tproviderConfig.Alibaba[\"Alibaba\"] = newAlibabaCloudSpec()\n\tproviderConfig.Anexia[\"Anexia\"] = newAnexiaCloudSpec()\n\tproviderConfig.Aws[\"Aws\"] = newAWSCloudSpec()\n\tproviderConfig.Azure[\"Azure\"] = newAzureCloudSpec()\n\tproviderConfig.Digitalocean[\"Digitalocean\"] = newDigitaloceanCloudSpec()\n\tproviderConfig.Fake[\"Fake\"] = newFakeCloudSpec()\n\tproviderConfig.Gcp[\"Gcp\"] = newGCPCloudSpec()\n\tproviderConfig.Hetzner[\"Hetzner\"] = newHetznerCloudSpec()\n\tproviderConfig.Kubevirt[\"Kubevirt\"] = newKubevirtCloudSpec()\n\tproviderConfig.Openstack[\"Openstack\"] = newOpenstackCloudSpec()\n\tproviderConfig.Packet[\"Packet\"] = newPacketCloudSpec()\n\tproviderConfig.Vsphere[\"Vsphere\"] = newVSphereCloudSpec()\n\n\treturn providerConfig\n}", "func (m *MockResolver) EvictSelf() error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"EvictSelf\")\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func Provider() tfbridge.ProviderInfo {\n\t// Instantiate the Terraform provider\n\tp := shimv2.NewProvider(shim.NewProvider())\n\n\t// Create a Pulumi provider mapping\n\tprov := tfbridge.ProviderInfo{\n\t\tP: p,\n\t\tName: \"azuread\",\n\t\tDisplayName: \"Azure Active Directory (Azure AD)\",\n\t\tDescription: \"A Pulumi package for creating and managing Azure Active Directory (Azure AD) cloud resources.\",\n\t\tKeywords: []string{\"pulumi\", \"azuread\"},\n\t\tLicense: \"Apache-2.0\",\n\t\tHomepage: \"https://pulumi.io\",\n\t\tGitHubOrg: \"hashicorp\",\n\t\tRepository: \"https://github.com/pulumi/pulumi-azuread\",\n\t\tConfig: map[string]*tfbridge.SchemaInfo{\n\t\t\t\"environment\": {\n\t\t\t\tDefault: &tfbridge.DefaultInfo{\n\t\t\t\t\tValue: \"public\",\n\t\t\t\t\tEnvVars: []string{\"ARM_ENVIRONMENT\"},\n\t\t\t\t},\n\t\t\t},\n\t\t\t\"msi_endpoint\": {\n\t\t\t\tDefault: &tfbridge.DefaultInfo{\n\t\t\t\t\tEnvVars: []string{\"ARM_MSI_ENDPOINT\"},\n\t\t\t\t},\n\t\t\t},\n\t\t\t\"use_msi\": {\n\t\t\t\tDefault: &tfbridge.DefaultInfo{\n\t\t\t\t\tValue: false,\n\t\t\t\t\tEnvVars: []string{\"ARM_USE_MSI\"},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tPreConfigureCallback: preConfigureCallback,\n\t\tResources: map[string]*tfbridge.ResourceInfo{\n\t\t\t\"azuread_application\": {Tok: makeResource(mainMod, \"Application\")},\n\t\t\t\"azuread_application_password\": {Tok: makeResource(mainMod, \"ApplicationPassword\")},\n\t\t\t\"azuread_group\": {Tok: makeResource(mainMod, \"Group\")},\n\t\t\t\"azuread_service_principal\": {Tok: makeResource(mainMod, \"ServicePrincipal\")},\n\t\t\t\"azuread_service_principal_password\": {Tok: makeResource(mainMod, \"ServicePrincipalPassword\")},\n\t\t\t\"azuread_service_principal_delegated_permission_grant\": {\n\t\t\t\tTok: makeResource(mainMod, \"ServicePrincipalDelegatedPermissionGrant\"),\n\t\t\t},\n\t\t\t\"azuread_user\": {Tok: makeResource(mainMod, \"User\")},\n\t\t\t\"azuread_group_member\": {Tok: makeResource(mainMod, \"GroupMember\")},\n\t\t\t\"azuread_application_certificate\": {Tok: makeResource(mainMod, \"ApplicationCertificate\")},\n\t\t\t\"azuread_service_principal_certificate\": {Tok: makeResource(mainMod, \"ServicePrincipalCertificate\")},\n\t\t\t\"azuread_service_principal_token_signing_certificate\": {\n\t\t\t\tTok: makeResource(mainMod, \"ServicePrincipalTokenSigningCertificate\"),\n\t\t\t},\n\t\t\t\"azuread_application_pre_authorized\": {Tok: makeResource(mainMod, \"ApplicationPreAuthorized\")},\n\t\t\t\"azuread_invitation\": {Tok: makeResource(mainMod, \"Invitation\")},\n\t\t\t\"azuread_conditional_access_policy\": {Tok: makeResource(mainMod, \"ConditionalAccessPolicy\")},\n\t\t\t\"azuread_named_location\": {Tok: makeResource(mainMod, \"NamedLocation\")},\n\t\t\t\"azuread_directory_role\": {Tok: makeResource(mainMod, \"DirectoryRole\")},\n\t\t\t\"azuread_directory_role_member\": {Tok: makeResource(mainMod, \"DirectoryRoleMember\")},\n\t\t\t\"azuread_app_role_assignment\": {Tok: makeResource(mainMod, \"AppRoleAssignment\")},\n\t\t\t\"azuread_administrative_unit\": {Tok: makeResource(mainMod, \"AdministrativeUnit\")},\n\t\t\t\"azuread_administrative_unit_member\": {Tok: makeResource(mainMod, \"AdministrativeUnitMember\")},\n\t\t\t\"azuread_application_federated_identity_credential\": {\n\t\t\t\tTok: makeResource(mainMod, \"ApplicationFederatedIdentityCredential\"),\n\t\t\t},\n\t\t\t\"azuread_custom_directory_role\": {Tok: makeResource(mainMod, \"CustomDirectoryRole\")},\n\t\t\t\"azuread_claims_mapping_policy\": {Tok: makeResource(mainMod, \"ClaimsMappingPolicy\")},\n\t\t\t\"azuread_directory_role_assignment\": {Tok: makeResource(mainMod, \"DirectoryRoleAssignment\")},\n\t\t\t\"azuread_service_principal_claims_mapping_policy_assignment\": {\n\t\t\t\tTok: makeResource(mainMod, \"ServicePrincipalClaimsMappingPolicyAssignment\"),\n\t\t\t},\n\t\t\t\"azuread_synchronization_job\": {Tok: makeResource(mainMod, \"SynchronizationJob\")},\n\t\t\t\"azuread_synchronization_secret\": {Tok: makeResource(mainMod, \"SynchronizationSecret\")},\n\t\t\t\"azuread_access_package\": {Tok: makeResource(mainMod, \"AccessPackage\")},\n\t\t\t\"azuread_access_package_assignment_policy\": {Tok: makeResource(mainMod, \"AccessPackageAssignmentPolicy\")},\n\t\t\t\"azuread_access_package_catalog\": {Tok: makeResource(mainMod, \"AccessPackageCatalog\")},\n\t\t\t\"azuread_access_package_resource_catalog_association\": {\n\t\t\t\tTok: makeResource(mainMod, \"AccessPackageResourceCatalogAssociation\"),\n\t\t\t},\n\t\t\t\"azuread_access_package_resource_package_association\": {\n\t\t\t\tTok: makeResource(mainMod, \"AccessPackageResourcePackageAssociation\"),\n\t\t\t},\n\t\t\t\"azuread_administrative_unit_role_member\": {Tok: makeResource(mainMod, \"AdministrativeUnitRoleMember\")},\n\t\t\t\"azuread_user_flow_attribute\": {Tok: makeResource(mainMod, \"UserFlowAttribute\")},\n\t\t},\n\t\tDataSources: map[string]*tfbridge.DataSourceInfo{\n\t\t\t\"azuread_client_config\": {Tok: makeDataSource(mainMod, \"getClientConfig\")},\n\t\t\t\"azuread_application_published_app_ids\": {Tok: makeDataSource(mainMod, \"getApplicationPublishedAppIds\")},\n\t\t\t\"azuread_application_template\": {Tok: makeDataSource(mainMod, \"getApplicationTemplate\")},\n\t\t\t\"azuread_service_principals\": {Tok: makeDataSource(mainMod, \"getServicePrincipals\")},\n\t\t\t\"azuread_administrative_unit\": {Tok: makeDataSource(mainMod, \"getAdministrativeUnit\")},\n\t\t\t\"azuread_directory_object\": {Tok: makeDataSource(mainMod, \"getDirectoryObject\")},\n\t\t\t\"azuread_directory_roles\": {Tok: makeDataSource(mainMod, \"getDirectoryRoles\")},\n\t\t\t\"azuread_access_package\": {Tok: makeDataSource(mainMod, \"getAccessPackage\")},\n\t\t\t\"azuread_access_package_catalog\": {Tok: makeDataSource(mainMod, \"getAccessPackageCatalog\")},\n\t\t},\n\t\tJavaScript: &tfbridge.JavaScriptInfo{\n\t\t\t// List any npm dependencies and their versions\n\t\t\tDependencies: map[string]string{\n\t\t\t\t\"@pulumi/pulumi\": \"^3.0.0\",\n\t\t\t},\n\t\t\tDevDependencies: map[string]string{\n\t\t\t\t\"@types/node\": \"^10.0.0\", // so we can access strongly typed node definitions.\n\t\t\t\t\"@types/mime\": \"^2.0.0\",\n\t\t\t},\n\t\t},\n\t\tPython: &tfbridge.PythonInfo{\n\t\t\tRequires: map[string]string{\n\t\t\t\t\"pulumi\": \">=3.0.0,<4.0.0\",\n\t\t\t},\n\t\t},\n\t\tGolang: &tfbridge.GolangInfo{\n\t\t\tImportBasePath: filepath.Join(\n\t\t\t\tfmt.Sprintf(\"github.com/pulumi/pulumi-%[1]s/sdk/\", mainPkg),\n\t\t\t\ttfbridge.GetModuleMajorVersion(version.Version),\n\t\t\t\t\"go\",\n\t\t\t\tmainPkg,\n\t\t\t),\n\t\t\tGenerateResourceContainerTypes: true,\n\t\t},\n\t\tCSharp: &tfbridge.CSharpInfo{\n\t\t\tPackageReferences: map[string]string{\n\t\t\t\t\"Pulumi\": \"3.*\",\n\t\t\t},\n\t\t\tNamespaces: map[string]string{\n\t\t\t\t\"azuread\": \"AzureAD\",\n\t\t\t},\n\t\t}, MetadataInfo: tfbridge.NewProviderMetadata(metadata),\n\t}\n\n\tprov.MustComputeTokens(tfbridgetokens.SingleModule(\"azuread_\", mainMod,\n\t\ttfbridgetokens.MakeStandard(mainPkg)))\n\tprov.SetAutonaming(255, \"-\")\n\tprov.MustApplyAutoAliases()\n\n\treturn prov\n}", "func (m *MockInfra) Region() string {\n\tret := m.ctrl.Call(m, \"Region\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func TestTimeoutToProviders(t *testing.T) {\n\tstart := time.Now()\n\n\tappCustom := App{\n\t\tContentProvider: NewContentProviderService(\n\t\t\tmap[Provider]Client{\n\t\t\t\tProvider1: SampleContentProvider{Source: Provider1},\n\t\t\t\tProvider2: SampleContentProvider{Source: Provider2},\n\t\t\t\tProvider3: &ClientMock{\n\t\t\t\t\tGetContentFn: func(userIP string, count int) ([]*ContentItem, error) {\n\t\t\t\t\t\t// let's imitate some pending request to provider\n\t\t\t\t\t\ttime.Sleep(5 * time.Second)\n\t\t\t\t\t\treturn []*ContentItem{{\n\t\t\t\t\t\t\tSource: \"3\",\n\t\t\t\t\t\t}}, nil\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tDefaultConfig,\n\t\t\tWithTimeOut(500*time.Millisecond),\n\t\t),\n\t}\n\n\tcontent := runRequest(t, appCustom, SimpleContentRequest)\n\tif len(content) != 4 {\n\t\tt.Fatalf(\"Got %d items back, want 4\", len(content))\n\t}\n\n\texecTime := time.Since(start)\n\tif execTime > time.Second {\n\t\tt.Fatalf(\"test time should be less then 1 second, got: %s\", execTime)\n\t}\n}", "func Test_provider_doTaskReporter(t *testing.T) {\n\tctrl := gomock.NewController(t)\n\tdefer ctrl.Finish()\n\tlogger := NewMockLogger(ctrl)\n\n\tlogger.EXPECT().Infof(\"begin do task report, taskID: %d\", uint64(1)).Return()\n\n\tvar (\n\t\tbdl *bundle.Bundle\n\t\tdbClient *dbclient.Client\n\t)\n\tmonkey.PatchInstanceMethod(reflect.TypeOf(bdl), \"PipelineCallback\",\n\t\tfunc(_ *bundle.Bundle, _ apistructs.PipelineCallbackRequest, openapiAddr, token string) error {\n\t\t\treturn nil\n\t\t})\n\tmonkey.PatchInstanceMethod(reflect.TypeOf(dbClient), \"GetPipelineTask\",\n\t\tfunc(_ *dbclient.Client, _ interface{}) (spec.PipelineTask, error) {\n\t\t\treturn spec.PipelineTask{ID: 1}, nil\n\t\t})\n\tdefer monkey.UnpatchAll()\n\n\ttype fields struct {\n\t\tbdl *bundle.Bundle\n\t\tdbClient *db.Client\n\t\tLog logs.Logger\n\t\tconfig *config\n\t}\n\ttype args struct {\n\t\tctx context.Context\n\t\ttaskID uint64\n\t}\n\ttests := []struct {\n\t\tname string\n\t\tfields fields\n\t\targs args\n\t\twantErr bool\n\t}{\n\t\t{\n\t\t\tname: \"test doTaskReporter\",\n\t\t\tfields: fields{\n\t\t\t\tbdl: bdl,\n\t\t\t\tdbClient: &db.Client{Client: dbClient},\n\t\t\t\tLog: logger,\n\t\t\t\tconfig: &config{},\n\t\t\t},\n\t\t\targs: args{\n\t\t\t\tctx: context.Background(),\n\t\t\t\ttaskID: 1,\n\t\t\t},\n\t\t\twantErr: false,\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tp := &provider{\n\t\t\t\tbdl: tt.fields.bdl,\n\t\t\t\tdbClient: tt.fields.dbClient,\n\t\t\t\tLog: tt.fields.Log,\n\t\t\t\tCfg: tt.fields.config,\n\t\t\t\tEdgeRegister: &edgepipeline_register.MockEdgeRegister{},\n\t\t\t}\n\t\t\tif err := p.doTaskReporter(tt.args.ctx, tt.args.taskID); (err != nil) != tt.wantErr {\n\t\t\t\tt.Errorf(\"doTaskReporter() error = %v, wantErr %v\", err, tt.wantErr)\n\t\t\t}\n\t\t})\n\t}\n}", "func (m *MockMachine) MainCollective() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"MainCollective\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func NewIdentityProviderBase()(*IdentityProviderBase) {\n m := &IdentityProviderBase{\n Entity: *NewEntity(),\n }\n return m\n}", "func (ts *Tester) Provider() string {\n\treturn \"eks\"\n}", "func (p *Provider) newGCPProviderSpec(windowsServerVersion windows.ServerVersion) (*mapi.GCPMachineProviderSpec, error) {\n\tlistOptions := meta.ListOptions{LabelSelector: \"machine.openshift.io/cluster-api-machine-role=worker\"}\n\tmachines, err := p.oc.Machine.Machines(clusterinfo.MachineAPINamespace).List(context.TODO(), listOptions)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(machines.Items) == 0 {\n\t\treturn nil, fmt.Errorf(\"found 0 worker role machines\")\n\t}\n\tfoundSpec := &mapi.GCPMachineProviderSpec{}\n\terr = json.Unmarshal(machines.Items[0].Spec.ProviderSpec.Value.Raw, foundSpec)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to unmarshal raw machine provider spec: %v\", err)\n\t}\n\n\treturn &mapi.GCPMachineProviderSpec{\n\t\tTypeMeta: meta.TypeMeta{\n\t\t\tAPIVersion: \"machine.openshift.io/v1beta1\",\n\t\t\tKind: \"GCPMachineProviderSpec\",\n\t\t},\n\t\tObjectMeta: meta.ObjectMeta{},\n\t\tUserDataSecret: &core.LocalObjectReference{\n\t\t\tName: clusterinfo.UserDataSecretName,\n\t\t},\n\t\tCredentialsSecret: &core.LocalObjectReference{\n\t\t\tName: foundSpec.CredentialsSecret.Name,\n\t\t},\n\t\tCanIPForward: false,\n\t\tDeletionProtection: false,\n\t\tDisks: []*mapi.GCPDisk{{\n\t\t\tAutoDelete: true,\n\t\t\tBoot: true,\n\t\t\tSizeGB: 128,\n\t\t\tType: \"pd-ssd\",\n\t\t\tImage: getImage(windowsServerVersion),\n\t\t}},\n\t\tNetworkInterfaces: foundSpec.NetworkInterfaces,\n\t\tServiceAccounts: foundSpec.ServiceAccounts,\n\t\tTags: foundSpec.Tags,\n\t\tMachineType: foundSpec.MachineType,\n\t\tRegion: foundSpec.Region,\n\t\tZone: foundSpec.Zone,\n\t\tProjectID: foundSpec.ProjectID,\n\t}, nil\n}", "func (m *MockBootstrapperProvider) String() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"String\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func (m *MockFileInfo) Sys() interface{} {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Sys\")\n\tret0, _ := ret[0].(interface{})\n\treturn ret0\n}", "func IgrenoreTestP2PServiceRunAddPeer(t *testing.T) {\n\tmockActor := new(MockActorService)\n\tdummyBlock := types.Block{Hash: dummyBlockHash, Header: &types.BlockHeader{BlockNo: dummyBlockHeight}}\n\tmockActor.On(\"CallRequest\", mock.Anything, mock.Anything).Return(message.GetBlockRsp{Block: &dummyBlock}, nil)\n\t//mockMF := new(MockMoFactory)\n\ttarget := &networkTransport{conf: config.NewServerContext(\"\", \"\").GetDefaultConfig().(*config.Config).P2P,\n\t\tlogger:log.NewLogger(\"test.p2p\") }\n\n\ttarget.Host = &mockHost{peerstore.NewPeerstore(pstoremem.NewKeyBook(), pstoremem.NewAddrBook(), pstoremem.NewPeerMetadata())}\n\ttarget.selfMeta.ID = peer.ID(\"gwegw\")\n\n\tsampleAddr1 := PeerMeta{ID: \"ddd\", IPAddress: \"192.168.0.1\", Port: 33888, Outbound: true}\n\tsampleAddr2 := PeerMeta{ID: \"fff\", IPAddress: \"192.168.0.2\", Port: 33888, Outbound: true}\n\ttarget.GetOrCreateStream(sampleAddr1, aergoP2PSub)\n\ttarget.GetOrCreateStream(sampleAddr1, aergoP2PSub)\n\ttime.Sleep(time.Second)\n\tif len(target.Peerstore().Peers()) != 1 {\n\t\tt.Errorf(\"Peer count : Expected %d, Actually %d\", 1, len(target.Peerstore().Peers()))\n\t}\n\ttarget.GetOrCreateStream(sampleAddr2, aergoP2PSub)\n\ttime.Sleep(time.Second * 1)\n\tif len(target.Peerstore().Peers()) != 2 {\n\t\tt.Errorf(\"Peer count : Expected %d, Actually %d\", 2, len(target.Peerstore().Peers()))\n\t}\n}", "func TestRestOfInternalCode(t *testing.T) {\n\n\t// In this case unit testing will not help as we need to actually corever\n\t// this package with test. Because real functions hide under internal structures\n\t// which we do not expose, so our previous approach will no longer works.\n\t// Well it works but coverage does not detect that we are testing actual\n\t// implementation\n\n\t// In order to cover this part we will need to either pretend that we are\n\t// testing something or create real integration tests and ensure that mongod\n\t// process is running. In my case I will just fake my testing and do not use\n\t// assert. This way my test will pass either way\n\n\t// Create database context. I use real database, but it is possible to mock\n\t// database and configuration through interfaces.\n\tconf := config.GetConfig()\n\tclient, _ := databases.NewClient(conf)\n\tclient.StartSession()\n\n\tdb := databases.NewDatabase(conf, client)\n\tclient.Connect()\n\tdb.Client()\n\tvar result interface{}\n\t// because we do not care for actual results, we just quickly timeout the\n\t// call and we use incorrect call method\n\ttimeoutCtx, _ := context.WithTimeout(context.Background(), 1*time.Microsecond)\n\tdb.Collection(\"non-fake-existing-collection\").FindOne(timeoutCtx, \"incorrect-value\").Decode(&result)\n\n\t// insert and delete functions seems to panic instead of returning and error.\n\t// I did not investigate anything in this case as this is not our main goal.\n\t// Just define assert panic function and use this panicing function in it.\n\tvar mongoPanics assert.PanicTestFunc\n\n\tmongoPanics = func() {\n\t\tdb.Collection(\"non-fake-existing-collection\").InsertOne(timeoutCtx, result)\n\t}\n\tassert.Panics(t, mongoPanics)\n\n\tmongoPanics = func() {\n\t\tdb.Collection(\"non-fake-existing-collection\").DeleteOne(timeoutCtx, result)\n\t}\n\tassert.Panics(t, mongoPanics)\n\n\t// And it is done. We do not need to have mongo running and our code is\n\t// covered 100%. Well the actual implementation is faked, but it should be\n\t// tested via integration tests, not unit tests.\n\n}", "func (m *MockAPI) HostMonitoring() {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"HostMonitoring\")\n}", "func providerConfigure(data *schema.ResourceData) (interface{}, error) {\n\tlog.Println(\"[INFO] Initializing Client\")\n\n\tconfig := Config{\n\t\tAPIKey: data.Get(\"api_key\").(string),\n\t\tAPIURL: data.Get(\"api_url\").(string),\n\t}\n\n\treturn config.Client()\n}", "func (m *MockProcessProvider) Provide() (Process, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Provide\")\n\tret0, _ := ret[0].(Process)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockProvider) OnEndpointsAdd(arg0 *v1.Endpoints) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"OnEndpointsAdd\", arg0)\n}", "func getProvider(id string) *provider {\n\tif mockGetProviderValue != nil {\n\t\treturn mockGetProviderValue\n\t}\n\tp, _ := auth.GetProviderByConfigID(auth.ProviderConfigID{Type: providerType, ID: id}).(*provider)\n\treturn p\n}", "func (a *Application) RegisterProvider() {\n\n}", "func Provider() tfbridge.ProviderInfo {\n\t// Instantiate the Terraform provider\n\tp := shimv2.NewProvider(xyz.Provider())\n\n\t// Create a Pulumi provider mapping\n\tprov := tfbridge.ProviderInfo{\n\t\tP: p,\n\t\tName: \"xyz\",\n\t\t// DisplayName is a way to be able to change the casing of the provider\n\t\t// name when being displayed on the Pulumi registry\n\t\tDisplayName: \"\",\n\t\t// The default publisher for all packages is Pulumi.\n\t\t// Change this to your personal name (or a company name) that you\n\t\t// would like to be shown in the Pulumi Registry if this package is published\n\t\t// there.\n\t\tPublisher: \"Pulumi\",\n\t\t// LogoURL is optional but useful to help identify your package in the Pulumi Registry\n\t\t// if this package is published there.\n\t\t//\n\t\t// You may host a logo on a domain you control or add an SVG logo for your package\n\t\t// in your repository and use the raw content URL for that file as your logo URL.\n\t\tLogoURL: \"\",\n\t\t// PluginDownloadURL is an optional URL used to download the Provider\n\t\t// for use in Pulumi programs\n\t\t// e.g https://github.com/org/pulumi-provider-name/releases/\n\t\tPluginDownloadURL: \"\",\n\t\tDescription: \"A Pulumi package for creating and managing xyz cloud resources.\",\n\t\t// category/cloud tag helps with categorizing the package in the Pulumi Registry.\n\t\t// For all available categories, see `Keywords` in\n\t\t// https://www.pulumi.com/docs/guides/pulumi-packages/schema/#package.\n\t\tKeywords: []string{\"pulumi\", \"xyz\", \"category/cloud\"},\n\t\tLicense: \"Apache-2.0\",\n\t\tHomepage: \"https://www.pulumi.com\",\n\t\tRepository: \"https://github.com/pulumi/pulumi-xyz\",\n\t\t// The GitHub Org for the provider - defaults to `terraform-providers`. Note that this\n\t\t// should match the TF provider module's require directive, not any replace directives.\n\t\tGitHubOrg: \"\",\n\t\tConfig: map[string]*tfbridge.SchemaInfo{\n\t\t\t// Add any required configuration here, or remove the example below if\n\t\t\t// no additional points are required.\n\t\t\t// \"region\": {\n\t\t\t// \tType: tfbridge.MakeType(\"region\", \"Region\"),\n\t\t\t// \tDefault: &tfbridge.DefaultInfo{\n\t\t\t// \t\tEnvVars: []string{\"AWS_REGION\", \"AWS_DEFAULT_REGION\"},\n\t\t\t// \t},\n\t\t\t// },\n\t\t},\n\t\tPreConfigureCallback: preConfigureCallback,\n\t\tResources: map[string]*tfbridge.ResourceInfo{\n\t\t\t// Map each resource in the Terraform provider to a Pulumi type. Two examples\n\t\t\t// are below - the single line form is the common case. The multi-line form is\n\t\t\t// needed only if you wish to override types or other default options.\n\t\t\t//\n\t\t\t// \"aws_iam_role\": {Tok: tfbridge.MakeResource(mainPkg, mainMod, \"IamRole\")}\n\t\t\t//\n\t\t\t// \"aws_acm_certificate\": {\n\t\t\t// \tTok: tfbridge.MakeResource(mainPkg, mainMod, \"Certificate\"),\n\t\t\t// \tFields: map[string]*tfbridge.SchemaInfo{\n\t\t\t// \t\t\"tags\": {Type: tfbridge.MakeType(mainPkg, \"Tags\")},\n\t\t\t// \t},\n\t\t\t// },\n\t\t},\n\t\tDataSources: map[string]*tfbridge.DataSourceInfo{\n\t\t\t// Map each resource in the Terraform provider to a Pulumi function. An example\n\t\t\t// is below.\n\t\t\t// \"aws_ami\": {Tok: tfbridge.MakeDataSource(mainPkg, mainMod, \"getAmi\")},\n\t\t},\n\t\tJavaScript: &tfbridge.JavaScriptInfo{\n\t\t\t// List any npm dependencies and their versions\n\t\t\tDependencies: map[string]string{\n\t\t\t\t\"@pulumi/pulumi\": \"^3.0.0\",\n\t\t\t},\n\t\t\tDevDependencies: map[string]string{\n\t\t\t\t\"@types/node\": \"^10.0.0\", // so we can access strongly typed node definitions.\n\t\t\t\t\"@types/mime\": \"^2.0.0\",\n\t\t\t},\n\t\t\t// See the documentation for tfbridge.OverlayInfo for how to lay out this\n\t\t\t// section, or refer to the AWS provider. Delete this section if there are\n\t\t\t// no overlay files.\n\t\t\t//Overlay: &tfbridge.OverlayInfo{},\n\t\t},\n\t\tPython: &tfbridge.PythonInfo{\n\t\t\t// List any Python dependencies and their version ranges\n\t\t\tRequires: map[string]string{\n\t\t\t\t\"pulumi\": \">=3.0.0,<4.0.0\",\n\t\t\t},\n\t\t},\n\t\tGolang: &tfbridge.GolangInfo{\n\t\t\tImportBasePath: filepath.Join(\n\t\t\t\tfmt.Sprintf(\"github.com/pulumi/pulumi-%[1]s/sdk/\", mainPkg),\n\t\t\t\ttfbridge.GetModuleMajorVersion(version.Version),\n\t\t\t\t\"go\",\n\t\t\t\tmainPkg,\n\t\t\t),\n\t\t\tGenerateResourceContainerTypes: true,\n\t\t},\n\t\tCSharp: &tfbridge.CSharpInfo{\n\t\t\tPackageReferences: map[string]string{\n\t\t\t\t\"Pulumi\": \"3.*\",\n\t\t\t},\n\t\t},\n\t}\n\n\t// These are new API's that you may opt to use to automatically compute resource tokens,\n\t// and apply auto aliasing for full backwards compatibility.\n\t// For more information, please reference: https://pkg.go.dev/github.com/pulumi/pulumi-terraform-bridge/v3/pkg/tfbridge#ProviderInfo.ComputeTokens\n\tprov.MustComputeTokens(tokens.SingleModule(\"xyz_\", mainMod,\n\t\ttokens.MakeStandard(mainPkg)))\n\tprov.MustApplyAutoAliasing()\n\tprov.SetAutonaming(255, \"-\")\n\n\treturn prov\n}", "func ToMockProvider(p goth.Provider) *MockProvider {\n\treturn p.(*MockProvider)\n}", "func (m *MockCandidatePropertyGetter) Cloudprovider() *models.SCloudprovider {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Cloudprovider\")\n\tret0, _ := ret[0].(*models.SCloudprovider)\n\treturn ret0\n}", "func (m *MockisCryptoApiRequest_CryptoApiReq) isCryptoApiRequest_CryptoApiReq() {\n\tm.ctrl.Call(m, \"isCryptoApiRequest_CryptoApiReq\")\n}", "func (m *MockProvider) OnServiceSynced() {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"OnServiceSynced\")\n}", "func SetupProvider(mgr ctrl.Manager, o controller.Options) error {\n\tname := \"packages/\" + strings.ToLower(v1.ProviderGroupKind)\n\tnp := func() v1.Package { return &v1.Provider{} }\n\tnr := func() v1.PackageRevision { return &v1.ProviderRevision{} }\n\tnrl := func() v1.PackageRevisionList { return &v1.ProviderRevisionList{} }\n\n\tcs, err := kubernetes.NewForConfig(mgr.GetConfig())\n\tif err != nil {\n\t\treturn errors.Wrap(err, errCreateK8sClient)\n\t}\n\tf, err := xpkg.NewK8sFetcher(cs, append(o.FetcherOptions, xpkg.WithNamespace(o.Namespace), xpkg.WithServiceAccount(o.ServiceAccount))...)\n\tif err != nil {\n\t\treturn errors.Wrap(err, errBuildFetcher)\n\t}\n\n\topts := []ReconcilerOption{\n\t\tWithNewPackageFn(np),\n\t\tWithNewPackageRevisionFn(nr),\n\t\tWithNewPackageRevisionListFn(nrl),\n\t\tWithRevisioner(NewPackageRevisioner(f, WithDefaultRegistry(o.DefaultRegistry))),\n\t\tWithLogger(o.Logger.WithValues(\"controller\", name)),\n\t\tWithRecorder(event.NewAPIRecorder(mgr.GetEventRecorderFor(name))),\n\t}\n\tif o.WebhookTLSSecretName != \"\" {\n\t\topts = append(opts, WithWebhookTLSSecretName(o.WebhookTLSSecretName))\n\t}\n\tif o.ESSOptions != nil && o.ESSOptions.TLSSecretName != nil {\n\t\topts = append(opts, WithESSTLSSecretName(o.ESSOptions.TLSSecretName))\n\t}\n\tif o.TLSServerSecretName != \"\" {\n\t\topts = append(opts, WithTLSServerSecretName(&o.TLSServerSecretName))\n\t}\n\tif o.TLSClientSecretName != \"\" {\n\t\topts = append(opts, WithTLSClientSecretName(&o.TLSClientSecretName))\n\t}\n\n\treturn ctrl.NewControllerManagedBy(mgr).\n\t\tNamed(name).\n\t\tFor(&v1.Provider{}).\n\t\tOwns(&v1.ProviderRevision{}).\n\t\tWithOptions(o.ForControllerRuntime()).\n\t\tComplete(ratelimiter.NewReconciler(name, NewReconciler(mgr, opts...), o.GlobalRateLimiter))\n}", "func (m *MockEnvironment) Fetch() map[string]interface{} {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Fetch\")\n\tret0, _ := ret[0].(map[string]interface{})\n\treturn ret0\n}", "func NewMockInterfaceProvider(managedInterfacesRegexp string, autoRefresh bool) (nt.InterfaceProvider,\n\tchan time.Time, error) {\n\tch := make(chan time.Time)\n\tip, err := nt.NewChanInterfaceProvider(ch, &MockInterfaceLister{}, managedInterfacesRegexp,\n\t\tautoRefresh)\n\treturn ip, ch, err\n}", "func (m *MockClusterScoper) BaseURI() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"BaseURI\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func (m *MockisCryptoApiResponse_CryptoApiResp) isCryptoApiResponse_CryptoApiResp() {\n\tm.ctrl.Call(m, \"isCryptoApiResponse_CryptoApiResp\")\n}", "func (m *MockProviderClient) Configure(arg0 context.Context, arg1 *tfplugin5.Configure_Request, arg2 ...grpc.CallOption) (*tfplugin5.Configure_Response, error) {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{arg0, arg1}\n\tfor _, a := range arg2 {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"Configure\", varargs...)\n\tret0, _ := ret[0].(*tfplugin5.Configure_Response)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (p *TestProvider) Provide(addr string) Client {\n\tc, ok := p.clients[addr]\n\tif !ok {\n\t\tlog.Panicf(\"addr %s not found\", addr)\n\t}\n\treturn c\n}", "func TestingBase(c context.Context) Base {\n\treturn func(h Handler) httprouter.Handle {\n\t\treturn func(rw http.ResponseWriter, r *http.Request, p httprouter.Params) {\n\t\t\th(c, rw, r, p)\n\t\t}\n\t}\n}", "func (m *MockSystemContract) Exec() error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Exec\")\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockClient) ForPlugin(plugin string) github.Client {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ForPlugin\", plugin)\n\tret0, _ := ret[0].(github.Client)\n\treturn ret0\n}", "func (m *MockSystemContract) Init(arg0 core.Keepers, arg1 types1.BaseTx, arg2 uint64) core.SystemContract {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Init\", arg0, arg1, arg2)\n\tret0, _ := ret[0].(core.SystemContract)\n\treturn ret0\n}", "func (m *MockBootstrapperProvider) EXPECT() *MockBootstrapperProviderMockRecorder {\n\treturn m.recorder\n}", "func Provider() terraform.ResourceProvider {\n\tvar p *schema.Provider\n\tp = &schema.Provider{\n\t\tSchema: map[string]*schema.Schema{\n\t\t\t\"subscription_id\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"ARM_SUBSCRIPTION_ID\", \"\"),\n\t\t\t},\n\n\t\t\t\"client_id\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"ARM_CLIENT_ID\", \"\"),\n\t\t\t},\n\n\t\t\t\"client_secret\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"ARM_CLIENT_SECRET\", \"\"),\n\t\t\t},\n\n\t\t\t\"tenant_id\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"ARM_TENANT_ID\", \"\"),\n\t\t\t},\n\n\t\t\t\"environment\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"ARM_ENVIRONMENT\", \"public\"),\n\t\t\t},\n\n\t\t\t\"skip_provider_registration\": {\n\t\t\t\tType: schema.TypeBool,\n\t\t\t\tOptional: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"ARM_SKIP_PROVIDER_REGISTRATION\", false),\n\t\t\t},\n\t\t},\n\n\t\tDataSourcesMap: map[string]*schema.Resource{\n\t\t\t\"azurerm_client_config\": dataSourceArmClientConfig(),\n\t\t},\n\n\t\tResourcesMap: map[string]*schema.Resource{\n\t\t\t// These resources use the Azure ARM SDK\n\t\t\t\"azurerm_availability_set\": resourceArmAvailabilitySet(),\n\t\t\t\"azurerm_cdn_endpoint\": resourceArmCdnEndpoint(),\n\t\t\t\"azurerm_cdn_profile\": resourceArmCdnProfile(),\n\t\t\t\"azurerm_container_registry\": resourceArmContainerRegistry(),\n\t\t\t\"azurerm_container_service\": resourceArmContainerService(),\n\n\t\t\t\"azurerm_eventhub\": resourceArmEventHub(),\n\t\t\t\"azurerm_eventhub_authorization_rule\": resourceArmEventHubAuthorizationRule(),\n\t\t\t\"azurerm_eventhub_consumer_group\": resourceArmEventHubConsumerGroup(),\n\t\t\t\"azurerm_eventhub_namespace\": resourceArmEventHubNamespace(),\n\n\t\t\t\"azurerm_lb\": resourceArmLoadBalancer(),\n\t\t\t\"azurerm_lb_backend_address_pool\": resourceArmLoadBalancerBackendAddressPool(),\n\t\t\t\"azurerm_lb_nat_rule\": resourceArmLoadBalancerNatRule(),\n\t\t\t\"azurerm_lb_nat_pool\": resourceArmLoadBalancerNatPool(),\n\t\t\t\"azurerm_lb_probe\": resourceArmLoadBalancerProbe(),\n\t\t\t\"azurerm_lb_rule\": resourceArmLoadBalancerRule(),\n\n\t\t\t\"azurerm_managed_disk\": resourceArmManagedDisk(),\n\n\t\t\t\"azurerm_key_vault\": resourceArmKeyVault(),\n\t\t\t\"azurerm_local_network_gateway\": resourceArmLocalNetworkGateway(),\n\t\t\t\"azurerm_network_interface\": resourceArmNetworkInterface(),\n\t\t\t\"azurerm_network_security_group\": resourceArmNetworkSecurityGroup(),\n\t\t\t\"azurerm_network_security_rule\": resourceArmNetworkSecurityRule(),\n\t\t\t\"azurerm_public_ip\": resourceArmPublicIp(),\n\t\t\t\"azurerm_redis_cache\": resourceArmRedisCache(),\n\t\t\t\"azurerm_route\": resourceArmRoute(),\n\t\t\t\"azurerm_route_table\": resourceArmRouteTable(),\n\t\t\t\"azurerm_servicebus_namespace\": resourceArmServiceBusNamespace(),\n\t\t\t\"azurerm_servicebus_subscription\": resourceArmServiceBusSubscription(),\n\t\t\t\"azurerm_servicebus_topic\": resourceArmServiceBusTopic(),\n\t\t\t\"azurerm_storage_account\": resourceArmStorageAccount(),\n\t\t\t\"azurerm_storage_blob\": resourceArmStorageBlob(),\n\t\t\t\"azurerm_storage_container\": resourceArmStorageContainer(),\n\t\t\t\"azurerm_storage_share\": resourceArmStorageShare(),\n\t\t\t\"azurerm_storage_queue\": resourceArmStorageQueue(),\n\t\t\t\"azurerm_storage_table\": resourceArmStorageTable(),\n\t\t\t\"azurerm_subnet\": resourceArmSubnet(),\n\t\t\t\"azurerm_template_deployment\": resourceArmTemplateDeployment(),\n\t\t\t\"azurerm_traffic_manager_endpoint\": resourceArmTrafficManagerEndpoint(),\n\t\t\t\"azurerm_traffic_manager_profile\": resourceArmTrafficManagerProfile(),\n\t\t\t\"azurerm_virtual_machine_extension\": resourceArmVirtualMachineExtensions(),\n\t\t\t\"azurerm_virtual_machine\": resourceArmVirtualMachine(),\n\t\t\t\"azurerm_virtual_machine_scale_set\": resourceArmVirtualMachineScaleSet(),\n\t\t\t\"azurerm_virtual_network\": resourceArmVirtualNetwork(),\n\t\t\t\"azurerm_virtual_network_peering\": resourceArmVirtualNetworkPeering(),\n\n\t\t\t// These resources use the Riviera SDK\n\t\t\t\"azurerm_dns_a_record\": resourceArmDnsARecord(),\n\t\t\t\"azurerm_dns_aaaa_record\": resourceArmDnsAAAARecord(),\n\t\t\t\"azurerm_dns_cname_record\": resourceArmDnsCNameRecord(),\n\t\t\t\"azurerm_dns_mx_record\": resourceArmDnsMxRecord(),\n\t\t\t\"azurerm_dns_ns_record\": resourceArmDnsNsRecord(),\n\t\t\t\"azurerm_dns_srv_record\": resourceArmDnsSrvRecord(),\n\t\t\t\"azurerm_dns_txt_record\": resourceArmDnsTxtRecord(),\n\t\t\t\"azurerm_dns_zone\": resourceArmDnsZone(),\n\t\t\t\"azurerm_resource_group\": resourceArmResourceGroup(),\n\t\t\t\"azurerm_search_service\": resourceArmSearchService(),\n\t\t\t\"azurerm_sql_database\": resourceArmSqlDatabase(),\n\t\t\t\"azurerm_sql_firewall_rule\": resourceArmSqlFirewallRule(),\n\t\t\t\"azurerm_sql_server\": resourceArmSqlServer(),\n\t\t},\n\t}\n\n\tp.ConfigureFunc = providerConfigure(p)\n\n\treturn p\n}", "func (m *MockRepo) Host() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Host\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func (m *MockrepoProvider) EXPECT() *MockrepoProviderMockRecorder {\n\treturn m.recorder\n}", "func (m *MockLocalConfigProvider) GetApplication() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetApplication\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func TestTrunkENI_CreateAndAssociateBranchENIs(t *testing.T) {\n\tctrl := gomock.NewController(t)\n\tdefer ctrl.Finish()\n\n\ttrunkENI, mockEC2APIHelper, mockInstance := getMockHelperInstanceAndTrunkObject(ctrl)\n\ttrunkENI.trunkENIId = trunkId\n\n\tmockInstance.EXPECT().Type().Return(InstanceType)\n\tmockInstance.EXPECT().SubnetID().Return(SubnetId).Times(2)\n\tmockInstance.EXPECT().SubnetCidrBlock().Return(SubnetCidrBlock).Times(2)\n\n\tmockEC2APIHelper.EXPECT().CreateNetworkInterface(&BranchEniDescription, &SubnetId, SecurityGroups,\n\t\tvlan1Tag, 0, nil).Return(BranchInterface1, nil)\n\tmockEC2APIHelper.EXPECT().AssociateBranchToTrunk(&trunkId, &Branch1Id, VlanId1).Return(nil, nil)\n\tmockEC2APIHelper.EXPECT().CreateNetworkInterface(&BranchEniDescription, &SubnetId, SecurityGroups, vlan2Tag,\n\t\t0, nil).Return(BranchInterface2, nil)\n\tmockEC2APIHelper.EXPECT().AssociateBranchToTrunk(&trunkId, &Branch2Id, VlanId2).Return(nil, nil)\n\n\teniDetails, err := trunkENI.CreateAndAssociateBranchENIs(MockPod2, SecurityGroups, 2)\n\texpectedENIDetails := []*ENIDetails{EniDetails1, EniDetails2}\n\n\tassert.NoError(t, err)\n\t// VLan ID are marked as used\n\tassert.True(t, trunkENI.usedVlanIds[VlanId1])\n\tassert.True(t, trunkENI.usedVlanIds[VlanId2])\n\t// The returned content is as expected\n\tassert.Equal(t, expectedENIDetails, eniDetails)\n\tassert.Equal(t, expectedENIDetails, trunkENI.uidToBranchENIMap[PodUID2])\n}", "func (m *MockUnsafeTodoServiceServer) mustEmbedUnimplementedTodoServiceServer() {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"mustEmbedUnimplementedTodoServiceServer\")\n}", "func (_m *MockEncoderPool) Init(alloc EncoderAllocate) {\n\t_m.ctrl.Call(_m, \"Init\", alloc)\n}", "func testSetup(t *testing.T) (ins c.Instance, loc *time.Location, appCfg c.AppConfig) {\n\n\tins = mock.Instance{\n\t\tApp: \"myapp\",\n\t\tAccount: \"prod\",\n\t\tStack: \"mystack\",\n\t\tCluster: \"mycluster\",\n\t\tRegion: \"us-east-1\",\n\t\tASG: \"myapp-mystack-mycluster-V123\",\n\t\tInstanceID: \"i-a96a0166\",\n\t}\n\n\tloc, err := time.LoadLocation(\"America/Los_Angeles\")\n\tif err != nil {\n\t\tt.Fatalf(err.Error())\n\t}\n\n\tappCfg = c.AppConfig{\n\t\tEnabled: true,\n\t\tRegionsAreIndependent: true,\n\t\tMeanTimeBetweenKillsInWorkDays: 5,\n\t\tMinTimeBetweenKillsInWorkDays: 1,\n\t\tGrouping: c.Cluster,\n\t\tExceptions: nil,\n\t}\n\n\treturn\n\n}", "func (p *ProviderConfig) GetProviderCloudSpec(providerName string, datacenter string, routerID string) *models.CloudSpec {\n\tcs := &models.CloudSpec{\n\t\tDatacenterName: datacenter,\n\t}\n\n\tproviderAlibaba, ok := p.Alibaba[providerName]\n\tif ok {\n\t\tcs.Alibaba = providerAlibaba\n\t}\n\tproviderAnexia, ok := p.Anexia[providerName]\n\tif ok {\n\t\tcs.Anexia = providerAnexia\n\t}\n\tproviderAws, ok := p.Aws[providerName]\n\tif ok {\n\t\tcs.Aws = providerAws\n\t}\n\tproviderAzure, ok := p.Azure[providerName]\n\tif ok {\n\t\tcs.Azure = providerAzure\n\t}\n\tproviderDigitalocean, ok := p.Digitalocean[providerName]\n\tif ok {\n\t\tcs.Digitalocean = providerDigitalocean\n\t}\n\tproviderFake, ok := p.Fake[providerName]\n\tif ok {\n\t\tcs.Fake = providerFake\n\t}\n\tproviderGcp, ok := p.Gcp[providerName]\n\tif ok {\n\t\tcs.Gcp = providerGcp\n\t}\n\tproviderHetzner, ok := p.Hetzner[providerName]\n\tif ok {\n\t\tcs.Hetzner = providerHetzner\n\t}\n\tproviderKubevirt, ok := p.Kubevirt[providerName]\n\tif ok {\n\t\tcs.Kubevirt = providerKubevirt\n\t}\n\tproviderOpenstack, ok := p.Openstack[providerName]\n\tif ok {\n\t\tcs.Openstack = providerOpenstack\n\t\tcs.Openstack.RouterID = routerID\n\t}\n\tproviderPacket, ok := p.Packet[providerName]\n\tif ok {\n\t\tcs.Packet = providerPacket\n\t}\n\tproviderVsphere, ok := p.Vsphere[providerName]\n\tif ok {\n\t\tcs.Vsphere = providerVsphere\n\t}\n\n\treturn cs\n}", "func NewFakeProvider(t *testing.T) *FakeProvider {\n\tbuilder := chain.NewBuilder(t, address.Address{})\n\treturn &FakeProvider{\n\t\tBuilder: builder,\n\t\tt: t,\n\t\tactors: make(map[address.Address]*types.Actor)}\n}", "func (m *MockProvider) GetEntrecote(weight int) (int, error) {\n\tret := m.ctrl.Call(m, \"GetEntrecote\", weight)\n\tret0, _ := ret[0].(int)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockClusterDescriber) BaseURI() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"BaseURI\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func initTestCase(f *framework.Framework, c clientset.Interface, pvConfig framework.PersistentVolumeConfig, pvcConfig framework.PersistentVolumeClaimConfig, ns, nodeName string) (*v1.Pod, *v1.PersistentVolume, *v1.PersistentVolumeClaim) {\n\tpv, pvc, err := framework.CreatePVPVC(c, pvConfig, pvcConfig, ns, false)\n\tdefer func() {\n\t\tif err != nil {\n\t\t\tframework.DeletePersistentVolumeClaim(c, pvc.Name, ns)\n\t\t\tframework.DeletePersistentVolume(c, pv.Name)\n\t\t}\n\t}()\n\tExpect(err).NotTo(HaveOccurred())\n\tpod := framework.MakePod(ns, []*v1.PersistentVolumeClaim{pvc}, true, \"\")\n\tpod.Spec.NodeName = nodeName\n\tframework.Logf(\"Creating NFS client pod.\")\n\tpod, err = c.CoreV1().Pods(ns).Create(pod)\n\tframework.Logf(\"NFS client Pod %q created on Node %q\", pod.Name, nodeName)\n\tExpect(err).NotTo(HaveOccurred())\n\tdefer func() {\n\t\tif err != nil {\n\t\t\tframework.DeletePodWithWait(f, c, pod)\n\t\t}\n\t}()\n\terr = framework.WaitForPodRunningInNamespace(c, pod)\n\tExpect(err).NotTo(HaveOccurred(), fmt.Sprintf(\"Pod %q timed out waiting for phase: Running\", pod.Name))\n\t// Return created api objects\n\tpod, err = c.CoreV1().Pods(ns).Get(pod.Name, metav1.GetOptions{})\n\tExpect(err).NotTo(HaveOccurred())\n\tpvc, err = c.CoreV1().PersistentVolumeClaims(ns).Get(pvc.Name, metav1.GetOptions{})\n\tExpect(err).NotTo(HaveOccurred())\n\tpv, err = c.CoreV1().PersistentVolumes().Get(pv.Name, metav1.GetOptions{})\n\tExpect(err).NotTo(HaveOccurred())\n\treturn pod, pv, pvc\n}", "func (m *MockProvider) Run(arg0 <-chan struct{}) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"Run\", arg0)\n}", "func (m *MockProvider) Service(arg0 string) (interface{}, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Service\", arg0)\n\tret0, _ := ret[0].(interface{})\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func newProviderImpl(name string) (Provider, error) {\n\tif name == LOCAL {\n\t\treturn &LocalProvider{}, nil\n\t}\n\n\tif name == AWS {\n\t\treturn &AwsProvider{}, nil\n\t}\n\n\treturn nil, errors.New(fmt.Sprintf(\"Provider '%s' doesn't exist\", name))\n}", "func TestNewBeerService_ReturnsBeerInteractor(t *testing.T) {\n\tt.Parallel()\n\tinteractor := &mocks.BeerInteractor{}\n\tassert.NotNil(t, adapters.NewBeerService(interactor))\n}", "func TestInternalFritzAPI(t *testing.T) {\n\ttestCases := []struct {\n\t\ttc func(t *testing.T, internal Internal)\n\t}{\n\t\t{testListLanDevices},\n\t\t{testListLogs},\n\t\t{testInetStats},\n\t\t{testBoxInfo},\n\t}\n\tfor _, testCase := range testCases {\n\t\tt.Run(fmt.Sprintf(\"Test aha api %s\", runtime.FuncForPC(reflect.ValueOf(testCase.tc).Pointer()).Name()), func(t *testing.T) {\n\t\t\tsrv := mock.New().Start()\n\t\t\tdefer srv.Close()\n\t\t\tinternal := setUpClient(t, srv)\n\t\t\tassert.NotNil(t, internal)\n\t\t\ttestCase.tc(t, internal)\n\t\t})\n\t}\n}", "func (_m *AppFunctionContext) PushToCore(event dtos.Event) (common.BaseWithIdResponse, error) {\n\tret := _m.Called(event)\n\n\tvar r0 common.BaseWithIdResponse\n\tif rf, ok := ret.Get(0).(func(dtos.Event) common.BaseWithIdResponse); ok {\n\t\tr0 = rf(event)\n\t} else {\n\t\tr0 = ret.Get(0).(common.BaseWithIdResponse)\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(dtos.Event) error); ok {\n\t\tr1 = rf(event)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (m *MockAuthorizer) CloudEnvironment() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"CloudEnvironment\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func (m *MockHandler) SendInfraEnvEvent(ctx context.Context, event InfraEnvEvent) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"SendInfraEnvEvent\", ctx, event)\n}", "func newKeyServerWithMocking(user upspin.UserName, ref string, data []byte) (*server, *storagetest.ExpectDownloadCapturePut) {\n\tmockGCP := &storagetest.ExpectDownloadCapturePut{\n\t\tRef: []string{ref},\n\t\tData: [][]byte{data},\n\t\tPutContents: make([][]byte, 0, 1),\n\t\tPutRef: make([]string, 0, 1),\n\t}\n\ts := &server{\n\t\tstorage: mockGCP,\n\t\tuser: user,\n\t\tlookupTXT: mockLookupTXT,\n\t\tlogger: &noopLogger{},\n\t\tcache: cache.NewLRU(10),\n\t\tnegCache: cache.NewLRU(10),\n\t}\n\treturn s, mockGCP\n}", "func (m *MockProvider) OnServiceAdd(arg0 *v1.Service) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"OnServiceAdd\", arg0)\n}", "func (m *MockProcessOptions) TopologyMapProvider() topology.MapProvider {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"TopologyMapProvider\")\n\tret0, _ := ret[0].(topology.MapProvider)\n\treturn ret0\n}", "func (achieveRepo *mockAchieveRepo) Initialize(ctx context.Context, db *sql.DB) {}", "func (m *MockManagedClusterScoper) BaseURI() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"BaseURI\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func (m *MockProviderManager) GetProviders(arg0 string) ([]*resource.ResourceProvider, error) {\n\tret := m.ctrl.Call(m, \"GetProviders\", arg0)\n\tret0, _ := ret[0].([]*resource.ResourceProvider)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockClient) LocalDiscoveryProvider() fab.LocalDiscoveryProvider {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"LocalDiscoveryProvider\")\n\tret0, _ := ret[0].(fab.LocalDiscoveryProvider)\n\treturn ret0\n}", "func (m *MockPrompt) forPlatformType() (string, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"forPlatformType\")\n\tret0, _ := ret[0].(string)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func Provider() terraform.ResourceProvider {\n\treturn &schema.Provider{\n\t\tSchema: map[string]*schema.Schema{\n\t\t\t\"public_key\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"UCLOUD_PUBLIC_KEY\", nil),\n\t\t\t\tDescription: descriptions[\"public_key\"],\n\t\t\t},\n\n\t\t\t\"private_key\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"UCLOUD_PRIVATE_KEY\", nil),\n\t\t\t\tDescription: descriptions[\"private_key\"],\n\t\t\t},\n\n\t\t\t\"region\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"UCLOUD_REGION\", nil),\n\t\t\t\tDescription: descriptions[\"region\"],\n\t\t\t},\n\n\t\t\t\"project_id\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"UCLOUD_PROJECT_ID\", nil),\n\t\t\t\tDescription: descriptions[\"project_id\"],\n\t\t\t},\n\n\t\t\t\"max_retries\": {\n\t\t\t\tType: schema.TypeInt,\n\t\t\t\tOptional: true,\n\t\t\t\tDefault: DefaultMaxRetries,\n\t\t\t\tDescription: descriptions[\"max_retries\"],\n\t\t\t},\n\n\t\t\t\"insecure\": {\n\t\t\t\tType: schema.TypeBool,\n\t\t\t\tOptional: true,\n\t\t\t\tDefault: DefaultInSecure,\n\t\t\t\tDescription: descriptions[\"insecure\"],\n\t\t\t},\n\t\t},\n\n\t\tDataSourcesMap: map[string]*schema.Resource{\n\t\t\t\"ucloud_instances\": dataSourceUCloudInstances(),\n\t\t\t\"ucloud_projects\": dataSourceUCloudProjects(),\n\t\t\t\"ucloud_images\": dataSourceUCloudImages(),\n\t\t\t\"ucloud_zones\": dataSourceUCloudZones(),\n\t\t\t\"ucloud_eips\": dataSourceUCloudEips(),\n\t\t},\n\t\tResourcesMap: map[string]*schema.Resource{\n\t\t\t\"ucloud_instance\": resourceUCloudInstance(),\n\t\t\t\"ucloud_eip\": resourceUCloudEIP(),\n\t\t\t\"ucloud_eip_association\": resourceUCloudEIPAssociation(),\n\t\t\t\"ucloud_vpc\": resourceUCloudVPC(),\n\t\t\t\"ucloud_subnet\": resourceUCloudSubnet(),\n\t\t\t\"ucloud_vpc_peering_connection\": resourceUCloudVPCPeeringConnection(),\n\t\t\t\"ucloud_lb\": resourceUCloudLB(),\n\t\t\t\"ucloud_lb_listener\": resourceUCloudLBListener(),\n\t\t\t\"ucloud_lb_attachment\": resourceUCloudLBAttachment(),\n\t\t\t\"ucloud_lb_rule\": resourceUCloudLBRule(),\n\t\t\t\"ucloud_disk\": resourceUCloudDisk(),\n\t\t\t\"ucloud_disk_attachment\": resourceUCloudDiskAttachment(),\n\t\t\t\"ucloud_security_group\": resourceUCloudSecurityGroup(),\n\t\t},\n\t\tConfigureFunc: providerConfigure,\n\t}\n}", "func (m *MockisKey_KeyInfo) isKey_KeyInfo() {\n\tm.ctrl.Call(m, \"isKey_KeyInfo\")\n}" ]
[ "0.66950154", "0.61172336", "0.5651182", "0.5620679", "0.5540909", "0.5528276", "0.54399544", "0.53394455", "0.53289324", "0.5326502", "0.53053826", "0.5295907", "0.5289515", "0.52590674", "0.5251287", "0.5249962", "0.52412957", "0.52379525", "0.51799697", "0.51713246", "0.5155932", "0.5145608", "0.5144195", "0.5138", "0.51276004", "0.5097182", "0.50903016", "0.5087548", "0.5068389", "0.50678015", "0.50607324", "0.50512064", "0.5048093", "0.50399464", "0.503411", "0.50300765", "0.5018892", "0.501024", "0.5010031", "0.4997261", "0.49823028", "0.49766088", "0.49665582", "0.49597958", "0.4956144", "0.4955618", "0.49500763", "0.49493417", "0.4949065", "0.49489698", "0.49472514", "0.49424955", "0.4939421", "0.49246833", "0.49198568", "0.4916341", "0.49071294", "0.4895889", "0.48820263", "0.4880439", "0.48755202", "0.4874325", "0.48659423", "0.48652476", "0.48588735", "0.48563534", "0.485597", "0.48492727", "0.48479217", "0.48398605", "0.48354605", "0.48336884", "0.48320982", "0.48264006", "0.4821987", "0.4819229", "0.48178384", "0.48136464", "0.48019865", "0.48013958", "0.4799529", "0.4798486", "0.479633", "0.4795281", "0.47950435", "0.47925833", "0.47912613", "0.4784728", "0.4783957", "0.478131", "0.47787452", "0.47759667", "0.47756046", "0.47713786", "0.47706047", "0.47691014", "0.47598657", "0.47538313", "0.47534677", "0.4751679" ]
0.680102
0
InfraProvider indicates an expected call of InfraProvider
func (mr *MockClientMockRecorder) InfraProvider() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "InfraProvider", reflect.TypeOf((*MockClient)(nil).InfraProvider)) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (mr *MockProvidersMockRecorder) InfraProvider() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"InfraProvider\", reflect.TypeOf((*MockProviders)(nil).InfraProvider))\n}", "func (c *Provider) InfraProvider() fab.InfraProvider {\n\treturn c.infraProvider\n}", "func (m *MockClient) InfraProvider() fab.InfraProvider {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"InfraProvider\")\n\tret0, _ := ret[0].(fab.InfraProvider)\n\treturn ret0\n}", "func (m *MockProviders) InfraProvider() fab.InfraProvider {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"InfraProvider\")\n\tret0, _ := ret[0].(fab.InfraProvider)\n\treturn ret0\n}", "func (o *KubernetesNodeGroupProfile) GetInfraProviderOk() (*KubernetesBaseInfrastructureProviderRelationship, bool) {\n\tif o == nil || o.InfraProvider == nil {\n\t\treturn nil, false\n\t}\n\treturn o.InfraProvider, true\n}", "func (o *KubernetesNodeGroupProfile) HasInfraProvider() bool {\n\tif o != nil && o.InfraProvider != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func infraFailure(err error) *build.InfraFailure {\n\tfailure := &build.InfraFailure{\n\t\tText: err.Error(),\n\t}\n\tif errors.Unwrap(err) == context.Canceled {\n\t\tfailure.Type = build.InfraFailure_CANCELED\n\t} else {\n\t\tfailure.Type = build.InfraFailure_BOOTSTRAPPER_ERROR\n\t\tfailure.BootstrapperCallStack = errors.RenderStack(err)\n\t}\n\n\treturn failure\n}", "func (o InfraAlertConditionOutput) IntegrationProvider() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *InfraAlertCondition) pulumi.StringPtrOutput { return v.IntegrationProvider }).(pulumi.StringPtrOutput)\n}", "func (ts *Tester) Provider() string {\n\treturn \"eks\"\n}", "func (u *UnknownProvider) GetProviderString() string {\n\treturn \"unknown\"\n}", "func (me TxsdNodeRoleSimpleContentExtensionCategory) IsInfra() bool { return me.String() == \"infra\" }", "func testAccSpinnakerApplication_cloudProvider(rName string, provider string) string {\n\treturn fmt.Sprintf(`\nresource \"spinnaker_application\" \"test\" {\n\tname = %q\n\temail = \"acceptance@test.com\"\n\tcloud_providers = [%q]\n}\n`, rName, provider)\n}", "func (a *Application) RegisterProvider() {\n\n}", "func Provider() terraform.ResourceProvider {\n\treturn &schema.Provider{\n\t\tSchema: map[string]*schema.Schema{\n\t\t\t\"access_key\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tDefault: \"\",\n\t\t\t\tDescription: \"The access key for API operations.\",\n\t\t\t},\n\t\t\t\"secret_key\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tDefault: \"\",\n\t\t\t\tDescription: \"The secret key for API operations.\",\n\t\t\t},\n\t\t\t\"endpoint\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tDescription: \"The endpoint for API operations.\",\n\t\t\t},\n\t\t\t\"region\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tDescription: \"The region where Nifcloud operations will take place.\",\n\t\t\t},\n\t\t},\n\n\t\tDataSourcesMap: map[string]*schema.Resource{\n\t\t\t// \"nifcloud_instance\": dataSourceInstance(),\n\t\t},\n\t\tResourcesMap: map[string]*schema.Resource{\n\t\t\t\"nifcloud_instance\": resourceNifcloudInstance(),\n\t\t\t\"nifcloud_network\": resourceNifcloudNetwork(),\n\t\t\t\"nifcloud_volume\": resourceNifcloudVolume(),\n\t\t\t\"nifcloud_securitygroup\": resourceNifcloudSecurityGroup(),\n\t\t\t\"nifcloud_securitygroup_rule\": resourceNifcloudSecurityGroupRule(),\n\t\t\t\"nifcloud_keypair\": resourceNifcloudKeyPair(),\n\t\t\t\"nifcloud_instancebackup_rule\": resourceNifcloudInstanceBackupRule(),\n\t\t\t\"nifcloud_image\": resourceNifcloudImage(),\n\t\t\t\"nifcloud_customer_gateway\": resourceNifcloudCustomerGateway(),\n\t\t\t\"nifcloud_vpn_gateway\": resourceNifcloudVpnGateway(),\n\t\t\t\"nifcloud_vpn_connection\": resourceNifcloudVpnConnection(),\n\t\t\t\"nifcloud_db_parameter_group\": resourceNifcloudDbParameterGroup(),\n\t\t\t\"nifcloud_db_security_group\": resourceNifcloudDbSecurityGroup(),\n\t\t\t\"nifcloud_db_instance\": resourceNifcloudDbInstance(),\n\t\t\t\"nifcloud_router\": resourceNifcloudRouter(),\n\t\t\t\"nifcloud_route_table\": resourceNifcloudRouteTable(),\n\t\t\t\"nifcloud_route\": resourceNifcloudRoute(),\n\t\t\t\"nifcloud_route_table_association\": resourceNifcloudRouteTableAssociation(),\n\t\t\t\"nifcloud_route_table_association_with_vpn_gateway\": resourceNifcloudRouteTableAssociationWithVpnGateway(),\n\t\t\t\"nifcloud_lb\": resourceNifcloudLb(),\n\t\t\t\"nifcloud_lb_port\": resourceNifcloudLbPort(),\n\t\t\t\"nifcloud_eip\": resourceNifcloudEip(),\n\t\t},\n\t\tConfigureFunc: providerConfigure,\n\t}\n}", "func Provider() tfbridge.ProviderInfo {\n\t// Instantiate the Terraform provider\n\tp := shimv2.NewProvider(xyz.Provider())\n\n\t// Create a Pulumi provider mapping\n\tprov := tfbridge.ProviderInfo{\n\t\tP: p,\n\t\tName: \"xyz\",\n\t\t// DisplayName is a way to be able to change the casing of the provider\n\t\t// name when being displayed on the Pulumi registry\n\t\tDisplayName: \"\",\n\t\t// The default publisher for all packages is Pulumi.\n\t\t// Change this to your personal name (or a company name) that you\n\t\t// would like to be shown in the Pulumi Registry if this package is published\n\t\t// there.\n\t\tPublisher: \"Pulumi\",\n\t\t// LogoURL is optional but useful to help identify your package in the Pulumi Registry\n\t\t// if this package is published there.\n\t\t//\n\t\t// You may host a logo on a domain you control or add an SVG logo for your package\n\t\t// in your repository and use the raw content URL for that file as your logo URL.\n\t\tLogoURL: \"\",\n\t\t// PluginDownloadURL is an optional URL used to download the Provider\n\t\t// for use in Pulumi programs\n\t\t// e.g https://github.com/org/pulumi-provider-name/releases/\n\t\tPluginDownloadURL: \"\",\n\t\tDescription: \"A Pulumi package for creating and managing xyz cloud resources.\",\n\t\t// category/cloud tag helps with categorizing the package in the Pulumi Registry.\n\t\t// For all available categories, see `Keywords` in\n\t\t// https://www.pulumi.com/docs/guides/pulumi-packages/schema/#package.\n\t\tKeywords: []string{\"pulumi\", \"xyz\", \"category/cloud\"},\n\t\tLicense: \"Apache-2.0\",\n\t\tHomepage: \"https://www.pulumi.com\",\n\t\tRepository: \"https://github.com/pulumi/pulumi-xyz\",\n\t\t// The GitHub Org for the provider - defaults to `terraform-providers`. Note that this\n\t\t// should match the TF provider module's require directive, not any replace directives.\n\t\tGitHubOrg: \"\",\n\t\tConfig: map[string]*tfbridge.SchemaInfo{\n\t\t\t// Add any required configuration here, or remove the example below if\n\t\t\t// no additional points are required.\n\t\t\t// \"region\": {\n\t\t\t// \tType: tfbridge.MakeType(\"region\", \"Region\"),\n\t\t\t// \tDefault: &tfbridge.DefaultInfo{\n\t\t\t// \t\tEnvVars: []string{\"AWS_REGION\", \"AWS_DEFAULT_REGION\"},\n\t\t\t// \t},\n\t\t\t// },\n\t\t},\n\t\tPreConfigureCallback: preConfigureCallback,\n\t\tResources: map[string]*tfbridge.ResourceInfo{\n\t\t\t// Map each resource in the Terraform provider to a Pulumi type. Two examples\n\t\t\t// are below - the single line form is the common case. The multi-line form is\n\t\t\t// needed only if you wish to override types or other default options.\n\t\t\t//\n\t\t\t// \"aws_iam_role\": {Tok: tfbridge.MakeResource(mainPkg, mainMod, \"IamRole\")}\n\t\t\t//\n\t\t\t// \"aws_acm_certificate\": {\n\t\t\t// \tTok: tfbridge.MakeResource(mainPkg, mainMod, \"Certificate\"),\n\t\t\t// \tFields: map[string]*tfbridge.SchemaInfo{\n\t\t\t// \t\t\"tags\": {Type: tfbridge.MakeType(mainPkg, \"Tags\")},\n\t\t\t// \t},\n\t\t\t// },\n\t\t},\n\t\tDataSources: map[string]*tfbridge.DataSourceInfo{\n\t\t\t// Map each resource in the Terraform provider to a Pulumi function. An example\n\t\t\t// is below.\n\t\t\t// \"aws_ami\": {Tok: tfbridge.MakeDataSource(mainPkg, mainMod, \"getAmi\")},\n\t\t},\n\t\tJavaScript: &tfbridge.JavaScriptInfo{\n\t\t\t// List any npm dependencies and their versions\n\t\t\tDependencies: map[string]string{\n\t\t\t\t\"@pulumi/pulumi\": \"^3.0.0\",\n\t\t\t},\n\t\t\tDevDependencies: map[string]string{\n\t\t\t\t\"@types/node\": \"^10.0.0\", // so we can access strongly typed node definitions.\n\t\t\t\t\"@types/mime\": \"^2.0.0\",\n\t\t\t},\n\t\t\t// See the documentation for tfbridge.OverlayInfo for how to lay out this\n\t\t\t// section, or refer to the AWS provider. Delete this section if there are\n\t\t\t// no overlay files.\n\t\t\t//Overlay: &tfbridge.OverlayInfo{},\n\t\t},\n\t\tPython: &tfbridge.PythonInfo{\n\t\t\t// List any Python dependencies and their version ranges\n\t\t\tRequires: map[string]string{\n\t\t\t\t\"pulumi\": \">=3.0.0,<4.0.0\",\n\t\t\t},\n\t\t},\n\t\tGolang: &tfbridge.GolangInfo{\n\t\t\tImportBasePath: filepath.Join(\n\t\t\t\tfmt.Sprintf(\"github.com/pulumi/pulumi-%[1]s/sdk/\", mainPkg),\n\t\t\t\ttfbridge.GetModuleMajorVersion(version.Version),\n\t\t\t\t\"go\",\n\t\t\t\tmainPkg,\n\t\t\t),\n\t\t\tGenerateResourceContainerTypes: true,\n\t\t},\n\t\tCSharp: &tfbridge.CSharpInfo{\n\t\t\tPackageReferences: map[string]string{\n\t\t\t\t\"Pulumi\": \"3.*\",\n\t\t\t},\n\t\t},\n\t}\n\n\t// These are new API's that you may opt to use to automatically compute resource tokens,\n\t// and apply auto aliasing for full backwards compatibility.\n\t// For more information, please reference: https://pkg.go.dev/github.com/pulumi/pulumi-terraform-bridge/v3/pkg/tfbridge#ProviderInfo.ComputeTokens\n\tprov.MustComputeTokens(tokens.SingleModule(\"xyz_\", mainMod,\n\t\ttokens.MakeStandard(mainPkg)))\n\tprov.MustApplyAutoAliasing()\n\tprov.SetAutonaming(255, \"-\")\n\n\treturn prov\n}", "func Test_Provider(t *testing.T) {\n\t// SetLogLevel(\"TRACE\")\n\t// CheckVersion()\n\n\t// Start provider API in the background\n\tgo InitProvider()\n\t// err := InitProvider()\n\t// if err != nil {\n\t// \tlog.Fatalf(\"Error initializing Provider %+v\", err)\n\t// }\n\n\tverifier := HTTPVerifier{}\n\t// Authorization middleware\n\t// This is your chance to modify the request before it hits your provider\n\t// NOTE: this should be used very carefully, as it has the potential to\n\t// _change_ the contract\n\t// f := func(next http.Handler) http.Handler {\n\t// \treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t// \t\tlog.Println(\"[DEBUG] HOOK request filter\")\n\t// \t\t// r.Header.Add(\"Authorization\", \"Bearer 1234-dynamic-value\")\n\t// \t\tnext.ServeHTTP(w, r)\n\t// \t})\n\t// }\n\n\t// Verify the Provider with local Pact Files\n\terr := verifier.VerifyProvider(t, VerifyRequest{\n\t\tProviderBaseURL: \"http://localhost:9000\",\n\t\tBrokerURL: \"http://localhost:9292\",\n\t\tProvider: \"GreetingAPI\",\n\t\tProviderVersion: \"1.0.0\",\n\t\tPublishVerificationResults: true,\n\t\t// PactFiles: []string{\n\t\t// \tfilepath.ToSlash(fmt.Sprintf(\"%s/GreetingAPIConsumer-GreetingAPI.json\", pactDir)),\n\t\t// },\n\t\t// RequestFilter: f,\n\t\t// BeforeEach: func() error {\n\t\t// \tlog.Println(\"[DEBUG] HOOK before each\")\n\t\t// \treturn nil\n\t\t// },\n\t\t// AfterEach: func() error {\n\t\t// \tlog.Println(\"[DEBUG] HOOK after each\")\n\t\t// \treturn nil\n\t\t// },\n\t\t// StateHandlers: StateHandlers{\n\t\t// \t\"User foo exists\": func(setup bool, s ProviderStateV3) (ProviderStateV3Response, error) {\n\n\t\t// \t\tif setup {\n\t\t// \t\t\tlog.Println(\"[DEBUG] HOOK calling user foo exists state handler\", s)\n\t\t// \t\t} else {\n\t\t// \t\t\tlog.Println(\"[DEBUG] HOOK teardown the 'User foo exists' state\")\n\t\t// \t\t}\n\n\t\t// \t\t// ... do something, such as create \"foo\" in the database\n\n\t\t// \t\t// Optionally (if there are generators in the pact) return provider state values to be used in the verification\n\t\t// \t\treturn ProviderStateV3Response{\"uuid\": \"1234\"}, nil\n\t\t// \t},\n\t\t// },\n\t})\n\n\tassert.NoError(t, err)\n}", "func (o *KubernetesNodeGroupProfile) SetInfraProvider(v KubernetesBaseInfrastructureProviderRelationship) {\n\to.InfraProvider = &v\n}", "func TestOverlayIOPExhaustiveness(t *testing.T) {\n\twellknownProviders := map[string]struct{}{\n\t\t\"prometheus\": {},\n\t\t\"envoy_file_access_log\": {},\n\t\t\"stackdriver\": {},\n\t\t\"envoy_otel_als\": {},\n\t\t\"envoy_ext_authz_http\": {},\n\t\t\"envoy_ext_authz_grpc\": {},\n\t\t\"zipkin\": {},\n\t\t\"lightstep\": {},\n\t\t\"datadog\": {},\n\t\t\"opencensus\": {},\n\t\t\"skywalking\": {},\n\t\t\"envoy_http_als\": {},\n\t\t\"envoy_tcp_als\": {},\n\t\t\"opentelemetry\": {},\n\t}\n\n\tunexpectedProviders := make([]string, 0)\n\n\tmsg := &meshconfig.MeshConfig_ExtensionProvider{}\n\tpb := msg.ProtoReflect()\n\tmd := pb.Descriptor()\n\n\tof := md.Oneofs().Get(0)\n\tfor i := 0; i < of.Fields().Len(); i++ {\n\t\to := of.Fields().Get(i)\n\t\tn := string(o.Name())\n\t\tif _, ok := wellknownProviders[n]; ok {\n\t\t\tdelete(wellknownProviders, n)\n\t\t} else {\n\t\t\tunexpectedProviders = append(unexpectedProviders, n)\n\t\t}\n\t}\n\n\tif len(wellknownProviders) != 0 || len(unexpectedProviders) != 0 {\n\t\tt.Errorf(\"unexpected provider not implemented in OverlayIOP, wellknownProviders: %v unexpectedProviders: %v\", wellknownProviders, unexpectedProviders)\n\t\tt.Fail()\n\t}\n}", "func NewProvider() *ProviderConfig {\n\tproviderConfig := &ProviderConfig{\n\t\tAlibaba: make(map[string]*models.AlibabaCloudSpec),\n\t\tAnexia: make(map[string]*models.AnexiaCloudSpec),\n\t\tAws: make(map[string]*models.AWSCloudSpec),\n\t\tAzure: make(map[string]*models.AzureCloudSpec),\n\t\tDigitalocean: make(map[string]*models.DigitaloceanCloudSpec),\n\t\tFake: make(map[string]*models.FakeCloudSpec),\n\t\tGcp: make(map[string]*models.GCPCloudSpec),\n\t\tHetzner: make(map[string]*models.HetznerCloudSpec),\n\t\tKubevirt: make(map[string]*models.KubevirtCloudSpec),\n\t\tOpenstack: make(map[string]*models.OpenstackCloudSpec),\n\t\tPacket: make(map[string]*models.PacketCloudSpec),\n\t\tVsphere: make(map[string]*models.VSphereCloudSpec),\n\t}\n\n\tproviderConfig.Alibaba[\"Alibaba\"] = newAlibabaCloudSpec()\n\tproviderConfig.Anexia[\"Anexia\"] = newAnexiaCloudSpec()\n\tproviderConfig.Aws[\"Aws\"] = newAWSCloudSpec()\n\tproviderConfig.Azure[\"Azure\"] = newAzureCloudSpec()\n\tproviderConfig.Digitalocean[\"Digitalocean\"] = newDigitaloceanCloudSpec()\n\tproviderConfig.Fake[\"Fake\"] = newFakeCloudSpec()\n\tproviderConfig.Gcp[\"Gcp\"] = newGCPCloudSpec()\n\tproviderConfig.Hetzner[\"Hetzner\"] = newHetznerCloudSpec()\n\tproviderConfig.Kubevirt[\"Kubevirt\"] = newKubevirtCloudSpec()\n\tproviderConfig.Openstack[\"Openstack\"] = newOpenstackCloudSpec()\n\tproviderConfig.Packet[\"Packet\"] = newPacketCloudSpec()\n\tproviderConfig.Vsphere[\"Vsphere\"] = newVSphereCloudSpec()\n\n\treturn providerConfig\n}", "func (o *KubernetesNodeGroupProfile) GetInfraProvider() KubernetesBaseInfrastructureProviderRelationship {\n\tif o == nil || o.InfraProvider == nil {\n\t\tvar ret KubernetesBaseInfrastructureProviderRelationship\n\t\treturn ret\n\t}\n\treturn *o.InfraProvider\n}", "func (o *StorageNetAppCloudTargetAllOf) GetProviderTypeOk() (*string, bool) {\n\tif o == nil || o.ProviderType == nil {\n\t\treturn nil, false\n\t}\n\treturn o.ProviderType, true\n}", "func shouldIncludeOIDCProvider(provider oidcProvider, excludeAfter time.Time, configObj config.Config) bool {\n\tif excludeAfter.Before(aws.TimeValue(provider.CreateTime)) {\n\t\treturn false\n\t}\n\n\treturn config.ShouldInclude(\n\t\taws.StringValue(provider.ProviderURL),\n\t\tconfigObj.OIDCProvider.IncludeRule.NamesRegExp,\n\t\tconfigObj.OIDCProvider.ExcludeRule.NamesRegExp,\n\t)\n}", "func (o *ClusterMetricsNodes) GetInfraOk() (*float64, bool) {\n\tif o == nil || o.Infra == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Infra, true\n}", "func (fi *FabricInterface) SupportsProvider(provider string) bool {\n\tif fi == nil {\n\t\treturn false\n\t}\n\n\t// format: [lib+]prov[,prov2,...]\n\tvar prefix string\n\tprovPieces := strings.Split(provider, \"+\")\n\tproviders := provPieces[0]\n\tif len(provPieces) > 1 {\n\t\tprefix = provPieces[0] + \"+\"\n\t\tproviders = provPieces[1]\n\t}\n\n\tfor _, prov := range strings.Split(providers, \",\") {\n\t\tprov = prefix + prov\n\t\tif !fi.Providers.Has(prov) {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}", "func TestConjur_Provider(t *testing.T) {\n\tvar err error\n\tvar provider plugin_v1.Provider\n\tname := \"conjur\"\n\n\toptions := plugin_v1.ProviderOptions{\n\t\tName: name,\n\t}\n\n\tt.Run(\"Can create the Conjur provider\", func(t *testing.T) {\n\t\tprovider, err = providers.ProviderFactories[name](options)\n\t\tassert.NoError(t, err)\n\t})\n\n\tt.Run(\"Has the expected provider name\", func(t *testing.T) {\n\t\tassert.Equal(t, \"conjur\", provider.GetName())\n\t})\n\n\tt.Run(\"Can provide an access token\", func(t *testing.T) {\n\t\tid := \"accessToken\"\n\t\tvalues, err := provider.GetValues(id)\n\n\t\tassert.NoError(t, err)\n\t\tassert.NotNil(t, values[id])\n\t\tassert.NoError(t, values[id].Error)\n\t\tassert.NotNil(t, values[id].Value)\n\n\t\ttoken := make(map[string]string)\n\t\terr = json.Unmarshal(values[id].Value, &token)\n\t\tassert.NoError(t, err)\n\t\tassert.NotNil(t, token[\"protected\"])\n\t\tassert.NotNil(t, token[\"payload\"])\n\t})\n\n\tt.Run(\"Reports an unknown value\",\n\t\ttestutils.Reports(\n\t\t\tprovider,\n\t\t\t\"foobar\",\n\t\t\t\"404 Not Found. CONJ00076E Variable dev:variable:foobar is empty or not found..\",\n\t\t),\n\t)\n\n\tt.Run(\"Provides\", func(t *testing.T) {\n\t\tfor _, testCase := range canProvideTestCases {\n\t\t\tt.Run(testCase.Description, testutils.CanProvide(provider, testCase.ID, testCase.ExpectedValue))\n\t\t}\n\t})\n}", "func (b *ClusterNodesBuilder) Infra(value int) *ClusterNodesBuilder {\n\tb.infra = &value\n\treturn b\n}", "func CheckProvider(provider string) (string, error) {\n\tprovider = strings.ToLower(provider)\n\tif provider == ProviderAWS {\n\t\treturn provider, nil\n\t}\n\n\treturn provider, fmt.Errorf(\"unsupported provider %s\", provider)\n}", "func (d *Deployment) EnsureProvider(provider string) error {\n\tif provider == \"\" {\n\t\treturn nil\n\t}\n\n\tproviderRef, err := providers.ParseReference(provider)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"invalid provider reference %v: %w\", provider, err)\n\t}\n\t_, has := d.GetProvider(providerRef)\n\tif !has {\n\t\t// We need to create the provider in the registry, find its old state and just \"Same\" it.\n\t\tvar providerResource *resource.State\n\t\tfor _, r := range d.prev.Resources {\n\t\t\tif r.URN == providerRef.URN() && r.ID == providerRef.ID() {\n\t\t\t\tproviderResource = r\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif providerResource == nil {\n\t\t\treturn fmt.Errorf(\"could not find provider %v\", providerRef)\n\t\t}\n\n\t\terr := d.SameProvider(providerResource)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"could not create provider %v: %w\", providerRef, err)\n\t\t}\n\t}\n\n\treturn nil\n}", "func ProviderIs(providers ...string) bool {\n\tfor _, provider := range providers {\n\t\tif strings.EqualFold(provider, TestContext.Provider) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func NewRegisterInfraEnvNotImplemented() *RegisterInfraEnvNotImplemented {\n\n\treturn &RegisterInfraEnvNotImplemented{}\n}", "func ec2Provider(providers []ProviderPayload) *ProviderPayload {\n\tfor _, provider := range providers {\n\t\tif provider.Name == providerEc2 {\n\t\t\treturn &provider\n\t\t}\n\t}\n\tlog.Fatal(\"ec2 provider is missing\")\n\treturn nil\n}", "func (mdhth *MockDHTHandler) Provider(string, bool) error {\n\treturn nil\n}", "func ProviderTestKOSeal() (configstore.ItemList, error) {\n\tret := configstore.ItemList{\n\t\tItems: []configstore.Item{\n\t\t\tconfigstore.NewItem(\n\t\t\t\tkeyloader.EncryptionKeyConfigName,\n\t\t\t\t`{\"key\":\"5fdb8af280b007a46553dfddb3f42bc10619dcabca8d4fdf5239b09445ab1a41\",\"identifier\":\"test\",\"sealed\":false,\"timestamp\":10,\"cipher\":\"aes-gcm\"}`,\n\t\t\t\t1,\n\t\t\t),\n\t\t\tconfigstore.NewItem(\n\t\t\t\tkeyloader.EncryptionKeyConfigName,\n\t\t\t\t`{\"key\":\"QXdDW4N/jmJzpMu7i1zu4YF1opTn7H+eOk9CLFGBSFg=\",\"identifier\":\"test\",\"sealed\":true,\"timestamp\":1,\"cipher\":\"xchacha20-poly1305\"}`,\n\t\t\t\t1,\n\t\t\t),\n\t\t},\n\t}\n\treturn ret, nil\n}", "func (scnb *SupplyChainNodeBuilder) requireProvider() bool {\n\tif scnb.currentProvider == nil {\n\t\treturn false\n\t}\n\treturn true\n}", "func (p *ProviderConfig) GetProviderCloudSpec(providerName string, datacenter string, routerID string) *models.CloudSpec {\n\tcs := &models.CloudSpec{\n\t\tDatacenterName: datacenter,\n\t}\n\n\tproviderAlibaba, ok := p.Alibaba[providerName]\n\tif ok {\n\t\tcs.Alibaba = providerAlibaba\n\t}\n\tproviderAnexia, ok := p.Anexia[providerName]\n\tif ok {\n\t\tcs.Anexia = providerAnexia\n\t}\n\tproviderAws, ok := p.Aws[providerName]\n\tif ok {\n\t\tcs.Aws = providerAws\n\t}\n\tproviderAzure, ok := p.Azure[providerName]\n\tif ok {\n\t\tcs.Azure = providerAzure\n\t}\n\tproviderDigitalocean, ok := p.Digitalocean[providerName]\n\tif ok {\n\t\tcs.Digitalocean = providerDigitalocean\n\t}\n\tproviderFake, ok := p.Fake[providerName]\n\tif ok {\n\t\tcs.Fake = providerFake\n\t}\n\tproviderGcp, ok := p.Gcp[providerName]\n\tif ok {\n\t\tcs.Gcp = providerGcp\n\t}\n\tproviderHetzner, ok := p.Hetzner[providerName]\n\tif ok {\n\t\tcs.Hetzner = providerHetzner\n\t}\n\tproviderKubevirt, ok := p.Kubevirt[providerName]\n\tif ok {\n\t\tcs.Kubevirt = providerKubevirt\n\t}\n\tproviderOpenstack, ok := p.Openstack[providerName]\n\tif ok {\n\t\tcs.Openstack = providerOpenstack\n\t\tcs.Openstack.RouterID = routerID\n\t}\n\tproviderPacket, ok := p.Packet[providerName]\n\tif ok {\n\t\tcs.Packet = providerPacket\n\t}\n\tproviderVsphere, ok := p.Vsphere[providerName]\n\tif ok {\n\t\tcs.Vsphere = providerVsphere\n\t}\n\n\treturn cs\n}", "func SetupProvider(mgr ctrl.Manager, o controller.Options) error {\n\tname := \"packages/\" + strings.ToLower(v1.ProviderGroupKind)\n\tnp := func() v1.Package { return &v1.Provider{} }\n\tnr := func() v1.PackageRevision { return &v1.ProviderRevision{} }\n\tnrl := func() v1.PackageRevisionList { return &v1.ProviderRevisionList{} }\n\n\tcs, err := kubernetes.NewForConfig(mgr.GetConfig())\n\tif err != nil {\n\t\treturn errors.Wrap(err, errCreateK8sClient)\n\t}\n\tf, err := xpkg.NewK8sFetcher(cs, append(o.FetcherOptions, xpkg.WithNamespace(o.Namespace), xpkg.WithServiceAccount(o.ServiceAccount))...)\n\tif err != nil {\n\t\treturn errors.Wrap(err, errBuildFetcher)\n\t}\n\n\topts := []ReconcilerOption{\n\t\tWithNewPackageFn(np),\n\t\tWithNewPackageRevisionFn(nr),\n\t\tWithNewPackageRevisionListFn(nrl),\n\t\tWithRevisioner(NewPackageRevisioner(f, WithDefaultRegistry(o.DefaultRegistry))),\n\t\tWithLogger(o.Logger.WithValues(\"controller\", name)),\n\t\tWithRecorder(event.NewAPIRecorder(mgr.GetEventRecorderFor(name))),\n\t}\n\tif o.WebhookTLSSecretName != \"\" {\n\t\topts = append(opts, WithWebhookTLSSecretName(o.WebhookTLSSecretName))\n\t}\n\tif o.ESSOptions != nil && o.ESSOptions.TLSSecretName != nil {\n\t\topts = append(opts, WithESSTLSSecretName(o.ESSOptions.TLSSecretName))\n\t}\n\tif o.TLSServerSecretName != \"\" {\n\t\topts = append(opts, WithTLSServerSecretName(&o.TLSServerSecretName))\n\t}\n\tif o.TLSClientSecretName != \"\" {\n\t\topts = append(opts, WithTLSClientSecretName(&o.TLSClientSecretName))\n\t}\n\n\treturn ctrl.NewControllerManagedBy(mgr).\n\t\tNamed(name).\n\t\tFor(&v1.Provider{}).\n\t\tOwns(&v1.ProviderRevision{}).\n\t\tWithOptions(o.ForControllerRuntime()).\n\t\tComplete(ratelimiter.NewReconciler(name, NewReconciler(mgr, opts...), o.GlobalRateLimiter))\n}", "func Provider() tfbridge.ProviderInfo {\n\t// Instantiate the Terraform provider\n\tp := shimv2.NewProvider(shim.NewProvider())\n\n\t// Create a Pulumi provider mapping\n\tprov := tfbridge.ProviderInfo{\n\t\tP: p,\n\t\tName: \"azuread\",\n\t\tDisplayName: \"Azure Active Directory (Azure AD)\",\n\t\tDescription: \"A Pulumi package for creating and managing Azure Active Directory (Azure AD) cloud resources.\",\n\t\tKeywords: []string{\"pulumi\", \"azuread\"},\n\t\tLicense: \"Apache-2.0\",\n\t\tHomepage: \"https://pulumi.io\",\n\t\tGitHubOrg: \"hashicorp\",\n\t\tRepository: \"https://github.com/pulumi/pulumi-azuread\",\n\t\tConfig: map[string]*tfbridge.SchemaInfo{\n\t\t\t\"environment\": {\n\t\t\t\tDefault: &tfbridge.DefaultInfo{\n\t\t\t\t\tValue: \"public\",\n\t\t\t\t\tEnvVars: []string{\"ARM_ENVIRONMENT\"},\n\t\t\t\t},\n\t\t\t},\n\t\t\t\"msi_endpoint\": {\n\t\t\t\tDefault: &tfbridge.DefaultInfo{\n\t\t\t\t\tEnvVars: []string{\"ARM_MSI_ENDPOINT\"},\n\t\t\t\t},\n\t\t\t},\n\t\t\t\"use_msi\": {\n\t\t\t\tDefault: &tfbridge.DefaultInfo{\n\t\t\t\t\tValue: false,\n\t\t\t\t\tEnvVars: []string{\"ARM_USE_MSI\"},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tPreConfigureCallback: preConfigureCallback,\n\t\tResources: map[string]*tfbridge.ResourceInfo{\n\t\t\t\"azuread_application\": {Tok: makeResource(mainMod, \"Application\")},\n\t\t\t\"azuread_application_password\": {Tok: makeResource(mainMod, \"ApplicationPassword\")},\n\t\t\t\"azuread_group\": {Tok: makeResource(mainMod, \"Group\")},\n\t\t\t\"azuread_service_principal\": {Tok: makeResource(mainMod, \"ServicePrincipal\")},\n\t\t\t\"azuread_service_principal_password\": {Tok: makeResource(mainMod, \"ServicePrincipalPassword\")},\n\t\t\t\"azuread_service_principal_delegated_permission_grant\": {\n\t\t\t\tTok: makeResource(mainMod, \"ServicePrincipalDelegatedPermissionGrant\"),\n\t\t\t},\n\t\t\t\"azuread_user\": {Tok: makeResource(mainMod, \"User\")},\n\t\t\t\"azuread_group_member\": {Tok: makeResource(mainMod, \"GroupMember\")},\n\t\t\t\"azuread_application_certificate\": {Tok: makeResource(mainMod, \"ApplicationCertificate\")},\n\t\t\t\"azuread_service_principal_certificate\": {Tok: makeResource(mainMod, \"ServicePrincipalCertificate\")},\n\t\t\t\"azuread_service_principal_token_signing_certificate\": {\n\t\t\t\tTok: makeResource(mainMod, \"ServicePrincipalTokenSigningCertificate\"),\n\t\t\t},\n\t\t\t\"azuread_application_pre_authorized\": {Tok: makeResource(mainMod, \"ApplicationPreAuthorized\")},\n\t\t\t\"azuread_invitation\": {Tok: makeResource(mainMod, \"Invitation\")},\n\t\t\t\"azuread_conditional_access_policy\": {Tok: makeResource(mainMod, \"ConditionalAccessPolicy\")},\n\t\t\t\"azuread_named_location\": {Tok: makeResource(mainMod, \"NamedLocation\")},\n\t\t\t\"azuread_directory_role\": {Tok: makeResource(mainMod, \"DirectoryRole\")},\n\t\t\t\"azuread_directory_role_member\": {Tok: makeResource(mainMod, \"DirectoryRoleMember\")},\n\t\t\t\"azuread_app_role_assignment\": {Tok: makeResource(mainMod, \"AppRoleAssignment\")},\n\t\t\t\"azuread_administrative_unit\": {Tok: makeResource(mainMod, \"AdministrativeUnit\")},\n\t\t\t\"azuread_administrative_unit_member\": {Tok: makeResource(mainMod, \"AdministrativeUnitMember\")},\n\t\t\t\"azuread_application_federated_identity_credential\": {\n\t\t\t\tTok: makeResource(mainMod, \"ApplicationFederatedIdentityCredential\"),\n\t\t\t},\n\t\t\t\"azuread_custom_directory_role\": {Tok: makeResource(mainMod, \"CustomDirectoryRole\")},\n\t\t\t\"azuread_claims_mapping_policy\": {Tok: makeResource(mainMod, \"ClaimsMappingPolicy\")},\n\t\t\t\"azuread_directory_role_assignment\": {Tok: makeResource(mainMod, \"DirectoryRoleAssignment\")},\n\t\t\t\"azuread_service_principal_claims_mapping_policy_assignment\": {\n\t\t\t\tTok: makeResource(mainMod, \"ServicePrincipalClaimsMappingPolicyAssignment\"),\n\t\t\t},\n\t\t\t\"azuread_synchronization_job\": {Tok: makeResource(mainMod, \"SynchronizationJob\")},\n\t\t\t\"azuread_synchronization_secret\": {Tok: makeResource(mainMod, \"SynchronizationSecret\")},\n\t\t\t\"azuread_access_package\": {Tok: makeResource(mainMod, \"AccessPackage\")},\n\t\t\t\"azuread_access_package_assignment_policy\": {Tok: makeResource(mainMod, \"AccessPackageAssignmentPolicy\")},\n\t\t\t\"azuread_access_package_catalog\": {Tok: makeResource(mainMod, \"AccessPackageCatalog\")},\n\t\t\t\"azuread_access_package_resource_catalog_association\": {\n\t\t\t\tTok: makeResource(mainMod, \"AccessPackageResourceCatalogAssociation\"),\n\t\t\t},\n\t\t\t\"azuread_access_package_resource_package_association\": {\n\t\t\t\tTok: makeResource(mainMod, \"AccessPackageResourcePackageAssociation\"),\n\t\t\t},\n\t\t\t\"azuread_administrative_unit_role_member\": {Tok: makeResource(mainMod, \"AdministrativeUnitRoleMember\")},\n\t\t\t\"azuread_user_flow_attribute\": {Tok: makeResource(mainMod, \"UserFlowAttribute\")},\n\t\t},\n\t\tDataSources: map[string]*tfbridge.DataSourceInfo{\n\t\t\t\"azuread_client_config\": {Tok: makeDataSource(mainMod, \"getClientConfig\")},\n\t\t\t\"azuread_application_published_app_ids\": {Tok: makeDataSource(mainMod, \"getApplicationPublishedAppIds\")},\n\t\t\t\"azuread_application_template\": {Tok: makeDataSource(mainMod, \"getApplicationTemplate\")},\n\t\t\t\"azuread_service_principals\": {Tok: makeDataSource(mainMod, \"getServicePrincipals\")},\n\t\t\t\"azuread_administrative_unit\": {Tok: makeDataSource(mainMod, \"getAdministrativeUnit\")},\n\t\t\t\"azuread_directory_object\": {Tok: makeDataSource(mainMod, \"getDirectoryObject\")},\n\t\t\t\"azuread_directory_roles\": {Tok: makeDataSource(mainMod, \"getDirectoryRoles\")},\n\t\t\t\"azuread_access_package\": {Tok: makeDataSource(mainMod, \"getAccessPackage\")},\n\t\t\t\"azuread_access_package_catalog\": {Tok: makeDataSource(mainMod, \"getAccessPackageCatalog\")},\n\t\t},\n\t\tJavaScript: &tfbridge.JavaScriptInfo{\n\t\t\t// List any npm dependencies and their versions\n\t\t\tDependencies: map[string]string{\n\t\t\t\t\"@pulumi/pulumi\": \"^3.0.0\",\n\t\t\t},\n\t\t\tDevDependencies: map[string]string{\n\t\t\t\t\"@types/node\": \"^10.0.0\", // so we can access strongly typed node definitions.\n\t\t\t\t\"@types/mime\": \"^2.0.0\",\n\t\t\t},\n\t\t},\n\t\tPython: &tfbridge.PythonInfo{\n\t\t\tRequires: map[string]string{\n\t\t\t\t\"pulumi\": \">=3.0.0,<4.0.0\",\n\t\t\t},\n\t\t},\n\t\tGolang: &tfbridge.GolangInfo{\n\t\t\tImportBasePath: filepath.Join(\n\t\t\t\tfmt.Sprintf(\"github.com/pulumi/pulumi-%[1]s/sdk/\", mainPkg),\n\t\t\t\ttfbridge.GetModuleMajorVersion(version.Version),\n\t\t\t\t\"go\",\n\t\t\t\tmainPkg,\n\t\t\t),\n\t\t\tGenerateResourceContainerTypes: true,\n\t\t},\n\t\tCSharp: &tfbridge.CSharpInfo{\n\t\t\tPackageReferences: map[string]string{\n\t\t\t\t\"Pulumi\": \"3.*\",\n\t\t\t},\n\t\t\tNamespaces: map[string]string{\n\t\t\t\t\"azuread\": \"AzureAD\",\n\t\t\t},\n\t\t}, MetadataInfo: tfbridge.NewProviderMetadata(metadata),\n\t}\n\n\tprov.MustComputeTokens(tfbridgetokens.SingleModule(\"azuread_\", mainMod,\n\t\ttfbridgetokens.MakeStandard(mainPkg)))\n\tprov.SetAutonaming(255, \"-\")\n\tprov.MustApplyAutoAliases()\n\n\treturn prov\n}", "func (r DeliveryResource) CloudProvider() string {\n\t// Kind is like ec2/cluster@v1 or titus/cluster@v1\n\t// but CloudProvider needs to be \"aws\" for \"ec2\"\n\t// so make that mapping here\n\tparts := strings.SplitN(r.Kind, \"/\", 2)\n\tif len(parts) == 0 {\n\t\treturn \"unknown-cloud-provider\"\n\t}\n\tif parts[0] == \"ec2\" {\n\t\treturn \"aws\"\n\t}\n\treturn parts[0]\n}", "func isInfraContainer(netNS string) bool {\n\treturn true\n}", "func Provider() terraform.ResourceProvider {\n\treturn &schema.Provider{\n\t\tSchema: map[string]*schema.Schema{\n\t\t\t\"public_key\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"UCLOUD_PUBLIC_KEY\", nil),\n\t\t\t\tDescription: descriptions[\"public_key\"],\n\t\t\t},\n\n\t\t\t\"private_key\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"UCLOUD_PRIVATE_KEY\", nil),\n\t\t\t\tDescription: descriptions[\"private_key\"],\n\t\t\t},\n\n\t\t\t\"region\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"UCLOUD_REGION\", nil),\n\t\t\t\tDescription: descriptions[\"region\"],\n\t\t\t},\n\n\t\t\t\"project_id\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"UCLOUD_PROJECT_ID\", nil),\n\t\t\t\tDescription: descriptions[\"project_id\"],\n\t\t\t},\n\n\t\t\t\"max_retries\": {\n\t\t\t\tType: schema.TypeInt,\n\t\t\t\tOptional: true,\n\t\t\t\tDefault: DefaultMaxRetries,\n\t\t\t\tDescription: descriptions[\"max_retries\"],\n\t\t\t},\n\n\t\t\t\"insecure\": {\n\t\t\t\tType: schema.TypeBool,\n\t\t\t\tOptional: true,\n\t\t\t\tDefault: DefaultInSecure,\n\t\t\t\tDescription: descriptions[\"insecure\"],\n\t\t\t},\n\t\t},\n\n\t\tDataSourcesMap: map[string]*schema.Resource{\n\t\t\t\"ucloud_instances\": dataSourceUCloudInstances(),\n\t\t\t\"ucloud_projects\": dataSourceUCloudProjects(),\n\t\t\t\"ucloud_images\": dataSourceUCloudImages(),\n\t\t\t\"ucloud_zones\": dataSourceUCloudZones(),\n\t\t\t\"ucloud_eips\": dataSourceUCloudEips(),\n\t\t},\n\t\tResourcesMap: map[string]*schema.Resource{\n\t\t\t\"ucloud_instance\": resourceUCloudInstance(),\n\t\t\t\"ucloud_eip\": resourceUCloudEIP(),\n\t\t\t\"ucloud_eip_association\": resourceUCloudEIPAssociation(),\n\t\t\t\"ucloud_vpc\": resourceUCloudVPC(),\n\t\t\t\"ucloud_subnet\": resourceUCloudSubnet(),\n\t\t\t\"ucloud_vpc_peering_connection\": resourceUCloudVPCPeeringConnection(),\n\t\t\t\"ucloud_lb\": resourceUCloudLB(),\n\t\t\t\"ucloud_lb_listener\": resourceUCloudLBListener(),\n\t\t\t\"ucloud_lb_attachment\": resourceUCloudLBAttachment(),\n\t\t\t\"ucloud_lb_rule\": resourceUCloudLBRule(),\n\t\t\t\"ucloud_disk\": resourceUCloudDisk(),\n\t\t\t\"ucloud_disk_attachment\": resourceUCloudDiskAttachment(),\n\t\t\t\"ucloud_security_group\": resourceUCloudSecurityGroup(),\n\t\t},\n\t\tConfigureFunc: providerConfigure,\n\t}\n}", "func Provider() terraform.ResourceProvider {\n\treturn &schema.Provider{\n\t\tSchema: map[string]*schema.Schema{\n\t\t\t\"api_token\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tSensitive: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"AIVEN_TOKEN\", nil),\n\t\t\t\tDescription: \"Aiven Authentication Token\",\n\t\t\t},\n\t\t},\n\n\t\tDataSourcesMap: map[string]*schema.Resource{\n\t\t\t\"aiven_connection_pool\": datasourceConnectionPool(),\n\t\t\t\"aiven_database\": datasourceDatabase(),\n\t\t\t\"aiven_kafka_acl\": datasourceKafkaACL(),\n\t\t\t\"aiven_kafka_topic\": datasourceKafkaTopic(),\n\t\t\t\"aiven_kafka_connector\": datasourceKafkaConnector(),\n\t\t\t\"aiven_kafka_schema\": datasourceKafkaSchema(),\n\t\t\t\"aiven_kafka_schema_configuration\": datasourceKafkaSchemaConfiguration(),\n\t\t\t\"aiven_elasticsearch_acl\": datasourceElasticsearchACL(),\n\t\t\t\"aiven_project\": datasourceProject(),\n\t\t\t\"aiven_project_user\": datasourceProjectUser(),\n\t\t\t\"aiven_project_vpc\": datasourceProjectVPC(),\n\t\t\t\"aiven_vpc_peering_connection\": datasourceVPCPeeringConnection(),\n\t\t\t\"aiven_service\": datasourceService(),\n\t\t\t\"aiven_service_integration\": datasourceServiceIntegration(),\n\t\t\t\"aiven_service_integration_endpoint\": datasourceServiceIntegrationEndpoint(),\n\t\t\t\"aiven_service_user\": datasourceServiceUser(),\n\t\t\t\"aiven_account\": datasourceAccount(),\n\t\t\t\"aiven_account_team\": datasourceAccountTeam(),\n\t\t\t\"aiven_account_team_project\": datasourceAccountTeamProject(),\n\t\t\t\"aiven_account_team_member\": datasourceAccountTeamMember(),\n\t\t\t\"aiven_mirrormaker_replication_flow\": datasourceMirrorMakerReplicationFlowTopic(),\n\t\t\t\"aiven_account_authentication\": datasourceAccountAuthentication(),\n\t\t\t\"aiven_kafka\": datasourceKafka(),\n\t\t\t\"aiven_kafka_connect\": datasourceKafkaConnect(),\n\t\t\t\"aiven_kafka_mirrormaker\": datasourceKafkaMirrormaker(),\n\t\t\t\"aiven_pg\": datasourcePG(),\n\t\t\t\"aiven_mysql\": datasourceMySQL(),\n\t\t\t\"aiven_cassandra\": datasourceCassandra(),\n\t\t\t\"aiven_elasticsearch\": datasourceElasticsearch(),\n\t\t\t\"aiven_grafana\": datasourceGrafana(),\n\t\t\t\"aiven_influxdb\": datasourceInfluxDB(),\n\t\t\t\"aiven_redis\": datasourceRedis(),\n\t\t},\n\n\t\tResourcesMap: map[string]*schema.Resource{\n\t\t\t\"aiven_connection_pool\": resourceConnectionPool(),\n\t\t\t\"aiven_database\": resourceDatabase(),\n\t\t\t\"aiven_kafka_acl\": resourceKafkaACL(),\n\t\t\t\"aiven_kafka_topic\": resourceKafkaTopic(),\n\t\t\t\"aiven_kafka_connector\": resourceKafkaConnector(),\n\t\t\t\"aiven_kafka_schema\": resourceKafkaSchema(),\n\t\t\t\"aiven_kafka_schema_configuration\": resourceKafkaSchemaConfiguration(),\n\t\t\t\"aiven_elasticsearch_acl\": resourceElasticsearchACL(),\n\t\t\t\"aiven_project\": resourceProject(),\n\t\t\t\"aiven_project_user\": resourceProjectUser(),\n\t\t\t\"aiven_project_vpc\": resourceProjectVPC(),\n\t\t\t\"aiven_vpc_peering_connection\": resourceVPCPeeringConnection(),\n\t\t\t\"aiven_service\": resourceService(),\n\t\t\t\"aiven_service_integration\": resourceServiceIntegration(),\n\t\t\t\"aiven_service_integration_endpoint\": resourceServiceIntegrationEndpoint(),\n\t\t\t\"aiven_service_user\": resourceServiceUser(),\n\t\t\t\"aiven_account\": resourceAccount(),\n\t\t\t\"aiven_account_team\": resourceAccountTeam(),\n\t\t\t\"aiven_account_team_project\": resourceAccountTeamProject(),\n\t\t\t\"aiven_account_team_member\": resourceAccountTeamMember(),\n\t\t\t\"aiven_mirrormaker_replication_flow\": resourceMirrorMakerReplicationFlow(),\n\t\t\t\"aiven_account_authentication\": resourceAccountAuthentication(),\n\t\t\t\"aiven_kafka\": resourceKafka(),\n\t\t\t\"aiven_kafka_connect\": resourceKafkaConnect(),\n\t\t\t\"aiven_kafka_mirrormaker\": resourceKafkaMirrormaker(),\n\t\t\t\"aiven_pg\": resourcePG(),\n\t\t\t\"aiven_mysql\": resourceMySQL(),\n\t\t\t\"aiven_cassandra\": resourceCassandra(),\n\t\t\t\"aiven_elasticsearch\": resourceElasticsearch(),\n\t\t\t\"aiven_grafana\": resourceGrafana(),\n\t\t\t\"aiven_influxdb\": resourceInfluxDB(),\n\t\t\t\"aiven_redis\": resourceRedis(),\n\t\t},\n\n\t\tConfigureFunc: func(d *schema.ResourceData) (interface{}, error) {\n\t\t\t_ = cache.NewTopicCache()\n\n\t\t\treturn aiven.NewTokenClient(d.Get(\"api_token\").(string), \"terraform-provider-aiven/\")\n\t\t},\n\t}\n}", "func TestDontWaitForOtherProvidersIfWeGotError(t *testing.T) {\n\tstart := time.Now()\n\n\tappCustom := App{\n\t\tContentProvider: NewContentProviderService(\n\t\t\tmap[Provider]Client{\n\t\t\t\tProvider1: &ClientMock{\n\t\t\t\t\tGetContentFn: func(userIP string, count int) ([]*ContentItem, error) {\n\t\t\t\t\t\treturn []*ContentItem{}, errors.New(\"some error from provider 1\")\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tProvider2: &ClientMock{\n\t\t\t\t\tGetContentFn: func(userIP string, count int) ([]*ContentItem, error) {\n\t\t\t\t\t\treturn []*ContentItem{}, errors.New(\"some error from provider 2\")\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tProvider3: &ClientMock{\n\t\t\t\t\tGetContentFn: func(userIP string, count int) ([]*ContentItem, error) {\n\t\t\t\t\t\t// let's imitate some pending request to provider\n\t\t\t\t\t\ttime.Sleep(5 * time.Second)\n\t\t\t\t\t\treturn []*ContentItem{{\n\t\t\t\t\t\t\tSource: \"3\",\n\t\t\t\t\t\t}}, nil\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tDefaultConfig,\n\t\t\tWithTimeOut(500*time.Millisecond),\n\t\t),\n\t}\n\n\tcontent := runRequest(t, appCustom, SimpleContentRequest)\n\n\tif len(content) != 0 {\n\t\tt.Fatalf(\"Got %d items back, want 0\", len(content))\n\t}\n\n\texecTime := time.Since(start)\n\tif execTime > time.Second {\n\t\tt.Fatalf(\"test time should be less then 1 second, got: %s\", execTime)\n\t}\n}", "func (cf *Config) IsCloudProviderEnabled(cloudProviderName string) bool {\n\tcloudProviderFromConfig := cf.CloudProviderMetadata\n\n\tfor _, cloudName := range cloudProviderFromConfig {\n\t\tif strings.ToLower(cloudName) == strings.ToLower(cloudProviderName) {\n\t\t\tklog.V(5).Infof(\"cloudProviderMetadata is set to %s in agent configuration, trying endpoints for %s Cloud Provider\",\n\t\t\t\tcloudProviderFromConfig,\n\t\t\t\tcloudProviderName)\n\t\t\treturn true\n\t\t}\n\t}\n\n\tklog.V(5).Infof(\"cloudProviderMetadata is set to %s in agent configuration, skipping %s Cloud Provider\",\n\t\tcloudProviderFromConfig,\n\t\tcloudProviderName)\n\treturn false\n}", "func Provider() *schema.Provider {\n\tprovider := &schema.Provider{\n\t\tDataSourcesMap: map[string]*schema.Resource{\n\t\t\t\"ucodecov_settings\": dataSourceCodecovSettings(),\n\t\t},\n\t}\n\treturn provider\n}", "func validateProviderInfo(provider register.ProviderRegistrar) bool {\n\t// All of the fields must have a value in them.\n\tif provider.GetNodeID() == \"\" {\n\t\tlogging.Warn(\"Provider registration issue: NodeID not set\")\n\t\treturn false\n\t}\n\tif provider.GetAddress() == \"\" {\n\t\tlogging.Warn(\"Provider registration issue: Provider IP address or domain name not set\")\n\t\treturn false\n\t}\n\tif provider.GetNetworkInfoGateway() == \"\" {\n\t\tlogging.Warn(\"Provider registration issue: Port for Gateway to Provider communications not set\")\n\t\treturn false\n\t}\n\tif provider.GetNetworkInfoClient() == \"\" {\n\t\tlogging.Warn(\"Provider registration issue: Port for Client to Provider communications not set\")\n\t\treturn false\n\t}\n\tif provider.GetNetworkInfoAdmin() == \"\" {\n\t\tlogging.Warn(\"Provider registration issue: Port for Admin to Provider communications not set\")\n\t\treturn false\n\t}\n\tif provider.GetRegionCode() == \"\" {\n\t\tlogging.Warn(\"Provider registration issue: Region Code not set\")\n\t\treturn false\n\t}\n\t_, err := provider.GetRootSigningKey()\n\tif err != nil {\n\t\tlogging.Warn(\"Provider registration issue: Root Signing Public Key error: %+v\", err)\n\t\treturn false\n\t}\n\t_, err = provider.GetSigningKey()\n\tif err != nil {\n\t\tlogging.Warn(\"Provider registration issue: Retrieval Signing Key error: %+v\", err)\n\t\treturn false\n\t}\n\treturn true\n}", "func providerConfigure(ctx context.Context, d *schema.ResourceData) (interface{}, diag.Diagnostics) {\n\n\tvar diags diag.Diagnostics\n\tbearerToken := d.Get(\"bearer_token\").(string)\n\n\tvar host string\n\thVal, ok := d.GetOk(\"host\")\n\tif ok {\n\t\ttempHost := hVal.(string)\n\t\thost = tempHost\n\t}\n\n\tc := NewClient(host, bearerToken, &http.Client{})\n\treturn c, diags\n}", "func (a *FixedAllocateAction) queryEniFromCloud() (pbcommon.ErrCode, string) {\n\teni, err := a.cloudIf.QueryEni(a.req.EniID)\n\tif err != nil {\n\t\treturn pbcommon.ErrCode_ERROR_CLOUD_NETSERVICE_CLOUDAPI_QUERY_ENI_FAILED, err.Error()\n\t}\n\tif a.req.VpcID != eni.VpcID ||\n\t\ta.req.Region != eni.Region ||\n\t\ta.req.SubnetID != eni.SubnetID {\n\n\t\treturn pbcommon.ErrCode_ERROR_CLOUD_NETSERVICE_CLOUDAPI_ENI_INFO_NOTMATCH, \"eni info not match request info\"\n\t}\n\n\treturn pbcommon.ErrCode_ERROR_OK, \"\"\n}", "func Provider() terraform.ResourceProvider {\n\tprovider := &schema.Provider{\n\t\tSchema: map[string]*schema.Schema{\n\t\t\t\"auth_url\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"OS_AUTH_URL\", \"\"),\n\t\t\t\tDescription: descriptions[\"auth_url\"],\n\t\t\t},\n\n\t\t\t\"region\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tDescription: descriptions[\"region\"],\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"OS_REGION_NAME\", \"\"),\n\t\t\t},\n\n\t\t\t\"user_name\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"OS_USERNAME\", \"\"),\n\t\t\t\tDescription: descriptions[\"user_name\"],\n\t\t\t},\n\n\t\t\t\"user_id\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"OS_USER_ID\", \"\"),\n\t\t\t\tDescription: descriptions[\"user_name\"],\n\t\t\t},\n\n\t\t\t\"application_credential_id\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"OS_APPLICATION_CREDENTIAL_ID\", \"\"),\n\t\t\t\tDescription: descriptions[\"application_credential_id\"],\n\t\t\t},\n\n\t\t\t\"application_credential_name\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"OS_APPLICATION_CREDENTIAL_NAME\", \"\"),\n\t\t\t\tDescription: descriptions[\"application_credential_name\"],\n\t\t\t},\n\n\t\t\t\"application_credential_secret\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"OS_APPLICATION_CREDENTIAL_SECRET\", \"\"),\n\t\t\t\tDescription: descriptions[\"application_credential_secret\"],\n\t\t\t},\n\n\t\t\t\"tenant_id\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tDefaultFunc: schema.MultiEnvDefaultFunc([]string{\n\t\t\t\t\t\"OS_TENANT_ID\",\n\t\t\t\t\t\"OS_PROJECT_ID\",\n\t\t\t\t}, \"\"),\n\t\t\t\tDescription: descriptions[\"tenant_id\"],\n\t\t\t},\n\n\t\t\t\"tenant_name\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tDefaultFunc: schema.MultiEnvDefaultFunc([]string{\n\t\t\t\t\t\"OS_TENANT_NAME\",\n\t\t\t\t\t\"OS_PROJECT_NAME\",\n\t\t\t\t}, \"\"),\n\t\t\t\tDescription: descriptions[\"tenant_name\"],\n\t\t\t},\n\n\t\t\t\"password\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tSensitive: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"OS_PASSWORD\", \"\"),\n\t\t\t\tDescription: descriptions[\"password\"],\n\t\t\t},\n\n\t\t\t\"token\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tDefaultFunc: schema.MultiEnvDefaultFunc([]string{\n\t\t\t\t\t\"OS_TOKEN\",\n\t\t\t\t\t\"OS_AUTH_TOKEN\",\n\t\t\t\t}, \"\"),\n\t\t\t\tDescription: descriptions[\"token\"],\n\t\t\t},\n\n\t\t\t\"user_domain_name\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"OS_USER_DOMAIN_NAME\", \"\"),\n\t\t\t\tDescription: descriptions[\"user_domain_name\"],\n\t\t\t},\n\n\t\t\t\"user_domain_id\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"OS_USER_DOMAIN_ID\", \"\"),\n\t\t\t\tDescription: descriptions[\"user_domain_id\"],\n\t\t\t},\n\n\t\t\t\"project_domain_name\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"OS_PROJECT_DOMAIN_NAME\", \"\"),\n\t\t\t\tDescription: descriptions[\"project_domain_name\"],\n\t\t\t},\n\n\t\t\t\"project_domain_id\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"OS_PROJECT_DOMAIN_ID\", \"\"),\n\t\t\t\tDescription: descriptions[\"project_domain_id\"],\n\t\t\t},\n\n\t\t\t\"domain_id\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"OS_DOMAIN_ID\", \"\"),\n\t\t\t\tDescription: descriptions[\"domain_id\"],\n\t\t\t},\n\n\t\t\t\"domain_name\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"OS_DOMAIN_NAME\", \"\"),\n\t\t\t\tDescription: descriptions[\"domain_name\"],\n\t\t\t},\n\n\t\t\t\"default_domain\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"OS_DEFAULT_DOMAIN\", \"default\"),\n\t\t\t\tDescription: descriptions[\"default_domain\"],\n\t\t\t},\n\n\t\t\t\"insecure\": {\n\t\t\t\tType: schema.TypeBool,\n\t\t\t\tOptional: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"OS_INSECURE\", nil),\n\t\t\t\tDescription: descriptions[\"insecure\"],\n\t\t\t},\n\n\t\t\t\"endpoint_type\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"OS_ENDPOINT_TYPE\", \"\"),\n\t\t\t},\n\n\t\t\t\"cacert_file\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"OS_CACERT\", \"\"),\n\t\t\t\tDescription: descriptions[\"cacert_file\"],\n\t\t\t},\n\n\t\t\t\"cert\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"OS_CERT\", \"\"),\n\t\t\t\tDescription: descriptions[\"cert\"],\n\t\t\t},\n\n\t\t\t\"key\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"OS_KEY\", \"\"),\n\t\t\t\tDescription: descriptions[\"key\"],\n\t\t\t},\n\n\t\t\t\"swauth\": {\n\t\t\t\tType: schema.TypeBool,\n\t\t\t\tOptional: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"OS_SWAUTH\", false),\n\t\t\t\tDescription: descriptions[\"swauth\"],\n\t\t\t},\n\n\t\t\t\"use_octavia\": {\n\t\t\t\tType: schema.TypeBool,\n\t\t\t\tOptional: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"OS_USE_OCTAVIA\", false),\n\t\t\t\tDescription: descriptions[\"use_octavia\"],\n\t\t\t},\n\n\t\t\t\"delayed_auth\": {\n\t\t\t\tType: schema.TypeBool,\n\t\t\t\tOptional: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"OS_DELAYED_AUTH\", true),\n\t\t\t\tDescription: descriptions[\"delayed_auth\"],\n\t\t\t},\n\n\t\t\t\"allow_reauth\": {\n\t\t\t\tType: schema.TypeBool,\n\t\t\t\tOptional: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"OS_ALLOW_REAUTH\", true),\n\t\t\t\tDescription: descriptions[\"allow_reauth\"],\n\t\t\t},\n\n\t\t\t\"cloud\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"OS_CLOUD\", \"\"),\n\t\t\t\tDescription: descriptions[\"cloud\"],\n\t\t\t},\n\n\t\t\t\"max_retries\": {\n\t\t\t\tType: schema.TypeInt,\n\t\t\t\tOptional: true,\n\t\t\t\tDefault: 0,\n\t\t\t\tDescription: descriptions[\"max_retries\"],\n\t\t\t},\n\n\t\t\t\"endpoint_overrides\": {\n\t\t\t\tType: schema.TypeMap,\n\t\t\t\tOptional: true,\n\t\t\t\tDescription: descriptions[\"endpoint_overrides\"],\n\t\t\t},\n\n\t\t\t\"disable_no_cache_header\": {\n\t\t\t\tType: schema.TypeBool,\n\t\t\t\tOptional: true,\n\t\t\t\tDefault: false,\n\t\t\t\tDescription: descriptions[\"disable_no_cache_header\"],\n\t\t\t},\n\t\t},\n\n\t\tDataSourcesMap: map[string]*schema.Resource{\n\t\t\t\"ironic_introspection\": dataSourceIronicIntrospection(),\n\t\t},\n\t\t//DataSourcesMap: map[string]*schema.Resource{\n\t\t//\t\"openstack_blockstorage_availability_zones_v3\": dataSourceBlockStorageAvailabilityZonesV3(),\n\t\t//\t\"openstack_blockstorage_snapshot_v2\": dataSourceBlockStorageSnapshotV2(),\n\t\t//\t\"openstack_blockstorage_snapshot_v3\": dataSourceBlockStorageSnapshotV3(),\n\t\t//\t\"openstack_blockstorage_volume_v2\": dataSourceBlockStorageVolumeV2(),\n\t\t//\t\"openstack_blockstorage_volume_v3\": dataSourceBlockStorageVolumeV3(),\n\t\t//\t\"openstack_compute_availability_zones_v2\": dataSourceComputeAvailabilityZonesV2(),\n\t\t//\t\"openstack_compute_instance_v2\": dataSourceComputeInstanceV2(),\n\t\t//\t\"openstack_compute_flavor_v2\": dataSourceComputeFlavorV2(),\n\t\t//\t\"openstack_compute_keypair_v2\": dataSourceComputeKeypairV2(),\n\t\t//\t\"openstack_containerinfra_clustertemplate_v1\": dataSourceContainerInfraClusterTemplateV1(),\n\t\t//\t\"openstack_containerinfra_cluster_v1\": dataSourceContainerInfraCluster(),\n\t\t//\t\"openstack_dns_zone_v2\": dataSourceDNSZoneV2(),\n\t\t//\t\"openstack_fw_policy_v1\": dataSourceFWPolicyV1(),\n\t\t//\t\"openstack_identity_role_v3\": dataSourceIdentityRoleV3(),\n\t\t//\t\"openstack_identity_project_v3\": dataSourceIdentityProjectV3(),\n\t\t//\t\"openstack_identity_user_v3\": dataSourceIdentityUserV3(),\n\t\t//\t\"openstack_identity_auth_scope_v3\": dataSourceIdentityAuthScopeV3(),\n\t\t//\t\"openstack_identity_endpoint_v3\": dataSourceIdentityEndpointV3(),\n\t\t//\t\"openstack_identity_service_v3\": dataSourceIdentityServiceV3(),\n\t\t//\t\"openstack_identity_group_v3\": dataSourceIdentityGroupV3(),\n\t\t//\t\"openstack_images_image_v2\": dataSourceImagesImageV2(),\n\t\t//\t\"openstack_networking_addressscope_v2\": dataSourceNetworkingAddressScopeV2(),\n\t\t//\t\"openstack_networking_network_v2\": dataSourceNetworkingNetworkV2(),\n\t\t//\t\"openstack_networking_qos_bandwidth_limit_rule_v2\": dataSourceNetworkingQoSBandwidthLimitRuleV2(),\n\t\t//\t\"openstack_networking_qos_dscp_marking_rule_v2\": dataSourceNetworkingQoSDSCPMarkingRuleV2(),\n\t\t//\t\"openstack_networking_qos_minimum_bandwidth_rule_v2\": dataSourceNetworkingQoSMinimumBandwidthRuleV2(),\n\t\t//\t\"openstack_networking_qos_policy_v2\": dataSourceNetworkingQoSPolicyV2(),\n\t\t//\t\"openstack_networking_subnet_v2\": dataSourceNetworkingSubnetV2(),\n\t\t//\t\"openstack_networking_secgroup_v2\": dataSourceNetworkingSecGroupV2(),\n\t\t//\t\"openstack_networking_subnetpool_v2\": dataSourceNetworkingSubnetPoolV2(),\n\t\t//\t\"openstack_networking_floatingip_v2\": dataSourceNetworkingFloatingIPV2(),\n\t\t//\t\"openstack_networking_router_v2\": dataSourceNetworkingRouterV2(),\n\t\t//\t\"openstack_networking_port_v2\": dataSourceNetworkingPortV2(),\n\t\t//\t\"openstack_networking_port_ids_v2\": dataSourceNetworkingPortIDsV2(),\n\t\t//\t\"openstack_networking_trunk_v2\": dataSourceNetworkingTrunkV2(),\n\t\t//\t\"openstack_sharedfilesystem_availability_zones_v2\": dataSourceSharedFilesystemAvailabilityZonesV2(),\n\t\t//\t\"openstack_sharedfilesystem_sharenetwork_v2\": dataSourceSharedFilesystemShareNetworkV2(),\n\t\t//\t\"openstack_sharedfilesystem_share_v2\": dataSourceSharedFilesystemShareV2(),\n\t\t//\t\"openstack_sharedfilesystem_snapshot_v2\": dataSourceSharedFilesystemSnapshotV2(),\n\t\t//\t\"openstack_keymanager_secret_v1\": dataSourceKeyManagerSecretV1(),\n\t\t//\t\"openstack_keymanager_container_v1\": dataSourceKeyManagerContainerV1(),\n\t\t//},\n\n\t\tResourcesMap: map[string]*schema.Resource{\n\t\t\t\"ironic_node_v1\": resourceNodeV1(),\n\t\t\t\"ironic_port_v1\": resourcePortV1(),\n\t\t\t\"ironic_allocation_v1\": resourceAllocationV1(),\n\t\t\t\"ironic_deployment\": resourceDeployment(),\n\t\t},\n\t\t//ResourcesMap: map[string]*schema.Resource{\n\t\t//\t\"openstack_blockstorage_quotaset_v2\": resourceBlockStorageQuotasetV2(),\n\t\t//\t\"openstack_blockstorage_quotaset_v3\": resourceBlockStorageQuotasetV3(),\n\t\t//\t\"openstack_blockstorage_volume_v1\": resourceBlockStorageVolumeV1(),\n\t\t//\t\"openstack_blockstorage_volume_v2\": resourceBlockStorageVolumeV2(),\n\t\t//\t\"openstack_blockstorage_volume_v3\": resourceBlockStorageVolumeV3(),\n\t\t//\t\"openstack_blockstorage_volume_attach_v2\": resourceBlockStorageVolumeAttachV2(),\n\t\t//\t\"openstack_blockstorage_volume_attach_v3\": resourceBlockStorageVolumeAttachV3(),\n\t\t//\t\"openstack_compute_flavor_v2\": resourceComputeFlavorV2(),\n\t\t//\t\"openstack_compute_flavor_access_v2\": resourceComputeFlavorAccessV2(),\n\t\t//\t\"openstack_compute_instance_v2\": resourceComputeInstanceV2(),\n\t\t//\t\"openstack_compute_interface_attach_v2\": resourceComputeInterfaceAttachV2(),\n\t\t//\t\"openstack_compute_keypair_v2\": resourceComputeKeypairV2(),\n\t\t//\t\"openstack_compute_secgroup_v2\": resourceComputeSecGroupV2(),\n\t\t//\t\"openstack_compute_servergroup_v2\": resourceComputeServerGroupV2(),\n\t\t//\t\"openstack_compute_quotaset_v2\": resourceComputeQuotasetV2(),\n\t\t//\t\"openstack_compute_floatingip_v2\": resourceComputeFloatingIPV2(),\n\t\t//\t\"openstack_compute_floatingip_associate_v2\": resourceComputeFloatingIPAssociateV2(),\n\t\t//\t\"openstack_compute_volume_attach_v2\": resourceComputeVolumeAttachV2(),\n\t\t//\t\"openstack_containerinfra_clustertemplate_v1\": resourceContainerInfraClusterTemplateV1(),\n\t\t//\t\"openstack_containerinfra_cluster_v1\": resourceContainerInfraClusterV1(),\n\t\t//\t\"openstack_db_instance_v1\": resourceDatabaseInstanceV1(),\n\t\t//\t\"openstack_db_user_v1\": resourceDatabaseUserV1(),\n\t\t//\t\"openstack_db_configuration_v1\": resourceDatabaseConfigurationV1(),\n\t\t//\t\"openstack_db_database_v1\": resourceDatabaseDatabaseV1(),\n\t\t//\t\"openstack_dns_recordset_v2\": resourceDNSRecordSetV2(),\n\t\t//\t\"openstack_dns_zone_v2\": resourceDNSZoneV2(),\n\t\t//\t\"openstack_fw_firewall_v1\": resourceFWFirewallV1(),\n\t\t//\t\"openstack_fw_policy_v1\": resourceFWPolicyV1(),\n\t\t//\t\"openstack_fw_rule_v1\": resourceFWRuleV1(),\n\t\t//\t\"openstack_identity_endpoint_v3\": resourceIdentityEndpointV3(),\n\t\t//\t\"openstack_identity_project_v3\": resourceIdentityProjectV3(),\n\t\t//\t\"openstack_identity_role_v3\": resourceIdentityRoleV3(),\n\t\t//\t\"openstack_identity_role_assignment_v3\": resourceIdentityRoleAssignmentV3(),\n\t\t//\t\"openstack_identity_service_v3\": resourceIdentityServiceV3(),\n\t\t//\t\"openstack_identity_user_v3\": resourceIdentityUserV3(),\n\t\t//\t\"openstack_identity_application_credential_v3\": resourceIdentityApplicationCredentialV3(),\n\t\t//\t\"openstack_images_image_v2\": resourceImagesImageV2(),\n\t\t//\t\"openstack_images_image_access_v2\": resourceImagesImageAccessV2(),\n\t\t//\t\"openstack_images_image_access_accept_v2\": resourceImagesImageAccessAcceptV2(),\n\t\t//\t\"openstack_lb_member_v1\": resourceLBMemberV1(),\n\t\t//\t\"openstack_lb_monitor_v1\": resourceLBMonitorV1(),\n\t\t//\t\"openstack_lb_pool_v1\": resourceLBPoolV1(),\n\t\t//\t\"openstack_lb_vip_v1\": resourceLBVipV1(),\n\t\t//\t\"openstack_lb_loadbalancer_v2\": resourceLoadBalancerV2(),\n\t\t//\t\"openstack_lb_listener_v2\": resourceListenerV2(),\n\t\t//\t\"openstack_lb_pool_v2\": resourcePoolV2(),\n\t\t//\t\"openstack_lb_member_v2\": resourceMemberV2(),\n\t\t//\t\"openstack_lb_members_v2\": resourceMembersV2(),\n\t\t//\t\"openstack_lb_monitor_v2\": resourceMonitorV2(),\n\t\t//\t\"openstack_lb_l7policy_v2\": resourceL7PolicyV2(),\n\t\t//\t\"openstack_lb_l7rule_v2\": resourceL7RuleV2(),\n\t\t//\t\"openstack_networking_floatingip_v2\": resourceNetworkingFloatingIPV2(),\n\t\t//\t\"openstack_networking_floatingip_associate_v2\": resourceNetworkingFloatingIPAssociateV2(),\n\t\t//\t\"openstack_networking_network_v2\": resourceNetworkingNetworkV2(),\n\t\t//\t\"openstack_networking_port_v2\": resourceNetworkingPortV2(),\n\t\t//\t\"openstack_networking_rbac_policy_v2\": resourceNetworkingRBACPolicyV2(),\n\t\t//\t\"openstack_networking_port_secgroup_associate_v2\": resourceNetworkingPortSecGroupAssociateV2(),\n\t\t//\t\"openstack_networking_qos_bandwidth_limit_rule_v2\": resourceNetworkingQoSBandwidthLimitRuleV2(),\n\t\t//\t\"openstack_networking_qos_dscp_marking_rule_v2\": resourceNetworkingQoSDSCPMarkingRuleV2(),\n\t\t//\t\"openstack_networking_qos_minimum_bandwidth_rule_v2\": resourceNetworkingQoSMinimumBandwidthRuleV2(),\n\t\t//\t\"openstack_networking_qos_policy_v2\": resourceNetworkingQoSPolicyV2(),\n\t\t//\t\"openstack_networking_quota_v2\": resourceNetworkingQuotaV2(),\n\t\t//\t\"openstack_networking_router_v2\": resourceNetworkingRouterV2(),\n\t\t//\t\"openstack_networking_router_interface_v2\": resourceNetworkingRouterInterfaceV2(),\n\t\t//\t\"openstack_networking_router_route_v2\": resourceNetworkingRouterRouteV2(),\n\t\t//\t\"openstack_networking_secgroup_v2\": resourceNetworkingSecGroupV2(),\n\t\t//\t\"openstack_networking_secgroup_rule_v2\": resourceNetworkingSecGroupRuleV2(),\n\t\t//\t\"openstack_networking_subnet_v2\": resourceNetworkingSubnetV2(),\n\t\t//\t\"openstack_networking_subnet_route_v2\": resourceNetworkingSubnetRouteV2(),\n\t\t//\t\"openstack_networking_subnetpool_v2\": resourceNetworkingSubnetPoolV2(),\n\t\t//\t\"openstack_networking_addressscope_v2\": resourceNetworkingAddressScopeV2(),\n\t\t//\t\"openstack_networking_trunk_v2\": resourceNetworkingTrunkV2(),\n\t\t//\t\"openstack_objectstorage_container_v1\": resourceObjectStorageContainerV1(),\n\t\t//\t\"openstack_objectstorage_object_v1\": resourceObjectStorageObjectV1(),\n\t\t//\t\"openstack_objectstorage_tempurl_v1\": resourceObjectstorageTempurlV1(),\n\t\t//\t\"openstack_orchestration_stack_v1\": resourceOrchestrationStackV1(),\n\t\t//\t\"openstack_vpnaas_ipsec_policy_v2\": resourceIPSecPolicyV2(),\n\t\t//\t\"openstack_vpnaas_service_v2\": resourceServiceV2(),\n\t\t//\t\"openstack_vpnaas_ike_policy_v2\": resourceIKEPolicyV2(),\n\t\t//\t\"openstack_vpnaas_endpoint_group_v2\": resourceEndpointGroupV2(),\n\t\t//\t\"openstack_vpnaas_site_connection_v2\": resourceSiteConnectionV2(),\n\t\t//\t\"openstack_sharedfilesystem_securityservice_v2\": resourceSharedFilesystemSecurityServiceV2(),\n\t\t//\t\"openstack_sharedfilesystem_sharenetwork_v2\": resourceSharedFilesystemShareNetworkV2(),\n\t\t//\t\"openstack_sharedfilesystem_share_v2\": resourceSharedFilesystemShareV2(),\n\t\t//\t\"openstack_sharedfilesystem_share_access_v2\": resourceSharedFilesystemShareAccessV2(),\n\t\t//\t\"openstack_keymanager_secret_v1\": resourceKeyManagerSecretV1(),\n\t\t//\t\"openstack_keymanager_container_v1\": resourceKeyManagerContainerV1(),\n\t\t//\t\"openstack_keymanager_order_v1\": resourceKeyManagerOrderV1(),\n\t\t//},\n\t}\n\n\tprovider.ConfigureFunc = func(d *schema.ResourceData) (interface{}, error) {\n\t\tterraformVersion := provider.TerraformVersion\n\t\tif terraformVersion == \"\" {\n\t\t\t// Terraform 0.12 introduced this field to the protocol\n\t\t\t// We can therefore assume that if it's missing it's 0.10 or 0.11\n\t\t\tterraformVersion = \"0.11+compatible\"\n\t\t}\n\t\treturn configureProvider(d, terraformVersion)\n\t}\n\n\treturn provider\n}", "func (o *SuperKeyRequest) GetProviderOk() (*string, bool) {\n\tif o == nil || o.Provider == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Provider, true\n}", "func (mr *MockCandidatePropertyGetterMockRecorder) Cloudprovider() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Cloudprovider\", reflect.TypeOf((*MockCandidatePropertyGetter)(nil).Cloudprovider))\n}", "func (v *Provider) Diagnose() {\n\trr, err := v.rr()\n\tif err != nil {\n\t\treturn\n\t}\n\n\ttw := tabwriter.NewWriter(os.Stdout, 0, 0, 1, ' ', 0)\n\n\tsort.Slice(rr.OperationList.ServiceInfo, func(i, j int) bool {\n\t\treturn rr.OperationList.ServiceInfo[i].ServiceId < rr.OperationList.ServiceInfo[j].ServiceId\n\t})\n\n\tfor _, si := range rr.OperationList.ServiceInfo {\n\t\tif si.InvocationUrl.Content != \"\" {\n\t\t\tfmt.Fprintf(tw, \"%s:\\t%s\\n\", si.ServiceId, si.InvocationUrl.Content)\n\t\t}\n\t}\n\n\t// list remaining service\n\tservices := lo.FilterMap(rr.OperationList.ServiceInfo, func(si ServiceInfo, _ int) (string, bool) {\n\t\treturn si.ServiceId, si.InvocationUrl.Content == \"\"\n\t})\n\n\tfmt.Fprintf(tw, \"without uri:\\t%s\\n\", strings.Join(services, \",\"))\n\n\ttw.Flush()\n}", "func infra(b *specs.TasksCfgBuilder, name string) string {\n\tb.MustAddTask(name, &specs.TaskSpec{\n\t\tCipdPackages: []*specs.CipdPackage{b.MustGetCipdPackageFromAsset(\"go\")},\n\t\tDimensions: []string{\n\t\t\t\"pool:Skia\",\n\t\t\tfmt.Sprintf(\"os:%s\", DEFAULT_OS_LINUX),\n\t\t\t\"gpu:none\",\n\t\t},\n\t\tExtraArgs: []string{\n\t\t\t\"--workdir\", \"../../..\", \"swarm_infra\",\n\t\t\tfmt.Sprintf(\"repository=%s\", specs.PLACEHOLDER_REPO),\n\t\t\tfmt.Sprintf(\"buildername=%s\", name),\n\t\t\t\"mastername=fake-master\",\n\t\t\t\"buildnumber=2\",\n\t\t\t\"slavename=fake-buildslave\",\n\t\t\t\"nobuildbot=True\",\n\t\t\tfmt.Sprintf(\"swarm_out_dir=%s\", specs.PLACEHOLDER_ISOLATED_OUTDIR),\n\t\t\tfmt.Sprintf(\"revision=%s\", specs.PLACEHOLDER_REVISION),\n\t\t\tfmt.Sprintf(\"patch_storage=%s\", specs.PLACEHOLDER_PATCH_STORAGE),\n\t\t\tfmt.Sprintf(\"patch_issue=%s\", specs.PLACEHOLDER_ISSUE),\n\t\t\tfmt.Sprintf(\"patch_set=%s\", specs.PLACEHOLDER_PATCHSET),\n\t\t},\n\t\tIsolate: \"swarm_recipe.isolate\",\n\t\tPriority: 0.8,\n\t})\n\treturn name\n}", "func TestGetCloudProvider(t *testing.T) {\n\tfakeCredFile := \"fake-cred-file.json\"\n\tfakeKubeConfig := \"fake-kube-config\"\n\temptyKubeConfig := \"empty-kube-config\"\n\tfakeContent := `\napiVersion: v1\nclusters:\n- cluster:\n server: https://localhost:8080\n name: foo-cluster\ncontexts:\n- context:\n cluster: foo-cluster\n user: foo-user\n namespace: bar\n name: foo-context\ncurrent-context: foo-context\nkind: Config\nusers:\n- name: foo-user\n user:\n exec:\n apiVersion: client.authentication.k8s.io/v1alpha1\n args:\n - arg-1\n - arg-2\n command: foo-command\n`\n\n\terr := createTestFile(emptyKubeConfig)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tdefer func() {\n\t\tif err := os.Remove(emptyKubeConfig); err != nil {\n\t\t\tt.Error(err)\n\t\t}\n\t}()\n\n\ttests := []struct {\n\t\tdesc string\n\t\tcreateFakeCredFile bool\n\t\tcreateFakeKubeConfig bool\n\t\tkubeconfig string\n\t\tnodeID string\n\t\tuserAgent string\n\t\tallowEmptyCloudConfig bool\n\t\texpectedErr error\n\t}{\n\t\t{\n\t\t\tdesc: \"out of cluster, no kubeconfig, no credential file\",\n\t\t\tkubeconfig: \"\",\n\t\t\tnodeID: \"\",\n\t\t\tallowEmptyCloudConfig: true,\n\t\t\texpectedErr: nil,\n\t\t},\n\t\t{\n\t\t\tdesc: \"[failure][disallowEmptyCloudConfig] out of cluster, no kubeconfig, no credential file\",\n\t\t\tkubeconfig: \"\",\n\t\t\tnodeID: \"\",\n\t\t\tallowEmptyCloudConfig: false,\n\t\t\texpectedErr: nil,\n\t\t},\n\t\t{\n\t\t\tdesc: \"[failure] out of cluster & in cluster, specify a non-exist kubeconfig, no credential file\",\n\t\t\tkubeconfig: \"/tmp/non-exist.json\",\n\t\t\tnodeID: \"\",\n\t\t\tallowEmptyCloudConfig: true,\n\t\t\texpectedErr: nil,\n\t\t},\n\t\t{\n\t\t\tdesc: \"[failure] out of cluster & in cluster, specify a empty kubeconfig, no credential file\",\n\t\t\tkubeconfig: emptyKubeConfig,\n\t\t\tnodeID: \"\",\n\t\t\tallowEmptyCloudConfig: true,\n\t\t\texpectedErr: fmt.Errorf(\"failed to get KubeClient: invalid configuration: no configuration has been provided, try setting KUBERNETES_MASTER environment variable\"),\n\t\t},\n\t\t{\n\t\t\tdesc: \"[failure] out of cluster & in cluster, specify a fake kubeconfig, no credential file\",\n\t\t\tcreateFakeKubeConfig: true,\n\t\t\tkubeconfig: fakeKubeConfig,\n\t\t\tnodeID: \"\",\n\t\t\tallowEmptyCloudConfig: true,\n\t\t\texpectedErr: nil,\n\t\t},\n\t\t{\n\t\t\tdesc: \"[success] out of cluster & in cluster, no kubeconfig, a fake credential file\",\n\t\t\tcreateFakeCredFile: true,\n\t\t\tkubeconfig: \"\",\n\t\t\tnodeID: \"\",\n\t\t\tuserAgent: \"useragent\",\n\t\t\tallowEmptyCloudConfig: true,\n\t\t\texpectedErr: nil,\n\t\t},\n\t}\n\n\tfor _, test := range tests {\n\t\tif test.createFakeKubeConfig {\n\t\t\tif err := createTestFile(fakeKubeConfig); err != nil {\n\t\t\t\tt.Error(err)\n\t\t\t}\n\t\t\tdefer func() {\n\t\t\t\tif err := os.Remove(fakeKubeConfig); err != nil {\n\t\t\t\t\tt.Error(err)\n\t\t\t\t}\n\t\t\t}()\n\n\t\t\tif err := os.WriteFile(fakeKubeConfig, []byte(fakeContent), 0666); err != nil {\n\t\t\t\tt.Error(err)\n\t\t\t}\n\t\t}\n\t\tif test.createFakeCredFile {\n\t\t\tif err := createTestFile(fakeCredFile); err != nil {\n\t\t\t\tt.Error(err)\n\t\t\t}\n\t\t\tdefer func() {\n\t\t\t\tif err := os.Remove(fakeCredFile); err != nil {\n\t\t\t\t\tt.Error(err)\n\t\t\t\t}\n\t\t\t}()\n\n\t\t\toriginalCredFile, ok := os.LookupEnv(DefaultAzureCredentialFileEnv)\n\t\t\tif ok {\n\t\t\t\tdefer os.Setenv(DefaultAzureCredentialFileEnv, originalCredFile)\n\t\t\t} else {\n\t\t\t\tdefer os.Unsetenv(DefaultAzureCredentialFileEnv)\n\t\t\t}\n\t\t\tos.Setenv(DefaultAzureCredentialFileEnv, fakeCredFile)\n\t\t}\n\t\tcloud, err := getCloudProvider(test.kubeconfig, test.nodeID, \"\", \"\", test.userAgent, test.allowEmptyCloudConfig, 25.0, 50)\n\t\tif !reflect.DeepEqual(err, test.expectedErr) && test.expectedErr != nil && !strings.Contains(err.Error(), test.expectedErr.Error()) {\n\t\t\tt.Errorf(\"desc: %s,\\n input: %q, GetCloudProvider err: %v, expectedErr: %v\", test.desc, test.kubeconfig, err, test.expectedErr)\n\t\t}\n\t\tif cloud == nil {\n\t\t\tt.Errorf(\"return value of getCloudProvider should not be nil even there is error\")\n\t\t} else {\n\t\t\tassert.Equal(t, cloud.Environment.StorageEndpointSuffix, storage.DefaultBaseURL)\n\t\t\tassert.Equal(t, cloud.UserAgent, test.userAgent)\n\t\t}\n\t}\n}", "func TestEndpointCase84(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"us-iso-west-1\"),\n\t\tUseFIPS: ptr.Bool(true),\n\t\tUseDualStack: ptr.Bool(true),\n\t\tConsumerARN: ptr.String(\"arn:aws-iso:kinesis:us-iso-west-1:123456789012:stream/testStream/consumer/test-consumer:1525898737\"),\n\t\tOperationType: ptr.String(\"control\"),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err == nil {\n\t\tt.Fatalf(\"expect error, got none\")\n\t}\n\tif e, a := \"FIPS and DualStack are enabled, but this partition does not support one or both\", err.Error(); !strings.Contains(a, e) {\n\t\tt.Errorf(\"expect %v error in %v\", e, a)\n\t}\n}", "func Provider() terraform.ResourceProvider {\n\tvar p *schema.Provider\n\tp = &schema.Provider{\n\t\tSchema: map[string]*schema.Schema{\n\t\t\t\"subscription_id\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"ARM_SUBSCRIPTION_ID\", \"\"),\n\t\t\t},\n\n\t\t\t\"client_id\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"ARM_CLIENT_ID\", \"\"),\n\t\t\t},\n\n\t\t\t\"client_secret\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"ARM_CLIENT_SECRET\", \"\"),\n\t\t\t},\n\n\t\t\t\"tenant_id\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"ARM_TENANT_ID\", \"\"),\n\t\t\t},\n\n\t\t\t\"environment\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"ARM_ENVIRONMENT\", \"public\"),\n\t\t\t},\n\n\t\t\t\"skip_provider_registration\": {\n\t\t\t\tType: schema.TypeBool,\n\t\t\t\tOptional: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"ARM_SKIP_PROVIDER_REGISTRATION\", false),\n\t\t\t},\n\t\t},\n\n\t\tDataSourcesMap: map[string]*schema.Resource{\n\t\t\t\"azurerm_client_config\": dataSourceArmClientConfig(),\n\t\t},\n\n\t\tResourcesMap: map[string]*schema.Resource{\n\t\t\t// These resources use the Azure ARM SDK\n\t\t\t\"azurerm_availability_set\": resourceArmAvailabilitySet(),\n\t\t\t\"azurerm_cdn_endpoint\": resourceArmCdnEndpoint(),\n\t\t\t\"azurerm_cdn_profile\": resourceArmCdnProfile(),\n\t\t\t\"azurerm_container_registry\": resourceArmContainerRegistry(),\n\t\t\t\"azurerm_container_service\": resourceArmContainerService(),\n\n\t\t\t\"azurerm_eventhub\": resourceArmEventHub(),\n\t\t\t\"azurerm_eventhub_authorization_rule\": resourceArmEventHubAuthorizationRule(),\n\t\t\t\"azurerm_eventhub_consumer_group\": resourceArmEventHubConsumerGroup(),\n\t\t\t\"azurerm_eventhub_namespace\": resourceArmEventHubNamespace(),\n\n\t\t\t\"azurerm_lb\": resourceArmLoadBalancer(),\n\t\t\t\"azurerm_lb_backend_address_pool\": resourceArmLoadBalancerBackendAddressPool(),\n\t\t\t\"azurerm_lb_nat_rule\": resourceArmLoadBalancerNatRule(),\n\t\t\t\"azurerm_lb_nat_pool\": resourceArmLoadBalancerNatPool(),\n\t\t\t\"azurerm_lb_probe\": resourceArmLoadBalancerProbe(),\n\t\t\t\"azurerm_lb_rule\": resourceArmLoadBalancerRule(),\n\n\t\t\t\"azurerm_managed_disk\": resourceArmManagedDisk(),\n\n\t\t\t\"azurerm_key_vault\": resourceArmKeyVault(),\n\t\t\t\"azurerm_local_network_gateway\": resourceArmLocalNetworkGateway(),\n\t\t\t\"azurerm_network_interface\": resourceArmNetworkInterface(),\n\t\t\t\"azurerm_network_security_group\": resourceArmNetworkSecurityGroup(),\n\t\t\t\"azurerm_network_security_rule\": resourceArmNetworkSecurityRule(),\n\t\t\t\"azurerm_public_ip\": resourceArmPublicIp(),\n\t\t\t\"azurerm_redis_cache\": resourceArmRedisCache(),\n\t\t\t\"azurerm_route\": resourceArmRoute(),\n\t\t\t\"azurerm_route_table\": resourceArmRouteTable(),\n\t\t\t\"azurerm_servicebus_namespace\": resourceArmServiceBusNamespace(),\n\t\t\t\"azurerm_servicebus_subscription\": resourceArmServiceBusSubscription(),\n\t\t\t\"azurerm_servicebus_topic\": resourceArmServiceBusTopic(),\n\t\t\t\"azurerm_storage_account\": resourceArmStorageAccount(),\n\t\t\t\"azurerm_storage_blob\": resourceArmStorageBlob(),\n\t\t\t\"azurerm_storage_container\": resourceArmStorageContainer(),\n\t\t\t\"azurerm_storage_share\": resourceArmStorageShare(),\n\t\t\t\"azurerm_storage_queue\": resourceArmStorageQueue(),\n\t\t\t\"azurerm_storage_table\": resourceArmStorageTable(),\n\t\t\t\"azurerm_subnet\": resourceArmSubnet(),\n\t\t\t\"azurerm_template_deployment\": resourceArmTemplateDeployment(),\n\t\t\t\"azurerm_traffic_manager_endpoint\": resourceArmTrafficManagerEndpoint(),\n\t\t\t\"azurerm_traffic_manager_profile\": resourceArmTrafficManagerProfile(),\n\t\t\t\"azurerm_virtual_machine_extension\": resourceArmVirtualMachineExtensions(),\n\t\t\t\"azurerm_virtual_machine\": resourceArmVirtualMachine(),\n\t\t\t\"azurerm_virtual_machine_scale_set\": resourceArmVirtualMachineScaleSet(),\n\t\t\t\"azurerm_virtual_network\": resourceArmVirtualNetwork(),\n\t\t\t\"azurerm_virtual_network_peering\": resourceArmVirtualNetworkPeering(),\n\n\t\t\t// These resources use the Riviera SDK\n\t\t\t\"azurerm_dns_a_record\": resourceArmDnsARecord(),\n\t\t\t\"azurerm_dns_aaaa_record\": resourceArmDnsAAAARecord(),\n\t\t\t\"azurerm_dns_cname_record\": resourceArmDnsCNameRecord(),\n\t\t\t\"azurerm_dns_mx_record\": resourceArmDnsMxRecord(),\n\t\t\t\"azurerm_dns_ns_record\": resourceArmDnsNsRecord(),\n\t\t\t\"azurerm_dns_srv_record\": resourceArmDnsSrvRecord(),\n\t\t\t\"azurerm_dns_txt_record\": resourceArmDnsTxtRecord(),\n\t\t\t\"azurerm_dns_zone\": resourceArmDnsZone(),\n\t\t\t\"azurerm_resource_group\": resourceArmResourceGroup(),\n\t\t\t\"azurerm_search_service\": resourceArmSearchService(),\n\t\t\t\"azurerm_sql_database\": resourceArmSqlDatabase(),\n\t\t\t\"azurerm_sql_firewall_rule\": resourceArmSqlFirewallRule(),\n\t\t\t\"azurerm_sql_server\": resourceArmSqlServer(),\n\t\t},\n\t}\n\n\tp.ConfigureFunc = providerConfigure(p)\n\n\treturn p\n}", "func ForProvider(p providerconfigtypes.CloudProvider, cvr *providerconfig.ConfigVarResolver) (cloudprovidertypes.Provider, error) {\n\tif p, found := providers[p]; found {\n\t\treturn NewValidationCacheWrappingCloudProvider(p(cvr)), nil\n\t}\n\tif p, found := communityProviders[p]; found {\n\t\treturn NewValidationCacheWrappingCloudProvider(p(cvr)), nil\n\t}\n\treturn nil, ErrProviderNotFound\n}", "func (scnb *SupplyChainNodeBuilder) Provider(provider proto.EntityDTO_EntityType, pType proto.Provider_ProviderType) *SupplyChainNodeBuilder {\n\tif scnb.err != nil {\n\t\treturn scnb\n\t}\n\tif hasTemplate := scnb.requireEntityTemplate(); !hasTemplate {\n\t\tscnb.err = fmt.Errorf(\"EntityTemplate is not found. Must set before call Provider().\")\n\t\treturn scnb\n\t}\n\n\tif pType == proto.Provider_LAYERED_OVER {\n\t\tmaxCardinality := int32(math.MaxInt32)\n\t\tminCardinality := int32(0)\n\t\tscnb.currentProvider = &proto.Provider{\n\t\t\tTemplateClass: &provider,\n\t\t\tProviderType: &pType,\n\t\t\tCardinalityMax: &maxCardinality,\n\t\t\tCardinalityMin: &minCardinality,\n\t\t}\n\t} else {\n\t\thostCardinality := int32(1)\n\t\tscnb.currentProvider = &proto.Provider{\n\t\t\tTemplateClass: &provider,\n\t\t\tProviderType: &pType,\n\t\t\tCardinalityMax: &hostCardinality,\n\t\t\tCardinalityMin: &hostCardinality,\n\t\t}\n\t}\n\n\treturn scnb\n}", "func ProviderSpec() *ProviderSpecApplyConfiguration {\n\treturn &ProviderSpecApplyConfiguration{}\n}", "func (fw IPtables) Provider() string {\n\treturn \"iptables\"\n}", "func CapaProviderFn(thread *starlark.Thread, _ *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {\n\n\tvar (\n\t\tworkloadCluster, namespace string\n\t\tnames, labels *starlark.List\n\t\tsshConfig, mgmtKubeConfig *starlarkstruct.Struct\n\t)\n\n\terr := starlark.UnpackArgs(\"capa_provider\", args, kwargs,\n\t\t\"ssh_config\", &sshConfig,\n\t\t\"mgmt_kube_config\", &mgmtKubeConfig,\n\t\t\"workload_cluster?\", &workloadCluster,\n\t\t\"namespace?\", &namespace,\n\t\t\"labels?\", &labels,\n\t\t\"nodes?\", &names)\n\tif err != nil {\n\t\treturn starlark.None, errors.Wrap(err, \"failed to unpack input arguments\")\n\t}\n\n\tctx, ok := thread.Local(identifiers.scriptCtx).(context.Context)\n\tif !ok || ctx == nil {\n\t\treturn starlark.None, fmt.Errorf(\"script context not found\")\n\t}\n\n\tif sshConfig == nil || mgmtKubeConfig == nil {\n\t\treturn starlark.None, errors.New(\"capa_provider requires the name of the management cluster, the ssh configuration and the management cluster kubeconfig\")\n\t}\n\n\tif mgmtKubeConfig == nil {\n\t\tmgmtKubeConfig = thread.Local(identifiers.kubeCfg).(*starlarkstruct.Struct)\n\t}\n\tmgmtKubeConfigPath, err := getKubeConfigPathFromStruct(mgmtKubeConfig)\n\tif err != nil {\n\t\treturn starlark.None, errors.Wrap(err, \"failed to extract management kubeconfig\")\n\t}\n\n\t// if workload cluster is not supplied, then the resources for the management cluster\n\t// should be enumerated\n\tclusterName := workloadCluster\n\tif clusterName == \"\" {\n\t\tconfig, err := k8s.LoadKubeCfg(mgmtKubeConfigPath)\n\t\tif err != nil {\n\t\t\treturn starlark.None, errors.Wrap(err, \"failed to load kube config\")\n\t\t}\n\t\tclusterName, err = config.GetClusterName()\n\t\tif err != nil {\n\t\t\treturn starlark.None, errors.Wrap(err, \"cannot find cluster with name \"+workloadCluster)\n\t\t}\n\t}\n\n\tbastionIpAddr, err := k8s.FetchBastionIpAddress(clusterName, namespace, mgmtKubeConfigPath)\n\tif err != nil {\n\t\treturn starlark.None, errors.Wrap(err, \"could not fetch jump host addresses\")\n\t}\n\n\tproviderConfigPath, err := provider.KubeConfig(mgmtKubeConfigPath, clusterName, namespace)\n\tif err != nil {\n\t\treturn starlark.None, err\n\t}\n\n\tnodeAddresses, err := k8s.GetNodeAddresses(ctx, providerConfigPath, toSlice(names), toSlice(labels))\n\tif err != nil {\n\t\treturn starlark.None, errors.Wrap(err, \"could not fetch host addresses\")\n\t}\n\n\t// dictionary for capa provider struct\n\tcapaProviderDict := starlark.StringDict{\n\t\t\"kind\": starlark.String(identifiers.capaProvider),\n\t\t\"transport\": starlark.String(\"ssh\"),\n\t\t\"kube_config\": starlark.String(providerConfigPath),\n\t}\n\n\t// add node info to dictionary\n\tvar nodeIps []starlark.Value\n\tfor _, node := range nodeAddresses {\n\t\tnodeIps = append(nodeIps, starlark.String(node))\n\t}\n\tcapaProviderDict[\"hosts\"] = starlark.NewList(nodeIps)\n\n\tsshConfigDict := starlark.StringDict{}\n\tsshConfig.ToStringDict(sshConfigDict)\n\n\t// modify ssh config jump credentials, if not specified\n\tif _, err := sshConfig.Attr(\"jump_host\"); err != nil {\n\t\tsshConfigDict[\"jump_host\"] = starlark.String(bastionIpAddr)\n\t}\n\tif _, err := sshConfig.Attr(\"jump_user\"); err != nil {\n\t\tsshConfigDict[\"jump_user\"] = starlark.String(\"ubuntu\")\n\t}\n\tcapaProviderDict[identifiers.sshCfg] = starlarkstruct.FromStringDict(starlark.String(identifiers.sshCfg), sshConfigDict)\n\n\treturn starlarkstruct.FromStringDict(starlark.String(identifiers.capaProvider), capaProviderDict), nil\n}", "func WithInfraProvider(infraProvider fab.InfraProvider) SDKContextParams {\n\treturn func(ctx *Provider) {\n\t\tctx.infraProvider = infraProvider\n\t}\n}", "func (mr *MockBootstrapperProviderMockRecorder) Provide() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Provide\", reflect.TypeOf((*MockBootstrapperProvider)(nil).Provide))\n}", "func NewACIProvider(config string, operatingSystem string, image string, deploymentFile string) (*ACIProvider, error) {\n\tvar p ACIProvider\n\tvar err error\n\n\tp.aciClient, err = CreateACIClient()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif config != \"\" {\n\t\tf, err := os.Open(config)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tdefer f.Close()\n\n\t\tif err := p.loadConfig(f); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tif rg := os.Getenv(\"ACI_RESOURCE_GROUP\"); rg != \"\" {\n\t\tp.resourceGroup = rg\n\t}\n\tif p.resourceGroup == \"\" {\n\t\treturn nil, errors.New(\"Resource group can not be empty please set ACI_RESOURCE_GROUP\")\n\t}\n\n\tif r := os.Getenv(\"ACI_REGION\"); r != \"\" {\n\t\tp.region = r\n\t}\n\tif p.region == \"\" {\n\t\treturn nil, errors.New(\"Region can not be empty please set ACI_REGION\")\n\t}\n\tif r := p.region; !isValidACIRegion(r) {\n\t\tunsupportedRegionMessage := fmt.Sprintf(\"Region %s is invalid. Current supported regions are: %s\",\n\t\t\tr, strings.Join(validAciRegions, \", \"))\n\n\t\treturn nil, errors.New(unsupportedRegionMessage)\n\t}\n\n\tregion := os.Getenv(\"ACI_REGION\")\n\tif region == \"\" {\n\t\treturn nil, errors.New(\"Region can not be empty please set ACI_REGION\")\n\t}\n\n\tp.cpu = \"20\"\n\tp.memory = \"100Gi\"\n\tp.cinstances = \"20\"\n\n\t//If a single image is given, create a basic worker instance\n\tif image != \"\" {\n\t\tcg, err := GetSingleImageContainerGroup(image, region, operatingSystem)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tp.workerInstance = cg\n\t} else if deploymentFile != \"\" {\n\t\treturn nil, errors.New(\"Currently do not support K8s deployment files.\")\n\t\t// deployment, err := GetDeploymentFromFile(deploymentFile)\n\t\t// if err != nil{\n\t\t// \treturn nil, err\n\t\t// }\n\t\t// cg, err := GetACIFromK8sPod(pod, region, operatingSystem)\n\t\t// p.workerInstance = cg\n\n\t\t// // Make sure the KIRIX_WORK env varible was added to one container\n\t\t// err = p.AddWork(\"\")\n\t\t// if err != nil {\n\t\t// \treturn nil, err\n\t\t// }\n\t} else {\n\t\treturn nil, errors.New(\"Must supply either an image or Kubernetes deployment spec.\")\n\t}\n\n\treturn &p, err\n}", "func providerFactory(_ io.Reader) (cloudprovider.Interface, error) {\n\tlog := klogr.NewWithOptions(klogr.WithFormat(klogr.FormatKlog))\n\tc, err := loadConfig(envconfig.OsLookuper())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tapiUrl := katapult.DefaultURL\n\tif c.APIHost != \"\" {\n\t\tlog.Info(\"default API base URL overrided\",\n\t\t\t\"url\", c.APIHost)\n\t\tapiUrl, err = url.Parse(c.APIHost)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to parse provided api url: %w\", err)\n\t\t}\n\t}\n\n\trm, err := katapult.New(\n\t\tkatapult.WithAPIKey(c.APIKey),\n\t\tkatapult.WithBaseURL(apiUrl),\n\t\tkatapult.WithUserAgent(\"kce-ccm\"), // TODO: Add version.\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tclient := core.New(rm)\n\n\treturn &provider{\n\t\tlog: log,\n\t\tkatapult: client,\n\t\tconfig: *c,\n\t\tloadBalancer: &loadBalancerManager{\n\t\t\tlog: log,\n\t\t\tconfig: *c,\n\t\t\tloadBalancerController: client.LoadBalancers,\n\t\t\tloadBalancerRuleController: client.LoadBalancerRules,\n\t\t},\n\t}, nil\n}", "func validateProvider(provider string) (string, error) {\n\tswitch sanitize(provider) {\n\tcase \"\":\n\t\treturn \"cloudflare\", nil\n\tcase \"cloudflare\":\n\t\treturn \"cloudflare\", nil\n\tcase \"dryrun\":\n\t\treturn \"dryrun\", nil\n\tdefault:\n\t\treturn \"\", fmt.Errorf(\"Invalid provider `%s` specified. Available providers: [`cloudflare`, `dryrun`]\", provider)\n\t}\n}", "func Provider(v interface{}) Annotation {\n\treturn &providerType{v}\n}", "func discriminateErrCtx(err error) error {\n\tif _, ok := err.(*runtime.APIError); ok {\n\t\t// the service can be reached\n\t\treturn emperror.With(err, cloudInfoService)\n\t}\n\t// handle other cloud info errors here\n\n\t// probably connectivity error (should it be analized further?!)\n\treturn emperror.With(err, cloudInfoClientComponent)\n}", "func (e ApplicationPubSub_NATSProviderValidationError) Cause() error { return e.cause }", "func (o *Okta) provider() *oidc.Provider {\n\tif o.myProvider == nil {\n\t\tctx := oidc.ClientContext(context.Background(), o.client())\n\t\tissuerURL := o.IssuerURL()\n\t\tprovider, err := oidc.NewProvider(ctx, issuerURL)\n\t\tif err != nil {\n\t\t\tpanic(fmt.Errorf(\"Failed to query provider %q: %v\", issuerURL, err))\n\t\t}\n\t\to.myProvider = provider\n\n\t}\n\treturn o.myProvider\n}", "func (adminAPIOp) SkipVerification() bool { return true }", "func (c *MockAzureCloud) ProviderID() kops.CloudProviderID {\n\treturn kops.CloudProviderAzure\n}", "func Provider() *schema.Provider {\n\tp := &schema.Provider{\n\t\tSchema: map[string]*schema.Schema{\n\t\t\t\"api_token\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tSensitive: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"IPINFO_TOKEN\", nil),\n\t\t\t\tDescription: \"ipinfo.io Authentication Token\",\n\t\t\t},\n\t\t},\n\n\t\tDataSourcesMap: map[string]*schema.Resource{\n\t\t\t\"ipinfo\": datasourceIPInfo(),\n\t\t},\n\t}\n\n\tp.ConfigureContextFunc = func(_ context.Context, d *schema.ResourceData) (interface{}, diag.Diagnostics) {\n\t\tterraformVersion := p.TerraformVersion\n\t\tif terraformVersion == \"\" {\n\t\t\t// Terraform 0.12 introduced this field to the protocol\n\t\t\t// We can therefore assume that if it's missing it's 0.10 or 0.11\n\t\t\tterraformVersion = \"0.11+compatible\"\n\t\t}\n\n\t\t// Get access token by signing up a free account at https://ipinfo.io/signup\n\t\tclient := ipinfo.NewClient(nil, nil, d.Get(\"api_token\").(string))\n\n\t\treturn client, nil\n\t}\n\n\treturn p\n}", "func MissingProviderSuggestion(ctx context.Context, addr addrs.Provider, source Source, reqs Requirements) addrs.Provider {\n\tif !addr.IsDefault() {\n\t\treturn addr\n\t}\n\n\t// Before possibly looking up legacy naming, see if the user has another provider\n\t// named in their requirements that is of the same type, and offer that\n\t// as a suggestion\n\tfor req := range reqs {\n\t\tif req != addr && req.Type == addr.Type {\n\t\t\treturn req\n\t\t}\n\t}\n\n\t// Our strategy here, for a default provider, is to use the default\n\t// registry's special API for looking up \"legacy\" providers and try looking\n\t// for a legacy provider whose type name matches the type of the given\n\t// provider. This should then find a suitable answer for any provider\n\t// that was originally auto-installable in v0.12 and earlier but moved\n\t// into a non-default namespace as part of introducing the hierarchical\n\t// provider namespace.\n\t//\n\t// To achieve that, we need to find the direct registry client in\n\t// particular from the given source, because that is the only Source\n\t// implementation that can actually handle a legacy provider lookup.\n\tregSource := findLegacyProviderLookupSource(addr.Hostname, source)\n\tif regSource == nil {\n\t\t// If there's no direct registry source in the installation config\n\t\t// then we can't provide a renaming suggestion.\n\t\treturn addr\n\t}\n\n\tdefaultNS, redirectNS, err := regSource.lookupLegacyProviderNamespace(ctx, addr.Hostname, addr.Type)\n\tif err != nil {\n\t\treturn addr\n\t}\n\n\tswitch {\n\tcase redirectNS != \"\":\n\t\treturn addrs.Provider{\n\t\t\tHostname: addr.Hostname,\n\t\t\tNamespace: redirectNS,\n\t\t\tType: addr.Type,\n\t\t}\n\tdefault:\n\t\treturn addrs.Provider{\n\t\t\tHostname: addr.Hostname,\n\t\t\tNamespace: defaultNS,\n\t\t\tType: addr.Type,\n\t\t}\n\t}\n}", "func (o *ClusterMetricsNodes) HasInfra() bool {\n\tif o != nil && o.Infra != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func NewProvider(ctx *pulumi.Context,\n\tname string, args *ProviderArgs, opts ...pulumi.ResourceOption) (*Provider, error) {\n\tif args == nil {\n\t\targs = &ProviderArgs{}\n\t}\n\n\tif args.AllowReauth == nil {\n\t\targs.AllowReauth = pulumi.BoolPtr(getEnvOrDefault(false, parseEnvBool, \"OS_ALLOW_REAUTH\").(bool))\n\t}\n\tif args.Cloud == nil {\n\t\targs.Cloud = pulumi.StringPtr(getEnvOrDefault(\"\", nil, \"OS_CLOUD\").(string))\n\t}\n\tif args.DelayedAuth == nil {\n\t\targs.DelayedAuth = pulumi.BoolPtr(getEnvOrDefault(false, parseEnvBool, \"OS_DELAYED_AUTH\").(bool))\n\t}\n\tif args.EndpointType == nil {\n\t\targs.EndpointType = pulumi.StringPtr(getEnvOrDefault(\"\", nil, \"OS_ENDPOINT_TYPE\").(string))\n\t}\n\tif args.Insecure == nil {\n\t\targs.Insecure = pulumi.BoolPtr(getEnvOrDefault(false, parseEnvBool, \"OS_INSECURE\").(bool))\n\t}\n\tif args.Region == nil {\n\t\targs.Region = pulumi.StringPtr(getEnvOrDefault(\"\", nil, \"OS_REGION_NAME\").(string))\n\t}\n\tif args.Swauth == nil {\n\t\targs.Swauth = pulumi.BoolPtr(getEnvOrDefault(false, parseEnvBool, \"OS_SWAUTH\").(bool))\n\t}\n\tif args.UseOctavia == nil {\n\t\targs.UseOctavia = pulumi.BoolPtr(getEnvOrDefault(false, parseEnvBool, \"OS_USE_OCTAVIA\").(bool))\n\t}\n\tvar resource Provider\n\terr := ctx.RegisterResource(\"pulumi:providers:openstack\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func TestENITrunkingEnabled(t *testing.T) {\n\tdefer setTestRegion()()\n\tdefer setTestEnv(\"ECS_ENABLE_TASK_ENI\", \"true\")()\n\tcfg, err := NewConfig(ec2.NewBlackholeEC2MetadataClient())\n\trequire.NoError(t, err)\n\n\tcfg.platformOverrides()\n\tassert.True(t, cfg.ENITrunkingEnabled.Enabled(), \"ENI trunking should be enabled\")\n}", "func (e Error) IsInfrastructure() bool {\n\treturn e.group == infrastructure\n}", "func TraceProvider() trace.Provider {\n\tif gp := globalTracer.Load(); gp != nil {\n\t\treturn gp.(traceProvider).tp\n\t}\n\treturn trace.NoopProvider{}\n}", "func (mr *MockProcessProviderMockRecorder) BootstrapperProvider() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"BootstrapperProvider\", reflect.TypeOf((*MockProcessProvider)(nil).BootstrapperProvider))\n}", "func detectProvider(format string) (string, error) {\n\tswitch {\n\tcase format == FORMAT_SYSTEMD:\n\t\treturn FORMAT_SYSTEMD, nil\n\tcase format == FORMAT_UPSTART:\n\t\treturn FORMAT_UPSTART, nil\n\tcase os.Args[0] == \"systemd-exporter\":\n\t\treturn FORMAT_SYSTEMD, nil\n\tcase os.Args[0] == \"upstart-exporter\":\n\t\treturn FORMAT_UPSTART, nil\n\tcase env.Which(\"systemctl\") != \"\":\n\t\treturn FORMAT_SYSTEMD, nil\n\tcase env.Which(\"initctl\") != \"\":\n\t\treturn FORMAT_UPSTART, nil\n\tdefault:\n\t\treturn \"\", fmt.Errorf(\"Can't find init system provider\")\n\t}\n}", "func TestEndpointCase75(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"us-east-1\"),\n\t\tUseFIPS: ptr.Bool(false),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tConsumerARN: ptr.String(\"arn\"),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err == nil {\n\t\tt.Fatalf(\"expect error, got none\")\n\t}\n\tif e, a := \"Invalid ARN: Failed to parse ARN.\", err.Error(); !strings.Contains(a, e) {\n\t\tt.Errorf(\"expect %v error in %v\", e, a)\n\t}\n}", "func Provider() terraform.ResourceProvider {\n\treturn &schema.Provider{\n\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\"ip\": &schema.Schema{\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"VCD_IP\", nil),\n\t\t\t\tDescription: \"The vcd IP for vcd API operations.\",\n\t\t\t},\n\n\t\t\t\"user\": &schema.Schema{\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"VCD_USER\", nil),\n\t\t\t\tDescription: \"The user name for vcd API operations.\",\n\t\t\t},\n\n\t\t\t\"password\": &schema.Schema{\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"VCD_PASSWORD\", nil),\n\t\t\t\tDescription: \"The user password for vcd API operations.\",\n\t\t\t},\n\n\t\t\t\"org\": &schema.Schema{\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"VCD_ORG\", nil),\n\t\t\t\tDescription: \"The vcd org for API operations\",\n\t\t\t},\n\n\t\t\t\"use_vcd_cli_profile\": &schema.Schema{\n\t\t\t\tType: schema.TypeBool,\n\t\t\t\tOptional: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"VCD_USE_VCD_CLI_PROFILE\", false),\n\t\t\t\tDescription: \"If set, VCDClient will use vcd cli profile and token .\",\n\t\t\t},\n\n\t\t\t\"allow_unverified_ssl\": &schema.Schema{\n\t\t\t\tType: schema.TypeBool,\n\t\t\t\tOptional: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"VCD_ALLOW_UNVERIFIED_SSL\", false),\n\t\t\t\tDescription: \"If set, VCDClient will permit unverifiable SSL certificates.\",\n\t\t\t},\n\t\t},\n\n\t\tResourcesMap: map[string]*schema.Resource{\n\n\t\t\t\"vcloud-director_catalog\": resourceCatalog(),\n\t\t\t\"vcloud-director_catalog_item_media\": resourceCatalogItemMedia(),\n\t\t\t\"vcloud-director_catalog_item_ova\": resourceCatalogItemOva(),\n\t\t\t\"vcloud-director_vapp\": resourceVApp(),\n\t\t\t\"vcloud-director_independent_disk\": resourceIndependentDisk(),\n\t\t\t\"vcloud-director_org\": resourceOrg(),\n\t\t\t\"vcloud-director_disk\": resourceIndependentDisk(),\n\t\t\t\"vcloud-director_user\": resourceUser(),\n\t\t\t\"vcloud-director_vdc\": resourceVdc(),\n\t\t\t\"vcloud-director_vapp_vm\": resourceVappVm(),\n\t\t},\n\n\t\tConfigureFunc: providerConfigure,\n\t}\n}", "func providerConfigure(d *schema.ResourceData) (interface{}, error) {\n\tif d.Get(\"url\") == nil {\n\t\treturn nil, fmt.Errorf(\"url cannot be nil\")\n\t}\n\n\tusername := d.Get(\"username\").(string)\n\tpassword := d.Get(\"password\").(string)\n\tapiKey := d.Get(\"api_key\").(string)\n\taccessToken := d.Get(\"access_token\").(string)\n\n\tlog.SetLogger(log.NewLogger(log.INFO, nil))\n\n\tvar client *http.Client\n\tdetails := auth.NewArtifactoryDetails()\n\n\turl := d.Get(\"url\").(string)\n\tif url[len(url)-1] != '/' {\n\t\turl += \"/\"\n\t}\n\tdetails.SetUrl(url)\n\n\tif username != \"\" && password != \"\" {\n\t\tdetails.SetUser(username)\n\t\tdetails.SetPassword(password)\n\t\ttp := transport.BasicAuth{\n\t\t\tUsername: username,\n\t\t\tPassword: password,\n\t\t}\n\t\tclient = tp.Client()\n\t} else if apiKey != \"\" {\n\t\tdetails.SetApiKey(apiKey)\n\t\ttp := &transport.ApiKeyAuth{\n\t\t\tApiKey: apiKey,\n\t\t}\n\t\tclient = tp.Client()\n\t} else if accessToken != \"\" {\n\t\tdetails.SetAccessToken(accessToken)\n\t\ttp := &transport.AccessTokenAuth{\n\t\t\tAccessToken: accessToken,\n\t\t}\n\t\tclient = tp.Client()\n\t} else {\n\t\treturn nil, fmt.Errorf(\"either [username, password] or [api_key] or [access_token] must be set to use provider\")\n\t}\n\n\tconfig, err := config.NewConfigBuilder().\n\t\tSetServiceDetails(details).\n\t\tSetDryRun(false).\n\t\tBuild()\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trtold, err := artifactoryold.NewClient(d.Get(\"url\").(string), client)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trtnew, err := artifactorynew.New(&details, config)\n\n\tif err != nil {\n\t\treturn nil, err\n\t} else if _, resp, err := rtold.V1.System.Ping(context.Background()); err != nil {\n\t\treturn nil, err\n\t} else if resp.StatusCode != 200 {\n\t\treturn nil, fmt.Errorf(\"failed to ping server. Got %d\", resp.StatusCode)\n\t} else if _, err := rtnew.Ping(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tproductid := \"terraform-provider-artifactory/\" + ProviderVersion\n\tcommandid := \"Terraform/\" + version.Version\n\tusage.SendReportUsage(productid, commandid, rtnew)\n\n\trt := &ArtClient{\n\t\tArtOld: rtold,\n\t\tArtNew: rtnew,\n\t}\n\n\treturn rt, nil\n}", "func IndirectlyTested() string {\n\treturn \"This function is tested via a function reference rather than a direct call\"\n}", "func TestConfigure_UseExistingASN(t *testing.T) {\n\tASNOnDevice := \"65001\"\n\tMockLeafDeviceAdapter := mock.DeviceAdapter{\n\t\tMockGetInterfaces: func(FabricID uint, DeviceID uint, DeviceIP string) ([]domain.Interface, error) {\n\n\t\t\treturn []domain.Interface{domain.Interface{FabricID: FabricID, DeviceID: DeviceID,\n\t\t\t\tIntType: \"ethernet\", IntName: \"1/11\", Mac: \"M1\", ConfigState: \"up\"}}, nil\n\n\t\t},\n\t\tMockGetLLDPs: func(FabricID uint, DeviceID uint, DeviceIP string) ([]domain.LLDP, error) {\n\n\t\t\treturn []domain.LLDP{domain.LLDP{FabricID: FabricID, DeviceID: DeviceID,\n\t\t\t\tLocalIntType: \"ethernet\", LocalIntName: \"1/11\", LocalIntMac: \"M1\",\n\t\t\t\tRemoteIntType: \"ethernet\", RemoteIntName: \"1/22\", RemoteIntMac: \"M2\"}}, nil\n\n\t\t},\n\t\tMockGetASN: func(FabricID uint, Device uint, DeviceIP string) (string, error) {\n\t\t\treturn ASNOnDevice, nil\n\t\t},\n\t}\n\n\tdatabase.Setup(constants.TESTDBLocation)\n\tdefer cleanupDB(database.GetWorkingInstance())\n\n\tDatabaseRepository := gateway.DatabaseRepository{Database: database.GetWorkingInstance()}\n\tdevUC := usecase.DeviceInteractor{Db: &DatabaseRepository, DeviceAdapterFactory: mock.GetDeviceAdapterFactory(MockLeafDeviceAdapter)}\n\tdevUC.AddFabric(context.Background(), MockFabricName)\n\n\tresp, err := devUC.AddDevices(context.Background(), MockFabricName, []string{MockLeaf1IP}, []string{},\n\t\tUserName, Password, false)\n\tassert.Contains(t, resp, usecase.AddDeviceResponse{FabricName: MockFabricName, FabricID: 1, IPAddress: MockLeaf1IP, Role: usecase.LeafRole})\n\n\tassert.Nil(t, err)\n\n\tswitchConfig, err := DatabaseRepository.GetSwitchConfigOnDeviceIP(MockFabricName, MockLeaf1IP)\n\tassert.Equal(t, ASNOnDevice, switchConfig.LocalAS)\n\t//Verify ASN is already on the Switch, so need to push\n\tassert.Equal(t, domain.ConfigNone, switchConfig.ASConfigType)\n\n\t//Next Call without Device having ASN\n\tMockLeafDeviceAdapterWithoutASN := mock.DeviceAdapter{\n\t\tMockGetInterfaces: func(FabricID uint, DeviceID uint, DeviceIP string) ([]domain.Interface, error) {\n\n\t\t\treturn []domain.Interface{domain.Interface{FabricID: FabricID, DeviceID: DeviceID,\n\t\t\t\tIntType: \"ethernet\", IntName: \"1/11\", Mac: \"M1\", ConfigState: \"up\"}}, nil\n\n\t\t},\n\t\tMockGetLLDPs: func(FabricID uint, DeviceID uint, DeviceIP string) ([]domain.LLDP, error) {\n\n\t\t\treturn []domain.LLDP{domain.LLDP{FabricID: FabricID, DeviceID: DeviceID,\n\t\t\t\tLocalIntType: \"ethernet\", LocalIntName: \"1/11\", LocalIntMac: \"M1\",\n\t\t\t\tRemoteIntType: \"ethernet\", RemoteIntName: \"1/22\", RemoteIntMac: \"M2\"}}, nil\n\n\t\t},\n\t}\n\tdevUC.DeviceAdapterFactory = mock.GetDeviceAdapterFactory(MockLeafDeviceAdapterWithoutASN)\n\tresp, err = devUC.AddDevices(context.Background(), MockFabricName, []string{MockLeaf1IP}, []string{},\n\t\tUserName, Password, false)\n\tassert.Contains(t, resp, usecase.AddDeviceResponse{FabricName: MockFabricName, FabricID: 1, IPAddress: MockLeaf1IP, Role: usecase.LeafRole})\n\n\tassert.Nil(t, err)\n\tswitchConfigSecond, err := DatabaseRepository.GetSwitchConfigOnDeviceIP(MockFabricName, MockLeaf1IP)\n\tassert.Equal(t, ASNOnDevice, switchConfigSecond.LocalAS)\n\t//Verify ASN is to be created\n\tassert.Equal(t, domain.ConfigCreate, switchConfigSecond.ASConfigType)\n}", "func (mr *MockProviderMockRecorder) Provide(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Provide\", reflect.TypeOf((*MockProvider)(nil).Provide), arg0)\n}", "func (p *Provider) newGCPProviderSpec(windowsServerVersion windows.ServerVersion) (*mapi.GCPMachineProviderSpec, error) {\n\tlistOptions := meta.ListOptions{LabelSelector: \"machine.openshift.io/cluster-api-machine-role=worker\"}\n\tmachines, err := p.oc.Machine.Machines(clusterinfo.MachineAPINamespace).List(context.TODO(), listOptions)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(machines.Items) == 0 {\n\t\treturn nil, fmt.Errorf(\"found 0 worker role machines\")\n\t}\n\tfoundSpec := &mapi.GCPMachineProviderSpec{}\n\terr = json.Unmarshal(machines.Items[0].Spec.ProviderSpec.Value.Raw, foundSpec)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to unmarshal raw machine provider spec: %v\", err)\n\t}\n\n\treturn &mapi.GCPMachineProviderSpec{\n\t\tTypeMeta: meta.TypeMeta{\n\t\t\tAPIVersion: \"machine.openshift.io/v1beta1\",\n\t\t\tKind: \"GCPMachineProviderSpec\",\n\t\t},\n\t\tObjectMeta: meta.ObjectMeta{},\n\t\tUserDataSecret: &core.LocalObjectReference{\n\t\t\tName: clusterinfo.UserDataSecretName,\n\t\t},\n\t\tCredentialsSecret: &core.LocalObjectReference{\n\t\t\tName: foundSpec.CredentialsSecret.Name,\n\t\t},\n\t\tCanIPForward: false,\n\t\tDeletionProtection: false,\n\t\tDisks: []*mapi.GCPDisk{{\n\t\t\tAutoDelete: true,\n\t\t\tBoot: true,\n\t\t\tSizeGB: 128,\n\t\t\tType: \"pd-ssd\",\n\t\t\tImage: getImage(windowsServerVersion),\n\t\t}},\n\t\tNetworkInterfaces: foundSpec.NetworkInterfaces,\n\t\tServiceAccounts: foundSpec.ServiceAccounts,\n\t\tTags: foundSpec.Tags,\n\t\tMachineType: foundSpec.MachineType,\n\t\tRegion: foundSpec.Region,\n\t\tZone: foundSpec.Zone,\n\t\tProjectID: foundSpec.ProjectID,\n\t}, nil\n}", "func (ind ErrInvalidNetworkDriver) BadRequest() {}", "func Provider() terraform.ResourceProvider {\n\treturn &schema.Provider{\n\t\tSchema: map[string]*schema.Schema{\n\t\t\t\"url\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"APPGATE_ADDRESS\", \"\"),\n\t\t\t},\n\t\t\t\"username\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"APPGATE_USERNAME\", \"\"),\n\t\t\t},\n\t\t\t\"password\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"APPGATE_PASSWORD\", \"\"),\n\t\t\t},\n\t\t\t\"provider\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"APPGATE_PROVIDER\", \"local\"),\n\t\t\t},\n\t\t\t\"insecure\": {\n\t\t\t\tType: schema.TypeBool,\n\t\t\t\tRequired: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"APPGATE_INSECURE\", true),\n\t\t\t},\n\t\t\t\"debug\": {\n\t\t\t\tType: schema.TypeBool,\n\t\t\t\tOptional: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"APPGATE_HTTP_DEBUG\", false),\n\t\t\t},\n\t\t},\n\t\tDataSourcesMap: map[string]*schema.Resource{\n\t\t\t\"appgate_appliance\": dataSourceAppgateAppliance(),\n\t\t\t\"appgate_entitlement\": dataSourceAppgateEntitlement(),\n\t\t\t\"appgate_site\": dataSourceAppgateSite(),\n\t\t\t\"appgate_condition\": dataSourceAppgateCondition(),\n\t\t\t\"appgate_policy\": dataSourceAppgatePolicy(),\n\t\t\t\"appgate_ringfence_rule\": dataSourceAppgateRingfenceRule(),\n\t\t\t\"appgate_criteria_script\": dataSourceCriteriaScript(),\n\t\t\t\"appgate_entitlement_script\": dataSourceEntitlementScript(),\n\t\t\t\"appgate_device_script\": dataSourceDeviceScript(),\n\t\t\t\"appgate_appliance_customization\": dataSourceAppgateApplianceCustomization(),\n\t\t\t\"appgate_ip_pool\": dataSourceAppgateIPPool(),\n\t\t\t\"appgate_administrative_role\": dataSourceAppgateAdministrativeRole(),\n\t\t\t\"appgate_global_settings\": dataSourceGlobalSettings(),\n\t\t\t\"appgate_trusted_certificate\": dataSourceAppgateTrustedCertificate(),\n\t\t\t\"appgate_mfa_provider\": dataSourceAppgateMfaProvider(),\n\t\t\t\"appgate_local_user\": dataSourceAppgateLocalUser(),\n\t\t\t\"appgate_identity_provider\": dataSourceAppgateIdentityProvider(),\n\t\t},\n\t\tResourcesMap: map[string]*schema.Resource{\n\t\t\t\"appgate_appliance\": resourceAppgateAppliance(),\n\t\t\t\"appgate_entitlement\": resourceAppgateEntitlement(),\n\t\t\t\"appgate_site\": resourceAppgateSite(),\n\t\t\t\"appgate_ringfence_rule\": resourceAppgateRingfenceRule(),\n\t\t\t\"appgate_condition\": resourceAppgateCondition(),\n\t\t\t\"appgate_policy\": resourceAppgatePolicy(),\n\t\t\t\"appgate_criteria_script\": resourceAppgateCriteriaScript(),\n\t\t\t\"appgate_entitlement_script\": resourceAppgateEntitlementScript(),\n\t\t\t\"appgate_device_script\": resourceAppgateDeviceScript(),\n\t\t\t\"appgate_appliance_customization\": resourceAppgateApplianceCustomizations(),\n\t\t\t\"appgate_ip_pool\": resourceAppgateIPPool(),\n\t\t\t\"appgate_administrative_role\": resourceAppgateAdministrativeRole(),\n\t\t\t\"appgate_global_settings\": resourceGlobalSettings(),\n\t\t\t\"appgate_ldap_identity_provider\": resourceAppgateLdapProvider(),\n\t\t\t\"appgate_trusted_certificate\": resourceAppgateTrustedCertificate(),\n\t\t\t\"appgate_mfa_provider\": resourceAppgateMfaProvider(),\n\t\t\t\"appgate_local_user\": resourceAppgateLocalUser(),\n\t\t\t\"appgate_license\": resourceAppgateLicense(),\n\t\t\t\"appgate_admin_mfa_settings\": resourceAdminMfaSettings(),\n\t\t\t\"appgate_client_connections\": resourceClientConnections(),\n\t\t\t\"appgate_blacklist_user\": resourceAppgateBlacklistUser(),\n\t\t},\n\t\tConfigureFunc: providerConfigure,\n\t}\n}", "func (m *Machine) GenerateProviderID() (string, error) {\n\tif m.vmiInstance == nil {\n\t\treturn \"\", errors.New(\"Underlying Kubevirt VM is NOT running\")\n\t}\n\n\tproviderID := fmt.Sprintf(\"kubevirt://%s\", m.machineContext.KubevirtMachine.Name)\n\n\treturn providerID, nil\n}", "func parseKogitoInfraResource(targetResourceType string) (*v1.InfraResource, error) {\n\tswitch targetResourceType {\n\t// case infrastructure.InfinispanKind:\n\t// \treturn &v1.InfraResource{APIVersion: infrastructure.InfinispanAPIVersion, Kind: infrastructure.InfinispanKind}, nil\n\tcase infrastructure.KafkaKind:\n\t\treturn &v1.InfraResource{APIVersion: infrastructure.KafkaAPIVersion, Kind: infrastructure.KafkaKind}, nil\n\t// case infrastructure.KeycloakKind:\n\t// \treturn &v1.InfraResource{APIVersion: infrastructure.KeycloakAPIVersion, Kind: infrastructure.KeycloakKind}, nil\n\t// case infrastructure.MongoDBKind:\n\t// \treturn &v1.InfraResource{APIVersion: infrastructure.MongoDBAPIVersion, Kind: infrastructure.MongoDBKind}, nil\n\t// case infrastructure.KnativeEventingBrokerKind:\n\t// \treturn &v1.InfraResource{APIVersion: infrastructure.KnativeEventingAPIVersion, Kind: infrastructure.KnativeEventingBrokerKind}, nil\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"Unknown KogitoInfra target resource type %s\", targetResourceType)\n\t}\n}", "func (e *ErrUnknownProvider) Is(target error) bool {\n\t_, ok := target.(*ErrUnknownProvider)\n\treturn ok\n}", "func (c *FilecoinRetrievalProviderAdmin) InitialiseProvider(providerRegistrar register.ProviderRegistrar, providerPrivKey *fcrcrypto.KeyPair, providerPrivKeyVer *fcrcrypto.KeyVersion) error {\n\terr := c.AdminApiCaller.RequestInitialiseKey(providerRegistrar, providerPrivKey, providerPrivKeyVer, c.Settings.providerAdminPrivateKey, c.Settings.providerAdminPrivateKeyVer)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Add this provider to the active providers list\n\tc.ActiveProvidersLock.Lock()\n\tc.ActiveProviders[providerRegistrar.GetNodeID()] = providerRegistrar\n\tc.ActiveProvidersLock.Unlock()\n\treturn nil\n}", "func (d *driver) Supported(\n\tctx types.Context,\n\topts types.Store) (bool, error) {\n\treturn utils.IsAzureInstance(ctx)\n}", "func TestConfigure_InvalidSpineASN(t *testing.T) {\n\tASNOnDevice := \"64519\"\n\tMockSpineDeviceAdapter := mock.DeviceAdapter{\n\t\tMockGetInterfaces: func(FabricID uint, DeviceID uint, DeviceIP string) ([]domain.Interface, error) {\n\n\t\t\treturn []domain.Interface{domain.Interface{FabricID: FabricID, DeviceID: DeviceID,\n\t\t\t\tIntType: \"ethernet\", IntName: \"1/11\", Mac: \"M1\", ConfigState: \"up\"}}, nil\n\n\t\t},\n\t\tMockGetLLDPs: func(FabricID uint, DeviceID uint, DeviceIP string) ([]domain.LLDP, error) {\n\n\t\t\treturn []domain.LLDP{domain.LLDP{FabricID: FabricID, DeviceID: DeviceID,\n\t\t\t\tLocalIntType: \"ethernet\", LocalIntName: \"1/11\", LocalIntMac: \"M1\",\n\t\t\t\tRemoteIntType: \"ethernet\", RemoteIntName: \"1/22\", RemoteIntMac: \"M2\"}}, nil\n\n\t\t},\n\t\tMockGetASN: func(FabricID uint, Device uint, DeviceIP string) (string, error) {\n\t\t\treturn ASNOnDevice, nil\n\t\t},\n\t}\n\n\tdatabase.Setup(constants.TESTDBLocation)\n\tdefer cleanupDB(database.GetWorkingInstance())\n\n\tDatabaseRepository := gateway.DatabaseRepository{Database: database.GetWorkingInstance()}\n\tdevUC := usecase.DeviceInteractor{Db: &DatabaseRepository, DeviceAdapterFactory: mock.GetDeviceAdapterFactory(MockSpineDeviceAdapter)}\n\tdevUC.AddFabric(context.Background(), MockFabricName)\n\n\tresp, err := devUC.AddDevices(context.Background(), MockFabricName, []string{}, []string{MockSpine1IP},\n\t\tUserName, Password, false)\n\tassert.Contains(t, resp, usecase.AddDeviceResponse{FabricName: MockFabricName, FabricID: 1, IPAddress: MockSpine1IP, Role: usecase.SpineRole,\n\t\tErrors: []error{errors.New(\"ASN 64519 not in range 64512\")}})\n\n\tassert.NotNil(t, err)\n\n}", "func TestLookupEndpointPanicsOnInvalidType(t *testing.T) {\n\tdefer func() {\n\t\tif r := recover(); r == nil {\n\t\t\tt.Error(\"lookupEndpoint should panic if an invalid conntype is specified.\")\n\t\t}\n\t}()\n\tlookupEndpoint(context.Background(), nil, nil, jid.JID{}, \"wssorbashorsomething\")\n}", "func Provider() terraform.ResourceProvider {\n\treturn &schema.Provider{\n\t\tSchema: map[string]*schema.Schema{\n\t\t\t\"apikey\": &schema.Schema{\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"NS1_APIKEY\", nil),\n\t\t\t\tDescription: descriptions[\"api_key\"],\n\t\t\t},\n\t\t\t\"endpoint\": &schema.Schema{\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"NS1_ENDPOINT\", nil),\n\t\t\t\tDescription: descriptions[\"endpoint\"],\n\t\t\t},\n\t\t\t\"ignore_ssl\": &schema.Schema{\n\t\t\t\tType: schema.TypeBool,\n\t\t\t\tOptional: true,\n\t\t\t\tDefaultFunc: schema.EnvDefaultFunc(\"NS1_IGNORE_SSL\", nil),\n\t\t\t\tDescription: descriptions[\"ignore_ssl\"],\n\t\t\t},\n\t\t},\n\t\tResourcesMap: map[string]*schema.Resource{\n\t\t\t\"ns1_zone\": zoneResource(),\n\t\t\t\"ns1_record\": recordResource(),\n\t\t\t\"ns1_datasource\": dataSourceResource(),\n\t\t\t\"ns1_datafeed\": dataFeedResource(),\n\t\t\t\"ns1_monitoringjob\": monitoringJobResource(),\n\t\t\t\"ns1_notifylist\": notifyListResource(),\n\t\t\t\"ns1_user\": userResource(),\n\t\t\t\"ns1_apikey\": apikeyResource(),\n\t\t\t\"ns1_team\": teamResource(),\n\t\t},\n\t\tConfigureFunc: ns1Configure,\n\t}\n}", "func checkAllProviders(e2eFile string) error {\n\tcheckFailed := false\n\tinConformanceCode := false\n\n\tregStartConformance := regexp.MustCompile(patternStartConformance)\n\tregEndConformance := regexp.MustCompile(patternEndConformance)\n\tregSkip := regexp.MustCompile(patternSkip)\n\n\tfileInput, err := os.ReadFile(e2eFile)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to read file %s: %w\", e2eFile, err)\n\t}\n\tscanner := bufio.NewScanner(bytes.NewReader(fileInput))\n\tscanner.Split(bufio.ScanLines)\n\n\tfor scanner.Scan() {\n\t\tline := scanner.Text()\n\t\tif regStartConformance.MatchString(line) {\n\t\t\tif inConformanceCode {\n\t\t\t\treturn errors.New(\"Missed the end of previous conformance test. There might be a bug in this script.\")\n\t\t\t}\n\t\t\tinConformanceCode = true\n\t\t}\n\t\tif inConformanceCode {\n\t\t\tif regSkip.MatchString(line) {\n\t\t\t\t// To list all invalid places in a single operation of this tool, here doesn't return error and continues checking.\n\t\t\t\tfmt.Fprintf(os.Stderr, \"%v: Conformance test should not call any e2eskipper.Skip*()\\n\", e2eFile)\n\t\t\t\tcheckFailed = true\n\t\t\t}\n\t\t\tif regEndConformance.MatchString(line) {\n\t\t\t\tinConformanceCode = false\n\t\t\t}\n\t\t}\n\t}\n\tif inConformanceCode {\n\t\treturn errors.New(\"Missed the end of previous conformance test. There might be a bug in this script.\")\n\t}\n\tif checkFailed {\n\t\treturn errors.New(\"We need to fix the above errors.\")\n\t}\n\treturn nil\n}", "func providerConfigure(data *schema.ResourceData) (interface{}, error) {\n\tlog.Println(\"[INFO] Initializing Client\")\n\n\tconfig := Config{\n\t\tAPIKey: data.Get(\"api_key\").(string),\n\t\tAPIURL: data.Get(\"api_url\").(string),\n\t}\n\n\treturn config.Client()\n}", "func (mr *MockHostEventMockRecorder) GetInfraEnvId() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetInfraEnvId\", reflect.TypeOf((*MockHostEvent)(nil).GetInfraEnvId))\n}" ]
[ "0.67692643", "0.6662635", "0.6476615", "0.63881326", "0.61153394", "0.56615096", "0.5628567", "0.54794973", "0.54453844", "0.53783494", "0.537697", "0.53449565", "0.53372407", "0.52543694", "0.5240322", "0.5237933", "0.5224655", "0.52222174", "0.5212903", "0.51686656", "0.51022714", "0.50986093", "0.5079922", "0.5047405", "0.50156784", "0.5001331", "0.49914533", "0.49805668", "0.4969226", "0.4946829", "0.49436405", "0.49191302", "0.49102053", "0.48998296", "0.48971635", "0.48802382", "0.48525852", "0.483853", "0.48279378", "0.4817419", "0.48120308", "0.48112103", "0.48108056", "0.47889236", "0.47570628", "0.4756431", "0.47562337", "0.47552004", "0.4753048", "0.47509164", "0.47338414", "0.47312003", "0.4727575", "0.47245926", "0.47193336", "0.47114468", "0.47080317", "0.4703157", "0.47000802", "0.46975157", "0.4696361", "0.46952435", "0.46844664", "0.46773052", "0.46771887", "0.4670099", "0.46682575", "0.46590912", "0.463814", "0.46376055", "0.4635734", "0.4633302", "0.4629643", "0.46180165", "0.4605766", "0.4603761", "0.46026373", "0.4602052", "0.46018347", "0.45981058", "0.45896065", "0.4589318", "0.45850897", "0.4579252", "0.45779085", "0.45767745", "0.45658326", "0.45542723", "0.45541194", "0.45425534", "0.45368734", "0.45226708", "0.45178437", "0.4514477", "0.45102844", "0.45094144", "0.45042726", "0.44983503", "0.44980642", "0.44968358" ]
0.6934428
0
LocalDiscoveryProvider mocks base method
func (m *MockClient) LocalDiscoveryProvider() fab.LocalDiscoveryProvider { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "LocalDiscoveryProvider") ret0, _ := ret[0].(fab.LocalDiscoveryProvider) return ret0 }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (m *MockProviders) LocalDiscoveryProvider() fab.LocalDiscoveryProvider {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"LocalDiscoveryProvider\")\n\tret0, _ := ret[0].(fab.LocalDiscoveryProvider)\n\treturn ret0\n}", "func (c *Provider) LocalDiscoveryProvider() fab.LocalDiscoveryProvider {\n\treturn c.localDiscoveryProvider\n}", "func (m *MockMemberList) LocalNode() discovery.Member {\n\tret := m.ctrl.Call(m, \"LocalNode\")\n\tret0, _ := ret[0].(discovery.Member)\n\treturn ret0\n}", "func NewMockDiscoveryProvider(err error, peers []fab.Peer) (*MockStaticDiscoveryProvider, error) {\n\treturn &MockStaticDiscoveryProvider{Error: err, Peers: peers}, nil\n}", "func TestLocalDomain_NetworkServiceRegistry(t *testing.T) {\n\tt.Cleanup(func() { goleak.VerifyNone(t) })\n\n\tctx, cancel := context.WithTimeout(context.Background(), time.Second)\n\tdefer cancel()\n\n\tdnsServer := sandbox.NewFakeResolver()\n\n\tdomain1 := sandbox.NewBuilder(ctx, t).\n\t\tSetNodesCount(0).\n\t\tSetDNSDomainName(\"cluster.local\").\n\t\tSetDNSResolver(dnsServer).\n\t\tBuild()\n\n\tclient1 := registryclient.NewNetworkServiceRegistryClient(ctx,\n\t\tregistryclient.WithDialOptions(grpc.WithTransportCredentials(insecure.NewCredentials())),\n\t\tregistryclient.WithClientURL(domain1.Registry.URL))\n\n\texpected, err := client1.Register(context.Background(), &registryapi.NetworkService{\n\t\tName: \"ns-1@\" + domain1.Name,\n\t})\n\n\trequire.Nil(t, err)\n\trequire.True(t, strings.Contains(expected.GetName(), \"@\"+domain1.Name))\n\n\tclient2 := registryclient.NewNetworkServiceRegistryClient(ctx,\n\t\tregistryclient.WithDialOptions(grpc.WithTransportCredentials(insecure.NewCredentials())),\n\t\tregistryclient.WithClientURL(domain1.Registry.URL))\n\n\tstream, err := client2.Find(context.Background(), &registryapi.NetworkServiceQuery{\n\t\tNetworkService: &registryapi.NetworkService{\n\t\t\tName: expected.Name,\n\t\t},\n\t})\n\n\trequire.Nil(t, err)\n\n\tlist := registryapi.ReadNetworkServiceList(stream)\n\n\trequire.Len(t, list, 1)\n\trequire.Equal(t, \"ns-1@cluster.local\", list[0].Name)\n}", "func Mock() Cluster { return mockCluster{} }", "func (_m *MockPlcDriver) SupportsDiscovery() bool {\n\tret := _m.Called()\n\n\tvar r0 bool\n\tif rf, ok := ret.Get(0).(func() bool); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tr0 = ret.Get(0).(bool)\n\t}\n\n\treturn r0\n}", "func mockedGranter(kubeutil *kube.Kube, app *v1.RadixRegistration, namespace string, serviceAccount *corev1.ServiceAccount) error {\n\treturn nil\n}", "func (dp *MockStaticDiscoveryProvider) CreateLocalDiscoveryService(mspID string) (fab.DiscoveryService, error) {\n\treturn &MockStaticDiscoveryService{Error: dp.Error, Peers: dp.Peers}, nil\n}", "func (c *Local) LocalDiscoveryService() fab.DiscoveryService {\n\treturn c.localDiscovery\n}", "func (m *MockService) Discovery() *idp.DiscoveryResponse {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Discovery\")\n\tret0, _ := ret[0].(*idp.DiscoveryResponse)\n\treturn ret0\n}", "func (m *MockInterface) Discovery() discovery.DiscoveryInterface {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Discovery\")\n\tret0, _ := ret[0].(discovery.DiscoveryInterface)\n\treturn ret0\n}", "func (m *MockEarlyConnection) LocalAddr() net.Addr {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"LocalAddr\")\n\tret0, _ := ret[0].(net.Addr)\n\treturn ret0\n}", "func newLocalService(config fab.EndpointConfig, mspID string, opts ...coptions.Opt) *LocalService {\n\tlogger.Debug(\"Creating new local discovery service\")\n\n\ts := &LocalService{mspID: mspID}\n\ts.service = newService(config, s.queryPeers, opts...)\n\treturn s\n}", "func (m *MockInformation) LocalLocation() *universe.View {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"LocalLocation\")\n\tret0, _ := ret[0].(*universe.View)\n\treturn ret0\n}", "func (l *Factory) CreateLocalDiscoveryProvider(config fabApi.EndpointConfig) (fabApi.LocalDiscoveryProvider, error) {\n\tlogger.Debug(\"create local Provider Impl\")\n\treturn &impl{config, l.LocalPeer, l.LocalPeerTLSCertPem}, nil\n}", "func newLocalProviderWithClock(t []string, clock clock.Clock) Provider {\n\tp := &localProvider{\n\t\ttags: t,\n\t\texpectedTags: t,\n\t}\n\n\tif config.IsExpectedTagsSet(coreConfig.Datadog) {\n\t\tp.expectedTags = append(p.tags, hostMetadataUtils.GetHostTags(context.TODO(), false, coreConfig.Datadog).System...)\n\n\t\t// expected tags deadline is based on the agent start time, which may have been earlier\n\t\t// than the current time.\n\t\texpectedTagsDeadline := coreConfig.StartTime.Add(coreConfig.Datadog.GetDuration(\"logs_config.expected_tags_duration\"))\n\n\t\t// reset submitExpectedTags after deadline elapsed\n\t\tclock.AfterFunc(expectedTagsDeadline.Sub(clock.Now()), func() {\n\t\t\tp.Lock()\n\t\t\tdefer p.Unlock()\n\t\t\tp.expectedTags = nil\n\t\t})\n\t}\n\n\treturn p\n}", "func TestExternalNameService(t *testing.T) {\n\trh, c, done := setup(t, enableExternalNameService(t))\n\tdefer done()\n\n\ts1 := fixture.NewService(\"kuard\").\n\t\tWithSpec(v1.ServiceSpec{\n\t\t\tPorts: []v1.ServicePort{{\n\t\t\t\tPort: 80,\n\t\t\t\tTargetPort: intstr.FromInt(8080),\n\t\t\t}},\n\t\t\tExternalName: \"foo.io\",\n\t\t\tType: v1.ServiceTypeExternalName,\n\t\t})\n\n\ti1 := &networking_v1.Ingress{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: \"kuard\",\n\t\t\tNamespace: s1.Namespace,\n\t\t},\n\t\tSpec: networking_v1.IngressSpec{\n\t\t\tDefaultBackend: featuretests.IngressBackend(s1),\n\t\t},\n\t}\n\trh.OnAdd(s1)\n\trh.OnAdd(i1)\n\n\tc.Request(routeType).Equals(&envoy_discovery_v3.DiscoveryResponse{\n\t\tResources: resources(t,\n\t\t\tenvoy_v3.RouteConfiguration(\"ingress_http\",\n\t\t\t\tenvoy_v3.VirtualHost(\"*\",\n\t\t\t\t\t&envoy_route_v3.Route{\n\t\t\t\t\t\tMatch: routePrefix(\"/\"),\n\t\t\t\t\t\tAction: routeCluster(\"default/kuard/80/da39a3ee5e\"),\n\t\t\t\t\t},\n\t\t\t\t),\n\t\t\t),\n\t\t),\n\t\tTypeUrl: routeType,\n\t})\n\n\tc.Request(clusterType).Equals(&envoy_discovery_v3.DiscoveryResponse{\n\t\tResources: resources(t,\n\t\t\texternalNameCluster(\"default/kuard/80/da39a3ee5e\", \"default/kuard\", \"default_kuard_80\", \"foo.io\", 80),\n\t\t),\n\t\tTypeUrl: clusterType,\n\t})\n\n\trh.OnDelete(i1)\n\n\trh.OnAdd(fixture.NewProxy(\"kuard\").\n\t\tWithFQDN(\"kuard.projectcontour.io\").\n\t\tWithSpec(contour_api_v1.HTTPProxySpec{\n\t\t\tRoutes: []contour_api_v1.Route{{\n\t\t\t\tServices: []contour_api_v1.Service{{\n\t\t\t\t\tName: s1.Name,\n\t\t\t\t\tPort: 80,\n\t\t\t\t}},\n\t\t\t}},\n\t\t}),\n\t)\n\n\tc.Request(routeType).Equals(&envoy_discovery_v3.DiscoveryResponse{\n\t\tResources: resources(t,\n\t\t\tenvoy_v3.RouteConfiguration(\"ingress_http\",\n\t\t\t\tenvoy_v3.VirtualHost(\"kuard.projectcontour.io\",\n\t\t\t\t\t&envoy_route_v3.Route{\n\t\t\t\t\t\tMatch: routePrefix(\"/\"),\n\t\t\t\t\t\tAction: routeCluster(\"default/kuard/80/a28d1ec01b\"),\n\t\t\t\t\t},\n\t\t\t\t),\n\t\t\t),\n\t\t),\n\t\tTypeUrl: routeType,\n\t})\n\n\tc.Request(clusterType).Equals(&envoy_discovery_v3.DiscoveryResponse{\n\t\tResources: resources(t,\n\t\t\texternalNameCluster(\"default/kuard/80/a28d1ec01b\", \"default/kuard\", \"default_kuard_80\", \"foo.io\", 80),\n\t\t),\n\t\tTypeUrl: clusterType,\n\t})\n\n\t// After we set the Host header, the cluster should remain\n\t// the same, but the Route should do update the Host header.\n\trh.OnDelete(fixture.NewProxy(\"kuard\").WithSpec(contour_api_v1.HTTPProxySpec{}))\n\trh.OnAdd(fixture.NewProxy(\"kuard\").\n\t\tWithFQDN(\"kuard.projectcontour.io\").\n\t\tWithSpec(contour_api_v1.HTTPProxySpec{\n\t\t\tRoutes: []contour_api_v1.Route{{\n\t\t\t\tServices: []contour_api_v1.Service{{\n\t\t\t\t\tName: s1.Name,\n\t\t\t\t\tPort: 80,\n\t\t\t\t}},\n\t\t\t\tRequestHeadersPolicy: &contour_api_v1.HeadersPolicy{\n\t\t\t\t\tSet: []contour_api_v1.HeaderValue{{\n\t\t\t\t\t\tName: \"Host\",\n\t\t\t\t\t\tValue: \"external.address\",\n\t\t\t\t\t}},\n\t\t\t\t},\n\t\t\t}},\n\t\t}),\n\t)\n\n\tc.Request(routeType).Equals(&envoy_discovery_v3.DiscoveryResponse{\n\t\tTypeUrl: routeType,\n\t\tResources: resources(t,\n\t\t\tenvoy_v3.RouteConfiguration(\"ingress_http\",\n\t\t\t\tenvoy_v3.VirtualHost(\"kuard.projectcontour.io\",\n\t\t\t\t\t&envoy_route_v3.Route{\n\t\t\t\t\t\tMatch: routePrefix(\"/\"),\n\t\t\t\t\t\tAction: routeHostRewrite(\"default/kuard/80/95e871afaf\", \"external.address\"),\n\t\t\t\t\t},\n\t\t\t\t),\n\t\t\t),\n\t\t),\n\t})\n\n\tc.Request(clusterType).Equals(&envoy_discovery_v3.DiscoveryResponse{\n\t\tTypeUrl: clusterType,\n\t\tResources: resources(t,\n\t\t\texternalNameCluster(\"default/kuard/80/95e871afaf\", \"default/kuard\", \"default_kuard_80\", \"foo.io\", 80),\n\t\t),\n\t})\n\n\t// Now try the same configuration, but enable HTTP/2. We\n\t// should still find that the same configuration applies, but\n\t// TLS is enabled and the SNI server name is overwritten from\n\t// the Host header.\n\trh.OnDelete(fixture.NewProxy(\"kuard\").WithSpec(contour_api_v1.HTTPProxySpec{}))\n\trh.OnAdd(fixture.NewProxy(\"kuard\").\n\t\tWithFQDN(\"kuard.projectcontour.io\").\n\t\tWithSpec(contour_api_v1.HTTPProxySpec{\n\t\t\tRoutes: []contour_api_v1.Route{{\n\t\t\t\tServices: []contour_api_v1.Service{{\n\t\t\t\t\tProtocol: ref.To(\"h2\"),\n\t\t\t\t\tName: s1.Name,\n\t\t\t\t\tPort: 80,\n\t\t\t\t}},\n\t\t\t\tRequestHeadersPolicy: &contour_api_v1.HeadersPolicy{\n\t\t\t\t\tSet: []contour_api_v1.HeaderValue{{\n\t\t\t\t\t\tName: \"Host\",\n\t\t\t\t\t\tValue: \"external.address\",\n\t\t\t\t\t}},\n\t\t\t\t},\n\t\t\t}},\n\t\t}),\n\t)\n\n\tc.Request(routeType).Equals(&envoy_discovery_v3.DiscoveryResponse{\n\t\tTypeUrl: routeType,\n\t\tResources: resources(t,\n\t\t\tenvoy_v3.RouteConfiguration(\"ingress_http\",\n\t\t\t\tenvoy_v3.VirtualHost(\"kuard.projectcontour.io\",\n\t\t\t\t\t&envoy_route_v3.Route{\n\t\t\t\t\t\tMatch: routePrefix(\"/\"),\n\t\t\t\t\t\tAction: routeHostRewrite(\"default/kuard/80/cdbf075ad8\", \"external.address\"),\n\t\t\t\t\t},\n\t\t\t\t),\n\t\t\t),\n\t\t),\n\t})\n\n\tc.Request(clusterType).Equals(&envoy_discovery_v3.DiscoveryResponse{\n\t\tTypeUrl: clusterType,\n\t\tResources: resources(t,\n\t\t\tDefaultCluster(\n\t\t\t\texternalNameCluster(\"default/kuard/80/cdbf075ad8\", \"default/kuard\", \"default_kuard_80\", \"foo.io\", 80),\n\t\t\t\t&envoy_cluster_v3.Cluster{\n\t\t\t\t\tTypedExtensionProtocolOptions: map[string]*anypb.Any{\n\t\t\t\t\t\t\"envoy.extensions.upstreams.http.v3.HttpProtocolOptions\": protobuf.MustMarshalAny(\n\t\t\t\t\t\t\t&envoy_extensions_upstream_http_v3.HttpProtocolOptions{\n\t\t\t\t\t\t\t\tUpstreamProtocolOptions: &envoy_extensions_upstream_http_v3.HttpProtocolOptions_ExplicitHttpConfig_{\n\t\t\t\t\t\t\t\t\tExplicitHttpConfig: &envoy_extensions_upstream_http_v3.HttpProtocolOptions_ExplicitHttpConfig{\n\t\t\t\t\t\t\t\t\t\tProtocolConfig: &envoy_extensions_upstream_http_v3.HttpProtocolOptions_ExplicitHttpConfig_Http2ProtocolOptions{},\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t&envoy_cluster_v3.Cluster{\n\t\t\t\t\tTransportSocket: envoy_v3.UpstreamTLSTransportSocket(\n\t\t\t\t\t\tenvoy_v3.UpstreamTLSContext(nil, \"external.address\", nil, \"h2\"),\n\t\t\t\t\t),\n\t\t\t\t},\n\t\t\t),\n\t\t),\n\t})\n\n\t// Now try the same configuration, but enable TLS (which\n\t// means HTTP/1.1 over TLS) rather than HTTP/2. We should get\n\t// TLS enabled with the overridden SNI name. but no HTTP/2\n\t// protocol config.\n\trh.OnDelete(fixture.NewProxy(\"kuard\").WithSpec(contour_api_v1.HTTPProxySpec{}))\n\trh.OnAdd(fixture.NewProxy(\"kuard\").\n\t\tWithFQDN(\"kuard.projectcontour.io\").\n\t\tWithSpec(contour_api_v1.HTTPProxySpec{\n\t\t\tRoutes: []contour_api_v1.Route{{\n\t\t\t\tServices: []contour_api_v1.Service{{\n\t\t\t\t\tProtocol: ref.To(\"tls\"),\n\t\t\t\t\tName: s1.Name,\n\t\t\t\t\tPort: 80,\n\t\t\t\t}},\n\t\t\t\tRequestHeadersPolicy: &contour_api_v1.HeadersPolicy{\n\t\t\t\t\tSet: []contour_api_v1.HeaderValue{{\n\t\t\t\t\t\tName: \"Host\",\n\t\t\t\t\t\tValue: \"external.address\",\n\t\t\t\t\t}},\n\t\t\t\t},\n\t\t\t}},\n\t\t}),\n\t)\n\n\tc.Request(routeType).Equals(&envoy_discovery_v3.DiscoveryResponse{\n\t\tTypeUrl: routeType,\n\t\tResources: resources(t,\n\t\t\tenvoy_v3.RouteConfiguration(\"ingress_http\",\n\t\t\t\tenvoy_v3.VirtualHost(\"kuard.projectcontour.io\",\n\t\t\t\t\t&envoy_route_v3.Route{\n\t\t\t\t\t\tMatch: routePrefix(\"/\"),\n\t\t\t\t\t\tAction: routeHostRewrite(\"default/kuard/80/f9439c1de8\", \"external.address\"),\n\t\t\t\t\t},\n\t\t\t\t),\n\t\t\t),\n\t\t),\n\t})\n\n\tc.Request(clusterType).Equals(&envoy_discovery_v3.DiscoveryResponse{\n\t\tTypeUrl: clusterType,\n\t\tResources: resources(t,\n\t\t\tDefaultCluster(\n\t\t\t\texternalNameCluster(\"default/kuard/80/f9439c1de8\", \"default/kuard\", \"default_kuard_80\", \"foo.io\", 80),\n\t\t\t\t&envoy_cluster_v3.Cluster{\n\t\t\t\t\tTransportSocket: envoy_v3.UpstreamTLSTransportSocket(\n\t\t\t\t\t\tenvoy_v3.UpstreamTLSContext(nil, \"external.address\", nil),\n\t\t\t\t\t),\n\t\t\t\t},\n\t\t\t),\n\t\t),\n\t})\n\n\tsec1 := &v1.Secret{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: \"secret\",\n\t\t\tNamespace: \"default\",\n\t\t},\n\t\tType: \"kubernetes.io/tls\",\n\t\tData: featuretests.Secretdata(featuretests.CERTIFICATE, featuretests.RSA_PRIVATE_KEY),\n\t}\n\n\t// Create TCPProxy with upstream protocol 'tls' to an externalName type service\n\t// and verify that the SNI on the upstream request matches the externalName value.\n\trh.OnDelete(fixture.NewProxy(\"kuard\").WithSpec(contour_api_v1.HTTPProxySpec{}))\n\trh.OnAdd(sec1)\n\trh.OnAdd(fixture.NewProxy(\"kuard\").\n\t\tWithFQDN(\"kuard.projectcontour.io\").\n\t\tWithCertificate(sec1.Name).\n\t\tWithSpec(contour_api_v1.HTTPProxySpec{\n\t\t\tTCPProxy: &contour_api_v1.TCPProxy{\n\t\t\t\tServices: []contour_api_v1.Service{{\n\t\t\t\t\tProtocol: ref.To(\"tls\"),\n\t\t\t\t\tName: s1.Name,\n\t\t\t\t\tPort: 80,\n\t\t\t\t}},\n\t\t\t},\n\t\t}),\n\t)\n\n\tc.Request(clusterType).Equals(&envoy_discovery_v3.DiscoveryResponse{\n\t\tTypeUrl: clusterType,\n\t\tResources: resources(t,\n\t\t\tDefaultCluster(\n\t\t\t\texternalNameCluster(\"default/kuard/80/7d449598f5\", \"default/kuard\", \"default_kuard_80\", \"foo.io\", 80),\n\t\t\t\t&envoy_cluster_v3.Cluster{\n\t\t\t\t\tTransportSocket: envoy_v3.UpstreamTLSTransportSocket(\n\t\t\t\t\t\tenvoy_v3.UpstreamTLSContext(nil, \"foo.io\", nil),\n\t\t\t\t\t),\n\t\t\t\t},\n\t\t\t),\n\t\t),\n\t})\n}", "func setupDiscovery(ctx context.Context, h host.Host) error {\n\t// setup mDNS discovery to find local peers\n\tdisc, err := discovery.NewMdnsService(ctx, h, DiscoveryInterval, DiscoveryServiceTag)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tn := discoveryNotifee{h: h}\n\tdisc.RegisterNotifee(&n)\n\treturn nil\n}", "func fakeDiscovery() discovery.DiscoveryInterface {\n\tfake := &fakediscovery.FakeDiscovery{Fake: &coretesting.Fake{}}\n\tapps := []metav1.APIResource{\n\t\t{Name: \"deployments\", Namespaced: true, Kind: \"Deployment\"},\n\t\t{Name: \"controllerrevisions\", Namespaced: true, Kind: \"ControllerRevision\"},\n\t\t{Name: \"daemonsets\", Namespaced: true, Kind: \"DaemonSet\"},\n\t\t{Name: \"replicasets\", Namespaced: true, Kind: \"ReplicaSet\"},\n\t\t{Name: \"statefulsets\", Namespaced: true, Kind: \"StatefulSet\"},\n\t}\n\tfake.Resources = []*metav1.APIResourceList{\n\t\t{\n\t\t\tGroupVersion: corev1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"bindings\", Namespaced: true, Kind: \"Binding\"},\n\t\t\t\t{Name: \"componentstatuses\", Kind: \"ComponentStatus\"},\n\t\t\t\t{Name: \"configmaps\", Namespaced: true, Kind: \"ConfigMap\"},\n\t\t\t\t{Name: \"endpoints\", Namespaced: true, Kind: \"Endpoints\"},\n\t\t\t\t{Name: \"events\", Namespaced: true, Kind: \"Event\"},\n\t\t\t\t{Name: \"limitranges\", Namespaced: true, Kind: \"LimitRange\"},\n\t\t\t\t{Name: \"namespaces\", Kind: \"Namespace\"},\n\t\t\t\t{Name: \"nodes\", Kind: \"Node\"},\n\t\t\t\t{Name: \"persistentvolumeclaims\", Namespaced: true, Kind: \"PersistentVolumeClaim\"},\n\t\t\t\t{Name: \"persistentvolumes\", Kind: \"PersistentVolume\"},\n\t\t\t\t{Name: \"pods\", Namespaced: true, Kind: \"Pod\"},\n\t\t\t\t{Name: \"podtemplates\", Namespaced: true, Kind: \"PodTemplate\"},\n\t\t\t\t{Name: \"replicationcontrollers\", Namespaced: true, Kind: \"ReplicationController\"},\n\t\t\t\t{Name: \"resourcequotas\", Namespaced: true, Kind: \"ResourceQuota\"},\n\t\t\t\t{Name: \"secrets\", Namespaced: true, Kind: \"Secret\"},\n\t\t\t\t{Name: \"serviceaccounts\", Namespaced: true, Kind: \"ServiceAccount\"},\n\t\t\t\t{Name: \"services\", Namespaced: true, Kind: \"Service\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: rbacv1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"clusterroles\", Kind: \"ClusterRole\"},\n\t\t\t\t{Name: \"clusterrolebindings\", Kind: \"ClusterRoleBinding\"},\n\t\t\t\t{Name: \"clusterroles\", Kind: \"ClusterRole\"},\n\t\t\t\t{Name: \"rolebindings\", Namespaced: true, Kind: \"RoleBinding\"},\n\t\t\t\t{Name: \"roles\", Namespaced: true, Kind: \"Role\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: appsv1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: apps,\n\t\t},\n\t\t{\n\t\t\tGroupVersion: appsv1beta1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: apps,\n\t\t},\n\t\t{\n\t\t\tGroupVersion: appsv1beta2.SchemeGroupVersion.String(),\n\t\t\tAPIResources: apps,\n\t\t},\n\t\t{\n\t\t\tGroupVersion: apiextensionsv1beta1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"customresourcedefinitions\", Kind: \"CustomResourceDefinition\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: apiextensionsv1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"customresourcedefinitions\", Kind: \"CustomResourceDefinition\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: storagev1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"storageclasses\", Kind: \"StorageClass\"},\n\t\t\t\t{Name: \"volumeattachments\", Kind: \"VolumeAttachment\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: storagev1beta1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"storageclasses\", Kind: \"StorageClass\"},\n\t\t\t\t{Name: \"volumeattachments\", Kind: \"VolumeAttachment\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: extensionsv1beta1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"ingresses\", Namespaced: true, Kind: \"Ingress\"},\n\t\t\t\t{Name: \"networkpolicies\", Namespaced: true, Kind: \"NetworkPolicy\"},\n\t\t\t\t{Name: \"podsecuritypolicies\", Kind: \"PodSecurityPolicy\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: networkingv1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"networkpolicies\", Namespaced: true, Kind: \"NetworkPolicy\"},\n\t\t\t\t{Name: \"ingresses\", Namespaced: true, Kind: \"Ingress\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: authenticationv1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"tokenreviews\", Kind: \"TokenReview\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: autoscalingv1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"horizontalpodautoscalers\", Kind: \"HorizontalPodAutoscaler\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: autoscalingv2beta1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"horizontalpodautoscalers\", Kind: \"HorizontalPodAutoscaler\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: autoscalingv2beta2.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"horizontalpodautoscalers\", Kind: \"HorizontalPodAutoscaler\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: policyv1beta1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"poddisruptionbudgets\", Namespaced: true, Kind: \"PodDisruptionBudget\"},\n\t\t\t\t{Name: \"podsecuritypolicies\", Kind: \"PodSecurityPolicy\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: rbacsyncv1alpha.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"clusterrbacsyncconfigs\", Kind: \"ClusterRBACSyncConfig\"},\n\t\t\t\t{Name: \"rbacsyncconfigs\", Namespaced: true, Kind: \"RBACSyncConfig\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: batchv1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"jobs\", Namespaced: true, Kind: \"Job\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: batchv1b1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"cronjobs\", Namespaced: true, Kind: \"CronJob\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: arkv1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"backups\", Namespaced: true, Kind: \"Backup\"},\n\t\t\t\t{Name: \"backupstoragelocations\", Namespaced: true, Kind: \"BackupStorageLocation\"},\n\t\t\t\t{Name: \"configs\", Namespaced: true, Kind: \"Config\"},\n\t\t\t\t{Name: \"deletebackuprequests\", Namespaced: true, Kind: \"DeleteBackupRequest\"},\n\t\t\t\t{Name: \"downloadrequests\", Namespaced: true, Kind: \"DownloadRequest\"},\n\t\t\t\t{Name: \"podvolumebackups\", Namespaced: true, Kind: \"PodVolumeBackup\"},\n\t\t\t\t{Name: \"podvolumerestores\", Namespaced: true, Kind: \"PodVolumeRestore\"},\n\t\t\t\t{Name: \"resticrepositories\", Namespaced: true, Kind: \"ResticRepository\"},\n\t\t\t\t{Name: \"restores\", Namespaced: true, Kind: \"Restore\"},\n\t\t\t\t{Name: \"schedules\", Namespaced: true, Kind: \"Schedule\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: istio.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"sidecar\", Namespaced: true, Kind: \"Sidecar\"},\n\t\t\t\t{Name: \"virtualservice\", Namespaced: true, Kind: \"VirtualService\"},\n\t\t\t\t{Name: \"destinationrule\", Namespaced: true, Kind: \"DestinationRule\"},\n\t\t\t\t{Name: \"gateway\", Namespaced: true, Kind: \"Gateway\"},\n\t\t\t\t{Name: \"serviceentry\", Kind: \"ServiceEntry\"},\n\t\t\t\t{Name: \"envoyfilter\", Namespaced: true, Kind: \"EnvoyFilter\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: istiov1b1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"sidecar\", Namespaced: true, Kind: \"Sidecar\"},\n\t\t\t\t{Name: \"virtualservice\", Namespaced: true, Kind: \"VirtualService\"},\n\t\t\t\t{Name: \"destinationrule\", Namespaced: true, Kind: \"DestinationRule\"},\n\t\t\t\t{Name: \"gateway\", Namespaced: true, Kind: \"Gateway\"},\n\t\t\t\t{Name: \"serviceentry\", Kind: \"ServiceEntry\"},\n\t\t\t\t{Name: \"envoyfilter\", Namespaced: true, Kind: \"EnvoyFilter\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: istiosecurityv1beta1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"authorizationpolicy\", Namespaced: true, Kind: \"AuthorizationPolicy\"},\n\t\t\t\t{Name: \"peerauthentication\", Namespaced: true, Kind: \"PeerAuthentication\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: csr.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"certificatesigningrequests\", Kind: \"CertificateSigningRequest\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: csrv1b1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"certificatesigningrequests\", Kind: \"CertificateSigningRequest\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: admissionregistrationv1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"validatingwebhookconfigurations\", Kind: \"ValidatingWebhookConfiguration\"},\n\t\t\t\t{Name: \"mutatingwebhookconfigurations\", Kind: \"MutatingWebhookConfiguration\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: admissionregistrationv1b1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"validatingwebhookconfigurations\", Kind: \"ValidatingWebhookConfiguration\"},\n\t\t\t\t{Name: \"mutatingwebhookconfigurations\", Kind: \"MutatingWebhookConfiguration\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: schedulingv1beta1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"priorityclass\", Kind: \"PriorityClass\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: schedulingv1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"priorityclass\", Kind: \"PriorityClass\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: apiregistrationv1b1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"apiservice\", Kind: \"APIService\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: apiregistrationv1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"apiservice\", Kind: \"APIService\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: vpav1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"verticalpodautoscalers\", Kind: \"VerticalPodAutoscaler\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: vpav1beta2.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"verticalpodautoscalers\", Kind: \"VerticalPodAutoscaler\"},\n\t\t\t},\n\t\t},\n\t}\n\treturn fake\n}", "func (m *MockPacketHandler) LocalAddr() net.Addr {\n\tret := m.ctrl.Call(m, \"LocalAddr\")\n\tret0, _ := ret[0].(net.Addr)\n\treturn ret0\n}", "func (r *EtcdResolver) JustForTest() {\n\tr.usedForTest = true\n}", "func (m *MockLocalConfigProvider) ListURLs() ([]LocalURL, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ListURLs\")\n\tret0, _ := ret[0].([]LocalURL)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func NewLocalProvider(t []string) Provider {\n\treturn newLocalProviderWithClock(t, clock.New())\n}", "func (sc *ShamClient) fallbackDiscovery() {\n\tif len(sc.localRegistry) == 0 {\n\t\tsc.setLocalRegistry(sc.serviceRegistry.Fallback)\n\t\tsc.logger.Infof(\"using Fallback registry for service %s: %+v\", sc.serviceName, sc.localRegistry)\n\t} else {\n\t\tsc.logger.Infof(\"continue using local registry for service %s: %+v\", sc.serviceName, sc.localRegistry)\n\t}\n}", "func InitLocalPilotTestEnv(t *testing.T) *bootstrap.Server {\n\tinitMutex.Lock()\n\tdefer initMutex.Unlock()\n\n\tports := testenv.NewPorts(testenv.XDSTest)\n\n\tserver := istiotestutil.EnsureTestServer()\n\n\tlocalIP = iputil.GetLocalIP()\n\n\t// Service and endpoints for hello.default - used in v1 pilot tests\n\thostname := model.Hostname(\"hello.default.svc.cluster.local\")\n\tserver.EnvoyXdsServer.MemRegistry.AddService(hostname, &model.Service{\n\t\tHostname: hostname,\n\t\tAddress: \"10.10.0.3\",\n\t\tPorts: testPorts(0),\n\t})\n\tserver.EnvoyXdsServer.MemRegistry.AddInstance(hostname, &model.ServiceInstance{\n\t\tEndpoint: model.NetworkEndpoint{\n\t\t\tAddress: \"127.0.0.1\",\n\t\t\tPort: int(ports.BackendPort),\n\t\t\tServicePort: &model.Port{\n\t\t\t\tName: \"http\",\n\t\t\t\tPort: 80,\n\t\t\t\tProtocol: model.ProtocolHTTP,\n\t\t\t},\n\t\t},\n\t\tAvailabilityZone: \"az\",\n\t})\n\n\t// \"local\" service points to the current host and the in-process mixer http test endpoint\n\tserver.EnvoyXdsServer.MemRegistry.AddService(\"local.default.svc.cluster.local\", &model.Service{\n\t\tHostname: \"local.default.svc.cluster.local\",\n\t\tAddress: \"10.10.0.4\",\n\t\tPorts: []*model.Port{\n\t\t\t{\n\t\t\t\tName: \"http\",\n\t\t\t\tPort: 80,\n\t\t\t\tProtocol: model.ProtocolHTTP,\n\t\t\t}},\n\t})\n\tserver.EnvoyXdsServer.MemRegistry.AddInstance(\"local.default.svc.cluster.local\", &model.ServiceInstance{\n\t\tEndpoint: model.NetworkEndpoint{\n\t\t\tAddress: localIP,\n\t\t\tPort: int(ports.BackendPort),\n\t\t\tServicePort: &model.Port{\n\t\t\t\tName: \"http\",\n\t\t\t\tPort: 80,\n\t\t\t\tProtocol: model.ProtocolHTTP,\n\t\t\t},\n\t\t},\n\t\tAvailabilityZone: \"az\",\n\t})\n\n\t// Explicit test service, in the v2 memory registry. Similar with mock.MakeService,\n\t// but easier to read.\n\tserver.EnvoyXdsServer.MemRegistry.AddService(\"service3.default.svc.cluster.local\", &model.Service{\n\t\tHostname: \"service3.default.svc.cluster.local\",\n\t\tAddress: \"10.10.0.1\",\n\t\tPorts: testPorts(0),\n\t})\n\n\tserver.EnvoyXdsServer.MemRegistry.AddInstance(\"service3.default.svc.cluster.local\", &model.ServiceInstance{\n\t\tEndpoint: model.NetworkEndpoint{\n\t\t\tAddress: app3Ip,\n\t\t\tPort: 2080,\n\t\t\tServicePort: &model.Port{\n\t\t\t\tName: \"http-main\",\n\t\t\t\tPort: 1080,\n\t\t\t\tProtocol: model.ProtocolHTTP,\n\t\t\t},\n\t\t},\n\t\tLabels: map[string]string{\"version\": \"v1\"},\n\t\tAvailabilityZone: \"az\",\n\t})\n\tserver.EnvoyXdsServer.MemRegistry.AddInstance(\"service3.default.svc.cluster.local\", &model.ServiceInstance{\n\t\tEndpoint: model.NetworkEndpoint{\n\t\t\tAddress: gatewayIP,\n\t\t\tPort: 2080,\n\t\t\tServicePort: &model.Port{\n\t\t\t\tName: \"http-main\",\n\t\t\t\tPort: 1080,\n\t\t\t\tProtocol: model.ProtocolHTTP,\n\t\t\t},\n\t\t},\n\t\tLabels: map[string]string{\"version\": \"v2\", \"app\": \"my-gateway-controller\"},\n\t\tAvailabilityZone: \"az\",\n\t})\n\n\t// Mock ingress service\n\tserver.EnvoyXdsServer.MemRegistry.AddService(\"istio-ingress.istio-system.svc.cluster.local\", &model.Service{\n\t\tHostname: \"istio-ingress.istio-system.svc.cluster.local\",\n\t\tAddress: \"10.10.0.2\",\n\t\tPorts: []*model.Port{\n\t\t\t{\n\t\t\t\tName: \"http\",\n\t\t\t\tPort: 80,\n\t\t\t\tProtocol: model.ProtocolHTTP,\n\t\t\t},\n\t\t\t{\n\t\t\t\tName: \"https\",\n\t\t\t\tPort: 443,\n\t\t\t\tProtocol: model.ProtocolHTTPS,\n\t\t\t},\n\t\t},\n\t})\n\tserver.EnvoyXdsServer.MemRegistry.AddInstance(\"istio-ingress.istio-system.svc.cluster.local\", &model.ServiceInstance{\n\t\tEndpoint: model.NetworkEndpoint{\n\t\t\tAddress: ingressIP,\n\t\t\tPort: 80,\n\t\t\tServicePort: &model.Port{\n\t\t\t\tName: \"http\",\n\t\t\t\tPort: 80,\n\t\t\t\tProtocol: model.ProtocolHTTP,\n\t\t\t},\n\t\t},\n\t\tLabels: model.IstioIngressWorkloadLabels,\n\t\tAvailabilityZone: \"az\",\n\t})\n\tserver.EnvoyXdsServer.MemRegistry.AddInstance(\"istio-ingress.istio-system.svc.cluster.local\", &model.ServiceInstance{\n\t\tEndpoint: model.NetworkEndpoint{\n\t\t\tAddress: ingressIP,\n\t\t\tPort: 443,\n\t\t\tServicePort: &model.Port{\n\t\t\t\tName: \"https\",\n\t\t\t\tPort: 443,\n\t\t\t\tProtocol: model.ProtocolHTTPS,\n\t\t\t},\n\t\t},\n\t\tLabels: model.IstioIngressWorkloadLabels,\n\t\tAvailabilityZone: \"az\",\n\t})\n\n\t//RouteConf Service4 is using port 80, to test that we generate multiple clusters (regression)\n\t// service4 has no endpoints\n\tserver.EnvoyXdsServer.MemRegistry.AddService(\"service4.default.svc.cluster.local\", &model.Service{\n\t\tHostname: \"service4.default.svc.cluster.local\",\n\t\tAddress: \"10.1.0.4\",\n\t\tPorts: []*model.Port{\n\t\t\t{\n\t\t\t\tName: \"http-main\",\n\t\t\t\tPort: 80,\n\t\t\t\tProtocol: model.ProtocolHTTP,\n\t\t\t},\n\t\t},\n\t})\n\n\t// Update cache\n\tserver.EnvoyXdsServer.ClearCacheFunc()()\n\n\treturn server\n}", "func testMdns(t *testing.T) {\n\tservice := \"_liqo._tcp\"\n\tdomain := \"local.\"\n\n\tgo clientCluster.discoveryCtrl.Register()\n\n\ttime.Sleep(1 * time.Second)\n\n\ttxts := []*discovery.TxtData{}\n\tclientCluster.discoveryCtrl.Resolve(service, domain, 3, &txts)\n\n\ttime.Sleep(1 * time.Second)\n\n\t// TODO: find better way to test mDNS, local IP is not always detected\n\tassert.Assert(t, len(txts) >= 0, \"If this line is reached test would be successful, no foreign packet can reach our testing environment at the moment\")\n}", "func InitializeForTest(apicClient apic.Client) {\n\tagent.apiMap = cache.New()\n\tagent.apicClient = apicClient\n}", "func TestNewIdentityManager(t *testing.T) {\n\tt.Run(\"success\", func(t *testing.T) {\n\t\tepCfg := &mocks.EndpointConfig{}\n\t\tepCfg.NetworkConfigReturns(&fab.NetworkConfig{\n\t\t\tOrganizations: map[string]fab.OrganizationConfig{\"org1msp\": {}},\n\t\t})\n\n\t\tm, err := newIdentityManager(\"org1MSP\", &mocks.CryptoSuite{}, epCfg, \"./msp\")\n\t\trequire.NoError(t, err)\n\t\trequire.NotNil(t, m)\n\t})\n\n\tt.Run(\"No endpoint config -> error\", func(t *testing.T) {\n\t\tm, err := newIdentityManager(\"org1MSP\", &mocks.CryptoSuite{}, nil, \"./msp\")\n\t\trequire.EqualError(t, err, \"endpoint config is required\")\n\t\trequire.Nil(t, m)\n\t})\n\n\tt.Run(\"No org name -> error\", func(t *testing.T) {\n\t\tm, err := newIdentityManager(\"\", nil, &mocks.EndpointConfig{}, \"./msp\")\n\t\trequire.EqualError(t, err, \"orgName is required\")\n\t\trequire.Nil(t, m)\n\t})\n\n\tt.Run(\"No crypto suite -> error\", func(t *testing.T) {\n\t\tm, err := newIdentityManager(\"org1MSP\", nil, &mocks.EndpointConfig{}, \"./msp\")\n\t\trequire.EqualError(t, err, \"cryptoProvider is required\")\n\t\trequire.Nil(t, m)\n\t})\n\n\tt.Run(\"Org not found -> error\", func(t *testing.T) {\n\t\tepCfg := &mocks.EndpointConfig{}\n\t\tepCfg.NetworkConfigReturns(&fab.NetworkConfig{})\n\n\t\tm, err := newIdentityManager(\"org1MSP\", &mocks.CryptoSuite{}, epCfg, \"./msp\")\n\t\trequire.EqualError(t, err, \"org config retrieval failed\")\n\t\trequire.Nil(t, m)\n\t})\n\n\tt.Run(\"MSP config path not provided -> error\", func(t *testing.T) {\n\t\tepCfg := &mocks.EndpointConfig{}\n\t\tepCfg.NetworkConfigReturns(&fab.NetworkConfig{\n\t\t\tOrganizations: map[string]fab.OrganizationConfig{\"org1msp\": {}},\n\t\t})\n\n\t\tm, err := newIdentityManager(\"org1MSP\", &mocks.CryptoSuite{}, epCfg, \"\")\n\t\trequire.EqualError(t, err, \"either mspConfigPath or an embedded list of users is required\")\n\t\trequire.Nil(t, m)\n\t})\n}", "func TestLogConfigInLocal(t *testing.T) {\n\t// Check if\n}", "func (l *impl) CreateLocalDiscoveryService(mspID string) (fabApi.DiscoveryService, error) {\n\treturn &localDiscoveryService{l.clientConfig, l.localPeer, l.localPeerTLSCertPem}, nil\n}", "func NewLocal(clientProvider context.ClientProvider) (*Local, error) {\n\tclient, err := clientProvider()\n\tif err != nil {\n\t\treturn nil, errors.WithMessage(err, \"failed to get client context to create local context\")\n\t}\n\n\tdiscoveryService, err := client.LocalDiscoveryProvider().CreateLocalDiscoveryService(client.Identifier().MSPID)\n\tif err != nil {\n\t\treturn nil, errors.WithMessage(err, \"failed to create local discovery service\")\n\t}\n\n\tlocal := &Local{\n\t\tClient: client,\n\t\tlocalDiscovery: discoveryService,\n\t}\n\n\tif ci, ok := discoveryService.(localServiceInit); ok {\n\t\tif err := ci.Initialize(local); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn local, nil\n}", "func (_e *MockPlcDriver_Expecter) SupportsDiscovery() *MockPlcDriver_SupportsDiscovery_Call {\n\treturn &MockPlcDriver_SupportsDiscovery_Call{Call: _e.mock.On(\"SupportsDiscovery\")}\n}", "func providerFactory(_ io.Reader) (cloudprovider.Interface, error) {\n\tlog := klogr.NewWithOptions(klogr.WithFormat(klogr.FormatKlog))\n\tc, err := loadConfig(envconfig.OsLookuper())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tapiUrl := katapult.DefaultURL\n\tif c.APIHost != \"\" {\n\t\tlog.Info(\"default API base URL overrided\",\n\t\t\t\"url\", c.APIHost)\n\t\tapiUrl, err = url.Parse(c.APIHost)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to parse provided api url: %w\", err)\n\t\t}\n\t}\n\n\trm, err := katapult.New(\n\t\tkatapult.WithAPIKey(c.APIKey),\n\t\tkatapult.WithBaseURL(apiUrl),\n\t\tkatapult.WithUserAgent(\"kce-ccm\"), // TODO: Add version.\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tclient := core.New(rm)\n\n\treturn &provider{\n\t\tlog: log,\n\t\tkatapult: client,\n\t\tconfig: *c,\n\t\tloadBalancer: &loadBalancerManager{\n\t\t\tlog: log,\n\t\t\tconfig: *c,\n\t\t\tloadBalancerController: client.LoadBalancers,\n\t\t\tloadBalancerRuleController: client.LoadBalancerRules,\n\t\t},\n\t}, nil\n}", "func TestPreparerInterface(t *testing.T) {\n\tt.Parallel()\n\n\tassert.Implements(t, (*resource.Resource)(nil), new(user.Preparer))\n}", "func TestSetupReplaceMock(t *testing.T) {\n\tt.SkipNow()\n\tstudent, mocks, err := MockCluster(false, nil, t)\n\tif err != nil {\n\t\tt.Error(\"Couldn't set up mock cluster\", err)\n\t}\n\n\t// Create a new impl for an rpc function\n\tdenyVote := func(ctx context.Context, req *RequestVoteRequest) (*RequestVoteReply, error) {\n\t\treturn &RequestVoteReply{Term: req.Term, VoteGranted: false}, nil\n\t}\n\n\t// replace the existing impl\n\tmocks[0].RequestVote = denyVote\n\tmocks[1].RequestVote = denyVote\n\n\tmocks[0].JoinCluster()\n\tmocks[1].JoinCluster()\n\n\ttime.Sleep(DefaultConfig().ElectionTimeout * 4)\n\n\tt.Log(\"Student node is:\", student.State)\n\n\tif student.State != CANDIDATE_STATE {\n\t\tt.Error(\"student state was not candidate, was:\", student.State)\n\t}\n\n\t// test as part of an rpc function\n\tmocks[0].RequestVote = func(ctx context.Context, req *RequestVoteRequest) (*RequestVoteReply, error) {\n\t\tt.Logf(\"Mock 0 recieved request vote: last_idx: %v term: %v\", req.GetLastLogIndex(), req.GetLastLogTerm())\n\t\tif req.GetLastLogIndex() != 0 || req.GetLastLogTerm() != 0 {\n\t\t\tt.Errorf(\"Student node failed to request vote correctly: last_idx: %v term: %v\", req.GetLastLogIndex(), req.GetLastLogTerm())\n\t\t}\n\n\t\tif term := student.GetCurrentTerm(); req.GetTerm() != term {\n\t\t\tt.Errorf(\"Student node sent the wrong term: (sent %v, expecting %v)\", req.GetTerm(), term)\n\t\t}\n\t\treturn denyVote(ctx, req)\n\t}\n\n\ttime.Sleep(DefaultConfig().ElectionTimeout * 5)\n}", "func (m *MockClient) InfraProvider() fab.InfraProvider {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"InfraProvider\")\n\tret0, _ := ret[0].(fab.InfraProvider)\n\treturn ret0\n}", "func (_m *Session) LocalAddr() net.Addr {\n\tret := _m.Called()\n\n\tvar r0 net.Addr\n\tif rf, ok := ret.Get(0).(func() net.Addr); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(net.Addr)\n\t\t}\n\t}\n\n\treturn r0\n}", "func (mr *MockClientMockRecorder) LocalDiscoveryProvider() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"LocalDiscoveryProvider\", reflect.TypeOf((*MockClient)(nil).LocalDiscoveryProvider))\n}", "func Test_Provider(t *testing.T) {\n\t// SetLogLevel(\"TRACE\")\n\t// CheckVersion()\n\n\t// Start provider API in the background\n\tgo InitProvider()\n\t// err := InitProvider()\n\t// if err != nil {\n\t// \tlog.Fatalf(\"Error initializing Provider %+v\", err)\n\t// }\n\n\tverifier := HTTPVerifier{}\n\t// Authorization middleware\n\t// This is your chance to modify the request before it hits your provider\n\t// NOTE: this should be used very carefully, as it has the potential to\n\t// _change_ the contract\n\t// f := func(next http.Handler) http.Handler {\n\t// \treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t// \t\tlog.Println(\"[DEBUG] HOOK request filter\")\n\t// \t\t// r.Header.Add(\"Authorization\", \"Bearer 1234-dynamic-value\")\n\t// \t\tnext.ServeHTTP(w, r)\n\t// \t})\n\t// }\n\n\t// Verify the Provider with local Pact Files\n\terr := verifier.VerifyProvider(t, VerifyRequest{\n\t\tProviderBaseURL: \"http://localhost:9000\",\n\t\tBrokerURL: \"http://localhost:9292\",\n\t\tProvider: \"GreetingAPI\",\n\t\tProviderVersion: \"1.0.0\",\n\t\tPublishVerificationResults: true,\n\t\t// PactFiles: []string{\n\t\t// \tfilepath.ToSlash(fmt.Sprintf(\"%s/GreetingAPIConsumer-GreetingAPI.json\", pactDir)),\n\t\t// },\n\t\t// RequestFilter: f,\n\t\t// BeforeEach: func() error {\n\t\t// \tlog.Println(\"[DEBUG] HOOK before each\")\n\t\t// \treturn nil\n\t\t// },\n\t\t// AfterEach: func() error {\n\t\t// \tlog.Println(\"[DEBUG] HOOK after each\")\n\t\t// \treturn nil\n\t\t// },\n\t\t// StateHandlers: StateHandlers{\n\t\t// \t\"User foo exists\": func(setup bool, s ProviderStateV3) (ProviderStateV3Response, error) {\n\n\t\t// \t\tif setup {\n\t\t// \t\t\tlog.Println(\"[DEBUG] HOOK calling user foo exists state handler\", s)\n\t\t// \t\t} else {\n\t\t// \t\t\tlog.Println(\"[DEBUG] HOOK teardown the 'User foo exists' state\")\n\t\t// \t\t}\n\n\t\t// \t\t// ... do something, such as create \"foo\" in the database\n\n\t\t// \t\t// Optionally (if there are generators in the pact) return provider state values to be used in the verification\n\t\t// \t\treturn ProviderStateV3Response{\"uuid\": \"1234\"}, nil\n\t\t// \t},\n\t\t// },\n\t})\n\n\tassert.NoError(t, err)\n}", "func TestNewClient_CustomHttpClient(t *testing.T) {\n\tt.Parallel()\n\n\tclient := NewClient(nil, http.DefaultClient, ProviderPreev)\n\n\tif client == nil {\n\t\tt.Fatal(\"failed to load client\")\n\t}\n\n\t// Test providers\n\tif client.Providers[0] != ProviderPreev {\n\t\tt.Fatalf(\"expected the first provider to be %d, not %d\", ProviderPreev, client.Providers[0])\n\t}\n}", "func MockedProvider(t *testing.T, c *config.Config, callback string) (*config.Config, goth.Provider) {\n\tconst (\n\t\ttestClientKey = \"provider-test-client-key\"\n\t\ttestSecret = \"provider-test-secret\"\n\t\ttestCallback = \"http://auth.exmaple.com/test/callback\"\n\t)\n\tmp := newMockProvider(t, callback)\n\tp := provider.Name(mp.Name())\n\tprovider.AddExternal(p)\n\tt.Cleanup(func() {\n\t\tdelete(provider.External, p)\n\t})\n\tif callback == \"\" {\n\t\tcallback = testCallback\n\t}\n\tc.Authorization.Providers[p] = config.Provider{\n\t\tClientKey: testClientKey,\n\t\tSecret: testSecret,\n\t\tCallbackURL: callback,\n\t}\n\treturn c, mp\n}", "func TestInterdomainFloatingNetworkServiceRegistry(t *testing.T) {\n\tt.Cleanup(func() { goleak.VerifyNone(t) })\n\n\tctx, cancel := context.WithTimeout(context.Background(), time.Second*10)\n\tdefer cancel()\n\n\tdnsServer := sandbox.NewFakeResolver()\n\n\tdomain1 := sandbox.NewBuilder(ctx, t).\n\t\tSetNodesCount(0).\n\t\tSetDNSResolver(dnsServer).\n\t\tBuild()\n\n\tdomain2 := sandbox.NewBuilder(ctx, t).\n\t\tSetNodesCount(0).\n\t\tSetDNSResolver(dnsServer).\n\t\tBuild()\n\n\tdomain3 := sandbox.NewBuilder(ctx, t).\n\t\tSetNodesCount(0).\n\t\tSetRegistryProxySupplier(nil).\n\t\tSetNSMgrProxySupplier(nil).\n\t\tSetDNSResolver(dnsServer).\n\t\tSetDNSDomainName(\"floating.domain\").\n\t\tBuild()\n\n\tregistryClient := registryclient.NewNetworkServiceRegistryClient(ctx,\n\t\tregistryclient.WithDialOptions(grpc.WithTransportCredentials(insecure.NewCredentials())),\n\t\tregistryclient.WithClientURL(domain2.Registry.URL))\n\n\t_, err := registryClient.Register(\n\t\tctx,\n\t\t&registryapi.NetworkService{\n\t\t\tName: \"ns-1@\" + domain3.Name,\n\t\t},\n\t)\n\trequire.Nil(t, err)\n\n\tcc, err := grpc.DialContext(ctx, grpcutils.URLToTarget(domain1.Registry.URL), grpc.WithBlock(), grpc.WithTransportCredentials(insecure.NewCredentials()))\n\trequire.Nil(t, err)\n\tdefer func() {\n\t\t_ = cc.Close()\n\t}()\n\n\tclient := registryapi.NewNetworkServiceRegistryClient(cc)\n\n\tstream, err := client.Find(ctx, &registryapi.NetworkServiceQuery{\n\t\tNetworkService: &registryapi.NetworkService{\n\t\t\tName: \"ns-1@\" + domain3.Name,\n\t\t},\n\t})\n\n\trequire.Nil(t, err)\n\n\tlist := registryapi.ReadNetworkServiceList(stream)\n\n\trequire.Len(t, list, 1)\n\trequire.Equal(t, \"ns-1@\"+domain3.Name, list[0].Name)\n}", "func (sc *ShamClient) discover() error {\n\tsc.logger.Debugf(\"discovering endpoints for service %s\", sc.serviceName)\n\tresponse, err := sc.httpClient.Get(sc.serviceRegistry.URL + \"/sgulreg/services/\" + sc.serviceName)\n\tif err != nil {\n\t\tsc.logger.Errorf(\"Error making service discovery HTTP request: %s\", err)\n\t\tsc.fallbackDiscovery()\n\t\treturn ErrFailedDiscoveryRequest\n\t}\n\tsc.logger.Debugf(\"discovery response content-length: %s\", response.Header.Get(\"Content-length\"))\n\n\tbody, err := ioutil.ReadAll(response.Body)\n\tif err != nil {\n\t\tsc.logger.Errorf(\"Error reading service discovery HTTP response body: %s\", err)\n\t\tsc.fallbackDiscovery()\n\t\treturn ErrFailedDiscoveryResponseBody\n\t}\n\tdefer response.Body.Close()\n\n\tvar serviceInfo registry.ServiceInfoResponse\n\tjson.Unmarshal([]byte(body), &serviceInfo)\n\n\tif len(serviceInfo.Instances) > 0 {\n\t\tvar endpoints []string\n\t\tfor _, instance := range serviceInfo.Instances {\n\t\t\tsc.logger.Debugf(\"discovered service %s endpoint serviceID: %s\", sc.serviceName, instance.InstanceID)\n\t\t\tendpoint := fmt.Sprintf(\"%s://%s%s\", instance.Schema, instance.Host, sc.apiPath)\n\t\t\tendpoints = append(endpoints, endpoint)\n\t\t}\n\n\t\t// sc.localRegistry = endpoints\n\t\tsc.setLocalRegistry(endpoints)\n\t\tsc.logger.Infof(\"discovered service %s endpoints: %+v\", sc.serviceName, sc.localRegistry)\n\t}\n\n\tif len(sc.localRegistry) == 0 {\n\t\t// sc.localRegistry = sc.serviceRegistry.Fallback\n\t\tsc.setLocalRegistry(sc.serviceRegistry.Fallback)\n\t\tsc.logger.Infof(\"using Fallback registry for service %s: %+v\", sc.serviceName, sc.localRegistry)\n\t}\n\n\treturn nil\n}", "func (m *MockLocalConfigProvider) GetName() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetName\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func (m *MockResolver) Lookup(service, key string) (HostInfo, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Lookup\", service, key)\n\tret0, _ := ret[0].(HostInfo)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func newProviderImpl(name string) (Provider, error) {\n\tif name == LOCAL {\n\t\treturn &LocalProvider{}, nil\n\t}\n\n\tif name == AWS {\n\t\treturn &AwsProvider{}, nil\n\t}\n\n\treturn nil, errors.New(fmt.Sprintf(\"Provider '%s' doesn't exist\", name))\n}", "func testInMemoryDataStore() IDataStore {\n return NewInMemoryDataStore();\n}", "func TestInterdomainNetworkServiceRegistry(t *testing.T) {\n\tt.Cleanup(func() { goleak.VerifyNone(t) })\n\n\tctx, cancel := context.WithTimeout(context.Background(), time.Second*10)\n\tdefer cancel()\n\n\tdnsServer := sandbox.NewFakeResolver()\n\n\tdomain1 := sandbox.NewBuilder(ctx, t).\n\t\tSetNodesCount(0).\n\t\tSetDNSResolver(dnsServer).\n\t\tBuild()\n\n\tdomain2 := sandbox.NewBuilder(ctx, t).\n\t\tSetNodesCount(0).\n\t\tSetDNSResolver(dnsServer).\n\t\tSetDNSDomainName(\"cluster.remote\").\n\t\tBuild()\n\n\tclient1 := registryclient.NewNetworkServiceRegistryClient(ctx,\n\t\tregistryclient.WithDialOptions(grpc.WithTransportCredentials(insecure.NewCredentials())),\n\t\tregistryclient.WithClientURL(domain1.Registry.URL))\n\n\tclient2 := registryclient.NewNetworkServiceRegistryClient(ctx,\n\t\tregistryclient.WithDialOptions(grpc.WithTransportCredentials(insecure.NewCredentials())),\n\t\tregistryclient.WithClientURL(domain2.Registry.URL))\n\n\t_, err := client2.Register(context.Background(), &registryapi.NetworkService{Name: \"ns-1\"})\n\trequire.NoError(t, err)\n\n\tstream, err := client1.Find(ctx, &registryapi.NetworkServiceQuery{\n\t\tNetworkService: &registryapi.NetworkService{\n\t\t\tName: \"ns-1@\" + domain2.Name,\n\t\t},\n\t})\n\n\trequire.Nil(t, err)\n\n\tlist := registryapi.ReadNetworkServiceList(stream)\n\n\trequire.Len(t, list, 1)\n\trequire.Equal(t, \"ns-1@\"+domain2.Name, list[0].Name)\n}", "func (m *MockAPI) HostMonitoring() {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"HostMonitoring\")\n}", "func (p *PodmanTestIntegration) StartRemoteService() {\n}", "func Test_Init(t *testing.T) {\n\tclient, err := Load(\"\", true)\n\tassert.Nil(t, err)\n\tmockClient = client\n}", "func TestInterdomainFloatingNetworkServiceRegistry(t *testing.T) {\n\ttool := newInterdomainTestingTool(t)\n\tdefer tool.verifyNoneLeaks()\n\tdefer tool.cleanup()\n\tconst localRegistryDomain = \"domain1.local.registry\"\n\tconst proxyRegistryDomain = \"domain1.proxy.registry\"\n\tconst remoteRegistryDomain = \"domain3.local.registry\"\n\tconst remoteProxyRegistryDomain = \"domain3.proxy.registry\"\n\tconst floatingRegistryDomain = \"domain2.floating.registry\"\n\n\tfMem := memory.NewNetworkServiceRegistryServer()\n\tctx, cancel := context.WithCancel(context.Background())\n\tdefer cancel()\n\n\tproxyRegistryURL1 := tool.startNetworkServiceRegistryServerAsync(proxyRegistryDomain, proxyNSRegistryServer(ctx, localRegistryDomain, tool))\n\ttool.startNetworkServiceRegistryServerAsync(localRegistryDomain, localNSRegistryServer(ctx, proxyRegistryURL1))\n\n\tproxyRegistryURL2 := tool.startNetworkServiceRegistryServerAsync(remoteProxyRegistryDomain, proxyNSRegistryServer(ctx, remoteRegistryDomain, tool))\n\ttool.startNetworkServiceRegistryServerAsync(remoteRegistryDomain, localNSRegistryServer(ctx, proxyRegistryURL2))\n\n\ttool.startNetworkServiceRegistryServerAsync(floatingRegistryDomain, fMem)\n\n\tdomain2Client := registry.NewNetworkServiceRegistryClient(tool.dialDomain(remoteRegistryDomain))\n\t_, err := domain2Client.Register(context.Background(), &registry.NetworkService{\n\t\tName: \"ns-1@\" + floatingRegistryDomain,\n\t})\n\trequire.Nil(t, err)\n\n\tfStream, err := adapters.NetworkServiceServerToClient(fMem).Find(context.Background(), &registry.NetworkServiceQuery{NetworkService: &registry.NetworkService{}})\n\trequire.Nil(t, err)\n\trequire.Len(t, registry.ReadNetworkServiceList(fStream), 1)\n\n\tdomain1Client := registry.NewNetworkServiceRegistryClient(tool.dialDomain(localRegistryDomain))\n\n\tstream, err := domain1Client.Find(context.Background(), &registry.NetworkServiceQuery{\n\t\tNetworkService: &registry.NetworkService{\n\t\t\tName: \"ns-1@\" + floatingRegistryDomain,\n\t\t},\n\t})\n\n\trequire.Nil(t, err)\n\n\tlist := registry.ReadNetworkServiceList(stream)\n\n\trequire.Len(t, list, 1)\n\trequire.Equal(t, \"ns-1@\"+remoteRegistryDomain, list[0].Name)\n}", "func IgrenoreTestP2PServiceRunAddPeer(t *testing.T) {\n\tmockActor := new(MockActorService)\n\tdummyBlock := types.Block{Hash: dummyBlockHash, Header: &types.BlockHeader{BlockNo: dummyBlockHeight}}\n\tmockActor.On(\"CallRequest\", mock.Anything, mock.Anything).Return(message.GetBlockRsp{Block: &dummyBlock}, nil)\n\t//mockMF := new(MockMoFactory)\n\ttarget := &networkTransport{conf: config.NewServerContext(\"\", \"\").GetDefaultConfig().(*config.Config).P2P,\n\t\tlogger:log.NewLogger(\"test.p2p\") }\n\n\ttarget.Host = &mockHost{peerstore.NewPeerstore(pstoremem.NewKeyBook(), pstoremem.NewAddrBook(), pstoremem.NewPeerMetadata())}\n\ttarget.selfMeta.ID = peer.ID(\"gwegw\")\n\n\tsampleAddr1 := PeerMeta{ID: \"ddd\", IPAddress: \"192.168.0.1\", Port: 33888, Outbound: true}\n\tsampleAddr2 := PeerMeta{ID: \"fff\", IPAddress: \"192.168.0.2\", Port: 33888, Outbound: true}\n\ttarget.GetOrCreateStream(sampleAddr1, aergoP2PSub)\n\ttarget.GetOrCreateStream(sampleAddr1, aergoP2PSub)\n\ttime.Sleep(time.Second)\n\tif len(target.Peerstore().Peers()) != 1 {\n\t\tt.Errorf(\"Peer count : Expected %d, Actually %d\", 1, len(target.Peerstore().Peers()))\n\t}\n\ttarget.GetOrCreateStream(sampleAddr2, aergoP2PSub)\n\ttime.Sleep(time.Second * 1)\n\tif len(target.Peerstore().Peers()) != 2 {\n\t\tt.Errorf(\"Peer count : Expected %d, Actually %d\", 2, len(target.Peerstore().Peers()))\n\t}\n}", "func TestLocal(t *testing.T) {\n\tConvey(\"While using Local Shell\", t, func() {\n\n\t\tl := NewLocal()\n\n\t\tConvey(\"The generic Executor test should pass\", func() {\n\t\t\ttestExecutor(t, l)\n\t\t})\n\t})\n\n\tConvey(\"Local Executor with decorations\", t, func() {\n\t\tConvey(\"Should run properly when no decorations are used\", func() {\n\t\t\tl := NewLocalIsolated()\n\t\t\t_, err := l.Execute(\"echo NewLocalIsolated\")\n\t\t\tSo(err, ShouldBeNil)\n\t\t})\n\n\t\tConvey(\"Should run properly when no single decoration is used\", func() {\n\t\t\ttaskSet := isolation.Taskset{CPUList: isolation.NewIntSet(1, 2)}\n\t\t\tl := NewLocalIsolated(taskSet)\n\t\t\t_, err := l.Execute(\"echo NewLocalIsolated\")\n\t\t\tSo(err, ShouldBeNil)\n\t\t})\n\n\t\tConvey(\"Should run properly when multiple decorations are used\", func() {\n\t\t\ttaskSet := isolation.Taskset{CPUList: isolation.NewIntSet(1, 2)}\n\t\t\tl := NewLocalIsolated(taskSet, taskSet)\n\t\t\t_, err := l.Execute(\"echo NewLocalIsolated\")\n\t\t\tSo(err, ShouldBeNil)\n\t\t})\n\t})\n\n\tConvey(\"While using Local Shell using cgroups\", t, func() {\n\t\tuser, err := user.Current()\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Cannot get current user\")\n\t\t}\n\n\t\tif user.Name != \"root\" {\n\t\t\tt.Skipf(\"Need to be privileged user to run cgroups tests\")\n\t\t}\n\n\t\tcmd := exec.Command(\"cgexec\")\n\t\terr = cmd.Run()\n\t\tif err != nil {\n\t\t\tt.Skipf(\"%s\", err)\n\t\t}\n\n\t\tConvey(\"Creating a single cgroup with cpu set for core 0 numa node 0\", func() {\n\t\t\tcpuset, err := cgroup.NewCPUSet(\"/A\", isolation.NewIntSet(0), isolation.NewIntSet(0), false, false)\n\t\t\tSo(err, ShouldBeNil)\n\t\t\tcpuset.Create()\n\t\t\tdefer cpuset.Clean()\n\n\t\t\tl := NewLocalIsolated(cpuset)\n\t\t\ttask, err := l.Execute(\"/bin/echo foobar\")\n\t\t\tSo(err, ShouldBeNil)\n\t\t\tdefer task.EraseOutput()\n\n\t\t\t// Wait until command has terminated.\n\t\t\ttask.Wait(0)\n\n\t\t\t// Ensure task is not running any longer.\n\t\t\ttaskState := task.Status()\n\t\t\tSo(taskState, ShouldEqual, TERMINATED)\n\n\t\t\t// Verify that the exit code represents successful run (exit code 0).\n\t\t\texitcode, err := task.ExitCode()\n\t\t\tSo(err, ShouldBeNil)\n\t\t\tSo(exitcode, ShouldEqual, 0)\n\t\t})\n\n\t\tConvey(\"Creating a two cgroups (cpu shares and memory) for one command\", func() {\n\t\t\tshares := isolation.NewCPUShares(\"/A\", 1024)\n\t\t\tshares.Create()\n\t\t\tdefer shares.Clean()\n\n\t\t\tmemory := isolation.NewMemorySize(\"/A\", 64*1024*1024)\n\t\t\tmemory.Create()\n\t\t\tdefer memory.Clean()\n\n\t\t\tl := NewLocalIsolated(isolation.Decorators{shares, memory})\n\t\t\ttask, err := l.Execute(\"/bin/echo foobar\")\n\t\t\tSo(err, ShouldBeNil)\n\t\t\tdefer task.EraseOutput()\n\n\t\t\t// Wait until command has terminated.\n\t\t\ttask.Wait(0)\n\n\t\t\t// Ensure task is not running any longer.\n\t\t\ttaskState := task.Status()\n\t\t\tSo(taskState, ShouldEqual, TERMINATED)\n\n\t\t\t// Verify that the exit code represents successful run (exit code 0).\n\t\t\texitcode, err := task.ExitCode()\n\t\t\tSo(err, ShouldBeNil)\n\t\t\tSo(exitcode, ShouldEqual, 0)\n\t\t})\n\n\t\tConvey(\"Creating nested cgroups with cpu shares\", func() {\n\t\t\tsharesA := isolation.NewCPUShares(\"/A\", 1024)\n\t\t\tsharesA.Create()\n\t\t\tdefer sharesA.Clean()\n\n\t\t\tsharesB := isolation.NewCPUShares(\"/A/B\", 1024)\n\t\t\tsharesB.Create()\n\t\t\tdefer sharesB.Clean()\n\n\t\t\tsharesC := isolation.NewCPUShares(\"/A/C\", 1024)\n\t\t\tsharesC.Create()\n\t\t\tdefer sharesC.Clean()\n\n\t\t\t// First command.\n\t\t\tl1 := NewLocalIsolated(sharesB)\n\t\t\ttask1, err := l1.Execute(\"/bin/echo foobar\")\n\t\t\tSo(err, ShouldBeNil)\n\t\t\tdefer task1.EraseOutput()\n\n\t\t\t// Wait until command has terminated.\n\t\t\ttask1.Wait(0)\n\n\t\t\t// Ensure task is not running any longer.\n\t\t\ttaskState1 := task1.Status()\n\t\t\tSo(taskState1, ShouldEqual, TERMINATED)\n\n\t\t\t// Verify that the exit code represents successful run (exit code 0).\n\t\t\texitcode1, err := task1.ExitCode()\n\t\t\tSo(err, ShouldBeNil)\n\t\t\tSo(exitcode1, ShouldEqual, 0)\n\n\t\t\t// Second command.\n\t\t\tl2 := NewLocalIsolated(sharesC)\n\t\t\ttask2, err := l2.Execute(\"/bin/echo foobar\")\n\t\t\tSo(err, ShouldBeNil)\n\t\t\tdefer task2.EraseOutput()\n\n\t\t\t// Wait until command has terminated.\n\t\t\ttask2.Wait(0)\n\n\t\t\t// Ensure task is not running any longer.\n\t\t\ttaskState2 := task2.Status()\n\t\t\tSo(taskState2, ShouldEqual, TERMINATED)\n\n\t\t\t// Verify that the exit code represents successful run (exit code 0).\n\t\t\texitcode2, err := task2.ExitCode()\n\t\t\tSo(err, ShouldBeNil)\n\t\t\tSo(exitcode2, ShouldEqual, 0)\n\t\t})\n\t})\n}", "func Test(t *testing.T) {\n\tsuite.Run(t, &DiscoverySuite{})\n}", "func TestFromContext(t *testing.T) {\n\t// Create a mocked peers cache connected to a mock directory\n\tcache, mgds, err := makePeersCache()\n\trequire.NoError(t, err, \"could not create mocked peers cache\")\n\tdefer mgds.Shutdown()\n\n\t// Make assertions about what is being looked up in the GDS\n\tmgds.OnLookup = func(_ context.Context, in *gds.LookupRequest) (out *gds.LookupReply, err error) {\n\t\t// Assert that the expected common name is being looked up\n\t\trequire.Equal(t, \"server.trisa.dev\", in.CommonName, \"unexpected common name in lookup request\")\n\t\trequire.Empty(t, in.Id, \"unexpected id in lookup request\")\n\t\trequire.Empty(t, in.RegisteredDirectory, \"unexpected registered directory in lookup request\")\n\n\t\treturn &gds.LookupReply{\n\t\t\tId: \"0960c00e-68a7-4606-9d0f-ff8537186d34\",\n\t\t\tRegisteredDirectory: \"localhost\",\n\t\t\tCommonName: \"server.trisa.dev\",\n\t\t\tEndpoint: \"server.trisa.dev:4000\",\n\t\t\tName: \"Testing VASP\",\n\t\t\tCountry: \"US\",\n\t\t\tVerifiedOn: \"2022-05-10T22:29:55Z\",\n\t\t}, nil\n\t}\n\n\t// Create an mTLS connection to test the context over bufconn\n\tcerts, pool, err := loadCertificates(\"testdata/server.pem\")\n\trequire.NoError(t, err, \"could not load server certificate fixtures\")\n\n\tremote, err := apimock.NewAuth(nil, certs, pool)\n\trequire.NoError(t, err, \"could not create remote universal mock\")\n\tdefer remote.Shutdown()\n\n\t// Lookup the peer from the directory service and connect it to the remote\n\tpeer, err := cache.Lookup(\"server.trisa.dev\")\n\trequire.NoError(t, err, \"could not lookup peer from directory service\")\n\n\topts := make([]grpc.DialOption, 0, 2)\n\topts = append(opts, grpc.WithContextDialer(remote.Channel().Dialer))\n\n\tclientCerts, clientPool, err := loadCertificates(\"testdata/client.pem\")\n\trequire.NoError(t, err, \"could not load client certificate fixture\")\n\tcreds, err := mtls.ClientCreds(peer.Info().Endpoint, clientCerts, clientPool)\n\trequire.NoError(t, err, \"could not create mtls client credentials\")\n\topts = append(opts, creds)\n\n\terr = peer.Connect(opts...)\n\trequire.NoError(t, err, \"could not connect to remote peer with mtls credentials\")\n\n\t// Setup to get the context from the remote dialer\n\tremote.OnTransfer = func(ctx context.Context, _ *api.SecureEnvelope) (*api.SecureEnvelope, error) {\n\t\t// Ok, after all that work above we finally have an actual gRPC context with mTLS info\n\t\tpeer, err := cache.FromContext(ctx)\n\t\trequire.NoError(t, err, \"could not lookup peer from context\")\n\n\t\tinfo := peer.Info()\n\t\trequire.Equal(t, \"client.trisa.dev\", info.CommonName, \"unknown common name\")\n\n\t\t// Don't return anything\n\t\treturn &api.SecureEnvelope{}, nil\n\t}\n\n\t// Make the request with the client to finish the tests\n\t_, err = peer.Transfer(&api.SecureEnvelope{})\n\trequire.NoError(t, err, \"could not make transfer to initiate from context tests\")\n\n\t// TODO: Test with different certificates to make sure the auth info parsing in FromContext is correct\n}", "func NewFakeProvider(t *testing.T) *FakeProvider {\n\tbuilder := chain.NewBuilder(t, address.Address{})\n\treturn &FakeProvider{\n\t\tBuilder: builder,\n\t\tt: t,\n\t\tactors: make(map[address.Address]*types.Actor)}\n}", "func TestInterdomainNetworkServiceRegistry(t *testing.T) {\n\ttool := newInterdomainTestingTool(t)\n\tdefer tool.verifyNoneLeaks()\n\tdefer tool.cleanup()\n\n\tconst localRegistryDomain = \"domain1.local.registry\"\n\tconst proxyRegistryDomain = \"domain1.proxy.registry\"\n\tconst remoteRegistryDomain = \"domain2.local.registry\"\n\n\tctx, cancel := context.WithCancel(context.Background())\n\tdefer cancel()\n\n\tproxyRegistryURL := tool.startNetworkServiceRegistryServerAsync(proxyRegistryDomain, proxyNSRegistryServer(ctx, localRegistryDomain, tool))\n\ttool.startNetworkServiceRegistryServerAsync(localRegistryDomain, localNSRegistryServer(ctx, proxyRegistryURL))\n\n\tremoteMem := memory.NewNetworkServiceRegistryServer()\n\t_, err := remoteMem.Register(context.Background(), &registry.NetworkService{Name: \"ns-1\"})\n\trequire.Nil(t, err)\n\n\ttool.startNetworkServiceRegistryServerAsync(remoteRegistryDomain, remoteMem)\n\n\tclient := registry.NewNetworkServiceRegistryClient(tool.dialDomain(localRegistryDomain))\n\n\tstream, err := client.Find(context.Background(), &registry.NetworkServiceQuery{\n\t\tNetworkService: &registry.NetworkService{\n\t\t\tName: \"ns-1@\" + remoteRegistryDomain,\n\t\t},\n\t})\n\n\trequire.Nil(t, err)\n\n\tlist := registry.ReadNetworkServiceList(stream)\n\n\trequire.Len(t, list, 1)\n\trequire.Equal(t, \"ns-1@\"+remoteRegistryDomain, list[0].Name)\n}", "func (m *MockRepoClient) LocalPath() (string, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"LocalPath\")\n\tret0, _ := ret[0].(string)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func NewMockDiscoveryService(err error, peers ...fab.Peer) *MockStaticDiscoveryService {\n\treturn &MockStaticDiscoveryService{Error: err, Peers: peers}\n}", "func (sc *ShamClient) setLocalRegistry(endpoints []string) {\n\tsc.lrMutex.Lock()\n\tdefer sc.lrMutex.Unlock()\n\n\tsc.localRegistry = endpoints\n}", "func (m *MockProvider) OnEndpointsSynced() {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"OnEndpointsSynced\")\n}", "func Init(ctx *context.T, name string, auth security.Authorizer, localTag string, discoveryTTL time.Duration) (*context.T, func(), error) {\n\tprotocol, _ := flow.RegisteredProtocol(\"vine\")\n\tv := protocol.(*vine)\n\tctx, cancel := context.WithCancel(ctx)\n\t_, server, err := v23.WithNewServer(ctx, name, VineServer(v), auth)\n\tif err != nil {\n\t\tcancel()\n\t\treturn nil, func() {}, err\n\t}\n\tserverShutdown := func() {\n\t\tcancel()\n\t\t<-server.Closed()\n\t}\n\t// Nodes are not discoverable until the test controller sets nodes as discoverable.\n\tplugin, err := vineplugin.NewWithTTL(ctx, discoveryServerName(localTag), v.discPeers, discoveryTTL)\n\tif err != nil {\n\t\tserverShutdown()\n\t\treturn nil, func() {}, err\n\t}\n\tdf, err := discovery.NewFactory(ctx, plugin)\n\tif err != nil {\n\t\tserverShutdown()\n\t\treturn nil, func() {}, err\n\t}\n\tfactory.InjectFactory(df)\n\tlspec := v23.GetListenSpec(ctx).Copy()\n\tfor i, addr := range lspec.Addrs {\n\t\tlspec.Addrs[i].Protocol = \"vine\"\n\t\tlspec.Addrs[i].Address = createListeningAddress(addr.Protocol, addr.Address)\n\t}\n\tctx = v23.WithListenSpec(ctx, lspec)\n\tctx = WithLocalTag(ctx, localTag)\n\tshutdown := func() {\n\t\tdf.Shutdown()\n\t\tserverShutdown()\n\t}\n\treturn ctx, shutdown, nil\n}", "func TestEndpoints_LocalAlreadyRunning(t *testing.T) {\n\tendpoints1, config1, cleanup1 := newEndpoints(t)\n\tdefer cleanup1()\n\n\trequire.NoError(t, endpoints1.Up(config1))\n\n\tendpoints2, config2, cleanup2 := newEndpoints(t)\n\tconfig2.Dir = config1.Dir\n\tconfig2.UnixSocket = config1.UnixSocket\n\tdefer cleanup2()\n\n\terr := endpoints2.Up(config2)\n\tassert.EqualError(t, err, \"local endpoint: LXD is already running\")\n}", "func setupToDoListServiceTest(t *testing.T) func() {\n\tctrl := gomock.NewController(t)\n\tmockToDoListRepository = ports.NewMockToDoListRepository(ctrl)\n\tdefaultToDoListService = NewToDoListService(mockToDoListRepository)\n\treturn func() {\n\t\tdefaultToDoListService = nil\n\t\tdefer ctrl.Finish()\n\t}\n}", "func (m *MockDirStore) Lookup(arg0, arg1, arg2 string) (buildpack.Descriptor, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Lookup\", arg0, arg1, arg2)\n\tret0, _ := ret[0].(buildpack.Descriptor)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (_m *Interface) Discovery() discovery.DiscoveryInterface {\n\tret := _m.Called()\n\n\tvar r0 discovery.DiscoveryInterface\n\tif rf, ok := ret.Get(0).(func() discovery.DiscoveryInterface); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(discovery.DiscoveryInterface)\n\t\t}\n\t}\n\n\treturn r0\n}", "func (m *MockProviders) InfraProvider() fab.InfraProvider {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"InfraProvider\")\n\tret0, _ := ret[0].(fab.InfraProvider)\n\treturn ret0\n}", "func (s *TestBase) Setup() {\n\tvar err error\n\tshardID := 10\n\tclusterName := s.ClusterMetadata.GetCurrentClusterName()\n\n\ts.DefaultTestCluster.SetupTestDatabase()\n\tif s.VisibilityTestCluster != s.DefaultTestCluster {\n\t\ts.VisibilityTestCluster.SetupTestDatabase()\n\t}\n\n\tcfg := s.DefaultTestCluster.Config()\n\tfactory := client.NewFactory(&cfg, clusterName, nil, s.logger)\n\n\ts.TaskMgr, err = factory.NewTaskManager()\n\ts.fatalOnError(\"NewTaskManager\", err)\n\n\ts.MetadataManager, err = factory.NewMetadataManager()\n\ts.fatalOnError(\"NewMetadataManager\", err)\n\n\ts.HistoryV2Mgr, err = factory.NewHistoryManager()\n\ts.fatalOnError(\"NewHistoryManager\", err)\n\n\ts.ShardMgr, err = factory.NewShardManager()\n\ts.fatalOnError(\"NewShardManager\", err)\n\n\ts.ExecutionMgrFactory = factory\n\ts.ExecutionManager, err = factory.NewExecutionManager(shardID)\n\ts.fatalOnError(\"NewExecutionManager\", err)\n\n\tvisibilityFactory := factory\n\tif s.VisibilityTestCluster != s.DefaultTestCluster {\n\t\tvCfg := s.VisibilityTestCluster.Config()\n\t\tvisibilityFactory = client.NewFactory(&vCfg, clusterName, nil, s.logger)\n\t}\n\t// SQL currently doesn't have support for visibility manager\n\ts.VisibilityMgr, err = visibilityFactory.NewVisibilityManager()\n\tif err != nil {\n\t\ts.fatalOnError(\"NewVisibilityManager\", err)\n\t}\n\n\ts.ReadLevel = 0\n\ts.ReplicationReadLevel = 0\n\ts.ShardInfo = &p.ShardInfo{\n\t\tShardID: shardID,\n\t\tRangeID: 0,\n\t\tTransferAckLevel: 0,\n\t\tReplicationAckLevel: 0,\n\t\tTimerAckLevel: time.Time{},\n\t\tClusterTimerAckLevel: map[string]time.Time{clusterName: time.Time{}},\n\t\tClusterTransferAckLevel: map[string]int64{clusterName: 0},\n\t}\n\n\ts.TaskIDGenerator = &TestTransferTaskIDGenerator{}\n\terr = s.ShardMgr.CreateShard(&p.CreateShardRequest{ShardInfo: s.ShardInfo})\n\ts.fatalOnError(\"CreateShard\", err)\n\n\tqueue, err := factory.NewDomainReplicationQueue()\n\ts.fatalOnError(\"Create DomainReplicationQueue\", err)\n\ts.DomainReplicationQueue = queue\n}", "func (mr *MockProvidersMockRecorder) LocalDiscoveryProvider() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"LocalDiscoveryProvider\", reflect.TypeOf((*MockProviders)(nil).LocalDiscoveryProvider))\n}", "func Discovery(*DiscoveryRequest, *DiscoveryResponse) {}", "func (m *MockProvider) Provide(arg0 string) blobclient.Client {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Provide\", arg0)\n\tret0, _ := ret[0].(blobclient.Client)\n\treturn ret0\n}", "func TestGetCloudProvider(t *testing.T) {\n\tfakeCredFile := \"fake-cred-file.json\"\n\tfakeKubeConfig := \"fake-kube-config\"\n\temptyKubeConfig := \"empty-kube-config\"\n\tfakeContent := `\napiVersion: v1\nclusters:\n- cluster:\n server: https://localhost:8080\n name: foo-cluster\ncontexts:\n- context:\n cluster: foo-cluster\n user: foo-user\n namespace: bar\n name: foo-context\ncurrent-context: foo-context\nkind: Config\nusers:\n- name: foo-user\n user:\n exec:\n apiVersion: client.authentication.k8s.io/v1alpha1\n args:\n - arg-1\n - arg-2\n command: foo-command\n`\n\n\terr := createTestFile(emptyKubeConfig)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tdefer func() {\n\t\tif err := os.Remove(emptyKubeConfig); err != nil {\n\t\t\tt.Error(err)\n\t\t}\n\t}()\n\n\ttests := []struct {\n\t\tdesc string\n\t\tcreateFakeCredFile bool\n\t\tcreateFakeKubeConfig bool\n\t\tkubeconfig string\n\t\tnodeID string\n\t\tuserAgent string\n\t\tallowEmptyCloudConfig bool\n\t\texpectedErr error\n\t}{\n\t\t{\n\t\t\tdesc: \"out of cluster, no kubeconfig, no credential file\",\n\t\t\tkubeconfig: \"\",\n\t\t\tnodeID: \"\",\n\t\t\tallowEmptyCloudConfig: true,\n\t\t\texpectedErr: nil,\n\t\t},\n\t\t{\n\t\t\tdesc: \"[failure][disallowEmptyCloudConfig] out of cluster, no kubeconfig, no credential file\",\n\t\t\tkubeconfig: \"\",\n\t\t\tnodeID: \"\",\n\t\t\tallowEmptyCloudConfig: false,\n\t\t\texpectedErr: nil,\n\t\t},\n\t\t{\n\t\t\tdesc: \"[failure] out of cluster & in cluster, specify a non-exist kubeconfig, no credential file\",\n\t\t\tkubeconfig: \"/tmp/non-exist.json\",\n\t\t\tnodeID: \"\",\n\t\t\tallowEmptyCloudConfig: true,\n\t\t\texpectedErr: nil,\n\t\t},\n\t\t{\n\t\t\tdesc: \"[failure] out of cluster & in cluster, specify a empty kubeconfig, no credential file\",\n\t\t\tkubeconfig: emptyKubeConfig,\n\t\t\tnodeID: \"\",\n\t\t\tallowEmptyCloudConfig: true,\n\t\t\texpectedErr: fmt.Errorf(\"failed to get KubeClient: invalid configuration: no configuration has been provided, try setting KUBERNETES_MASTER environment variable\"),\n\t\t},\n\t\t{\n\t\t\tdesc: \"[failure] out of cluster & in cluster, specify a fake kubeconfig, no credential file\",\n\t\t\tcreateFakeKubeConfig: true,\n\t\t\tkubeconfig: fakeKubeConfig,\n\t\t\tnodeID: \"\",\n\t\t\tallowEmptyCloudConfig: true,\n\t\t\texpectedErr: nil,\n\t\t},\n\t\t{\n\t\t\tdesc: \"[success] out of cluster & in cluster, no kubeconfig, a fake credential file\",\n\t\t\tcreateFakeCredFile: true,\n\t\t\tkubeconfig: \"\",\n\t\t\tnodeID: \"\",\n\t\t\tuserAgent: \"useragent\",\n\t\t\tallowEmptyCloudConfig: true,\n\t\t\texpectedErr: nil,\n\t\t},\n\t}\n\n\tfor _, test := range tests {\n\t\tif test.createFakeKubeConfig {\n\t\t\tif err := createTestFile(fakeKubeConfig); err != nil {\n\t\t\t\tt.Error(err)\n\t\t\t}\n\t\t\tdefer func() {\n\t\t\t\tif err := os.Remove(fakeKubeConfig); err != nil {\n\t\t\t\t\tt.Error(err)\n\t\t\t\t}\n\t\t\t}()\n\n\t\t\tif err := os.WriteFile(fakeKubeConfig, []byte(fakeContent), 0666); err != nil {\n\t\t\t\tt.Error(err)\n\t\t\t}\n\t\t}\n\t\tif test.createFakeCredFile {\n\t\t\tif err := createTestFile(fakeCredFile); err != nil {\n\t\t\t\tt.Error(err)\n\t\t\t}\n\t\t\tdefer func() {\n\t\t\t\tif err := os.Remove(fakeCredFile); err != nil {\n\t\t\t\t\tt.Error(err)\n\t\t\t\t}\n\t\t\t}()\n\n\t\t\toriginalCredFile, ok := os.LookupEnv(DefaultAzureCredentialFileEnv)\n\t\t\tif ok {\n\t\t\t\tdefer os.Setenv(DefaultAzureCredentialFileEnv, originalCredFile)\n\t\t\t} else {\n\t\t\t\tdefer os.Unsetenv(DefaultAzureCredentialFileEnv)\n\t\t\t}\n\t\t\tos.Setenv(DefaultAzureCredentialFileEnv, fakeCredFile)\n\t\t}\n\t\tcloud, err := getCloudProvider(test.kubeconfig, test.nodeID, \"\", \"\", test.userAgent, test.allowEmptyCloudConfig, 25.0, 50)\n\t\tif !reflect.DeepEqual(err, test.expectedErr) && test.expectedErr != nil && !strings.Contains(err.Error(), test.expectedErr.Error()) {\n\t\t\tt.Errorf(\"desc: %s,\\n input: %q, GetCloudProvider err: %v, expectedErr: %v\", test.desc, test.kubeconfig, err, test.expectedErr)\n\t\t}\n\t\tif cloud == nil {\n\t\t\tt.Errorf(\"return value of getCloudProvider should not be nil even there is error\")\n\t\t} else {\n\t\t\tassert.Equal(t, cloud.Environment.StorageEndpointSuffix, storage.DefaultBaseURL)\n\t\t\tassert.Equal(t, cloud.UserAgent, test.userAgent)\n\t\t}\n\t}\n}", "func hackClusterConfigForLocalTestingInKIND(\n\tremoteCluster *api.Cluster,\n\tremoteContextName, clusterDomainOverride string,\n) error {\n\tserverUrl, err := url.Parse(remoteCluster.Server)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif strings.HasPrefix(remoteContextName, \"kind-\") &&\n\t\t(serverUrl.Hostname() == \"127.0.0.1\" || serverUrl.Hostname() == \"localhost\") &&\n\t\tclusterDomainOverride != \"\" {\n\n\t\tremoteCluster.Server = fmt.Sprintf(\"https://%s:%s\", clusterDomainOverride, serverUrl.Port())\n\t\tremoteCluster.InsecureSkipTLSVerify = true\n\t\tremoteCluster.CertificateAuthority = \"\"\n\t\tremoteCluster.CertificateAuthorityData = []byte(\"\")\n\t}\n\n\treturn nil\n}", "func (m *MockProvider) OnServiceSynced() {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"OnServiceSynced\")\n}", "func (m *MockBKDataApiConfigInformer) Lister() v10.BKDataApiConfigLister {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Lister\")\n\tret0, _ := ret[0].(v10.BKDataApiConfigLister)\n\treturn ret0\n}", "func (m *MockLocalConfigProvider) Exists() bool {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Exists\")\n\tret0, _ := ret[0].(bool)\n\treturn ret0\n}", "func Local(clArgs []string, stdin io.Reader, stdout, stderr io.Writer, reg *testing.Registry, d Delegate) int {\n\tcfg := NewStaticConfig(reg, localTestTimeout, d)\n\treturn run(context.Background(), clArgs, stdin, stdout, stderr, cfg)\n}", "func StartMockups() {\n\tenabledMocks = true\n}", "func (p *TestProvider) Provide(addr string) Client {\n\tc, ok := p.clients[addr]\n\tif !ok {\n\t\tlog.Panicf(\"addr %s not found\", addr)\n\t}\n\treturn c\n}", "func (_m *ComputeAPI) LookupClusters(project string) ([]*container.Cluster, error) {\n\tret := _m.Called(project)\n\n\tvar r0 []*container.Cluster\n\tif rf, ok := ret.Get(0).(func(string) []*container.Cluster); ok {\n\t\tr0 = rf(project)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).([]*container.Cluster)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(string) error); ok {\n\t\tr1 = rf(project)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func TestLookup(t *testing.T) {\n\t// Create a mocked peers cache connected to a mock directory\n\tcache, mgds, err := makePeersCache()\n\trequire.NoError(t, err, \"could not create mocked peers cache\")\n\tdefer mgds.Shutdown()\n\n\t// Handle the case where the GDS returns an error\n\tmgds.UseError(gdsmock.LookupRPC, codes.NotFound, \"could not find peer with that common name\")\n\tpeer, err := cache.Lookup(\"unknown\")\n\trequire.EqualError(t, err, \"rpc error: code = NotFound desc = could not find peer with that common name\")\n\trequire.Nil(t, peer, \"peer should be nil when an error is returned\")\n\n\t// Handle the case where the GDS returns an error in the lookup reply\n\tmgds.OnLookup = func(context.Context, *gds.LookupRequest) (*gds.LookupReply, error) {\n\t\treturn &gds.LookupReply{\n\t\t\tError: &gds.Error{\n\t\t\t\tCode: 99,\n\t\t\t\tMessage: \"the GDS really shouldn't be returning these errors\",\n\t\t\t},\n\t\t}, nil\n\t}\n\n\tpeer, err = cache.Lookup(\"unknown\")\n\trequire.EqualError(t, err, \"[99] the GDS really shouldn't be returning these errors\")\n\trequire.Nil(t, peer, \"peer should be nil when an error is returned\")\n\n\t// Lookup should not error if GDS returns a nil identity and nil signing certificate\n\trequire.NoError(t, mgds.UseFixture(gdsmock.LookupRPC, \"testdata/leonardo.trisa.dev.pb.json\"))\n\tpeer, err = cache.Lookup(\"leonardo.trisa.dev\")\n\trequire.NoError(t, err, \"could not lookup peer from directory service\")\n\trequire.Nil(t, peer.SigningKey(), \"signing key should be nil when no certificate is returned\")\n\n\t// Configure a reply fixture for the other lookup test cases\n\treply := &gds.LookupReply{}\n\trequire.NoError(t, loadGRPCFixture(\"testdata/leonardo.trisa.dev.pb.json\", reply))\n\tmgds.OnLookup = func(context.Context, *gds.LookupRequest) (*gds.LookupReply, error) {\n\t\treturn reply, nil\n\t}\n\n\t// Generate keys to distinguish between identity and signing certificates\n\torigCert, origKey, err := generateCertificate()\n\trequire.NoError(t, err, \"could not generate certificate\")\n\tidentityCert, _, err := generateCertificate()\n\trequire.NoError(t, err, \"could not generate certificate\")\n\tsigningCert, signingKey, err := generateCertificate()\n\trequire.NoError(t, err, \"could not generate certificate\")\n\n\t// Lookup should store the identity key if the identity certificate is available on the lookup reply\n\treply.CommonName = \"identity\"\n\treply.IdentityCertificate = origCert\n\tpeer, err = cache.Lookup(\"identity\")\n\trequire.NoError(t, err, \"could not lookup peer from directory service\")\n\trequire.Equal(t, origKey, peer.SigningKey(), \"identity key should be stored\")\n\n\t// Lookup should not overwrite an existing key on the peer\n\treply.IdentityCertificate = identityCert\n\tpeer, err = cache.Lookup(\"identity\")\n\trequire.NoError(t, err, \"could not lookup peer from directory service\")\n\trequire.Equal(t, origKey, peer.SigningKey(), \"identity key should not be overwritten\")\n\n\t// Lookup should store the signing key if the signing certificate is available on the lookup reply\n\treply.CommonName = \"signing\"\n\treply.IdentityCertificate = nil\n\treply.SigningCertificate = signingCert\n\tpeer, err = cache.Lookup(\"signing\")\n\trequire.NoError(t, err, \"could not lookup peer from directory service\")\n\trequire.Equal(t, signingKey, peer.SigningKey(), \"signing key should be stored\")\n\n\t// Lookup should prefer the signing certificate over the identity certificate if both are available on the lookup reply\n\treply.CommonName = \"both\"\n\treply.IdentityCertificate = identityCert\n\treply.SigningCertificate = signingCert\n\tpeer, err = cache.Lookup(\"both\")\n\trequire.NoError(t, err, \"could not lookup peer from directory service\")\n\trequire.Equal(t, signingKey, peer.SigningKey(), \"signing key should be stored\")\n\n\t// Handle the case where the GDS returns valid responses\n\tmgds.Reset()\n\tmgds.OnLookup = func(_ context.Context, in *gds.LookupRequest) (out *gds.LookupReply, err error) {\n\t\tout = &gds.LookupReply{}\n\t\tswitch in.CommonName {\n\t\tcase \"leonardo.trisa.dev\":\n\t\t\tif err = loadGRPCFixture(\"testdata/leonardo.trisa.dev.pb.json\", out); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\tcase \"donatello.example.com\":\n\t\t\tif err = loadGRPCFixture(\"testdata/donatello.example.com.pb.json\", out); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\tdefault:\n\t\t\treturn nil, status.Error(codes.NotFound, \"unknown TRISA counterparty\")\n\t\t}\n\t\treturn out, nil\n\t}\n\n\t// Test concurrent Lookup calls\n\tt.Run(\"lookup\", func(t *testing.T) {\n\t\ttests := []struct {\n\t\t\tname string\n\t\t\tpeer string\n\t\t}{\n\t\t\t{\"lookup-leonardo\", \"leonardo.trisa.dev\"},\n\t\t\t{\"lookup-donatello\", \"donatello.example.com\"},\n\t\t}\n\t\tfor _, tt := range tests {\n\t\t\ttt := tt\n\t\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\t\tt.Parallel()\n\t\t\t\tp, err := cache.Lookup(tt.peer)\n\t\t\t\trequire.NoError(t, err)\n\t\t\t\trequire.NotNil(t, p)\n\t\t\t})\n\t\t}\n\t})\n\n\trequire.Equal(t, 0, mgds.Calls[gdsmock.SearchRPC])\n\trequire.Equal(t, 2, mgds.Calls[gdsmock.LookupRPC])\n\trequire.Equal(t, 0, mgds.Calls[gdsmock.StatusRPC])\n\n\t// Cache should contain the two peers\n\tleonardo, err := cache.Get(\"leonardo.trisa.dev\")\n\trequire.NoError(t, err)\n\trequire.Equal(t, \"19d84515-007a-48cc-9efd-b153a263e77c\", leonardo.Info().ID)\n\trequire.Equal(t, \"testdirectory.org\", leonardo.Info().RegisteredDirectory)\n\trequire.Equal(t, \"leonardo.trisa.dev\", leonardo.Info().CommonName)\n\trequire.Equal(t, \"leonardo.trisa.dev:8000\", leonardo.Info().Endpoint)\n\n\tdonatello, err := cache.Get(\"donatello.example.com\")\n\trequire.NoError(t, err)\n\trequire.Equal(t, \"b19c9ebd-82f5-4bda-91ef-226e3ecee4b8\", donatello.Info().ID)\n\trequire.Equal(t, \"testdirectory.org\", donatello.Info().RegisteredDirectory)\n\trequire.Equal(t, \"donatello.example.com\", donatello.Info().CommonName)\n\trequire.Equal(t, \"donatello.example.com:443\", donatello.Info().Endpoint)\n}", "func TestSetupMock(t *testing.T) {\n\tt.SkipNow()\n\tstudent, mocks, err := MockCluster(true, nil, t)\n\tif err != nil {\n\t\tt.Error(\"Couldn't set up mock cluster\", err)\n\t}\n\n\tt.Log(\"Created student node:\", student)\n\tt.Log(\"Created mock nodes:\", mocks)\n\n\ttime.Sleep(DefaultConfig().ElectionTimeout * 2)\n\tt.Log(\"Student node is:\", student.State)\n\ttime.Sleep(DefaultConfig().ElectionTimeout * 2)\n\tt.Log(\"Student node is:\", student.State)\n}", "func (self *discovery) callDiscoveryService(action string, successState bool) error {\n\tlog.Infof(\"[Server] Attempting to %s with the discovery service...\", action)\n\n\tazName, _ := util.GetAwsAZName()\n\tregSize := reg.size()\n\tmachineClass := os.Getenv(\"H2O_MACHINE_CLASS\")\n\n\tendpoints := make([]*register.MultiRequest_Endpoint, regSize)\n\ti := 0\n\tfor _, endpoint := range reg.iterate() {\n\t\tendpoints[i] = &register.MultiRequest_Endpoint{\n\t\t\tName: proto.String(endpoint.Name),\n\t\t\tMean: proto.Int32(endpoint.Mean),\n\t\t\tUpper95: proto.Int32(endpoint.Upper95),\n\t\t\tSubscribe: proto.String(endpoint.Subscribe),\n\t\t}\n\n\t\ti++\n\t}\n\n\tservice := &dscShared.Service{\n\t\tName: proto.String(Name),\n\t\tDescription: proto.String(Description),\n\t\tVersion: proto.Uint64(Version),\n\t\tSource: proto.String(Source),\n\t\tOwnerEmail: proto.String(OwnerEmail),\n\t\tOwnerMobile: proto.String(OwnerMobile),\n\t\tOwnerTeam: proto.String(OwnerTeam),\n\t}\n\n\trequest, err := ScopedRequest(\n\t\t\"com.HailoOSS.kernel.discovery\",\n\t\taction,\n\t\t&register.MultiRequest{\n\t\t\tInstanceId: proto.String(InstanceID),\n\t\t\tHostname: proto.String(self.hostname),\n\t\t\tMachineClass: proto.String(machineClass),\n\t\t\tAzName: proto.String(azName),\n\t\t\tService: service,\n\t\t\tEndpoints: endpoints,\n\t\t},\n\t)\n\n\tif err != nil {\n\t\tlog.Warnf(\"[Server] Failed to build request when %sing services\", action)\n\t\treturn err\n\t}\n\n\t// explicitly define timeout, since we're happy to wait\n\tclientOptions := client.Options{\"retries\": 0, \"timeout\": 5 * time.Second}\n\n\trsp := &register.Response{}\n\tif err := client.Req(request, rsp, clientOptions); err != nil {\n\t\tlog.Warnf(\"[Server] Failed to %s services: %v\", action, err)\n\t\treturn err\n\t}\n\n\t// ok -- all done!\n\tself.connected = successState\n\tlog.Infof(\"[Server] Successfully %sed with the hive mind!\", action)\n\n\treturn nil\n}", "func NewMockInterfaceProvider(managedInterfacesRegexp string, autoRefresh bool) (nt.InterfaceProvider,\n\tchan time.Time, error) {\n\tch := make(chan time.Time)\n\tip, err := nt.NewChanInterfaceProvider(ch, &MockInterfaceLister{}, managedInterfacesRegexp,\n\t\tautoRefresh)\n\treturn ip, ch, err\n}", "func (bil *baseInstanceList) newMockCloud() cloud.Cloud {\n\tc := cloud.NewMockGCE(nil)\n\n\t// insert hooks to lazy create a instance when needed\n\tc.MockInstances.GetHook = bil.newGAGetHook()\n\tc.MockBetaInstances.GetHook = bil.newBetaGetHook()\n\n\treturn c\n}", "func unmanagedProviderFactory(provider addrs.Provider, reattach *plugin.ReattachConfig) providers.Factory {\n\treturn func() (providers.Interface, error) {\n\t\tconfig := &plugin.ClientConfig{\n\t\t\tHandshakeConfig: tfplugin.Handshake,\n\t\t\tLogger: logging.NewProviderLogger(\"unmanaged.\"),\n\t\t\tAllowedProtocols: []plugin.Protocol{plugin.ProtocolGRPC},\n\t\t\tManaged: false,\n\t\t\tReattach: reattach,\n\t\t\tSyncStdout: logging.PluginOutputMonitor(fmt.Sprintf(\"%s:stdout\", provider)),\n\t\t\tSyncStderr: logging.PluginOutputMonitor(fmt.Sprintf(\"%s:stderr\", provider)),\n\t\t}\n\n\t\tif reattach.ProtocolVersion == 0 {\n\t\t\t// As of the 0.15 release, sdk.v2 doesn't include the protocol\n\t\t\t// version in the ReattachConfig (only recently added to\n\t\t\t// go-plugin), so client.NegotiatedVersion() always returns 0. We\n\t\t\t// assume that an unmanaged provider reporting protocol version 0 is\n\t\t\t// actually using proto v5 for backwards compatibility.\n\t\t\tif defaultPlugins, ok := tfplugin.VersionedPlugins[5]; ok {\n\t\t\t\tconfig.Plugins = defaultPlugins\n\t\t\t} else {\n\t\t\t\treturn nil, errors.New(\"no supported plugins for protocol 0\")\n\t\t\t}\n\t\t} else if plugins, ok := tfplugin.VersionedPlugins[reattach.ProtocolVersion]; !ok {\n\t\t\treturn nil, fmt.Errorf(\"no supported plugins for protocol %d\", reattach.ProtocolVersion)\n\t\t} else {\n\t\t\tconfig.Plugins = plugins\n\t\t}\n\n\t\tclient := plugin.NewClient(config)\n\t\trpcClient, err := client.Client()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\traw, err := rpcClient.Dispense(tfplugin.ProviderPluginName)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// store the client so that the plugin can kill the child process\n\t\tprotoVer := client.NegotiatedVersion()\n\t\tswitch protoVer {\n\t\tcase 0, 5:\n\t\t\t// As of the 0.15 release, sdk.v2 doesn't include the protocol\n\t\t\t// version in the ReattachConfig (only recently added to\n\t\t\t// go-plugin), so client.NegotiatedVersion() always returns 0. We\n\t\t\t// assume that an unmanaged provider reporting protocol version 0 is\n\t\t\t// actually using proto v5 for backwards compatibility.\n\t\t\tp := raw.(*tfplugin.GRPCProvider)\n\t\t\tp.PluginClient = client\n\t\t\treturn p, nil\n\t\tcase 6:\n\t\t\tp := raw.(*tfplugin6.GRPCProvider)\n\t\t\tp.PluginClient = client\n\t\t\treturn p, nil\n\t\tdefault:\n\t\t\treturn nil, fmt.Errorf(\"unsupported protocol version %d\", protoVer)\n\t\t}\n\t}\n}", "func (m *MockRemotes) Lookup(arg0 string) (*git.Remote, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Lookup\", arg0)\n\tret0, _ := ret[0].(*git.Remote)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (c *Clientset) Discovery() discovery.DiscoveryInterface {\n\treturn c.FakeDiscovery\n}", "func (ds *localDiscoveryService) Initialize(ctx contextAPI.Local) error {\r\n\tds.mspID = ctx.Identifier().MSPID\r\n\treturn nil\r\n}", "func NewlocalShimClient(c *config.ClusterControllerConfig) ShimServiceClient {\n\tk8sClient, err := k8sclient.NewK8sClient(k8sclient.K8sOption{KubeConfig: c.KubeConfig})\n\tif err != nil {\n\t\tklog.Errorf(\"failed to create k8s client: %v\", err)\n\t\treturn nil\n\t}\n\n\tlocal := &localShimClient{\n\t\thandlers: make(map[string]handler.Handler),\n\t}\n\n\tlocal.handlers[otev1.ClusterControllerDestAPI] = handler.NewK8sHandler(k8sClient)\n\tlocal.handlers[otev1.ClusterControllerDestHelm] = handler.NewHTTPProxyHandler(c.HelmTillerAddr)\n\treturn local\n}", "func ProviderTest(initial Initial, observer invoker.Observer, settings Settings) (Configurator, func(), error) {\n\tc, e := NewMockConfigurator(initial, observer, settings)\n\treturn c, func() {}, e\n}", "func newDiscoveryTool(\n\tregions []string,\n\tproject string,\n\tlg telegraf.Logger,\n\tcredential auth.Credential,\n\trateLimit int,\n\tdiscoveryInterval time.Duration,\n) (*discoveryTool, error) {\n\tvar (\n\t\tdscReq = map[string]discoveryRequest{}\n\t\tcli = map[string]aliyunSdkClient{}\n\t\tresponseRootKey string\n\t\tresponseObjectIDKey string\n\t\terr error\n\t\tnoDiscoverySupportErr = fmt.Errorf(\"no discovery support for project %q\", project)\n\t)\n\n\tif len(regions) == 0 {\n\t\tregions = aliyunRegionList\n\t\tlg.Infof(\"'regions' is not provided! Discovery data will be queried across %d regions:\\n%s\",\n\t\t\tlen(aliyunRegionList), strings.Join(aliyunRegionList, \",\"))\n\t}\n\n\tif rateLimit == 0 { //Can be a rounding case\n\t\trateLimit = 1\n\t}\n\n\tfor _, region := range regions {\n\t\tswitch project {\n\t\tcase \"acs_ecs_dashboard\":\n\t\t\tdscReq[region] = ecs.CreateDescribeInstancesRequest()\n\t\t\tresponseRootKey = \"Instances\"\n\t\t\tresponseObjectIDKey = \"InstanceId\"\n\t\tcase \"acs_rds_dashboard\":\n\t\t\tdscReq[region] = rds.CreateDescribeDBInstancesRequest()\n\t\t\tresponseRootKey = \"Items\"\n\t\t\tresponseObjectIDKey = \"DBInstanceId\"\n\t\tcase \"acs_slb_dashboard\":\n\t\t\tdscReq[region] = slb.CreateDescribeLoadBalancersRequest()\n\t\t\tresponseRootKey = \"LoadBalancers\"\n\t\t\tresponseObjectIDKey = \"LoadBalancerId\"\n\t\tcase \"acs_memcache\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_ocs\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_oss\":\n\t\t\t// oss is really complicated and its' own format\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_vpc_eip\":\n\t\t\tdscReq[region] = vpc.CreateDescribeEipAddressesRequest()\n\t\t\tresponseRootKey = \"EipAddresses\"\n\t\t\tresponseObjectIDKey = \"AllocationId\"\n\t\tcase \"acs_kvstore\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_mns_new\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_cdn\":\n\t\t\t//API replies are in its own format.\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_polardb\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_gdb\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_ads\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_mongodb\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_express_connect\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_fc\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_nat_gateway\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_sls_dashboard\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_containerservice_dashboard\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_vpn\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_bandwidth_package\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_cen\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_ens\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_opensearch\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_scdn\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_drds\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_iot\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_directmail\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_elasticsearch\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_ess_dashboard\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_streamcompute\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_global_acceleration\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_hitsdb\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_kafka\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_openad\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_pcdn\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_dcdn\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_petadata\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_videolive\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_hybriddb\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_adb\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_mps\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_maxcompute_prepay\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_hdfs\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_ddh\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_hbr\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_hdr\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tcase \"acs_cds\":\n\t\t\treturn nil, noDiscoverySupportErr\n\t\tdefault:\n\t\t\treturn nil, fmt.Errorf(\"project %q is not recognized by discovery\", project)\n\t\t}\n\n\t\tcli[region], err = sdk.NewClientWithOptions(region, sdk.NewConfig(), credential)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tif len(dscReq) == 0 || len(cli) == 0 {\n\t\treturn nil, fmt.Errorf(\"can't build discovery request for project: %q, regions: %v\", project, regions)\n\t}\n\n\treturn &discoveryTool{\n\t\treq: dscReq,\n\t\tcli: cli,\n\t\trespRootKey: responseRootKey,\n\t\trespObjectIDKey: responseObjectIDKey,\n\t\trateLimit: rateLimit,\n\t\tinterval: discoveryInterval,\n\t\treqDefaultPageSize: 20,\n\t\tdataChan: make(chan map[string]interface{}, 1),\n\t\tlg: lg,\n\t}, nil\n}", "func TestInternalInit(t *testing.T) {\n\tvar err error\n\n\t// delete the default path\n\tdbPath := filepath.Join(fs.CacheDir, \"cache-backend\", *RemoteName+\".db\")\n\tboltDb, err = cache.GetPersistent(dbPath, &cache.Features{PurgeDb: true})\n\trequire.NoError(t, err)\n\tfstest.Initialise()\n\n\tif len(*WrapRemote) == 0 {\n\t\t*WrapRemote = \"localInternal:/var/tmp/rclone-cache\"\n\t\tfs.ConfigFileSet(\"localInternal\", \"type\", \"local\")\n\t\tfs.ConfigFileSet(\"localInternal\", \"nounc\", \"true\")\n\t}\n\n\tremoteExists := false\n\tfor _, s := range fs.ConfigFileSections() {\n\t\tif s == *RemoteName {\n\t\t\tremoteExists = true\n\t\t}\n\t}\n\n\tif !remoteExists {\n\t\tfs.ConfigFileSet(*RemoteName, \"type\", \"cache\")\n\t\tfs.ConfigFileSet(*RemoteName, \"remote\", *WrapRemote)\n\t\tfs.ConfigFileSet(*RemoteName, \"chunk_size\", \"1024\")\n\t\tfs.ConfigFileSet(*RemoteName, \"chunk_total_size\", \"2048\")\n\t\tfs.ConfigFileSet(*RemoteName, \"info_age\", infoAge.String())\n\t}\n\n\t_ = flag.Set(\"cache-chunk-no-memory\", \"true\")\n\t_ = flag.Set(\"cache-workers\", strconv.Itoa(workers))\n\t_ = flag.Set(\"cache-chunk-clean-interval\", chunkClean.String())\n\n\t// Instantiate root\n\trootFs, err = fs.NewFs(*RemoteName + \":\")\n\trequire.NoError(t, err)\n\t_ = rootFs.Features().Purge()\n\trequire.NoError(t, err)\n\terr = rootFs.Mkdir(\"\")\n\trequire.NoError(t, err)\n\n\t// flush cache\n\t_, err = getCacheFs(rootFs)\n\trequire.NoError(t, err)\n}", "func Mock(codec codec.Codec) (*Client, io.Closer, error) {\n\tdir, err := ioutil.TempDir(\"\", \"etcd\")\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tcfg := embed.NewConfig()\n\tcfg.Logger = \"zap\"\n\tcfg.Dir = dir\n\tlpurl, _ := url.Parse(\"http://localhost:0\")\n\tlcurl, _ := url.Parse(\"http://localhost:0\")\n\tcfg.LPUrls = []url.URL{*lpurl}\n\tcfg.LCUrls = []url.URL{*lcurl}\n\n\tetcd, err := embed.StartEtcd(cfg)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tselect {\n\tcase <-etcd.Server.ReadyNotify():\n\tcase <-time.After(etcdStartTimeout):\n\t\tetcd.Server.Stop() // trigger a shutdown\n\t\treturn nil, nil, fmt.Errorf(\"server took too long to start\")\n\t}\n\n\tcloser := CloserFunc(func() error {\n\t\tetcd.Server.Stop()\n\t\treturn nil\n\t})\n\n\tvar config Config\n\tflagext.DefaultValues(&config)\n\n\tclient := &Client{\n\t\tcfg: config,\n\t\tcodec: codec,\n\t\tcli: v3client.New(etcd.Server),\n\t}\n\n\treturn client, closer, nil\n}", "func (m *MockUpstreamIntf) LocalHeight() uint64 {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"LocalHeight\")\n\tret0, _ := ret[0].(uint64)\n\treturn ret0\n}", "func (m *MockInterface) Init(kubeconfigPath, kubeconfigContext string) error {\n\treturn nil\n}", "func WithLocalDiscoveryProvider(discoveryProvider fab.LocalDiscoveryProvider) SDKContextParams {\n\treturn func(ctx *Provider) {\n\t\tctx.localDiscoveryProvider = discoveryProvider\n\t}\n}", "func (m *MockClusterScoper) Location() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Location\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}" ]
[ "0.7134569", "0.632302", "0.5986372", "0.58804214", "0.5836367", "0.56410253", "0.5597734", "0.5465775", "0.5429311", "0.54236996", "0.5394687", "0.53897685", "0.5385342", "0.53083503", "0.5291153", "0.5270716", "0.5252473", "0.52352184", "0.5203148", "0.5182315", "0.51554424", "0.51373076", "0.51317257", "0.5131219", "0.51069343", "0.5104862", "0.5101072", "0.50829625", "0.50779665", "0.50580496", "0.50442785", "0.5015747", "0.5007717", "0.50073826", "0.49975476", "0.49859568", "0.4977625", "0.49743494", "0.49542406", "0.49527407", "0.49426416", "0.4939108", "0.49213752", "0.49193934", "0.49170017", "0.4905363", "0.4891342", "0.48856932", "0.48853382", "0.4885069", "0.48847178", "0.48819792", "0.48745868", "0.48625183", "0.4855074", "0.48422745", "0.4837798", "0.48357165", "0.48329988", "0.4817016", "0.48164788", "0.4812812", "0.48124698", "0.48033565", "0.48010418", "0.47864047", "0.4778217", "0.47769454", "0.47767922", "0.47681028", "0.47661555", "0.4762952", "0.47612557", "0.47560406", "0.47491106", "0.47456867", "0.474457", "0.4738789", "0.47361666", "0.4736134", "0.47360688", "0.47348568", "0.4726774", "0.47182944", "0.4711988", "0.47100633", "0.47040755", "0.47027513", "0.47025004", "0.4702348", "0.46925232", "0.468725", "0.46867567", "0.46827984", "0.46812293", "0.46764582", "0.46750093", "0.4665986", "0.4664836", "0.46601477" ]
0.7341058
0
LocalDiscoveryProvider indicates an expected call of LocalDiscoveryProvider
func (mr *MockClientMockRecorder) LocalDiscoveryProvider() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "LocalDiscoveryProvider", reflect.TypeOf((*MockClient)(nil).LocalDiscoveryProvider)) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (c *Provider) LocalDiscoveryProvider() fab.LocalDiscoveryProvider {\n\treturn c.localDiscoveryProvider\n}", "func (mr *MockProvidersMockRecorder) LocalDiscoveryProvider() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"LocalDiscoveryProvider\", reflect.TypeOf((*MockProviders)(nil).LocalDiscoveryProvider))\n}", "func (m *MockClient) LocalDiscoveryProvider() fab.LocalDiscoveryProvider {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"LocalDiscoveryProvider\")\n\tret0, _ := ret[0].(fab.LocalDiscoveryProvider)\n\treturn ret0\n}", "func (m *MockProviders) LocalDiscoveryProvider() fab.LocalDiscoveryProvider {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"LocalDiscoveryProvider\")\n\tret0, _ := ret[0].(fab.LocalDiscoveryProvider)\n\treturn ret0\n}", "func (c *Local) LocalDiscoveryService() fab.DiscoveryService {\n\treturn c.localDiscovery\n}", "func (_e *MockPlcDriver_Expecter) SupportsDiscovery() *MockPlcDriver_SupportsDiscovery_Call {\n\treturn &MockPlcDriver_SupportsDiscovery_Call{Call: _e.mock.On(\"SupportsDiscovery\")}\n}", "func (sc *ShamClient) fallbackDiscovery() {\n\tif len(sc.localRegistry) == 0 {\n\t\tsc.setLocalRegistry(sc.serviceRegistry.Fallback)\n\t\tsc.logger.Infof(\"using Fallback registry for service %s: %+v\", sc.serviceName, sc.localRegistry)\n\t} else {\n\t\tsc.logger.Infof(\"continue using local registry for service %s: %+v\", sc.serviceName, sc.localRegistry)\n\t}\n}", "func (m *Module) gatherProviderLocalNames() {\n\tproviders := make(map[addrs.Provider]string)\n\tfor k, v := range m.ProviderRequirements.RequiredProviders {\n\t\tproviders[v.Type] = k\n\t}\n\tm.ProviderLocalNames = providers\n}", "func (l *Factory) CreateLocalDiscoveryProvider(config fabApi.EndpointConfig) (fabApi.LocalDiscoveryProvider, error) {\n\tlogger.Debug(\"create local Provider Impl\")\n\treturn &impl{config, l.LocalPeer, l.LocalPeerTLSCertPem}, nil\n}", "func WithLocalDiscoveryProvider(discoveryProvider fab.LocalDiscoveryProvider) SDKContextParams {\n\treturn func(ctx *Provider) {\n\t\tctx.localDiscoveryProvider = discoveryProvider\n\t}\n}", "func (s *gossipServiceDiscovery) LocalDiscovery(ctx context.Context) (*localPeersDTO, error) {\n\treq := discClient.\n\t\tNewRequest().AddLocalPeersQuery()\n\n\tres, err := s.client.Send(ctx, req, s.getAuthInfo())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpeers, err := res.ForLocal().Peers()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdc := newLocalPeersDTO()\n\n\treturn s.parseDiscoverLocalPeers(dc, peers), nil\n}", "func (m *MockMemberList) LocalNode() discovery.Member {\n\tret := m.ctrl.Call(m, \"LocalNode\")\n\tret0, _ := ret[0].(discovery.Member)\n\treturn ret0\n}", "func MissingProviderSuggestion(ctx context.Context, addr addrs.Provider, source Source, reqs Requirements) addrs.Provider {\n\tif !addr.IsDefault() {\n\t\treturn addr\n\t}\n\n\t// Before possibly looking up legacy naming, see if the user has another provider\n\t// named in their requirements that is of the same type, and offer that\n\t// as a suggestion\n\tfor req := range reqs {\n\t\tif req != addr && req.Type == addr.Type {\n\t\t\treturn req\n\t\t}\n\t}\n\n\t// Our strategy here, for a default provider, is to use the default\n\t// registry's special API for looking up \"legacy\" providers and try looking\n\t// for a legacy provider whose type name matches the type of the given\n\t// provider. This should then find a suitable answer for any provider\n\t// that was originally auto-installable in v0.12 and earlier but moved\n\t// into a non-default namespace as part of introducing the hierarchical\n\t// provider namespace.\n\t//\n\t// To achieve that, we need to find the direct registry client in\n\t// particular from the given source, because that is the only Source\n\t// implementation that can actually handle a legacy provider lookup.\n\tregSource := findLegacyProviderLookupSource(addr.Hostname, source)\n\tif regSource == nil {\n\t\t// If there's no direct registry source in the installation config\n\t\t// then we can't provide a renaming suggestion.\n\t\treturn addr\n\t}\n\n\tdefaultNS, redirectNS, err := regSource.lookupLegacyProviderNamespace(ctx, addr.Hostname, addr.Type)\n\tif err != nil {\n\t\treturn addr\n\t}\n\n\tswitch {\n\tcase redirectNS != \"\":\n\t\treturn addrs.Provider{\n\t\t\tHostname: addr.Hostname,\n\t\t\tNamespace: redirectNS,\n\t\t\tType: addr.Type,\n\t\t}\n\tdefault:\n\t\treturn addrs.Provider{\n\t\t\tHostname: addr.Hostname,\n\t\t\tNamespace: defaultNS,\n\t\t\tType: addr.Type,\n\t\t}\n\t}\n}", "func NewLocalProvider(t []string) Provider {\n\treturn newLocalProviderWithClock(t, clock.New())\n}", "func (c *TestConnection) LocalAddr() net.Addr {\n return nil\n}", "func Discovery(*DiscoveryRequest, *DiscoveryResponse) {}", "func TestLogConfigInLocal(t *testing.T) {\n\t// Check if\n}", "func NewLocal(clientProvider context.ClientProvider) (*Local, error) {\n\tclient, err := clientProvider()\n\tif err != nil {\n\t\treturn nil, errors.WithMessage(err, \"failed to get client context to create local context\")\n\t}\n\n\tdiscoveryService, err := client.LocalDiscoveryProvider().CreateLocalDiscoveryService(client.Identifier().MSPID)\n\tif err != nil {\n\t\treturn nil, errors.WithMessage(err, \"failed to create local discovery service\")\n\t}\n\n\tlocal := &Local{\n\t\tClient: client,\n\t\tlocalDiscovery: discoveryService,\n\t}\n\n\tif ci, ok := discoveryService.(localServiceInit); ok {\n\t\tif err := ci.Initialize(local); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn local, nil\n}", "func (mr *MockInterfaceMockRecorder) Discovery() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Discovery\", reflect.TypeOf((*MockInterface)(nil).Discovery))\n}", "func (mph *MockPeerHandler) LocalAddr() string {\n\treturn \"\"\n}", "func (_m *MockPlcDriver) SupportsDiscovery() bool {\n\tret := _m.Called()\n\n\tvar r0 bool\n\tif rf, ok := ret.Get(0).(func() bool); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tr0 = ret.Get(0).(bool)\n\t}\n\n\treturn r0\n}", "func setupDiscovery(ctx context.Context, h host.Host) error {\n\t// setup mDNS discovery to find local peers\n\tdisc, err := discovery.NewMdnsService(ctx, h, DiscoveryInterval, DiscoveryServiceTag)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tn := discoveryNotifee{h: h}\n\tdisc.RegisterNotifee(&n)\n\treturn nil\n}", "func hackClusterConfigForLocalTestingInKIND(\n\tremoteCluster *api.Cluster,\n\tremoteContextName, clusterDomainOverride string,\n) error {\n\tserverUrl, err := url.Parse(remoteCluster.Server)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif strings.HasPrefix(remoteContextName, \"kind-\") &&\n\t\t(serverUrl.Hostname() == \"127.0.0.1\" || serverUrl.Hostname() == \"localhost\") &&\n\t\tclusterDomainOverride != \"\" {\n\n\t\tremoteCluster.Server = fmt.Sprintf(\"https://%s:%s\", clusterDomainOverride, serverUrl.Port())\n\t\tremoteCluster.InsecureSkipTLSVerify = true\n\t\tremoteCluster.CertificateAuthority = \"\"\n\t\tremoteCluster.CertificateAuthorityData = []byte(\"\")\n\t}\n\n\treturn nil\n}", "func TestLocalDomain_NetworkServiceRegistry(t *testing.T) {\n\tt.Cleanup(func() { goleak.VerifyNone(t) })\n\n\tctx, cancel := context.WithTimeout(context.Background(), time.Second)\n\tdefer cancel()\n\n\tdnsServer := sandbox.NewFakeResolver()\n\n\tdomain1 := sandbox.NewBuilder(ctx, t).\n\t\tSetNodesCount(0).\n\t\tSetDNSDomainName(\"cluster.local\").\n\t\tSetDNSResolver(dnsServer).\n\t\tBuild()\n\n\tclient1 := registryclient.NewNetworkServiceRegistryClient(ctx,\n\t\tregistryclient.WithDialOptions(grpc.WithTransportCredentials(insecure.NewCredentials())),\n\t\tregistryclient.WithClientURL(domain1.Registry.URL))\n\n\texpected, err := client1.Register(context.Background(), &registryapi.NetworkService{\n\t\tName: \"ns-1@\" + domain1.Name,\n\t})\n\n\trequire.Nil(t, err)\n\trequire.True(t, strings.Contains(expected.GetName(), \"@\"+domain1.Name))\n\n\tclient2 := registryclient.NewNetworkServiceRegistryClient(ctx,\n\t\tregistryclient.WithDialOptions(grpc.WithTransportCredentials(insecure.NewCredentials())),\n\t\tregistryclient.WithClientURL(domain1.Registry.URL))\n\n\tstream, err := client2.Find(context.Background(), &registryapi.NetworkServiceQuery{\n\t\tNetworkService: &registryapi.NetworkService{\n\t\t\tName: expected.Name,\n\t\t},\n\t})\n\n\trequire.Nil(t, err)\n\n\tlist := registryapi.ReadNetworkServiceList(stream)\n\n\trequire.Len(t, list, 1)\n\trequire.Equal(t, \"ns-1@cluster.local\", list[0].Name)\n}", "func (o *LocalDatabaseProvider) GetBlockLocalDnsRequestsOk() (*bool, bool) {\n\tif o == nil || o.BlockLocalDnsRequests == nil {\n\t\treturn nil, false\n\t}\n\treturn o.BlockLocalDnsRequests, true\n}", "func (o *LocalDatabaseProvider) HasBlockLocalDnsRequests() bool {\n\tif o != nil && o.BlockLocalDnsRequests != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (ds *localDiscoveryService) Initialize(ctx contextAPI.Local) error {\r\n\tds.mspID = ctx.Identifier().MSPID\r\n\treturn nil\r\n}", "func newLocalProviderWithClock(t []string, clock clock.Clock) Provider {\n\tp := &localProvider{\n\t\ttags: t,\n\t\texpectedTags: t,\n\t}\n\n\tif config.IsExpectedTagsSet(coreConfig.Datadog) {\n\t\tp.expectedTags = append(p.tags, hostMetadataUtils.GetHostTags(context.TODO(), false, coreConfig.Datadog).System...)\n\n\t\t// expected tags deadline is based on the agent start time, which may have been earlier\n\t\t// than the current time.\n\t\texpectedTagsDeadline := coreConfig.StartTime.Add(coreConfig.Datadog.GetDuration(\"logs_config.expected_tags_duration\"))\n\n\t\t// reset submitExpectedTags after deadline elapsed\n\t\tclock.AfterFunc(expectedTagsDeadline.Sub(clock.Now()), func() {\n\t\t\tp.Lock()\n\t\t\tdefer p.Unlock()\n\t\t\tp.expectedTags = nil\n\t\t})\n\t}\n\n\treturn p\n}", "func TestDiscoveryFeatureGate(t *testing.T) {\n\tnewIntegrationTest(\"minimal.example.com\", \"public-jwks-apiserver\").\n\t\twithDefaultServiceAccountRoles24().\n\t\twithServiceAccountRole(\"aws-node-termination-handler.kube-system\", true).\n\t\twithDefaultAddons24().\n\t\twithOIDCDiscovery().\n\t\trunTestTerraformAWS(t)\n}", "func requiresNativeServiceDiscovery(group string, services []*Service, basic, checks *set.Set[string]) {\n\tfor _, tgService := range services {\n\t\tif tgService.Provider == ServiceProviderNomad {\n\t\t\tbasic.Insert(group)\n\t\t\tif len(tgService.Checks) > 0 {\n\t\t\t\tchecks.Insert(group)\n\t\t\t}\n\t\t}\n\t}\n}", "func IndirectlyTested() string {\n\treturn \"This function is tested via a function reference rather than a direct call\"\n}", "func (m *MockEarlyConnection) LocalAddr() net.Addr {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"LocalAddr\")\n\tret0, _ := ret[0].(net.Addr)\n\treturn ret0\n}", "func NewNewDiscoveryOK() *NewDiscoveryOK {\n\treturn &NewDiscoveryOK{}\n}", "func (dp *MockStaticDiscoveryProvider) CreateLocalDiscoveryService(mspID string) (fab.DiscoveryService, error) {\n\treturn &MockStaticDiscoveryService{Error: dp.Error, Peers: dp.Peers}, nil\n}", "func TestDefaultProviderIsWarnOnceProvider(t *testing.T) {\n\t// create logger that writes to buffer using the default logger provider\n\tbuf := &bytes.Buffer{}\n\tlogger := svc1log.New(buf, wlog.DebugLevel) // uses default provider\n\n\t// verify that output provides warning that no logger provider was specified\n\tlogger.Info(\"Test output 1\")\n\tconst wantOutput = `[WARNING] Logging operation that uses the default logger provider was performed without specifying a logger provider implementation. To see logger output, set the global logger provider implementation using wlog.SetDefaultLoggerProvider or by importing an implementation. This warning can be disabled by setting the global logger provider to be the noop logger provider using wlog.SetDefaultLoggerProvider(wlog.NewNoopLoggerProvider()).` + \"\\n\"\n\tgot := buf.String()\n\tassert.Equal(t, wantOutput, got)\n\n\t// verify that warning is only written on first call to logger\n\tlogger.Info(\"Test output 2\")\n\tbuf.Reset()\n\tgot = buf.String()\n\tassert.Equal(t, \"\", got)\n}", "func shouldUseLocalWithFallback(ic *operatorv1.IngressController, service *corev1.Service) (bool, error) {\n\t// By default, use local-with-fallback when using the \"Local\" external\n\t// traffic policy.\n\tif service.Spec.ExternalTrafficPolicy != corev1.ServiceExternalTrafficPolicyTypeLocal {\n\t\treturn false, nil\n\t}\n\n\t// Allow the user to override local-with-fallback.\n\tif len(ic.Spec.UnsupportedConfigOverrides.Raw) > 0 {\n\t\tvar unsupportedConfigOverrides struct {\n\t\t\tLocalWithFallback string `json:\"localWithFallback\"`\n\t\t}\n\t\tif err := json.Unmarshal(ic.Spec.UnsupportedConfigOverrides.Raw, &unsupportedConfigOverrides); err != nil {\n\t\t\treturn false, fmt.Errorf(\"ingresscontroller %q has invalid spec.unsupportedConfigOverrides: %w\", ic.Name, err)\n\t\t}\n\t\toverride := unsupportedConfigOverrides.LocalWithFallback\n\t\tif len(override) != 0 {\n\t\t\tif val, err := strconv.ParseBool(override); err != nil {\n\t\t\t\treturn false, fmt.Errorf(\"ingresscontroller %q has invalid spec.unsupportedConfigOverrides.localWithFallback: %w\", ic.Name, err)\n\t\t\t} else {\n\t\t\t\treturn val, nil\n\t\t\t}\n\t\t}\n\t}\n\n\treturn true, nil\n}", "func (l *impl) CreateLocalDiscoveryService(mspID string) (fabApi.DiscoveryService, error) {\n\treturn &localDiscoveryService{l.clientConfig, l.localPeer, l.localPeerTLSCertPem}, nil\n}", "func testMdns(t *testing.T) {\n\tservice := \"_liqo._tcp\"\n\tdomain := \"local.\"\n\n\tgo clientCluster.discoveryCtrl.Register()\n\n\ttime.Sleep(1 * time.Second)\n\n\ttxts := []*discovery.TxtData{}\n\tclientCluster.discoveryCtrl.Resolve(service, domain, 3, &txts)\n\n\ttime.Sleep(1 * time.Second)\n\n\t// TODO: find better way to test mDNS, local IP is not always detected\n\tassert.Assert(t, len(txts) >= 0, \"If this line is reached test would be successful, no foreign packet can reach our testing environment at the moment\")\n}", "func (r *NamespaceMapReconciler) checkLocalClusterID() error {\n\tif r.LocalClusterID == \"\" {\n\t\tclusterID, err := liqoutils.GetClusterID(r.Client)\n\t\tif err != nil || clusterID == \"\" {\n\t\t\treturn err\n\t\t}\n\t\tr.LocalClusterID = clusterID\n\t}\n\treturn nil\n}", "func (mr *MockServiceMockRecorder) Discovery() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Discovery\", reflect.TypeOf((*MockService)(nil).Discovery))\n}", "func (_m *Session) LocalAddr() net.Addr {\n\tret := _m.Called()\n\n\tvar r0 net.Addr\n\tif rf, ok := ret.Get(0).(func() net.Addr); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(net.Addr)\n\t\t}\n\t}\n\n\treturn r0\n}", "func (mr *MockMemberListMockRecorder) LocalNode() *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"LocalNode\", reflect.TypeOf((*MockMemberList)(nil).LocalNode))\n}", "func (m *MockPacketHandler) LocalAddr() net.Addr {\n\tret := m.ctrl.Call(m, \"LocalAddr\")\n\tret0, _ := ret[0].(net.Addr)\n\treturn ret0\n}", "func newLocalService(config fab.EndpointConfig, mspID string, opts ...coptions.Opt) *LocalService {\n\tlogger.Debug(\"Creating new local discovery service\")\n\n\ts := &LocalService{mspID: mspID}\n\ts.service = newService(config, s.queryPeers, opts...)\n\treturn s\n}", "func (mr *MockEarlyConnectionMockRecorder) LocalAddr() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"LocalAddr\", reflect.TypeOf((*MockEarlyConnection)(nil).LocalAddr))\n}", "func (m *Module) ProviderForLocalConfig(pc addrs.LocalProviderConfig) addrs.Provider {\n\treturn m.ImpliedProviderForUnqualifiedType(pc.LocalName)\n}", "func TestEndpoints_LocalAlreadyRunning(t *testing.T) {\n\tendpoints1, config1, cleanup1 := newEndpoints(t)\n\tdefer cleanup1()\n\n\trequire.NoError(t, endpoints1.Up(config1))\n\n\tendpoints2, config2, cleanup2 := newEndpoints(t)\n\tconfig2.Dir = config1.Dir\n\tconfig2.UnixSocket = config1.UnixSocket\n\tdefer cleanup2()\n\n\terr := endpoints2.Up(config2)\n\tassert.EqualError(t, err, \"local endpoint: LXD is already running\")\n}", "func NonLocalReplicasFallback() func(policy *tokenAwareHostPolicy) {\n\treturn func(t *tokenAwareHostPolicy) {\n\t\tt.nonLocalReplicasFallback = true\n\t}\n}", "func (i *localInitializer) Initialize(plugin admission.Interface) {\n\tif wants, ok := plugin.(WantsDefaultNodeSelector); ok {\n\t\twants.SetDefaultNodeSelector(i.defaultNodeSelector)\n\t}\n}", "func gatherDiscovery(dataType string, info Info) bool {\n\tif info.ServiceDiscovery == nil {\n\t\tinfo.Status.Warning(\"The Submariner service discovery components are not installed\")\n\t\treturn true\n\t}\n\n\tswitch dataType {\n\tcase Logs:\n\t\tgatherServiceDiscoveryPodLogs(&info)\n\t\tgatherCoreDNSPodLogs(&info)\n\tcase Resources:\n\t\tgatherServiceExports(&info, corev1.NamespaceAll)\n\t\tgatherServiceImports(&info, corev1.NamespaceAll)\n\t\tgatherEndpointSlices(&info, corev1.NamespaceAll)\n\t\tgatherConfigMapLighthouseDNS(&info, info.ServiceDiscovery.Namespace)\n\t\tgatherConfigMapCoreDNS(&info)\n\t\tgatherLabeledServices(&info, internalSvcLabel)\n\tdefault:\n\t\treturn false\n\t}\n\n\treturn true\n}", "func startDiscovery() (err error) {\n\tlogger := log.New()\n\n\tif debug {\n\t\tlogger.Level = log.DebugLevel\n\t}\n\tgolifx.SetLogger(logger)\n\n\tif err := initClient(); err != nil {\n\t\ttick := time.Tick(2 * time.Second)\n\t\tdone := make(chan bool)\n\t\tselect {\n\t\tcase <-done:\n\t\tcase <-tick:\n\t\t\terr = initClient()\n\t\t\tif err == nil {\n\t\t\t\tdone <- true\n\t\t\t}\n\t\t}\n\t}\n\n\tclient.SetDiscoveryInterval(30 * time.Second)\n\n\tif timeout > 0 {\n\t\tclient.SetTimeout(time.Duration(timeout))\n\t}\n\n\tlog.Info(`Initiated LIFX client`)\n\n\treturn nil\n}", "func (me TxsdRegistryHandleSimpleContentExtensionRegistry) IsLocal() bool {\n\treturn me.String() == \"local\"\n}", "func (s *Drive) Local() bool { return s.config.OAuth.ClientID == \"\" }", "func discoverer() {\n\t// use \"peerdiscovery\" package to actively discover\n\t// new peers on the network\n\t// every time there's a new peer, \"store\" it in \"peers\"\n\t// and \"add\" the user on the UI (i.e use ui.AddUser)\n\t// if there's an error, log.Fatal ;)\n}", "func TestPeopleTracking(t *testing.T) {\n\tsomeone := trackSomeone()\n\tassert.NotNil(t, someone.location)\n}", "func unmanagedProviderFactory(provider addrs.Provider, reattach *plugin.ReattachConfig) providers.Factory {\n\treturn func() (providers.Interface, error) {\n\t\tconfig := &plugin.ClientConfig{\n\t\t\tHandshakeConfig: tfplugin.Handshake,\n\t\t\tLogger: logging.NewProviderLogger(\"unmanaged.\"),\n\t\t\tAllowedProtocols: []plugin.Protocol{plugin.ProtocolGRPC},\n\t\t\tManaged: false,\n\t\t\tReattach: reattach,\n\t\t\tSyncStdout: logging.PluginOutputMonitor(fmt.Sprintf(\"%s:stdout\", provider)),\n\t\t\tSyncStderr: logging.PluginOutputMonitor(fmt.Sprintf(\"%s:stderr\", provider)),\n\t\t}\n\n\t\tif reattach.ProtocolVersion == 0 {\n\t\t\t// As of the 0.15 release, sdk.v2 doesn't include the protocol\n\t\t\t// version in the ReattachConfig (only recently added to\n\t\t\t// go-plugin), so client.NegotiatedVersion() always returns 0. We\n\t\t\t// assume that an unmanaged provider reporting protocol version 0 is\n\t\t\t// actually using proto v5 for backwards compatibility.\n\t\t\tif defaultPlugins, ok := tfplugin.VersionedPlugins[5]; ok {\n\t\t\t\tconfig.Plugins = defaultPlugins\n\t\t\t} else {\n\t\t\t\treturn nil, errors.New(\"no supported plugins for protocol 0\")\n\t\t\t}\n\t\t} else if plugins, ok := tfplugin.VersionedPlugins[reattach.ProtocolVersion]; !ok {\n\t\t\treturn nil, fmt.Errorf(\"no supported plugins for protocol %d\", reattach.ProtocolVersion)\n\t\t} else {\n\t\t\tconfig.Plugins = plugins\n\t\t}\n\n\t\tclient := plugin.NewClient(config)\n\t\trpcClient, err := client.Client()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\traw, err := rpcClient.Dispense(tfplugin.ProviderPluginName)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// store the client so that the plugin can kill the child process\n\t\tprotoVer := client.NegotiatedVersion()\n\t\tswitch protoVer {\n\t\tcase 0, 5:\n\t\t\t// As of the 0.15 release, sdk.v2 doesn't include the protocol\n\t\t\t// version in the ReattachConfig (only recently added to\n\t\t\t// go-plugin), so client.NegotiatedVersion() always returns 0. We\n\t\t\t// assume that an unmanaged provider reporting protocol version 0 is\n\t\t\t// actually using proto v5 for backwards compatibility.\n\t\t\tp := raw.(*tfplugin.GRPCProvider)\n\t\t\tp.PluginClient = client\n\t\t\treturn p, nil\n\t\tcase 6:\n\t\t\tp := raw.(*tfplugin6.GRPCProvider)\n\t\t\tp.PluginClient = client\n\t\t\treturn p, nil\n\t\tdefault:\n\t\t\treturn nil, fmt.Errorf(\"unsupported protocol version %d\", protoVer)\n\t\t}\n\t}\n}", "func TestEndpoints_LocalUnknownUnixGroup(t *testing.T) {\n\tendpoints, config, cleanup := newEndpoints(t)\n\tdefer cleanup()\n\n\tconfig.LocalUnixSocketGroup = \"xquibaz\"\n\terr := endpoints.Up(config)\n\n\tassert.EqualError(\n\t\tt, err, \"local endpoint: cannot get group ID of 'xquibaz': group: unknown group xquibaz\")\n}", "func (m *MockInformation) LocalLocation() *universe.View {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"LocalLocation\")\n\tret0, _ := ret[0].(*universe.View)\n\treturn ret0\n}", "func NewMockDiscoveryProvider(err error, peers []fab.Peer) (*MockStaticDiscoveryProvider, error) {\n\treturn &MockStaticDiscoveryProvider{Error: err, Peers: peers}, nil\n}", "func TestGatherOnSetLocalDescription(t *testing.T) {\n\tlim := test.TimeOut(time.Second * 30)\n\tdefer lim.Stop()\n\n\treport := test.CheckRoutines(t)\n\tdefer report()\n\n\tpcOfferGathered := make(chan SessionDescription)\n\tpcAnswerGathered := make(chan SessionDescription)\n\n\ts := SettingEngine{}\n\tapi := NewAPI(WithSettingEngine(s))\n\n\tpcOffer, err := api.NewPeerConnection(Configuration{})\n\tif err != nil {\n\t\tt.Error(err.Error())\n\t}\n\n\t// We need to create a data channel in order to trigger ICE\n\tif _, err = pcOffer.CreateDataChannel(\"initial_data_channel\", nil); err != nil {\n\t\tt.Error(err.Error())\n\t}\n\n\tpcOffer.OnICECandidate(func(i *ICECandidate) {\n\t\tif i == nil {\n\t\t\tclose(pcOfferGathered)\n\t\t}\n\t})\n\n\toffer, err := pcOffer.CreateOffer(nil)\n\tif err != nil {\n\t\tt.Error(err.Error())\n\t} else if err = pcOffer.SetLocalDescription(offer); err != nil {\n\t\tt.Error(err.Error())\n\t}\n\n\t<-pcOfferGathered\n\n\tpcAnswer, err := api.NewPeerConnection(Configuration{})\n\tif err != nil {\n\t\tt.Error(err.Error())\n\t}\n\n\tpcAnswer.OnICECandidate(func(i *ICECandidate) {\n\t\tif i == nil {\n\t\t\tclose(pcAnswerGathered)\n\t\t}\n\t})\n\n\tif err = pcAnswer.SetRemoteDescription(offer); err != nil {\n\t\tt.Error(err.Error())\n\t}\n\n\tselect {\n\tcase <-pcAnswerGathered:\n\t\tt.Fatal(\"pcAnswer started gathering with no SetLocalDescription\")\n\t// Gathering is async, not sure of a better way to catch this currently\n\tcase <-time.After(3 * time.Second):\n\t}\n\n\tanswer, err := pcAnswer.CreateAnswer(nil)\n\tif err != nil {\n\t\tt.Error(err.Error())\n\t} else if err = pcAnswer.SetLocalDescription(answer); err != nil {\n\t\tt.Error(err.Error())\n\t}\n\t<-pcAnswerGathered\n\tclosePairNow(t, pcOffer, pcAnswer)\n}", "func (mr *MockClientMockRecorder) InfraProvider() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"InfraProvider\", reflect.TypeOf((*MockClient)(nil).InfraProvider))\n}", "func (rs *EpNodeAccelRisers) discoverLocalPhase2() error {\n\tvar savedError error\n\tfor i, r := range rs.OIDs {\n\t\tr.discoverLocalPhase2()\n\t\tif r.LastStatus == RedfishSubtypeNoSupport {\n\t\t\terrlog.Printf(\"Key %s: RF NodeAccelRiser type not supported: %s\",\n\t\t\t\ti, r.RedfishSubtype)\n\t\t} else if r.LastStatus != DiscoverOK {\n\t\t\terr := fmt.Errorf(\"Key %s: %s\", i, r.LastStatus)\n\t\t\terrlog.Printf(\"NodeAccelRisers discoverLocalPhase2: saw error: %s\", err)\n\t\t\tsavedError = err\n\t\t}\n\t}\n\treturn savedError\n}", "func (mr *MockPacketHandlerMockRecorder) LocalAddr() *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"LocalAddr\", reflect.TypeOf((*MockPacketHandler)(nil).LocalAddr))\n}", "func (ts *Tester) Provider() string {\n\treturn \"eks\"\n}", "func TestExternalNameService(t *testing.T) {\n\trh, c, done := setup(t, enableExternalNameService(t))\n\tdefer done()\n\n\ts1 := fixture.NewService(\"kuard\").\n\t\tWithSpec(v1.ServiceSpec{\n\t\t\tPorts: []v1.ServicePort{{\n\t\t\t\tPort: 80,\n\t\t\t\tTargetPort: intstr.FromInt(8080),\n\t\t\t}},\n\t\t\tExternalName: \"foo.io\",\n\t\t\tType: v1.ServiceTypeExternalName,\n\t\t})\n\n\ti1 := &networking_v1.Ingress{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: \"kuard\",\n\t\t\tNamespace: s1.Namespace,\n\t\t},\n\t\tSpec: networking_v1.IngressSpec{\n\t\t\tDefaultBackend: featuretests.IngressBackend(s1),\n\t\t},\n\t}\n\trh.OnAdd(s1)\n\trh.OnAdd(i1)\n\n\tc.Request(routeType).Equals(&envoy_discovery_v3.DiscoveryResponse{\n\t\tResources: resources(t,\n\t\t\tenvoy_v3.RouteConfiguration(\"ingress_http\",\n\t\t\t\tenvoy_v3.VirtualHost(\"*\",\n\t\t\t\t\t&envoy_route_v3.Route{\n\t\t\t\t\t\tMatch: routePrefix(\"/\"),\n\t\t\t\t\t\tAction: routeCluster(\"default/kuard/80/da39a3ee5e\"),\n\t\t\t\t\t},\n\t\t\t\t),\n\t\t\t),\n\t\t),\n\t\tTypeUrl: routeType,\n\t})\n\n\tc.Request(clusterType).Equals(&envoy_discovery_v3.DiscoveryResponse{\n\t\tResources: resources(t,\n\t\t\texternalNameCluster(\"default/kuard/80/da39a3ee5e\", \"default/kuard\", \"default_kuard_80\", \"foo.io\", 80),\n\t\t),\n\t\tTypeUrl: clusterType,\n\t})\n\n\trh.OnDelete(i1)\n\n\trh.OnAdd(fixture.NewProxy(\"kuard\").\n\t\tWithFQDN(\"kuard.projectcontour.io\").\n\t\tWithSpec(contour_api_v1.HTTPProxySpec{\n\t\t\tRoutes: []contour_api_v1.Route{{\n\t\t\t\tServices: []contour_api_v1.Service{{\n\t\t\t\t\tName: s1.Name,\n\t\t\t\t\tPort: 80,\n\t\t\t\t}},\n\t\t\t}},\n\t\t}),\n\t)\n\n\tc.Request(routeType).Equals(&envoy_discovery_v3.DiscoveryResponse{\n\t\tResources: resources(t,\n\t\t\tenvoy_v3.RouteConfiguration(\"ingress_http\",\n\t\t\t\tenvoy_v3.VirtualHost(\"kuard.projectcontour.io\",\n\t\t\t\t\t&envoy_route_v3.Route{\n\t\t\t\t\t\tMatch: routePrefix(\"/\"),\n\t\t\t\t\t\tAction: routeCluster(\"default/kuard/80/a28d1ec01b\"),\n\t\t\t\t\t},\n\t\t\t\t),\n\t\t\t),\n\t\t),\n\t\tTypeUrl: routeType,\n\t})\n\n\tc.Request(clusterType).Equals(&envoy_discovery_v3.DiscoveryResponse{\n\t\tResources: resources(t,\n\t\t\texternalNameCluster(\"default/kuard/80/a28d1ec01b\", \"default/kuard\", \"default_kuard_80\", \"foo.io\", 80),\n\t\t),\n\t\tTypeUrl: clusterType,\n\t})\n\n\t// After we set the Host header, the cluster should remain\n\t// the same, but the Route should do update the Host header.\n\trh.OnDelete(fixture.NewProxy(\"kuard\").WithSpec(contour_api_v1.HTTPProxySpec{}))\n\trh.OnAdd(fixture.NewProxy(\"kuard\").\n\t\tWithFQDN(\"kuard.projectcontour.io\").\n\t\tWithSpec(contour_api_v1.HTTPProxySpec{\n\t\t\tRoutes: []contour_api_v1.Route{{\n\t\t\t\tServices: []contour_api_v1.Service{{\n\t\t\t\t\tName: s1.Name,\n\t\t\t\t\tPort: 80,\n\t\t\t\t}},\n\t\t\t\tRequestHeadersPolicy: &contour_api_v1.HeadersPolicy{\n\t\t\t\t\tSet: []contour_api_v1.HeaderValue{{\n\t\t\t\t\t\tName: \"Host\",\n\t\t\t\t\t\tValue: \"external.address\",\n\t\t\t\t\t}},\n\t\t\t\t},\n\t\t\t}},\n\t\t}),\n\t)\n\n\tc.Request(routeType).Equals(&envoy_discovery_v3.DiscoveryResponse{\n\t\tTypeUrl: routeType,\n\t\tResources: resources(t,\n\t\t\tenvoy_v3.RouteConfiguration(\"ingress_http\",\n\t\t\t\tenvoy_v3.VirtualHost(\"kuard.projectcontour.io\",\n\t\t\t\t\t&envoy_route_v3.Route{\n\t\t\t\t\t\tMatch: routePrefix(\"/\"),\n\t\t\t\t\t\tAction: routeHostRewrite(\"default/kuard/80/95e871afaf\", \"external.address\"),\n\t\t\t\t\t},\n\t\t\t\t),\n\t\t\t),\n\t\t),\n\t})\n\n\tc.Request(clusterType).Equals(&envoy_discovery_v3.DiscoveryResponse{\n\t\tTypeUrl: clusterType,\n\t\tResources: resources(t,\n\t\t\texternalNameCluster(\"default/kuard/80/95e871afaf\", \"default/kuard\", \"default_kuard_80\", \"foo.io\", 80),\n\t\t),\n\t})\n\n\t// Now try the same configuration, but enable HTTP/2. We\n\t// should still find that the same configuration applies, but\n\t// TLS is enabled and the SNI server name is overwritten from\n\t// the Host header.\n\trh.OnDelete(fixture.NewProxy(\"kuard\").WithSpec(contour_api_v1.HTTPProxySpec{}))\n\trh.OnAdd(fixture.NewProxy(\"kuard\").\n\t\tWithFQDN(\"kuard.projectcontour.io\").\n\t\tWithSpec(contour_api_v1.HTTPProxySpec{\n\t\t\tRoutes: []contour_api_v1.Route{{\n\t\t\t\tServices: []contour_api_v1.Service{{\n\t\t\t\t\tProtocol: ref.To(\"h2\"),\n\t\t\t\t\tName: s1.Name,\n\t\t\t\t\tPort: 80,\n\t\t\t\t}},\n\t\t\t\tRequestHeadersPolicy: &contour_api_v1.HeadersPolicy{\n\t\t\t\t\tSet: []contour_api_v1.HeaderValue{{\n\t\t\t\t\t\tName: \"Host\",\n\t\t\t\t\t\tValue: \"external.address\",\n\t\t\t\t\t}},\n\t\t\t\t},\n\t\t\t}},\n\t\t}),\n\t)\n\n\tc.Request(routeType).Equals(&envoy_discovery_v3.DiscoveryResponse{\n\t\tTypeUrl: routeType,\n\t\tResources: resources(t,\n\t\t\tenvoy_v3.RouteConfiguration(\"ingress_http\",\n\t\t\t\tenvoy_v3.VirtualHost(\"kuard.projectcontour.io\",\n\t\t\t\t\t&envoy_route_v3.Route{\n\t\t\t\t\t\tMatch: routePrefix(\"/\"),\n\t\t\t\t\t\tAction: routeHostRewrite(\"default/kuard/80/cdbf075ad8\", \"external.address\"),\n\t\t\t\t\t},\n\t\t\t\t),\n\t\t\t),\n\t\t),\n\t})\n\n\tc.Request(clusterType).Equals(&envoy_discovery_v3.DiscoveryResponse{\n\t\tTypeUrl: clusterType,\n\t\tResources: resources(t,\n\t\t\tDefaultCluster(\n\t\t\t\texternalNameCluster(\"default/kuard/80/cdbf075ad8\", \"default/kuard\", \"default_kuard_80\", \"foo.io\", 80),\n\t\t\t\t&envoy_cluster_v3.Cluster{\n\t\t\t\t\tTypedExtensionProtocolOptions: map[string]*anypb.Any{\n\t\t\t\t\t\t\"envoy.extensions.upstreams.http.v3.HttpProtocolOptions\": protobuf.MustMarshalAny(\n\t\t\t\t\t\t\t&envoy_extensions_upstream_http_v3.HttpProtocolOptions{\n\t\t\t\t\t\t\t\tUpstreamProtocolOptions: &envoy_extensions_upstream_http_v3.HttpProtocolOptions_ExplicitHttpConfig_{\n\t\t\t\t\t\t\t\t\tExplicitHttpConfig: &envoy_extensions_upstream_http_v3.HttpProtocolOptions_ExplicitHttpConfig{\n\t\t\t\t\t\t\t\t\t\tProtocolConfig: &envoy_extensions_upstream_http_v3.HttpProtocolOptions_ExplicitHttpConfig_Http2ProtocolOptions{},\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t&envoy_cluster_v3.Cluster{\n\t\t\t\t\tTransportSocket: envoy_v3.UpstreamTLSTransportSocket(\n\t\t\t\t\t\tenvoy_v3.UpstreamTLSContext(nil, \"external.address\", nil, \"h2\"),\n\t\t\t\t\t),\n\t\t\t\t},\n\t\t\t),\n\t\t),\n\t})\n\n\t// Now try the same configuration, but enable TLS (which\n\t// means HTTP/1.1 over TLS) rather than HTTP/2. We should get\n\t// TLS enabled with the overridden SNI name. but no HTTP/2\n\t// protocol config.\n\trh.OnDelete(fixture.NewProxy(\"kuard\").WithSpec(contour_api_v1.HTTPProxySpec{}))\n\trh.OnAdd(fixture.NewProxy(\"kuard\").\n\t\tWithFQDN(\"kuard.projectcontour.io\").\n\t\tWithSpec(contour_api_v1.HTTPProxySpec{\n\t\t\tRoutes: []contour_api_v1.Route{{\n\t\t\t\tServices: []contour_api_v1.Service{{\n\t\t\t\t\tProtocol: ref.To(\"tls\"),\n\t\t\t\t\tName: s1.Name,\n\t\t\t\t\tPort: 80,\n\t\t\t\t}},\n\t\t\t\tRequestHeadersPolicy: &contour_api_v1.HeadersPolicy{\n\t\t\t\t\tSet: []contour_api_v1.HeaderValue{{\n\t\t\t\t\t\tName: \"Host\",\n\t\t\t\t\t\tValue: \"external.address\",\n\t\t\t\t\t}},\n\t\t\t\t},\n\t\t\t}},\n\t\t}),\n\t)\n\n\tc.Request(routeType).Equals(&envoy_discovery_v3.DiscoveryResponse{\n\t\tTypeUrl: routeType,\n\t\tResources: resources(t,\n\t\t\tenvoy_v3.RouteConfiguration(\"ingress_http\",\n\t\t\t\tenvoy_v3.VirtualHost(\"kuard.projectcontour.io\",\n\t\t\t\t\t&envoy_route_v3.Route{\n\t\t\t\t\t\tMatch: routePrefix(\"/\"),\n\t\t\t\t\t\tAction: routeHostRewrite(\"default/kuard/80/f9439c1de8\", \"external.address\"),\n\t\t\t\t\t},\n\t\t\t\t),\n\t\t\t),\n\t\t),\n\t})\n\n\tc.Request(clusterType).Equals(&envoy_discovery_v3.DiscoveryResponse{\n\t\tTypeUrl: clusterType,\n\t\tResources: resources(t,\n\t\t\tDefaultCluster(\n\t\t\t\texternalNameCluster(\"default/kuard/80/f9439c1de8\", \"default/kuard\", \"default_kuard_80\", \"foo.io\", 80),\n\t\t\t\t&envoy_cluster_v3.Cluster{\n\t\t\t\t\tTransportSocket: envoy_v3.UpstreamTLSTransportSocket(\n\t\t\t\t\t\tenvoy_v3.UpstreamTLSContext(nil, \"external.address\", nil),\n\t\t\t\t\t),\n\t\t\t\t},\n\t\t\t),\n\t\t),\n\t})\n\n\tsec1 := &v1.Secret{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: \"secret\",\n\t\t\tNamespace: \"default\",\n\t\t},\n\t\tType: \"kubernetes.io/tls\",\n\t\tData: featuretests.Secretdata(featuretests.CERTIFICATE, featuretests.RSA_PRIVATE_KEY),\n\t}\n\n\t// Create TCPProxy with upstream protocol 'tls' to an externalName type service\n\t// and verify that the SNI on the upstream request matches the externalName value.\n\trh.OnDelete(fixture.NewProxy(\"kuard\").WithSpec(contour_api_v1.HTTPProxySpec{}))\n\trh.OnAdd(sec1)\n\trh.OnAdd(fixture.NewProxy(\"kuard\").\n\t\tWithFQDN(\"kuard.projectcontour.io\").\n\t\tWithCertificate(sec1.Name).\n\t\tWithSpec(contour_api_v1.HTTPProxySpec{\n\t\t\tTCPProxy: &contour_api_v1.TCPProxy{\n\t\t\t\tServices: []contour_api_v1.Service{{\n\t\t\t\t\tProtocol: ref.To(\"tls\"),\n\t\t\t\t\tName: s1.Name,\n\t\t\t\t\tPort: 80,\n\t\t\t\t}},\n\t\t\t},\n\t\t}),\n\t)\n\n\tc.Request(clusterType).Equals(&envoy_discovery_v3.DiscoveryResponse{\n\t\tTypeUrl: clusterType,\n\t\tResources: resources(t,\n\t\t\tDefaultCluster(\n\t\t\t\texternalNameCluster(\"default/kuard/80/7d449598f5\", \"default/kuard\", \"default_kuard_80\", \"foo.io\", 80),\n\t\t\t\t&envoy_cluster_v3.Cluster{\n\t\t\t\t\tTransportSocket: envoy_v3.UpstreamTLSTransportSocket(\n\t\t\t\t\t\tenvoy_v3.UpstreamTLSContext(nil, \"foo.io\", nil),\n\t\t\t\t\t),\n\t\t\t\t},\n\t\t\t),\n\t\t),\n\t})\n}", "func become_discoverable(args []string) {\n\tsongs := get_local_song_info(args[2])\n\tmsg_content := \"\"\n\tfor _, s := range songs {\n\t\tmsg_content += s\n\t}\n\tmsg := prepare_msg(INIT, 0, []byte(msg_content))\n\ttracker := send(*msg, TRACKER_IP+args[1])\n\tdefer tracker.Close()\n}", "func (o *SmscSession) GetLocalAddrOk() (*string, bool) {\n\tif o == nil || o.LocalAddr == nil {\n\t\treturn nil, false\n\t}\n\treturn o.LocalAddr, true\n}", "func (r *EpNodeAccelRiser) discoverLocalPhase2() {\n\t// Should never happen\n\tif r.epRF == nil {\n\t\terrlog.Printf(\"Error: RedfishEP == nil for odataID: %s\\n\",\n\t\t\tr.OdataID)\n\t\tr.LastStatus = EndpointInvalid\n\t\treturn\n\t}\n\tif r.LastStatus != VerifyingData {\n\t\treturn\n\t}\n\n\tr.Ordinal = r.epRF.getNodeAccelRiserOrdinal(r)\n\tr.Type = r.epRF.getNodeAccelRiserHMSType(r)\n\tr.ID = r.epRF.getNodeAccelRiserHMSID(r, r.Type, r.Ordinal)\n\tif r.NodeAccelRiserRF.Status.State != \"Absent\" {\n\t\tr.Status = \"Populated\"\n\t\tr.State = base.StatePopulated.String()\n\t\tr.Flag = base.FlagOK.String()\n\t\tgeneratedFRUID, err := GetNodeAccelRiserFRUID(r)\n\t\tif err != nil {\n\t\t\terrlog.Printf(\"FRUID Error: %s\\n\", err.Error())\n\t\t\terrlog.Printf(\"Using untrackable FRUID: %s\\n\", generatedFRUID)\n\t\t}\n\t\tr.FRUID = generatedFRUID\n\t} else {\n\t\tr.Status = \"Empty\"\n\t\tr.State = base.StateEmpty.String()\n\t\t//the state of the component is known (empty), it is not locked, does not have an alert or warning, so therefore Flag defaults to OK.\n\t\tr.Flag = base.FlagOK.String()\n\t}\n\t// Check if we have something valid to insert into the data store\n\tif (base.GetHMSType(r.ID) == base.NodeAccelRiser) && (r.Type == base.NodeAccelRiser.String()) {\n\t\terrlog.Printf(\"NodeAccelRiser discoverLocalPhase2: VALID xname ID ('%s') and Type ('%s') for: %s\\n\",\n\t\t\tr.ID, r.Type, r.NodeAccelRiserURL)\n\t} else {\n\t\terrlog.Printf(\"Error: Bad xname ID ('%s') or Type ('%s') for: %s\\n\",\n\t\t\tr.ID, r.Type, r.NodeAccelRiserURL)\n\t\tr.LastStatus = VerificationFailed\n\t\treturn\n\t}\n\tif rfVerbose > 0 {\n\t\tjout, _ := json.MarshalIndent(r, \"\", \" \")\n\t\terrlog.Printf(\"%s\\n\", jout)\n\t\terrlog.Printf(\"NodeAccelRiser ID: %s\\n\", r.ID)\n\t\terrlog.Printf(\"NodeAccelRiser FRUID: %s\\n\", r.FRUID)\n\t}\n\tr.LastStatus = DiscoverOK\n}", "func TestUnreachableMarks(t *testing.T) {\n\tseeds := []string {\"127.0.0.1:6000\",}\n\tmanager1 := CreatePeerManager(6000, 6001, nil, FullMode)\n\tmanager2 := CreatePeerManager(7000, 7001, seeds, FullMode)\n\tmanager3 := CreatePeerManager(8000, 8001, seeds, FullMode)\n\n\t// Change update period to lengthen the time between marking a peer unreachable \n\t// and the next status update\n\tmanager1.StatusUpdatePeriod=500*time.Millisecond\n\tmanager2.StatusUpdatePeriod=500*time.Millisecond\n\tmanager3.StatusUpdatePeriod=500*time.Millisecond\n\n\tmarkPeer := func(t *testing.T) {\n\t\tmanager1.MarkPeerUnreachable(\"127.0.0.1:8001\")\n\t\tmanager1.MarkPeerUnreachable(\"127.0.0.1:8001\")\n\t\tmanager1.MarkPeerUnreachable(\"127.0.0.1:8001\")\n\t\tavailable := GetPeerManagerAvailablePeers(manager1)\n\t\texpected := []string {\"127.0.0.1:6001\", \"127.0.0.1:7001\"}\n\t\tif !MapOnlyContains(available, expected) {\n\t\t\tt.Errorf(\"Peer 127.0.0.1:8001 wasn't marked unreachable %v\\n\", available)\n\t\t}\n\t}\n\n\t// After some time has passed all the peers should be available again\n\tallPeers := []string {\"127.0.0.1:6001\", \"127.0.0.1:7001\", \"127.0.0.1:8001\"}\n\tPeerManagerPropagationHelper(t, manager1, manager2, manager3,\n\t\tallPeers, allPeers, allPeers, markPeer, 3200*time.Millisecond, 8*time.Second)\n}", "func IsClusterLocal(domain string) bool {\n\treturn strings.HasSuffix(domain, pkgnet.GetClusterDomainName())\n}", "func loadProvider(providerConfig *provider.Config) (provider.Provider, error) {\n\tp, ok := providerCollection[providerConfig.Label]\n\tif !ok {\n\t\treturn nil, errors.NotFoundf(\"provider called `%s`\", providerConfig.Label)\n\t}\n\n\tvar err error\n\tp, err = p.Initialize(providerConfig)\n\tif err != nil {\n\t\tannotation := fmt.Sprintf(\"loading provider %s\", providerConfig.Label)\n\t\treturn nil, errors.Annotate(err, annotation)\n\t}\n\n\treturn p, nil\n}", "func (c *ChannelConn) LocalAddr() net.Addr {\n\treturn nil\n}", "func genLocalAddr() string {\n\treturn fmt.Sprintf(\"localhost:%d\", test.GetFreePort())\n}", "func TestEntryInitiallyUnknown(t *testing.T) {\n\tc := DefaultNUDConfigurations()\n\te, nudDisp, linkRes, clock := entryTestSetup(c)\n\n\te.mu.Lock()\n\tif e.mu.neigh.State != Unknown {\n\t\tt.Errorf(\"got e.mu.neigh.State = %q, want = %q\", e.mu.neigh.State, Unknown)\n\t}\n\te.mu.Unlock()\n\n\tclock.Advance(c.RetransmitTimer)\n\n\t// No probes should have been sent.\n\tlinkRes.mu.Lock()\n\tdiff := cmp.Diff([]entryTestProbeInfo(nil), linkRes.mu.probes)\n\tlinkRes.mu.Unlock()\n\tif diff != \"\" {\n\t\tt.Fatalf(\"link address resolver probes mismatch (-want, +got):\\n%s\", diff)\n\t}\n\n\t// No events should have been dispatched.\n\tnudDisp.mu.Lock()\n\tif diff := cmp.Diff([]testEntryEventInfo(nil), nudDisp.mu.events); diff != \"\" {\n\t\tt.Errorf(\"nud dispatcher events mismatch (-want, +got):\\n%s\", diff)\n\t}\n\tnudDisp.mu.Unlock()\n}", "func (m *Monitor) AddLocalCluster(versionObj *unstructured.Unstructured) bool {\n\tvar clusterVersionGvr = schema.GroupVersionResource{\n\t\tGroup: \"config.openshift.io\",\n\t\tVersion: \"v1\",\n\t\tResource: \"clusterversions\",\n\t}\n\tvar dynamicClient dynamic.Interface\n\tvar err error\n\tglog.V(2).Info(\"Adding Local Cluster ID.\")\n\tif versionObj == nil {\n\t\tdynamicClient = config.GetDynamicClient()\n\t\tversionObj, err = dynamicClient.Resource(clusterVersionGvr).Get(context.TODO(), \"version\", metav1.GetOptions{})\n\t}\n\tif err != nil {\n\t\tglog.V(2).Infof(\"Failed to get clusterversions : %v\", err)\n\t\treturn false\n\t}\n\tclusterID, _, err := unstructured.NestedString(versionObj.Object, \"spec\", \"clusterID\")\n\tif err != nil {\n\t\tglog.V(2).Infof(\"Failed to get OCP clusterID from version: %v\", err)\n\t\treturn false\n\t}\n\t// If the cluster ID is not empty add to list and return true\n\tif clusterID != \"\" {\n\t\tlock.Lock()\n\t\tm.ManagedClusterInfo = append(m.ManagedClusterInfo, types.ManagedClusterInfo{\n\t\t\tClusterID: clusterID,\n\t\t\tNamespace: localClusterName,\n\t\t})\n\t\tlock.Unlock()\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (a AppContext) DiscoveryToken() string {\n\treturn DiscoveryToken\n}", "func fakeDiscovery() discovery.DiscoveryInterface {\n\tfake := &fakediscovery.FakeDiscovery{Fake: &coretesting.Fake{}}\n\tapps := []metav1.APIResource{\n\t\t{Name: \"deployments\", Namespaced: true, Kind: \"Deployment\"},\n\t\t{Name: \"controllerrevisions\", Namespaced: true, Kind: \"ControllerRevision\"},\n\t\t{Name: \"daemonsets\", Namespaced: true, Kind: \"DaemonSet\"},\n\t\t{Name: \"replicasets\", Namespaced: true, Kind: \"ReplicaSet\"},\n\t\t{Name: \"statefulsets\", Namespaced: true, Kind: \"StatefulSet\"},\n\t}\n\tfake.Resources = []*metav1.APIResourceList{\n\t\t{\n\t\t\tGroupVersion: corev1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"bindings\", Namespaced: true, Kind: \"Binding\"},\n\t\t\t\t{Name: \"componentstatuses\", Kind: \"ComponentStatus\"},\n\t\t\t\t{Name: \"configmaps\", Namespaced: true, Kind: \"ConfigMap\"},\n\t\t\t\t{Name: \"endpoints\", Namespaced: true, Kind: \"Endpoints\"},\n\t\t\t\t{Name: \"events\", Namespaced: true, Kind: \"Event\"},\n\t\t\t\t{Name: \"limitranges\", Namespaced: true, Kind: \"LimitRange\"},\n\t\t\t\t{Name: \"namespaces\", Kind: \"Namespace\"},\n\t\t\t\t{Name: \"nodes\", Kind: \"Node\"},\n\t\t\t\t{Name: \"persistentvolumeclaims\", Namespaced: true, Kind: \"PersistentVolumeClaim\"},\n\t\t\t\t{Name: \"persistentvolumes\", Kind: \"PersistentVolume\"},\n\t\t\t\t{Name: \"pods\", Namespaced: true, Kind: \"Pod\"},\n\t\t\t\t{Name: \"podtemplates\", Namespaced: true, Kind: \"PodTemplate\"},\n\t\t\t\t{Name: \"replicationcontrollers\", Namespaced: true, Kind: \"ReplicationController\"},\n\t\t\t\t{Name: \"resourcequotas\", Namespaced: true, Kind: \"ResourceQuota\"},\n\t\t\t\t{Name: \"secrets\", Namespaced: true, Kind: \"Secret\"},\n\t\t\t\t{Name: \"serviceaccounts\", Namespaced: true, Kind: \"ServiceAccount\"},\n\t\t\t\t{Name: \"services\", Namespaced: true, Kind: \"Service\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: rbacv1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"clusterroles\", Kind: \"ClusterRole\"},\n\t\t\t\t{Name: \"clusterrolebindings\", Kind: \"ClusterRoleBinding\"},\n\t\t\t\t{Name: \"clusterroles\", Kind: \"ClusterRole\"},\n\t\t\t\t{Name: \"rolebindings\", Namespaced: true, Kind: \"RoleBinding\"},\n\t\t\t\t{Name: \"roles\", Namespaced: true, Kind: \"Role\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: appsv1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: apps,\n\t\t},\n\t\t{\n\t\t\tGroupVersion: appsv1beta1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: apps,\n\t\t},\n\t\t{\n\t\t\tGroupVersion: appsv1beta2.SchemeGroupVersion.String(),\n\t\t\tAPIResources: apps,\n\t\t},\n\t\t{\n\t\t\tGroupVersion: apiextensionsv1beta1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"customresourcedefinitions\", Kind: \"CustomResourceDefinition\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: apiextensionsv1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"customresourcedefinitions\", Kind: \"CustomResourceDefinition\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: storagev1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"storageclasses\", Kind: \"StorageClass\"},\n\t\t\t\t{Name: \"volumeattachments\", Kind: \"VolumeAttachment\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: storagev1beta1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"storageclasses\", Kind: \"StorageClass\"},\n\t\t\t\t{Name: \"volumeattachments\", Kind: \"VolumeAttachment\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: extensionsv1beta1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"ingresses\", Namespaced: true, Kind: \"Ingress\"},\n\t\t\t\t{Name: \"networkpolicies\", Namespaced: true, Kind: \"NetworkPolicy\"},\n\t\t\t\t{Name: \"podsecuritypolicies\", Kind: \"PodSecurityPolicy\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: networkingv1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"networkpolicies\", Namespaced: true, Kind: \"NetworkPolicy\"},\n\t\t\t\t{Name: \"ingresses\", Namespaced: true, Kind: \"Ingress\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: authenticationv1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"tokenreviews\", Kind: \"TokenReview\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: autoscalingv1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"horizontalpodautoscalers\", Kind: \"HorizontalPodAutoscaler\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: autoscalingv2beta1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"horizontalpodautoscalers\", Kind: \"HorizontalPodAutoscaler\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: autoscalingv2beta2.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"horizontalpodautoscalers\", Kind: \"HorizontalPodAutoscaler\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: policyv1beta1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"poddisruptionbudgets\", Namespaced: true, Kind: \"PodDisruptionBudget\"},\n\t\t\t\t{Name: \"podsecuritypolicies\", Kind: \"PodSecurityPolicy\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: rbacsyncv1alpha.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"clusterrbacsyncconfigs\", Kind: \"ClusterRBACSyncConfig\"},\n\t\t\t\t{Name: \"rbacsyncconfigs\", Namespaced: true, Kind: \"RBACSyncConfig\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: batchv1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"jobs\", Namespaced: true, Kind: \"Job\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: batchv1b1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"cronjobs\", Namespaced: true, Kind: \"CronJob\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: arkv1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"backups\", Namespaced: true, Kind: \"Backup\"},\n\t\t\t\t{Name: \"backupstoragelocations\", Namespaced: true, Kind: \"BackupStorageLocation\"},\n\t\t\t\t{Name: \"configs\", Namespaced: true, Kind: \"Config\"},\n\t\t\t\t{Name: \"deletebackuprequests\", Namespaced: true, Kind: \"DeleteBackupRequest\"},\n\t\t\t\t{Name: \"downloadrequests\", Namespaced: true, Kind: \"DownloadRequest\"},\n\t\t\t\t{Name: \"podvolumebackups\", Namespaced: true, Kind: \"PodVolumeBackup\"},\n\t\t\t\t{Name: \"podvolumerestores\", Namespaced: true, Kind: \"PodVolumeRestore\"},\n\t\t\t\t{Name: \"resticrepositories\", Namespaced: true, Kind: \"ResticRepository\"},\n\t\t\t\t{Name: \"restores\", Namespaced: true, Kind: \"Restore\"},\n\t\t\t\t{Name: \"schedules\", Namespaced: true, Kind: \"Schedule\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: istio.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"sidecar\", Namespaced: true, Kind: \"Sidecar\"},\n\t\t\t\t{Name: \"virtualservice\", Namespaced: true, Kind: \"VirtualService\"},\n\t\t\t\t{Name: \"destinationrule\", Namespaced: true, Kind: \"DestinationRule\"},\n\t\t\t\t{Name: \"gateway\", Namespaced: true, Kind: \"Gateway\"},\n\t\t\t\t{Name: \"serviceentry\", Kind: \"ServiceEntry\"},\n\t\t\t\t{Name: \"envoyfilter\", Namespaced: true, Kind: \"EnvoyFilter\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: istiov1b1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"sidecar\", Namespaced: true, Kind: \"Sidecar\"},\n\t\t\t\t{Name: \"virtualservice\", Namespaced: true, Kind: \"VirtualService\"},\n\t\t\t\t{Name: \"destinationrule\", Namespaced: true, Kind: \"DestinationRule\"},\n\t\t\t\t{Name: \"gateway\", Namespaced: true, Kind: \"Gateway\"},\n\t\t\t\t{Name: \"serviceentry\", Kind: \"ServiceEntry\"},\n\t\t\t\t{Name: \"envoyfilter\", Namespaced: true, Kind: \"EnvoyFilter\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: istiosecurityv1beta1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"authorizationpolicy\", Namespaced: true, Kind: \"AuthorizationPolicy\"},\n\t\t\t\t{Name: \"peerauthentication\", Namespaced: true, Kind: \"PeerAuthentication\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: csr.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"certificatesigningrequests\", Kind: \"CertificateSigningRequest\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: csrv1b1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"certificatesigningrequests\", Kind: \"CertificateSigningRequest\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: admissionregistrationv1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"validatingwebhookconfigurations\", Kind: \"ValidatingWebhookConfiguration\"},\n\t\t\t\t{Name: \"mutatingwebhookconfigurations\", Kind: \"MutatingWebhookConfiguration\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: admissionregistrationv1b1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"validatingwebhookconfigurations\", Kind: \"ValidatingWebhookConfiguration\"},\n\t\t\t\t{Name: \"mutatingwebhookconfigurations\", Kind: \"MutatingWebhookConfiguration\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: schedulingv1beta1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"priorityclass\", Kind: \"PriorityClass\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: schedulingv1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"priorityclass\", Kind: \"PriorityClass\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: apiregistrationv1b1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"apiservice\", Kind: \"APIService\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: apiregistrationv1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"apiservice\", Kind: \"APIService\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: vpav1.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"verticalpodautoscalers\", Kind: \"VerticalPodAutoscaler\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tGroupVersion: vpav1beta2.SchemeGroupVersion.String(),\n\t\t\tAPIResources: []metav1.APIResource{\n\t\t\t\t{Name: \"verticalpodautoscalers\", Kind: \"VerticalPodAutoscaler\"},\n\t\t\t},\n\t\t},\n\t}\n\treturn fake\n}", "func Provider() tfbridge.ProviderInfo {\n\t// Instantiate the Terraform provider\n\tp := shimv2.NewProvider(xyz.Provider())\n\n\t// Create a Pulumi provider mapping\n\tprov := tfbridge.ProviderInfo{\n\t\tP: p,\n\t\tName: \"xyz\",\n\t\t// DisplayName is a way to be able to change the casing of the provider\n\t\t// name when being displayed on the Pulumi registry\n\t\tDisplayName: \"\",\n\t\t// The default publisher for all packages is Pulumi.\n\t\t// Change this to your personal name (or a company name) that you\n\t\t// would like to be shown in the Pulumi Registry if this package is published\n\t\t// there.\n\t\tPublisher: \"Pulumi\",\n\t\t// LogoURL is optional but useful to help identify your package in the Pulumi Registry\n\t\t// if this package is published there.\n\t\t//\n\t\t// You may host a logo on a domain you control or add an SVG logo for your package\n\t\t// in your repository and use the raw content URL for that file as your logo URL.\n\t\tLogoURL: \"\",\n\t\t// PluginDownloadURL is an optional URL used to download the Provider\n\t\t// for use in Pulumi programs\n\t\t// e.g https://github.com/org/pulumi-provider-name/releases/\n\t\tPluginDownloadURL: \"\",\n\t\tDescription: \"A Pulumi package for creating and managing xyz cloud resources.\",\n\t\t// category/cloud tag helps with categorizing the package in the Pulumi Registry.\n\t\t// For all available categories, see `Keywords` in\n\t\t// https://www.pulumi.com/docs/guides/pulumi-packages/schema/#package.\n\t\tKeywords: []string{\"pulumi\", \"xyz\", \"category/cloud\"},\n\t\tLicense: \"Apache-2.0\",\n\t\tHomepage: \"https://www.pulumi.com\",\n\t\tRepository: \"https://github.com/pulumi/pulumi-xyz\",\n\t\t// The GitHub Org for the provider - defaults to `terraform-providers`. Note that this\n\t\t// should match the TF provider module's require directive, not any replace directives.\n\t\tGitHubOrg: \"\",\n\t\tConfig: map[string]*tfbridge.SchemaInfo{\n\t\t\t// Add any required configuration here, or remove the example below if\n\t\t\t// no additional points are required.\n\t\t\t// \"region\": {\n\t\t\t// \tType: tfbridge.MakeType(\"region\", \"Region\"),\n\t\t\t// \tDefault: &tfbridge.DefaultInfo{\n\t\t\t// \t\tEnvVars: []string{\"AWS_REGION\", \"AWS_DEFAULT_REGION\"},\n\t\t\t// \t},\n\t\t\t// },\n\t\t},\n\t\tPreConfigureCallback: preConfigureCallback,\n\t\tResources: map[string]*tfbridge.ResourceInfo{\n\t\t\t// Map each resource in the Terraform provider to a Pulumi type. Two examples\n\t\t\t// are below - the single line form is the common case. The multi-line form is\n\t\t\t// needed only if you wish to override types or other default options.\n\t\t\t//\n\t\t\t// \"aws_iam_role\": {Tok: tfbridge.MakeResource(mainPkg, mainMod, \"IamRole\")}\n\t\t\t//\n\t\t\t// \"aws_acm_certificate\": {\n\t\t\t// \tTok: tfbridge.MakeResource(mainPkg, mainMod, \"Certificate\"),\n\t\t\t// \tFields: map[string]*tfbridge.SchemaInfo{\n\t\t\t// \t\t\"tags\": {Type: tfbridge.MakeType(mainPkg, \"Tags\")},\n\t\t\t// \t},\n\t\t\t// },\n\t\t},\n\t\tDataSources: map[string]*tfbridge.DataSourceInfo{\n\t\t\t// Map each resource in the Terraform provider to a Pulumi function. An example\n\t\t\t// is below.\n\t\t\t// \"aws_ami\": {Tok: tfbridge.MakeDataSource(mainPkg, mainMod, \"getAmi\")},\n\t\t},\n\t\tJavaScript: &tfbridge.JavaScriptInfo{\n\t\t\t// List any npm dependencies and their versions\n\t\t\tDependencies: map[string]string{\n\t\t\t\t\"@pulumi/pulumi\": \"^3.0.0\",\n\t\t\t},\n\t\t\tDevDependencies: map[string]string{\n\t\t\t\t\"@types/node\": \"^10.0.0\", // so we can access strongly typed node definitions.\n\t\t\t\t\"@types/mime\": \"^2.0.0\",\n\t\t\t},\n\t\t\t// See the documentation for tfbridge.OverlayInfo for how to lay out this\n\t\t\t// section, or refer to the AWS provider. Delete this section if there are\n\t\t\t// no overlay files.\n\t\t\t//Overlay: &tfbridge.OverlayInfo{},\n\t\t},\n\t\tPython: &tfbridge.PythonInfo{\n\t\t\t// List any Python dependencies and their version ranges\n\t\t\tRequires: map[string]string{\n\t\t\t\t\"pulumi\": \">=3.0.0,<4.0.0\",\n\t\t\t},\n\t\t},\n\t\tGolang: &tfbridge.GolangInfo{\n\t\t\tImportBasePath: filepath.Join(\n\t\t\t\tfmt.Sprintf(\"github.com/pulumi/pulumi-%[1]s/sdk/\", mainPkg),\n\t\t\t\ttfbridge.GetModuleMajorVersion(version.Version),\n\t\t\t\t\"go\",\n\t\t\t\tmainPkg,\n\t\t\t),\n\t\t\tGenerateResourceContainerTypes: true,\n\t\t},\n\t\tCSharp: &tfbridge.CSharpInfo{\n\t\t\tPackageReferences: map[string]string{\n\t\t\t\t\"Pulumi\": \"3.*\",\n\t\t\t},\n\t\t},\n\t}\n\n\t// These are new API's that you may opt to use to automatically compute resource tokens,\n\t// and apply auto aliasing for full backwards compatibility.\n\t// For more information, please reference: https://pkg.go.dev/github.com/pulumi/pulumi-terraform-bridge/v3/pkg/tfbridge#ProviderInfo.ComputeTokens\n\tprov.MustComputeTokens(tokens.SingleModule(\"xyz_\", mainMod,\n\t\ttokens.MakeStandard(mainPkg)))\n\tprov.MustApplyAutoAliasing()\n\tprov.SetAutonaming(255, \"-\")\n\n\treturn prov\n}", "func (m *Module) LocalNameForProvider(p addrs.Provider) string {\n\tif existing, exists := m.ProviderLocalNames[p]; exists {\n\t\treturn existing\n\t} else {\n\t\t// If there isn't a map entry, fall back to the default:\n\t\t// Type = LocalName\n\t\treturn p.Type\n\t}\n}", "func NewLocalDatabaseProvider(name string, type_ string) *LocalDatabaseProvider {\n\tthis := LocalDatabaseProvider{}\n\tthis.Name = name\n\tthis.Type = type_\n\tvar deviceLimitPerUser int32 = 100\n\tthis.DeviceLimitPerUser = &deviceLimitPerUser\n\tvar adminProvider bool = false\n\tthis.AdminProvider = &adminProvider\n\tvar inactivityTimeoutMinutes int32 = 0\n\tthis.InactivityTimeoutMinutes = &inactivityTimeoutMinutes\n\tvar networkInactivityTimeoutEnabled bool = false\n\tthis.NetworkInactivityTimeoutEnabled = &networkInactivityTimeoutEnabled\n\tvar blockLocalDnsRequests bool = false\n\tthis.BlockLocalDnsRequests = &blockLocalDnsRequests\n\tvar userLockoutThreshold int32 = 5\n\tthis.UserLockoutThreshold = &userLockoutThreshold\n\tvar userLockoutDurationMinutes int32 = 1\n\tthis.UserLockoutDurationMinutes = &userLockoutDurationMinutes\n\tvar minPasswordLength int32 = 0\n\tthis.MinPasswordLength = &minPasswordLength\n\treturn &this\n}", "func (sc *ShamClient) discover() error {\n\tsc.logger.Debugf(\"discovering endpoints for service %s\", sc.serviceName)\n\tresponse, err := sc.httpClient.Get(sc.serviceRegistry.URL + \"/sgulreg/services/\" + sc.serviceName)\n\tif err != nil {\n\t\tsc.logger.Errorf(\"Error making service discovery HTTP request: %s\", err)\n\t\tsc.fallbackDiscovery()\n\t\treturn ErrFailedDiscoveryRequest\n\t}\n\tsc.logger.Debugf(\"discovery response content-length: %s\", response.Header.Get(\"Content-length\"))\n\n\tbody, err := ioutil.ReadAll(response.Body)\n\tif err != nil {\n\t\tsc.logger.Errorf(\"Error reading service discovery HTTP response body: %s\", err)\n\t\tsc.fallbackDiscovery()\n\t\treturn ErrFailedDiscoveryResponseBody\n\t}\n\tdefer response.Body.Close()\n\n\tvar serviceInfo registry.ServiceInfoResponse\n\tjson.Unmarshal([]byte(body), &serviceInfo)\n\n\tif len(serviceInfo.Instances) > 0 {\n\t\tvar endpoints []string\n\t\tfor _, instance := range serviceInfo.Instances {\n\t\t\tsc.logger.Debugf(\"discovered service %s endpoint serviceID: %s\", sc.serviceName, instance.InstanceID)\n\t\t\tendpoint := fmt.Sprintf(\"%s://%s%s\", instance.Schema, instance.Host, sc.apiPath)\n\t\t\tendpoints = append(endpoints, endpoint)\n\t\t}\n\n\t\t// sc.localRegistry = endpoints\n\t\tsc.setLocalRegistry(endpoints)\n\t\tsc.logger.Infof(\"discovered service %s endpoints: %+v\", sc.serviceName, sc.localRegistry)\n\t}\n\n\tif len(sc.localRegistry) == 0 {\n\t\t// sc.localRegistry = sc.serviceRegistry.Fallback\n\t\tsc.setLocalRegistry(sc.serviceRegistry.Fallback)\n\t\tsc.logger.Infof(\"using Fallback registry for service %s: %+v\", sc.serviceName, sc.localRegistry)\n\t}\n\n\treturn nil\n}", "func (a *Adapter) makeProviderOrDie() provider.CustomMetricsProvider {\n\tconfig, err := a.ClientConfig()\n\tif err != nil {\n\t\tklog.Fatalf(\"unable to construct dynamic client: %v\", err)\n\t}\n\n\tclient, err := a.DynamicClient()\n\tif err != nil {\n\t\tklog.Fatalf(\"unable to construct dynamic client: %v\", err)\n\t}\n\n\tmapper, err := a.RESTMapper()\n\tif err != nil {\n\t\tklog.Fatalf(\"unable to construct discovery REST mapper: %v\", err)\n\t}\n\n\treturn customprovider.New(client, config, mapper)\n}", "func TestMinimal_NoneDNS(t *testing.T) {\n\tt.Setenv(\"KOPS_RUN_TOO_NEW_VERSION\", \"1\")\n\n\tnewIntegrationTest(\"minimal.example.com\", \"minimal-dns-none\").\n\t\twithAddons(\n\t\t\tawsEBSCSIAddon,\n\t\t\tawsCCMAddon,\n\t\t).\n\t\trunTestTerraformAWS(t)\n}", "func (o *LocalDatabaseProvider) GetAdminProviderOk() (*bool, bool) {\n\tif o == nil || o.AdminProvider == nil {\n\t\treturn nil, false\n\t}\n\treturn o.AdminProvider, true\n}", "func (m *Meta) providerLocalCacheDir() *providercache.Dir {\n\tm.fixupMissingWorkingDir()\n\tdir := m.WorkingDir.ProviderLocalCacheDir()\n\treturn providercache.NewDir(dir)\n}", "func Test_Provider(t *testing.T) {\n\t// SetLogLevel(\"TRACE\")\n\t// CheckVersion()\n\n\t// Start provider API in the background\n\tgo InitProvider()\n\t// err := InitProvider()\n\t// if err != nil {\n\t// \tlog.Fatalf(\"Error initializing Provider %+v\", err)\n\t// }\n\n\tverifier := HTTPVerifier{}\n\t// Authorization middleware\n\t// This is your chance to modify the request before it hits your provider\n\t// NOTE: this should be used very carefully, as it has the potential to\n\t// _change_ the contract\n\t// f := func(next http.Handler) http.Handler {\n\t// \treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t// \t\tlog.Println(\"[DEBUG] HOOK request filter\")\n\t// \t\t// r.Header.Add(\"Authorization\", \"Bearer 1234-dynamic-value\")\n\t// \t\tnext.ServeHTTP(w, r)\n\t// \t})\n\t// }\n\n\t// Verify the Provider with local Pact Files\n\terr := verifier.VerifyProvider(t, VerifyRequest{\n\t\tProviderBaseURL: \"http://localhost:9000\",\n\t\tBrokerURL: \"http://localhost:9292\",\n\t\tProvider: \"GreetingAPI\",\n\t\tProviderVersion: \"1.0.0\",\n\t\tPublishVerificationResults: true,\n\t\t// PactFiles: []string{\n\t\t// \tfilepath.ToSlash(fmt.Sprintf(\"%s/GreetingAPIConsumer-GreetingAPI.json\", pactDir)),\n\t\t// },\n\t\t// RequestFilter: f,\n\t\t// BeforeEach: func() error {\n\t\t// \tlog.Println(\"[DEBUG] HOOK before each\")\n\t\t// \treturn nil\n\t\t// },\n\t\t// AfterEach: func() error {\n\t\t// \tlog.Println(\"[DEBUG] HOOK after each\")\n\t\t// \treturn nil\n\t\t// },\n\t\t// StateHandlers: StateHandlers{\n\t\t// \t\"User foo exists\": func(setup bool, s ProviderStateV3) (ProviderStateV3Response, error) {\n\n\t\t// \t\tif setup {\n\t\t// \t\t\tlog.Println(\"[DEBUG] HOOK calling user foo exists state handler\", s)\n\t\t// \t\t} else {\n\t\t// \t\t\tlog.Println(\"[DEBUG] HOOK teardown the 'User foo exists' state\")\n\t\t// \t\t}\n\n\t\t// \t\t// ... do something, such as create \"foo\" in the database\n\n\t\t// \t\t// Optionally (if there are generators in the pact) return provider state values to be used in the verification\n\t\t// \t\treturn ProviderStateV3Response{\"uuid\": \"1234\"}, nil\n\t\t// \t},\n\t\t// },\n\t})\n\n\tassert.NoError(t, err)\n}", "func TestPreparerInterface(t *testing.T) {\n\tt.Parallel()\n\n\tassert.Implements(t, (*resource.Resource)(nil), new(user.Preparer))\n}", "func LivenessProbe(w http.ResponseWriter, r *http.Request) {\n\tglog.V(2).Info(\"livenessProbe - Checking local cluster id.\")\n\tmonitor := monitor.NewClusterMonitor()\n\n\t//Get local-cluster id , if -1 is returned then service will\n\t// not be able to get to cloud.redhat.com\n\tif monitor.GetLocalCluster() == \"-1\" {\n\t\t// Respond with error.\n\t\tglog.Warning(\"Cannot get local-cluster id.\")\n\t\thttp.Error(w, \"Cannot get local-cluster id.\", 503)\n\t\treturn\n\t}\n\t// Respond with success\n\tfmt.Fprint(w, \"OK\")\n}", "func shouldDiscoverHost(name string) bool {\n\tparts := strings.Split(name, \".\")\n\tif len(parts) == 1 {\n\t\tif parts[0] == \"localhost\" {\n\t\t\treturn false\n\t\t}\n\t\treturn true\n\t}\n\treturn parts[len(parts)-1] == domain\n}", "func Local(clArgs []string, stdin io.Reader, stdout, stderr io.Writer, reg *testing.Registry, d Delegate) int {\n\tcfg := NewStaticConfig(reg, localTestTimeout, d)\n\treturn run(context.Background(), clArgs, stdin, stdout, stderr, cfg)\n}", "func (i instances) discoverNodeByProviderID(ctx context.Context, providerID string) (*vmopv1alpha1.VirtualMachine, error) {\n\treturn discoverNodeByProviderID(ctx, providerID, i.namespace, i.vmClient)\n}", "func (mr *MockInformationMockRecorder) LocalLocation() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"LocalLocation\", reflect.TypeOf((*MockInformation)(nil).LocalLocation))\n}", "func (_m *AuthServer) mustEmbedUnimplementedAuthServer() {\n\t_m.Called()\n}", "func DiscoveryRegister() (cancel context.CancelFunc) {\n\tconf := &naming.Config{\n\t\tNodes: config.Nodes, // NOTE: 配置种子节点(1个或多个),client内部可根据/discovery/nodes节点获取全部node(方便后面增减节点)\n\t\tZone: config.Zone,\n\t\tEnv: config.Env,\n\t}\n\tdis := naming.New(conf)\n\tins := &naming.Instance{\n\t\tZone: config.Zone,\n\t\tEnv: config.Env,\n\t\tAppID: config.AppID,\n\t\t// Hostname:\"\", // NOTE: hostname 不需要,会优先使用discovery new时Config配置的值,如没有则从os.Hostname方法获取!!!\n\t\tAddrs: config.Addrs,\n\t\tLastTs: time.Now().Unix(),\n\t\tMetadata: config.Metadata,\n\t}\n\tcancel, _ = dis.Register(ins)\n\tfmt.Println(\"register\")\n\t// Unordered output4\n\treturn\n}", "func (a AppContext) DiscoveryAddress() string {\n\treturn DiscoveryURL\n}", "func (s *Drive) Local() bool {\n\treturn s.client.Local()\n}", "func loadLocalOrCmConfigIfValid() {\n\n\tswitch len(devStartOps.LocalSyncDir) {\n\tcase 0:\n\t\tp, err := nocalhostSvc.GetProfile()\n\t\tmust(err)\n\n\t\tif p.Associate == \"\" {\n\t\t\tmust(errors.New(\"'local-sync(-s)' should specify while svc is not associate with local dir\"))\n\t\t}\n\t\tdevStartOps.LocalSyncDir = append(devStartOps.LocalSyncDir, p.Associate)\n\n\t\t_ = nocalhostApp.ReloadSvcCfg(deployment, base.SvcTypeOf(serviceType), false, false)\n\tcase 1:\n\t\tmust(nocalhostSvc.Associate(devStartOps.LocalSyncDir[0]))\n\n\t\t_ = nocalhostApp.ReloadSvcCfg(deployment, base.SvcTypeOf(serviceType), false, false)\n\tdefault:\n\t\tlog.Fatal(errors.New(\"Can not define multi 'local-sync(-s)'\"))\n\t}\n}", "func (udp *UdpServer) handleDiscovery(dev *iotDev) ([]byte, error) {\n var err error\n var ips []net.IP\n\n ips, err = udp.getItfIps(udp.itf)\n if err != nil {\n return nil, err\n }\n\n if len(ips) == 0 {\n msg := fmt.Sprintf(\"wifiItf %f has no IP addresses.\\n\", udp.itf.Name)\n return nil, errors.New(msg)\n }\n\n return dev.sendCmd(udp.cfg.UdpPort, newServerCmd(ips[0], udp.cfg.TcpPort))\n}", "func (u *UnknownProvider) GetProviderString() string {\n\treturn \"unknown\"\n}", "func TestExternalIP(t *testing.T) {\n\t_, err := ExternalIP()\n\tif err != nil {\n\t\tt.Errorf(\"ExternalIP failed : %w\", err)\n\t}\n}" ]
[ "0.7037146", "0.7020437", "0.66114974", "0.6474944", "0.5546048", "0.5539704", "0.55262434", "0.55180764", "0.5477116", "0.5337827", "0.52536297", "0.52428377", "0.5181303", "0.5100078", "0.5093676", "0.509003", "0.5075192", "0.5007985", "0.49998957", "0.49982086", "0.49700177", "0.49427873", "0.49334773", "0.49278128", "0.49228305", "0.48673707", "0.48529282", "0.48302767", "0.4821692", "0.4812568", "0.4810243", "0.47995466", "0.47780803", "0.47775128", "0.47739094", "0.4763164", "0.47615978", "0.47608915", "0.47448874", "0.47310007", "0.47281405", "0.47171745", "0.46718708", "0.4665009", "0.46612445", "0.46556732", "0.46483856", "0.46367523", "0.46310568", "0.46271062", "0.458665", "0.45667934", "0.45661154", "0.4547736", "0.454137", "0.45378563", "0.4534224", "0.45237008", "0.45030773", "0.44984004", "0.44900227", "0.4489459", "0.44875947", "0.44839355", "0.4473335", "0.44713357", "0.44587627", "0.44537935", "0.4453793", "0.4452523", "0.44363734", "0.44327113", "0.44267768", "0.4426143", "0.44196156", "0.4419439", "0.44179124", "0.44171548", "0.4415467", "0.44045547", "0.4402821", "0.44022715", "0.4400437", "0.4400359", "0.43985456", "0.4397389", "0.43966454", "0.43958127", "0.43803078", "0.43796116", "0.4376081", "0.43708915", "0.4369251", "0.43680543", "0.43650123", "0.43533868", "0.4343478", "0.43426666", "0.43424764", "0.43420917" ]
0.71185607
0
PrivateKey mocks base method
func (m *MockClient) PrivateKey() core.Key { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "PrivateKey") ret0, _ := ret[0].(core.Key) return ret0 }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (m *MockisCryptoAsymApiReqSetupPrivateKeyEx_Key) isCryptoAsymApiReqSetupPrivateKeyEx_Key() {\n\tm.ctrl.Call(m, \"isCryptoAsymApiReqSetupPrivateKeyEx_Key\")\n}", "func (c *HTTPClientMock) APIKeyPrivate() string {\n\treturn c.apiKeyPrivate\n}", "func (c CryptoServiceTester) TestGetPrivateKeyMultipleKeystores(t *testing.T) {\n\tcryptoService := c.cryptoServiceFactory()\n\tcryptoService.keyStores = append(cryptoService.keyStores,\n\t\ttrustmanager.NewKeyMemoryStore(passphraseRetriever))\n\n\tprivKey, err := utils.GenerateECDSAKey(rand.Reader)\n\trequire.NoError(t, err, c.errorMsg(\"error creating key\"))\n\n\tfor _, store := range cryptoService.keyStores {\n\t\terr := store.AddKey(trustmanager.KeyInfo{Role: c.role, Gun: c.gun}, privKey)\n\t\trequire.NoError(t, err)\n\t}\n\n\tfoundKey, role, err := cryptoService.GetPrivateKey(privKey.ID())\n\trequire.NoError(t, err, c.errorMsg(\"failed to get private key\"))\n\trequire.Equal(t, c.role, role)\n\trequire.Equal(t, privKey.ID(), foundKey.ID())\n}", "func TestGenPrivateKey(t *testing.T) {\n\t// test that calling by default generates an RSA private key\n\ttpl := `{{genPrivateKey \"\"}}`\n\tout, err := runRaw(tpl, nil)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tif !strings.Contains(out, \"RSA PRIVATE KEY\") {\n\t\tt.Error(\"Expected RSA PRIVATE KEY\")\n\t}\n\t// test all acceptable arguments\n\ttpl = `{{genPrivateKey \"rsa\"}}`\n\tout, err = runRaw(tpl, nil)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tif !strings.Contains(out, \"RSA PRIVATE KEY\") {\n\t\tt.Error(\"Expected RSA PRIVATE KEY\")\n\t}\n\ttpl = `{{genPrivateKey \"dsa\"}}`\n\tout, err = runRaw(tpl, nil)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tif !strings.Contains(out, \"DSA PRIVATE KEY\") {\n\t\tt.Error(\"Expected DSA PRIVATE KEY\")\n\t}\n\ttpl = `{{genPrivateKey \"ecdsa\"}}`\n\tout, err = runRaw(tpl, nil)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tif !strings.Contains(out, \"EC PRIVATE KEY\") {\n\t\tt.Error(\"Expected EC PRIVATE KEY\")\n\t}\n\ttpl = `{{genPrivateKey \"ed25519\"}}`\n\tout, err = runRaw(tpl, nil)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tif !strings.Contains(out, \"PRIVATE KEY\") {\n\t\tt.Error(\"Expected PRIVATE KEY\")\n\t}\n\t// test bad\n\ttpl = `{{genPrivateKey \"bad\"}}`\n\tout, err = runRaw(tpl, nil)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tif out != \"Unknown type bad\" {\n\t\tt.Error(\"Expected type 'bad' to be an unknown crypto algorithm\")\n\t}\n\t// ensure that we can base64 encode the string\n\ttpl = `{{genPrivateKey \"rsa\" | b64enc}}`\n\t_, err = runRaw(tpl, nil)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n}", "func (m *MockisCryptoAsymApiRespSetupPrivateKey_KeyInfo) isCryptoAsymApiRespSetupPrivateKey_KeyInfo() {\n\tm.ctrl.Call(m, \"isCryptoAsymApiRespSetupPrivateKey_KeyInfo\")\n}", "func TestPrivateKey(t *testing.T) {\n\tconst jsonKey = `{\"keys\":\n [\n {\"kty\":\"EC\",\n \"crv\":\"P-256\",\n \"x\":\"MKBCTNIcKUSDii11ySs3526iDZ8AiTo7Tu6KPAqv7D4\",\n \"y\":\"4Etl6SRW2YiLUrN5vfvVHuhp7x8PxltmWWlbbM4IFyM\",\n \"d\":\"870MB6gfuTJ4HtUnUvYMyJpr5eUZNP4Bk43bVdj3eAE\",\n \"use\":\"enc\",\n \"kid\":\"1\"},\n\n {\"kty\":\"RSA\",\n \"n\":\"0vx7agoebGcQSuuPiLJXZptN9nndrQmbXEps2aiAFbWhM78LhWx4cbbfAAtVT86zwu1RK7aPFFxuhDR1L6tSoc_BJECPebWKRXjBZCiFV4n3oknjhMstn64tZ_2W-5JsGY4Hc5n9yBXArwl93lqt7_RN5w6Cf0h4QyQ5v-65YGjQR0_FDW2QvzqY368QQMicAtaSqzs8KJZgnYb9c7d0zgdAZHzu6qMQvRL5hajrn1n91CbOpbISD08qNLyrdkt-bFTWhAI4vMQFh6WeZu0fM4lFd2NcRwr3XPksINHaQ-G_xBniIqbw0Ls1jF44-csFCur-kEgU8awapJzKnqDKgw\",\n \"e\":\"AQAB\",\n \"d\":\"X4cTteJY_gn4FYPsXB8rdXix5vwsg1FLN5E3EaG6RJoVH-HLLKD9M7dx5oo7GURknchnrRweUkC7hT5fJLM0WbFAKNLWY2vv7B6NqXSzUvxT0_YSfqijwp3RTzlBaCxWp4doFk5N2o8Gy_nHNKroADIkJ46pRUohsXywbReAdYaMwFs9tv8d_cPVY3i07a3t8MN6TNwm0dSawm9v47UiCl3Sk5ZiG7xojPLu4sbg1U2jx4IBTNBznbJSzFHK66jT8bgkuqsk0GjskDJk19Z4qwjwbsnn4j2WBii3RL-Us2lGVkY8fkFzme1z0HbIkfz0Y6mqnOYtqc0X4jfcKoAC8Q\",\n \"p\":\"83i-7IvMGXoMXCskv73TKr8637FiO7Z27zv8oj6pbWUQyLPQBQxtPVnwD20R-60eTDmD2ujnMt5PoqMrm8RfmNhVWDtjjMmCMjOpSXicFHj7XOuVIYQyqVWlWEh6dN36GVZYk93N8Bc9vY41xy8B9RzzOGVQzXvNEvn7O0nVbfs\",\n \"q\":\"3dfOR9cuYq-0S-mkFLzgItgMEfFzB2q3hWehMuG0oCuqnb3vobLyumqjVZQO1dIrdwgTnCdpYzBcOfW5r370AFXjiWft_NGEiovonizhKpo9VVS78TzFgxkIdrecRezsZ-1kYd_s1qDbxtkDEgfAITAG9LUnADun4vIcb6yelxk\",\n \"dp\":\"G4sPXkc6Ya9y8oJW9_ILj4xuppu0lzi_H7VTkS8xj5SdX3coE0oimYwxIi2emTAue0UOa5dpgFGyBJ4c8tQ2VF402XRugKDTP8akYhFo5tAA77Qe_NmtuYZc3C3m3I24G2GvR5sSDxUyAN2zq8Lfn9EUms6rY3Ob8YeiKkTiBj0\",\n \"dq\":\"s9lAH9fggBsoFR8Oac2R_E2gw282rT2kGOAhvIllETE1efrA6huUUvMfBcMpn8lqeW6vzznYY5SSQF7pMdC_agI3nG8Ibp1BUb0JUiraRNqUfLhcQb_d9GF4Dh7e74WbRsobRonujTYN1xCaP6TO61jvWrX-L18txXw494Q_cgk\",\n \"qi\":\"GyM_p6JrXySiz1toFgKbWV-JdI3jQ4ypu9rbMWx3rQJBfmt0FoYzgUIZEVFEcOqwemRN81zoDAaa-Bk0KWNGDjJHZDdDmFhW3AN7lI-puxk_mHZGJ11rxyR8O55XLSe3SPmRfKwZI6yU24ZxvQKFYItdldUKGzO6Ia6zTKhAVRU\",\n \"alg\":\"RS256\",\n \"kid\":\"2011-04-29\"}\n ]\n }`\n\n\tjwt, err := Unmarshal([]byte(jsonKey))\n\tif err != nil {\n\t\tt.Fatal(\"Unmarshal: \", err)\n\t} else if len(jwt.Keys) != 2 {\n\t\tt.Fatalf(\"Expected 2 keys, got %d\", len(jwt.Keys))\n\t}\n\n\tkeys := make([]crypto.PrivateKey, len(jwt.Keys))\n\tfor ii, jwt := range jwt.Keys {\n\t\tkeys[ii], err = jwt.DecodePrivateKey()\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Failed to decode key %d: %v\", ii, err)\n\t\t}\n\t}\n\n\tif key0, ok := keys[0].(*ecdsa.PrivateKey); !ok {\n\t\tt.Fatalf(\"Expected ECDSA key[0], got %T\", keys[0])\n\t} else if key1, ok := keys[1].(*rsa.PrivateKey); !ok {\n\t\tt.Fatalf(\"Expected RSA key[1], got %T\", keys[1])\n\t} else if key0.Curve != elliptic.P256() {\n\t\tt.Fatalf(\"Key[0] is not using P-256 curve\")\n\t} else if !bytes.Equal(key0.X.Bytes(), []byte{0x30, 0xa0, 0x42, 0x4c, 0xd2,\n\t\t0x1c, 0x29, 0x44, 0x83, 0x8a, 0x2d, 0x75, 0xc9, 0x2b, 0x37, 0xe7, 0x6e, 0xa2,\n\t\t0xd, 0x9f, 0x0, 0x89, 0x3a, 0x3b, 0x4e, 0xee, 0x8a, 0x3c, 0xa, 0xaf, 0xec, 0x3e}) {\n\t\tt.Fatalf(\"Bad key[0].X, got %v\", key0.X.Bytes())\n\t} else if !bytes.Equal(key0.Y.Bytes(), []byte{0xe0, 0x4b, 0x65, 0xe9, 0x24,\n\t\t0x56, 0xd9, 0x88, 0x8b, 0x52, 0xb3, 0x79, 0xbd, 0xfb, 0xd5, 0x1e, 0xe8,\n\t\t0x69, 0xef, 0x1f, 0xf, 0xc6, 0x5b, 0x66, 0x59, 0x69, 0x5b, 0x6c, 0xce,\n\t\t0x8, 0x17, 0x23}) {\n\t\tt.Fatalf(\"Bad key[0].Y, got %v\", key0.Y.Bytes())\n\t} else if !bytes.Equal(key0.D.Bytes(), []byte{0xf3, 0xbd, 0xc, 0x7, 0xa8,\n\t\t0x1f, 0xb9, 0x32, 0x78, 0x1e, 0xd5, 0x27, 0x52, 0xf6, 0xc, 0xc8, 0x9a,\n\t\t0x6b, 0xe5, 0xe5, 0x19, 0x34, 0xfe, 0x1, 0x93, 0x8d, 0xdb, 0x55, 0xd8,\n\t\t0xf7, 0x78, 0x1}) {\n\t\tt.Fatalf(\"Bad key[0].D, got %v\", key0.D.Bytes())\n\t} else if key1.E != 0x10001 {\n\t\tt.Fatalf(\"Bad key[1].E: %d\", key1.E)\n\t} else if !bytes.Equal(key1.N.Bytes(), []byte{0xd2, 0xfc, 0x7b, 0x6a, 0xa, 0x1e,\n\t\t0x6c, 0x67, 0x10, 0x4a, 0xeb, 0x8f, 0x88, 0xb2, 0x57, 0x66, 0x9b, 0x4d, 0xf6,\n\t\t0x79, 0xdd, 0xad, 0x9, 0x9b, 0x5c, 0x4a, 0x6c, 0xd9, 0xa8, 0x80, 0x15, 0xb5,\n\t\t0xa1, 0x33, 0xbf, 0xb, 0x85, 0x6c, 0x78, 0x71, 0xb6, 0xdf, 0x0, 0xb, 0x55,\n\t\t0x4f, 0xce, 0xb3, 0xc2, 0xed, 0x51, 0x2b, 0xb6, 0x8f, 0x14, 0x5c, 0x6e, 0x84,\n\t\t0x34, 0x75, 0x2f, 0xab, 0x52, 0xa1, 0xcf, 0xc1, 0x24, 0x40, 0x8f, 0x79, 0xb5,\n\t\t0x8a, 0x45, 0x78, 0xc1, 0x64, 0x28, 0x85, 0x57, 0x89, 0xf7, 0xa2, 0x49, 0xe3,\n\t\t0x84, 0xcb, 0x2d, 0x9f, 0xae, 0x2d, 0x67, 0xfd, 0x96, 0xfb, 0x92, 0x6c, 0x19,\n\t\t0x8e, 0x7, 0x73, 0x99, 0xfd, 0xc8, 0x15, 0xc0, 0xaf, 0x9, 0x7d, 0xde, 0x5a,\n\t\t0xad, 0xef, 0xf4, 0x4d, 0xe7, 0xe, 0x82, 0x7f, 0x48, 0x78, 0x43, 0x24, 0x39,\n\t\t0xbf, 0xee, 0xb9, 0x60, 0x68, 0xd0, 0x47, 0x4f, 0xc5, 0xd, 0x6d, 0x90, 0xbf,\n\t\t0x3a, 0x98, 0xdf, 0xaf, 0x10, 0x40, 0xc8, 0x9c, 0x2, 0xd6, 0x92, 0xab, 0x3b,\n\t\t0x3c, 0x28, 0x96, 0x60, 0x9d, 0x86, 0xfd, 0x73, 0xb7, 0x74, 0xce, 0x7, 0x40,\n\t\t0x64, 0x7c, 0xee, 0xea, 0xa3, 0x10, 0xbd, 0x12, 0xf9, 0x85, 0xa8, 0xeb, 0x9f,\n\t\t0x59, 0xfd, 0xd4, 0x26, 0xce, 0xa5, 0xb2, 0x12, 0xf, 0x4f, 0x2a, 0x34, 0xbc,\n\t\t0xab, 0x76, 0x4b, 0x7e, 0x6c, 0x54, 0xd6, 0x84, 0x2, 0x38, 0xbc, 0xc4, 0x5, 0x87,\n\t\t0xa5, 0x9e, 0x66, 0xed, 0x1f, 0x33, 0x89, 0x45, 0x77, 0x63, 0x5c, 0x47, 0xa,\n\t\t0xf7, 0x5c, 0xf9, 0x2c, 0x20, 0xd1, 0xda, 0x43, 0xe1, 0xbf, 0xc4, 0x19, 0xe2,\n\t\t0x22, 0xa6, 0xf0, 0xd0, 0xbb, 0x35, 0x8c, 0x5e, 0x38, 0xf9, 0xcb, 0x5, 0xa, 0xea,\n\t\t0xfe, 0x90, 0x48, 0x14, 0xf1, 0xac, 0x1a, 0xa4, 0x9c, 0xca, 0x9e, 0xa0, 0xca, 0x83}) {\n\t\tt.Fatalf(\"Bad key[1].N, got %v\", key1.N.Bytes())\n\t} else if !bytes.Equal(key1.D.Bytes(), []byte{0x5f, 0x87, 0x13, 0xb5, 0xe2, 0x58,\n\t\t0xfe, 0x9, 0xf8, 0x15, 0x83, 0xec, 0x5c, 0x1f, 0x2b, 0x75, 0x78, 0xb1, 0xe6,\n\t\t0xfc, 0x2c, 0x83, 0x51, 0x4b, 0x37, 0x91, 0x37, 0x11, 0xa1, 0xba, 0x44, 0x9a,\n\t\t0x15, 0x1f, 0xe1, 0xcb, 0x2c, 0xa0, 0xfd, 0x33, 0xb7, 0x71, 0xe6, 0x8a, 0x3b,\n\t\t0x19, 0x44, 0x64, 0x9d, 0xc8, 0x67, 0xad, 0x1c, 0x1e, 0x52, 0x40, 0xbb, 0x85,\n\t\t0x3e, 0x5f, 0x24, 0xb3, 0x34, 0x59, 0xb1, 0x40, 0x28, 0xd2, 0xd6, 0x63, 0x6b,\n\t\t0xef, 0xec, 0x1e, 0x8d, 0xa9, 0x74, 0xb3, 0x52, 0xfc, 0x53, 0xd3, 0xf6, 0x12,\n\t\t0x7e, 0xa8, 0xa3, 0xc2, 0x9d, 0xd1, 0x4f, 0x39, 0x41, 0x68, 0x2c, 0x56, 0xa7,\n\t\t0x87, 0x68, 0x16, 0x4e, 0x4d, 0xda, 0x8f, 0x6, 0xcb, 0xf9, 0xc7, 0x34, 0xaa,\n\t\t0xe8, 0x0, 0x32, 0x24, 0x27, 0x8e, 0xa9, 0x45, 0x4a, 0x21, 0xb1, 0x7c, 0xb0,\n\t\t0x6d, 0x17, 0x80, 0x75, 0x86, 0x8c, 0xc0, 0x5b, 0x3d, 0xb6, 0xff, 0x1d, 0xfd,\n\t\t0xc3, 0xd5, 0x63, 0x78, 0xb4, 0xed, 0xad, 0xed, 0xf0, 0xc3, 0x7a, 0x4c, 0xdc,\n\t\t0x26, 0xd1, 0xd4, 0x9a, 0xc2, 0x6f, 0x6f, 0xe3, 0xb5, 0x22, 0xa, 0x5d, 0xd2,\n\t\t0x93, 0x96, 0x62, 0x1b, 0xbc, 0x68, 0x8c, 0xf2, 0xee, 0xe2, 0xc6, 0xe0, 0xd5,\n\t\t0x4d, 0xa3, 0xc7, 0x82, 0x1, 0x4c, 0xd0, 0x73, 0x9d, 0xb2, 0x52, 0xcc, 0x51,\n\t\t0xca, 0xeb, 0xa8, 0xd3, 0xf1, 0xb8, 0x24, 0xba, 0xab, 0x24, 0xd0, 0x68, 0xec,\n\t\t0x90, 0x32, 0x64, 0xd7, 0xd6, 0x78, 0xab, 0x8, 0xf0, 0x6e, 0xc9, 0xe7, 0xe2,\n\t\t0x3d, 0x96, 0x6, 0x28, 0xb7, 0x44, 0xbf, 0x94, 0xb3, 0x69, 0x46, 0x56, 0x46,\n\t\t0x3c, 0x7e, 0x41, 0x73, 0x99, 0xed, 0x73, 0xd0, 0x76, 0xc8, 0x91, 0xfc, 0xf4,\n\t\t0x63, 0xa9, 0xaa, 0x9c, 0xe6, 0x2d, 0xa9, 0xcd, 0x17, 0xe2, 0x37, 0xdc, 0x2a,\n\t\t0x80, 0x2, 0xf1}) {\n\t\tt.Fatalf(\"Bad key[1].D, got %v\", key1.D.Bytes())\n\t}\n}", "func (c CryptoServiceTester) TestGetPrivateKeyPasswordInvalid(t *testing.T) {\n\ttempBaseDir, err := ioutil.TempDir(\"\", \"cs-test-\")\n\trequire.NoError(t, err, \"failed to create a temporary directory: %s\", err)\n\tdefer os.RemoveAll(tempBaseDir)\n\n\t// Do not use c.cryptoServiceFactory(), we need a KeyFileStore.\n\tretriever := passphrase.ConstantRetriever(\"password\")\n\tstore, err := trustmanager.NewKeyFileStore(tempBaseDir, retriever)\n\trequire.NoError(t, err)\n\tcryptoService := NewCryptoService(store)\n\tpubKey, err := cryptoService.Create(c.role, c.gun, c.keyAlgo)\n\trequire.NoError(t, err, \"error generating key: %s\", err)\n\n\t// cryptoService's FileKeyStore caches the unlocked private key, so to test\n\t// private key unlocking we need a new instance.\n\tstore, err = trustmanager.NewKeyFileStore(tempBaseDir, giveUpPassphraseRetriever)\n\trequire.NoError(t, err)\n\tcryptoService = NewCryptoService(store)\n\n\t_, _, err = cryptoService.GetPrivateKey(pubKey.ID())\n\trequire.EqualError(t, err, trustmanager.ErrPasswordInvalid{}.Error())\n}", "func (kp *MockKeyProvider) GetPrivateKey() (crypto.PrivateKey, error) {\n\treturn kp.PrivateKey, kp.Err\n}", "func (m *MockisKey_KeyInfo) isKey_KeyInfo() {\n\tm.ctrl.Call(m, \"isKey_KeyInfo\")\n}", "func test_generateEthAddrFromPrivateKey(t *testing.T) {\n\t//services.RunOnTestNet()\n\t// generate eth address using gateway\n\toriginalAddr, originalPrivateKey, err := eth_gateway.EthWrapper.GenerateEthAddr()\n\tif err != nil {\n\t\tt.Fatalf(\"error creating ethereum network address\")\n\t}\n\n\tgeneratedAddress := eth_gateway.EthWrapper.GenerateEthAddrFromPrivateKey(originalPrivateKey)\n\n\t// ensure address is what we expected\n\tif originalAddr != generatedAddress {\n\t\tt.Fatalf(\"generated address was %s but we expected %s\", generatedAddress, originalAddr)\n\t}\n\tt.Logf(\"generated address :%v\", generatedAddress.Hex())\n}", "func TestPrivateData(t *testing.T) {\n\tsdk := mainSDK\n\n\torgsContext := setupMultiOrgContext(t, sdk)\n\terr := integration.EnsureChannelCreatedAndPeersJoined(t, sdk, orgChannelID, \"orgchannel.tx\", orgsContext)\n\trequire.NoError(t, err)\n\n\tcoll1 := \"collection1\"\n\tccID := integration.GenerateExamplePvtID(true)\n\tcollConfig, err := newCollectionConfig(coll1, \"OR('Org2MSP.member')\", 0, 2, 1000)\n\trequire.NoError(t, err)\n\n\terr = integration.InstallExamplePvtChaincode(orgsContext, ccID)\n\trequire.NoError(t, err)\n\terr = integration.InstantiateExamplePvtChaincode(orgsContext, orgChannelID, ccID, \"OR('Org1MSP.member','Org2MSP.member')\", collConfig)\n\trequire.NoError(t, err)\n\n\tctxProvider := sdk.ChannelContext(orgChannelID, fabsdk.WithUser(org1User), fabsdk.WithOrg(org1Name))\n\n\tchClient, err := channel.New(ctxProvider)\n\trequire.NoError(t, err)\n\n\tt.Run(\"Specified Invocation Chain\", func(t *testing.T) {\n\t\tresponse, err := chClient.Execute(\n\t\t\tchannel.Request{\n\t\t\t\tChaincodeID: ccID,\n\t\t\t\tFcn: \"putprivate\",\n\t\t\t\tArgs: [][]byte{[]byte(coll1), []byte(\"key\"), []byte(\"value\")},\n\t\t\t\tInvocationChain: []*fab.ChaincodeCall{\n\t\t\t\t\t{ID: ccID, Collections: []string{coll1}},\n\t\t\t\t},\n\t\t\t},\n\t\t\tchannel.WithRetry(retry.TestRetryOpts),\n\t\t)\n\t\trequire.NoError(t, err)\n\t\tt.Logf(\"Got %d response(s)\", len(response.Responses))\n\t\trequire.NotEmptyf(t, response.Responses, \"expecting at least one response\")\n\t})\n\n\tt.Run(\"Auto-detect Invocation Chain\", func(t *testing.T) {\n\t\tresponse, err := chClient.Execute(\n\t\t\tchannel.Request{\n\t\t\t\tChaincodeID: ccID,\n\t\t\t\tFcn: \"putprivate\",\n\t\t\t\tArgs: [][]byte{[]byte(coll1), []byte(\"key\"), []byte(\"value\")},\n\t\t\t},\n\t\t\tchannel.WithRetry(retry.TestRetryOpts),\n\t\t)\n\t\trequire.NoError(t, err)\n\t\tt.Logf(\"Got %d response(s)\", len(response.Responses))\n\t\trequire.NotEmptyf(t, response.Responses, \"expecting at least one response\")\n\t})\n}", "func GeneratePrivateKey() *PrivateKey {\n\tpriv := new(PrivateKey)\n\tseckey := NewSeckey()\n\tpriv.seckey = seckey\n\treturn priv\n}", "func (c CryptoServiceTester) TestGetPrivateKeyAttemptsExceeded(t *testing.T) {\n\ttempBaseDir, err := ioutil.TempDir(\"\", \"cs-test-\")\n\trequire.NoError(t, err, \"failed to create a temporary directory: %s\", err)\n\tdefer os.RemoveAll(tempBaseDir)\n\n\t// Do not use c.cryptoServiceFactory(), we need a KeyFileStore.\n\tretriever := passphrase.ConstantRetriever(\"password\")\n\tstore, err := trustmanager.NewKeyFileStore(tempBaseDir, retriever)\n\trequire.NoError(t, err)\n\tcryptoService := NewCryptoService(store)\n\tpubKey, err := cryptoService.Create(c.role, c.gun, c.keyAlgo)\n\trequire.NoError(t, err, \"error generating key: %s\", err)\n\n\t// trustmanager.KeyFileStore and trustmanager.KeyMemoryStore both cache the unlocked\n\t// private key, so to test private key unlocking we need a new instance using the\n\t// same underlying storage; this also makes trustmanager.KeyMemoryStore (and\n\t// c.cryptoServiceFactory()) unsuitable.\n\tretriever = passphrase.ConstantRetriever(\"incorrect password\")\n\tstore, err = trustmanager.NewKeyFileStore(tempBaseDir, retriever)\n\trequire.NoError(t, err)\n\tcryptoService = NewCryptoService(store)\n\n\t_, _, err = cryptoService.GetPrivateKey(pubKey.ID())\n\trequire.EqualError(t, err, trustmanager.ErrAttemptsExceeded{}.Error())\n}", "func newPrivateKey(size int) (*rsa.PrivateKey, error) {\n\t// TODO: support more key types\n\tprivateKey, err := rsa.GenerateKey(rand.Reader, size)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn privateKey, nil\n}", "func TestPrivateData(t *testing.T) {\n\tsdk := mainSDK\n\n\torgsContext := setupMultiOrgContext(t, sdk)\n\terr := integration.EnsureChannelCreatedAndPeersJoined(t, sdk, orgChannelID, \"orgchannel.tx\", orgsContext)\n\trequire.NoError(t, err)\n\n\tcoll1 := \"collection1\"\n\tccID := integration.GenerateExamplePvtID(true)\n\tcollConfig, err := newCollectionConfig(coll1, \"OR('Org2MSP.member')\", 0, 2, 1000)\n\trequire.NoError(t, err)\n\n\tif metadata.CCMode == \"lscc\" {\n\t\terr = integration.InstallExamplePvtChaincode(orgsContext, ccID)\n\t\trequire.NoError(t, err)\n\t\terr = integration.InstantiateExamplePvtChaincode(orgsContext, orgChannelID, ccID, \"OR('Org1MSP.member','Org2MSP.member')\", collConfig)\n\t\trequire.NoError(t, err)\n\t} else {\n\t\terr := integration.InstantiatePvtExampleChaincodeLc(sdk, orgsContext, orgChannelID, ccID, \"OR('Org1MSP.member','Org2MSP.member')\", collConfig)\n\t\trequire.NoError(t, err)\n\t}\n\n\tctxProvider := sdk.ChannelContext(orgChannelID, fabsdk.WithUser(org1User), fabsdk.WithOrg(org1Name))\n\n\tchClient, err := channel.New(ctxProvider)\n\trequire.NoError(t, err)\n\n\tt.Run(\"Specified Invocation Chain\", func(t *testing.T) {\n\t\tresponse, err := chClient.Execute(\n\t\t\tchannel.Request{\n\t\t\t\tChaincodeID: ccID,\n\t\t\t\tFcn: \"putprivate\",\n\t\t\t\tArgs: [][]byte{[]byte(coll1), []byte(\"key\"), []byte(\"value\")},\n\t\t\t\tInvocationChain: []*fab.ChaincodeCall{\n\t\t\t\t\t{ID: ccID, Collections: []string{coll1}},\n\t\t\t\t},\n\t\t\t},\n\t\t\tchannel.WithRetry(retry.TestRetryOpts),\n\t\t)\n\t\trequire.NoError(t, err)\n\t\tt.Logf(\"Got %d response(s)\", len(response.Responses))\n\t\trequire.NotEmptyf(t, response.Responses, \"expecting at least one response\")\n\t})\n\n\tt.Run(\"Auto-detect Invocation Chain\", func(t *testing.T) {\n\t\tresponse, err := chClient.Execute(\n\t\t\tchannel.Request{\n\t\t\t\tChaincodeID: ccID,\n\t\t\t\tFcn: \"putprivate\",\n\t\t\t\tArgs: [][]byte{[]byte(coll1), []byte(\"key\"), []byte(\"value\")},\n\t\t\t},\n\t\t\tchannel.WithRetry(retry.TestRetryOpts),\n\t\t)\n\t\trequire.NoError(t, err)\n\t\tt.Logf(\"Got %d response(s)\", len(response.Responses))\n\t\trequire.NotEmptyf(t, response.Responses, \"expecting at least one response\")\n\t})\n}", "func mockKeyFile(server string) (string, error) {\n\tpwd, err := os.Getwd()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tkf, err := os.CreateTemp(pwd, \"test_oauth2\")\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\t_, err = kf.WriteString(fmt.Sprintf(`{\n \"type\":\"resource\",\n \"client_id\":\"client-id\",\n \"client_secret\":\"client-secret\",\n \"client_email\":\"oauth@test.org\",\n \"issuer_url\":\"%s\"\n}`, server))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn kf.Name(), nil\n}", "func TestDeriveKeys(t *testing.T) {\r\n\r\n\t// Derive the keys\r\n\t_, _, err := deriveKeys(\"\", 0)\r\n\tif err == nil {\r\n\t\tt.Fatalf(\"error should have occurred\")\r\n\t}\r\n\r\n\t// Entity / Service Provider's Identity Private Key\r\n\tentityPk := \"xprv9s21ZrQH143K3PZSwbEeXEYq74EbnfMngzAiMCZcfjzyRpUvt2vQJnaHRTZjeuEmLXeN6BzYRoFsEckfobxE9XaRzeLGfQoxzPzTRyRb6oE\"\r\n\r\n\t// Derive the keys\r\n\tvar entitySigningAddress, entitySigningKey string\r\n\tentitySigningKey, entitySigningAddress, err = deriveKeys(entityPk, 0)\r\n\tif err != nil {\r\n\t\tt.Fatalf(\"error occurred: %s\", err.Error())\r\n\t}\r\n\tif entitySigningKey != \"127d0ab318252b4622d8eac61407359a4cab7c1a5d67754b5bf9db910eaf052c\" {\r\n\t\tt.Fatalf(\"signing key does not match: %s vs %s\", entitySigningKey, \"\")\r\n\t}\r\n\tif entitySigningAddress != \"1AFc9feffQmxT61iEftzkaYvWTgLCyU6j\" {\r\n\t\tt.Fatalf(\"signing address does not match: %s vs %s\", entitySigningAddress, \"\")\r\n\t}\r\n}", "func (a *Account) GetPrivateKey() crypto.PrivateKey { return a.key }", "func (m *MockConfiguration) AuthMethodPrivateKeyJWTSupported() bool {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"AuthMethodPrivateKeyJWTSupported\")\n\tret0, _ := ret[0].(bool)\n\treturn ret0\n}", "func (_m *TranslationKeyStore) GetPoisonPrivateKeys() ([]*keys.PrivateKey, error) {\n\tret := _m.Called()\n\n\tvar r0 []*keys.PrivateKey\n\tif rf, ok := ret.Get(0).(func() []*keys.PrivateKey); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).([]*keys.PrivateKey)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func() error); ok {\n\t\tr1 = rf()\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (m *MockisCryptoAsymApiReqSetupPrivateKeyEx_Key) EXPECT() *MockisCryptoAsymApiReqSetupPrivateKeyEx_KeyMockRecorder {\n\treturn m.recorder\n}", "func GeneratePrivateKey() (privateKey PrivateKey, err error) {\n\t_, privateKey, err = GenerateKey()\n\n\treturn\n}", "func (c CryptoServiceTester) TestGetNonexistentKey(t *testing.T) {\n\tcryptoService := c.cryptoServiceFactory()\n\n\trequire.Nil(t, cryptoService.GetKey(\"boguskeyid\"),\n\t\tc.errorMsg(\"non-nil result for bogus keyid\"))\n\n\t_, _, err := cryptoService.GetPrivateKey(\"boguskeyid\")\n\trequire.Error(t, err)\n\t// The underlying error has been correctly propagated.\n\t_, ok := err.(trustmanager.ErrKeyNotFound)\n\trequire.True(t, ok)\n}", "func TestPrivateDataPutAndGet(t *testing.T) {\n\tsdk := mainSDK\n\n\torgsContext := setupMultiOrgContext(t, sdk)\n\terr := integration.EnsureChannelCreatedAndPeersJoined(t, sdk, orgChannelID, \"orgchannel.tx\", orgsContext)\n\trequire.NoError(t, err)\n\n\tcoll1 := \"collection1\"\n\tccID := integration.GenerateExamplePvtID(true)\n\tcollConfig, err := newCollectionConfig(coll1, \"OR('Org1MSP.member','Org2MSP.member')\", 0, 2, 1000)\n\trequire.NoError(t, err)\n\n\terr = integration.InstallExamplePvtChaincode(orgsContext, ccID)\n\trequire.NoError(t, err)\n\terr = integration.InstantiateExamplePvtChaincode(orgsContext, orgChannelID, ccID, \"OR('Org1MSP.member','Org2MSP.member')\", collConfig)\n\trequire.NoError(t, err)\n\n\tctxProvider := sdk.ChannelContext(orgChannelID, fabsdk.WithUser(org1User), fabsdk.WithOrg(org1Name))\n\n\tchClient, err := channel.New(ctxProvider)\n\trequire.NoError(t, err)\n\n\tkey1 := \"key1\"\n\tkey2 := \"key2\"\n\tkey3 := \"key3\"\n\tvalue1 := \"pvtValue1\"\n\tvalue2 := \"pvtValue2\"\n\tvalue3 := \"pvtValue3\"\n\n\tresponse, err := chClient.Query(\n\t\tchannel.Request{\n\t\t\tChaincodeID: ccID,\n\t\t\tFcn: \"getprivate\",\n\t\t\tArgs: [][]byte{[]byte(coll1), []byte(key1)},\n\t\t},\n\t\tchannel.WithRetry(retry.DefaultChannelOpts),\n\t)\n\trequire.NoError(t, err)\n\tt.Logf(\"Got response payload: [%s]\", string(response.Payload))\n\trequire.Nil(t, response.Payload)\n\n\tresponse, err = chClient.Query(\n\t\tchannel.Request{\n\t\t\tChaincodeID: ccID,\n\t\t\tFcn: \"getprivatebyrange\",\n\t\t\tArgs: [][]byte{[]byte(coll1), []byte(key1), []byte(key3)},\n\t\t},\n\t\tchannel.WithRetry(retry.DefaultChannelOpts),\n\t)\n\trequire.NoError(t, err)\n\tt.Logf(\"Got response payload: [%s]\", string(response.Payload))\n\trequire.Empty(t, string(response.Payload))\n\n\tresponse, err = chClient.Execute(\n\t\tchannel.Request{\n\t\t\tChaincodeID: ccID,\n\t\t\tFcn: \"putprivate\",\n\t\t\tArgs: [][]byte{[]byte(coll1), []byte(key1), []byte(value1)},\n\t\t},\n\t\tchannel.WithRetry(retry.DefaultChannelOpts),\n\t)\n\trequire.NoError(t, err)\n\trequire.NotEmptyf(t, response.Responses, \"expecting at least one response\")\n\n\tresponse, err = chClient.Execute(\n\t\tchannel.Request{\n\t\t\tChaincodeID: ccID,\n\t\t\tFcn: \"putprivate\",\n\t\t\tArgs: [][]byte{[]byte(coll1), []byte(key2), []byte(value2)},\n\t\t},\n\t\tchannel.WithRetry(retry.DefaultChannelOpts),\n\t)\n\trequire.NoError(t, err)\n\trequire.NotEmptyf(t, response.Responses, \"expecting at least one response\")\n\n\tresponse, err = chClient.Execute(\n\t\tchannel.Request{\n\t\t\tChaincodeID: ccID,\n\t\t\tFcn: \"putprivate\",\n\t\t\tArgs: [][]byte{[]byte(coll1), []byte(key3), []byte(value3)},\n\t\t},\n\t\tchannel.WithRetry(retry.TestRetryOpts),\n\t)\n\trequire.NoError(t, err)\n\trequire.NotEmptyf(t, response.Responses, \"expecting at least one response\")\n\n\tresponse, err = chClient.Query(\n\t\tchannel.Request{\n\t\t\tChaincodeID: ccID,\n\t\t\tFcn: \"getprivate\",\n\t\t\tArgs: [][]byte{[]byte(coll1), []byte(key1)},\n\t\t},\n\t\tchannel.WithRetry(retry.TestRetryOpts),\n\t)\n\trequire.NoError(t, err)\n\tt.Logf(\"Got response payload: %s\", string(response.Payload))\n\trequire.Equal(t, value1, string(response.Payload))\n\n\tresponse, err = chClient.Query(\n\t\tchannel.Request{\n\t\t\tChaincodeID: ccID,\n\t\t\tFcn: \"getprivatebyrange\",\n\t\t\tArgs: [][]byte{[]byte(coll1), []byte(key1), []byte(key3)},\n\t\t},\n\t\tchannel.WithRetry(retry.DefaultChannelOpts),\n\t)\n\trequire.NoError(t, err)\n\tt.Logf(\"Got response payload: [%s]\", string(response.Payload))\n\trequire.NotEmpty(t, string(response.Payload))\n}", "func (o *Gojwt) SetPrivKeyPath(path string)(){\n o.privKeyPath = path\n}", "func TestAuthenticationKeyRequest(t *testing.T) {\n\ttestKeys := MakeTestKeys(3)\n\n\t// Give sish a temp directory to generate a server ssh host key\n\tdir, err := os.MkdirTemp(\"\", \"sish_keys\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer os.RemoveAll(dir)\n\tviper.Set(\"private-keys-directory\", dir)\n\tviper.Set(\"authentication\", true)\n\n\ttestCases := []struct {\n\t\tclientPrivateKey *rsa.PrivateKey\n\t\tclientUser string\n\t\tvalidPublicKeys []rsa.PublicKey\n\t\tvalidUsernames []string\n\t\texpectSuccessAuth bool\n\t\toverrideHttpUrl string\n\t}{\n\t\t// valid key, should succeed auth\n\t\t{\n\t\t\tclientPrivateKey: testKeys[0],\n\t\t\tclientUser: \"ubuntu\",\n\t\t\tvalidPublicKeys: []rsa.PublicKey{testKeys[0].PublicKey},\n\t\t\tvalidUsernames: []string{\"ubuntu\"},\n\t\t\texpectSuccessAuth: true,\n\t\t\toverrideHttpUrl: \"\",\n\t\t},\n\t\t// invalid key, should be rejected\n\t\t{\n\t\t\tclientPrivateKey: testKeys[0],\n\t\t\tclientUser: \"ubuntu\",\n\t\t\tvalidPublicKeys: []rsa.PublicKey{testKeys[1].PublicKey, testKeys[2].PublicKey},\n\t\t\tvalidUsernames: []string{\"ubuntu\"},\n\t\t\texpectSuccessAuth: false,\n\t\t\toverrideHttpUrl: \"\",\n\t\t},\n\t\t// invalid username, should be rejected\n\t\t{\n\t\t\tclientPrivateKey: testKeys[0],\n\t\t\tclientUser: \"windows\",\n\t\t\tvalidPublicKeys: []rsa.PublicKey{testKeys[0].PublicKey},\n\t\t\tvalidUsernames: []string{\"ubuntu\"},\n\t\t\texpectSuccessAuth: false,\n\t\t\toverrideHttpUrl: \"\",\n\t\t},\n\t\t// no http service listening on server url, should be rejected\n\t\t{\n\t\t\tclientPrivateKey: testKeys[0],\n\t\t\tclientUser: \"ubuntu\",\n\t\t\tvalidPublicKeys: []rsa.PublicKey{testKeys[0].PublicKey},\n\t\t\tvalidUsernames: []string{\"ubuntu\"},\n\t\t\texpectSuccessAuth: false,\n\t\t\toverrideHttpUrl: \"http://localhost:61234\",\n\t\t},\n\t\t// invalid http url, should be rejected\n\t\t{\n\t\t\tclientPrivateKey: testKeys[0],\n\t\t\tclientUser: \"ubuntu\",\n\t\t\tvalidPublicKeys: []rsa.PublicKey{testKeys[0].PublicKey},\n\t\t\tvalidUsernames: []string{\"ubuntu\"},\n\t\t\texpectSuccessAuth: false,\n\t\t\toverrideHttpUrl: \"notarealurl\",\n\t\t},\n\t}\n\n\tfor caseIdx, c := range testCases {\n\t\tif c.overrideHttpUrl == \"\" {\n\t\t\t// start an http server that will validate against the specified public keys\n\t\t\thttpSrv := httptest.NewServer(http.HandlerFunc(PubKeyHttpHandler(&c.validPublicKeys, &c.validUsernames)))\n\t\t\tdefer httpSrv.Close()\n\n\t\t\t// set viper to this http server URL as the auth request url it will\n\t\t\t// send public keys to for auth validation\n\t\t\tviper.Set(\"authentication-key-request-url\", httpSrv.URL)\n\t\t} else {\n\t\t\tviper.Set(\"authentication-key-request-url\", c.overrideHttpUrl)\n\t\t}\n\n\t\tsshListener, err := net.Listen(\"tcp\", \"localhost:0\")\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t}\n\t\tdefer sshListener.Close()\n\n\t\tsuccessAuth := make(chan bool)\n\t\tgo HandleSSHConn(sshListener, &successAuth)\n\n\t\t// attempt to connect to the ssh server using the specified private key\n\t\tsigner, err := ssh.NewSignerFromKey(c.clientPrivateKey)\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t}\n\t\tclientConfig := &ssh.ClientConfig{\n\t\t\tAuth: []ssh.AuthMethod{\n\t\t\t\tssh.PublicKeys(signer),\n\t\t\t},\n\t\t\tHostKeyCallback: ssh.InsecureIgnoreHostKey(),\n\t\t\tUser: c.clientUser,\n\t\t}\n\t\tt.Log(clientConfig)\n\n\t\tclient, err := ssh.Dial(\"tcp\", sshListener.Addr().String(), clientConfig)\n\t\tif err != nil {\n\t\t\tt.Log(\"ssh client rejected\", err)\n\t\t} else {\n\t\t\tt.Log(\"ssh client connected\")\n\t\t\tclient.Close()\n\t\t}\n\n\t\tdidAuth := <-successAuth\n\n\t\tif didAuth != c.expectSuccessAuth {\n\t\t\tt.Errorf(\"Auth %t when should have been %t for case %d\", didAuth, c.expectSuccessAuth, caseIdx)\n\t\t}\n\t}\n}", "func generatePrivateKey(bitSize int) (*rsa.PrivateKey, error) {\n\t// Private Key generation\n\tprivateKey, err := rsa.GenerateKey(rand.Reader, bitSize)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Validate Private Key\n\terr = privateKey.Validate()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn privateKey, nil\n}", "func (m *MockCall) Key() []byte {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Key\")\n\tret0, _ := ret[0].([]byte)\n\treturn ret0\n}", "func (_m *Keychain) GetStoredKeyPairInLibP2PFormat() (crypto.PrivKey, crypto.PubKey, error) {\n\tret := _m.Called()\n\n\tvar r0 crypto.PrivKey\n\tif rf, ok := ret.Get(0).(func() crypto.PrivKey); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(crypto.PrivKey)\n\t\t}\n\t}\n\n\tvar r1 crypto.PubKey\n\tif rf, ok := ret.Get(1).(func() crypto.PubKey); ok {\n\t\tr1 = rf()\n\t} else {\n\t\tif ret.Get(1) != nil {\n\t\t\tr1 = ret.Get(1).(crypto.PubKey)\n\t\t}\n\t}\n\n\tvar r2 error\n\tif rf, ok := ret.Get(2).(func() error); ok {\n\t\tr2 = rf()\n\t} else {\n\t\tr2 = ret.Error(2)\n\t}\n\n\treturn r0, r1, r2\n}", "func (m *MockapprunnerClient) PrivateURL(vicARN string) (string, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"PrivateURL\", vicARN)\n\tret0, _ := ret[0].(string)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func createPrivateKey() {\n\tnewPrivateKey, err := rsa.GenerateKey(rand.Reader, KEY_BITS)\n\tif err != nil {\n\t\tlog.Fatalf(\"Failed to generate private key: %s\", err)\n\t}\n\n\tprivateKey = newPrivateKey\n\tkeyOut, err := os.OpenFile(PrivateKeyFile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)\n\tif err != nil {\n\t\tlog.Fatalf(\"Failed to open %s for writing: %s\", PrivateKeyFile, err)\n\t}\n\tif err := pem.Encode(keyOut, &pem.Block{Type: PEM_HEADER_PRIVATE_KEY, Bytes: x509.MarshalPKCS1PrivateKey(privateKey)}); err != nil {\n\t\tlog.Fatalf(\"Unable to PEM encode private key: %s\", err)\n\t}\n\tkeyOut.Close()\n\tlog.Printf(\"Wrote private key to %s\", PrivateKeyFile)\n}", "func (c CryptoServiceTester) TestSignNoMatchingKeys(t *testing.T) {\n\tcryptoService := c.cryptoServiceFactory()\n\n\tprivKey, err := utils.GenerateECDSAKey(rand.Reader)\n\trequire.NoError(t, err, c.errorMsg(\"error creating key\"))\n\n\t// Test Sign\n\t_, _, err = cryptoService.GetPrivateKey(privKey.ID())\n\trequire.Error(t, err, c.errorMsg(\"Should not have found private key\"))\n}", "func TestPrivateDataPutAndGet(t *testing.T) {\n\tsdk := mainSDK\n\n\torgsContext := setupMultiOrgContext(t, sdk)\n\terr := integration.EnsureChannelCreatedAndPeersJoined(t, sdk, orgChannelID, \"orgchannel.tx\", orgsContext)\n\trequire.NoError(t, err)\n\n\tcoll1 := \"collection1\"\n\tccID := integration.GenerateExamplePvtID(true)\n\tcollConfig, err := newCollectionConfig(coll1, \"OR('Org1MSP.member','Org2MSP.member')\", 0, 2, 1000)\n\trequire.NoError(t, err)\n\n\tif metadata.CCMode == \"lscc\" {\n\t\terr = integration.InstallExamplePvtChaincode(orgsContext, ccID)\n\t\trequire.NoError(t, err)\n\t\terr = integration.InstantiateExamplePvtChaincode(orgsContext, orgChannelID, ccID, \"OR('Org1MSP.member','Org2MSP.member')\", collConfig)\n\t\trequire.NoError(t, err)\n\t} else {\n\t\terr := integration.InstantiatePvtExampleChaincodeLc(sdk, orgsContext, orgChannelID, ccID, \"OR('Org1MSP.member','Org2MSP.member')\", collConfig)\n\t\trequire.NoError(t, err)\n\t}\n\n\tctxProvider := sdk.ChannelContext(orgChannelID, fabsdk.WithUser(org1User), fabsdk.WithOrg(org1Name))\n\n\tchClient, err := channel.New(ctxProvider)\n\trequire.NoError(t, err)\n\n\tkey1 := \"key1\"\n\tkey2 := \"key2\"\n\tkey3 := \"key3\"\n\tvalue1 := \"pvtValue1\"\n\tvalue2 := \"pvtValue2\"\n\tvalue3 := \"pvtValue3\"\n\n\tresponse, err := chClient.Query(\n\t\tchannel.Request{\n\t\t\tChaincodeID: ccID,\n\t\t\tFcn: \"getprivate\",\n\t\t\tArgs: [][]byte{[]byte(coll1), []byte(key1)},\n\t\t},\n\t\tchannel.WithRetry(retry.DefaultChannelOpts),\n\t)\n\trequire.NoError(t, err)\n\tt.Logf(\"Got response payload: [%s]\", string(response.Payload))\n\trequire.Nil(t, response.Payload)\n\n\tresponse, err = chClient.Query(\n\t\tchannel.Request{\n\t\t\tChaincodeID: ccID,\n\t\t\tFcn: \"getprivatebyrange\",\n\t\t\tArgs: [][]byte{[]byte(coll1), []byte(key1), []byte(key3)},\n\t\t},\n\t\tchannel.WithRetry(retry.DefaultChannelOpts),\n\t)\n\trequire.NoError(t, err)\n\tt.Logf(\"Got response payload: [%s]\", string(response.Payload))\n\trequire.Empty(t, string(response.Payload))\n\n\tresponse, err = chClient.Execute(\n\t\tchannel.Request{\n\t\t\tChaincodeID: ccID,\n\t\t\tFcn: \"putprivate\",\n\t\t\tArgs: [][]byte{[]byte(coll1), []byte(key1), []byte(value1)},\n\t\t},\n\t\tchannel.WithRetry(retry.DefaultChannelOpts),\n\t)\n\trequire.NoError(t, err)\n\trequire.NotEmptyf(t, response.Responses, \"expecting at least one response\")\n\n\tresponse, err = chClient.Execute(\n\t\tchannel.Request{\n\t\t\tChaincodeID: ccID,\n\t\t\tFcn: \"putprivate\",\n\t\t\tArgs: [][]byte{[]byte(coll1), []byte(key2), []byte(value2)},\n\t\t},\n\t\tchannel.WithRetry(retry.DefaultChannelOpts),\n\t)\n\trequire.NoError(t, err)\n\trequire.NotEmptyf(t, response.Responses, \"expecting at least one response\")\n\n\tresponse, err = chClient.Execute(\n\t\tchannel.Request{\n\t\t\tChaincodeID: ccID,\n\t\t\tFcn: \"putprivate\",\n\t\t\tArgs: [][]byte{[]byte(coll1), []byte(key3), []byte(value3)},\n\t\t},\n\t\tchannel.WithRetry(retry.TestRetryOpts),\n\t)\n\trequire.NoError(t, err)\n\trequire.NotEmptyf(t, response.Responses, \"expecting at least one response\")\n\n\tresponse, err = chClient.Query(\n\t\tchannel.Request{\n\t\t\tChaincodeID: ccID,\n\t\t\tFcn: \"getprivate\",\n\t\t\tArgs: [][]byte{[]byte(coll1), []byte(key1)},\n\t\t},\n\t\tchannel.WithRetry(retry.TestRetryOpts),\n\t)\n\trequire.NoError(t, err)\n\tt.Logf(\"Got response payload: %s\", string(response.Payload))\n\trequire.Equal(t, value1, string(response.Payload))\n\n\tresponse, err = chClient.Query(\n\t\tchannel.Request{\n\t\t\tChaincodeID: ccID,\n\t\t\tFcn: \"getprivatebyrange\",\n\t\t\tArgs: [][]byte{[]byte(coll1), []byte(key1), []byte(key3)},\n\t\t},\n\t\tchannel.WithRetry(retry.DefaultChannelOpts),\n\t)\n\trequire.NoError(t, err)\n\tt.Logf(\"Got response payload: [%s]\", string(response.Payload))\n\trequire.NotEmpty(t, string(response.Payload))\n}", "func (e *Domain) Private() *PrivateKey {\n\tif e.ClearPrivateKey == nil {\n\t\te.decrypt_privatekey()\n\t}\n\treturn e.ClearPrivateKey\n}", "func PrivateKeyValidate(priv *rsa.PrivateKey,) error", "func (_m *TranslationKeyStore) GetServerDecryptionPrivateKey(id []byte) (*keys.PrivateKey, error) {\n\tret := _m.Called(id)\n\n\tvar r0 *keys.PrivateKey\n\tif rf, ok := ret.Get(0).(func([]byte) *keys.PrivateKey); ok {\n\t\tr0 = rf(id)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*keys.PrivateKey)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func([]byte) error); ok {\n\t\tr1 = rf(id)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (o *Gojwt) GetPrivKeyPath()(string){\n return o.privKeyPath\n}", "func newPrivateKey(pSeed, qSeed big.Int) (*PrivateKey, error) {\n\tq := &qSeed\n\tp := &pSeed\n\tvar tmp big.Int\n\ttest := big.NewInt(0x7743)\n\tvar q1, phi, keyD, keyN big.Int\n\tfor count := 0; count < rsaCreateGiveup; count++ {\n\t\tq = primize(q)\n\t\tq1.Add(q, tmp.SetInt64(-1))\n\t\tp = primize(p)\n\t\tphi.Add(p, tmp.SetInt64(-1))\n\t\tphi.Mul(&phi, &q1)\n\t\tkeyD.ModInverse(rsaPublicE, &phi)\n\t\tif keyD.Cmp(tmp.SetInt64(0)) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tkeyN.Mul(p, q)\n\t\ttmp.Exp(test, rsaPublicE, &keyN)\n\t\ttmp.Exp(&tmp, &keyD, &keyN)\n\t\tif tmp.Cmp(test) == 0 {\n\t\t\treturn &PrivateKey{&keyN, &keyD}, nil\n\t\t}\n\t\tp.Add(p, tmp.SetInt64(2))\n\t\tq.Add(q, tmp.SetInt64(2))\n\t}\n\terr := errors.New(\"cannot generate private key\")\n\tlog.Fatal(err)\n\treturn nil, err\n}", "func (m *MockIInterConnector) Key() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Key\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func GeneratePrivateKey(algo ...Algorithm) (PrivateKey, error) {\n\tif len(algo) != 0 {\n\t\tswitch algo[0] {\n\t\tcase KeyAlgoSecp256k1:\n\t\t\treturn GenerateSECP256K1PrivateKey()\n\t\tdefault:\n\t\t\treturn GenerateSM2PrivateKey()\n\t\t}\n\t}\n\treturn GenerateSM2PrivateKey()\n}", "func (sc Credential) getPrivateKey(privateKeyPath string, privateKeyPassphrase string) (ssh.AuthMethod, error) {\n\tif !fileExist(privateKeyPath) {\n\t\tprivateKeyPath = filepath.Join(os.Getenv(\"HOME\"), \".ssh/id_rsa\")\n\t}\n\n\tkey, err := ioutil.ReadFile(privateKeyPath)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to parse private key: %v\", err)\n\t}\n\n\tvar signer ssh.Signer\n\tif privateKeyPassphrase != \"\" {\n\t\tsigner, err = ssh.ParsePrivateKeyWithPassphrase(key, []byte(privateKeyPassphrase))\n\t} else {\n\t\tsigner, err = ssh.ParsePrivateKey(key)\n\t}\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"parse private key failed: %v\", err)\n\t}\n\n\treturn ssh.PublicKeys(signer), nil\n}", "func (mph *MockPeerHandler) PrivKey() libp2pcry.PrivKey {\n\treturn nil\n}", "func (e *EtcdClientCert) PrivateKeyPath() string { return path.Join(e.BaseDir, etcdClientKeyFileName) }", "func (e *EtcdCert) PrivateKeyPath() string { return path.Join(e.BaseDir, etcdKeyFileName) }", "func (c CryptoServiceTester) TestAddKey(t *testing.T) {\n\tcryptoService := c.cryptoServiceFactory()\n\tcryptoService.keyStores = append(cryptoService.keyStores,\n\t\ttrustmanager.NewKeyMemoryStore(passphraseRetriever))\n\n\tprivKey, err := utils.GenerateECDSAKey(rand.Reader)\n\trequire.NoError(t, err)\n\n\t// Add the key to the targets role\n\trequire.NoError(t, cryptoService.AddKey(data.CanonicalTargetsRole, c.gun, privKey))\n\n\t// Check that we added the key and its info to only the first keystore\n\tretrievedKey, retrievedRole, err := cryptoService.keyStores[0].GetKey(privKey.ID())\n\trequire.NoError(t, err)\n\trequire.Equal(t, privKey.Private(), retrievedKey.Private())\n\trequire.Equal(t, data.CanonicalTargetsRole, retrievedRole)\n\n\tretrievedKeyInfo, err := cryptoService.keyStores[0].GetKeyInfo(privKey.ID())\n\trequire.NoError(t, err)\n\trequire.Equal(t, data.CanonicalTargetsRole, retrievedKeyInfo.Role)\n\trequire.Equal(t, c.gun, retrievedKeyInfo.Gun)\n\n\t// The key should not exist in the second keystore\n\t_, _, err = cryptoService.keyStores[1].GetKey(privKey.ID())\n\trequire.Error(t, err)\n\t_, err = cryptoService.keyStores[1].GetKeyInfo(privKey.ID())\n\trequire.Error(t, err)\n\n\t// We should be able to successfully get the key from the cryptoservice level\n\tretrievedKey, retrievedRole, err = cryptoService.GetPrivateKey(privKey.ID())\n\trequire.NoError(t, err)\n\trequire.Equal(t, privKey.Private(), retrievedKey.Private())\n\trequire.Equal(t, data.CanonicalTargetsRole, retrievedRole)\n\tretrievedKeyInfo, err = cryptoService.GetKeyInfo(privKey.ID())\n\trequire.NoError(t, err)\n\trequire.Equal(t, data.CanonicalTargetsRole, retrievedKeyInfo.Role)\n\trequire.Equal(t, c.gun, retrievedKeyInfo.Gun)\n\n\t// Add the same key to the targets role, since the info is the same we should have no error\n\trequire.NoError(t, cryptoService.AddKey(data.CanonicalTargetsRole, c.gun, privKey))\n\n\t// Try to add the same key to the snapshot role, which should error due to the role mismatch\n\trequire.Error(t, cryptoService.AddKey(data.CanonicalSnapshotRole, c.gun, privKey))\n}", "func (m *MockisIpsecCbKeyHandle_KeyOrHandle) isIpsecCbKeyHandle_KeyOrHandle() {\n\tm.ctrl.Call(m, \"isIpsecCbKeyHandle_KeyOrHandle\")\n}", "func (m *MockClientStore) GetLvl2Key(arg0 context.Context, arg1 drkey.Lvl2Meta, arg2 time.Time) (drkey.Lvl2Key, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetLvl2Key\", arg0, arg1, arg2)\n\tret0, _ := ret[0].(drkey.Lvl2Key)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func TestAuthenticatedRequest(t *testing.T) {\n\tvar e error\n\tprivateKey, e = readPrivateKey()\n\tif e != nil {\n\t\tpanic(e)\n\t}\n\tConvey(\"Simple authenticated requests\", t, func() {\n\t\tConvey(\"Authenticated GET to / path should return a 200 response\", func() {\n\t\t\tw := makeAuthenticatedRequest(\"GET\", \"/\", jwt.MapClaims{\"foo\": \"bar\"}, nil)\n\t\t\tSo(w.Code, ShouldEqual, http.StatusOK)\n\t\t})\n\t\tConvey(\"Authenticated GET to /protected path should return a 200 response if expected algorithm is not specified\", func() {\n\t\t\tvar expectedAlgorithm jwt.SigningMethod = nil\n\t\t\tw := makeAuthenticatedRequest(\"GET\", \"/protected\", jwt.MapClaims{\"foo\": \"bar\"}, expectedAlgorithm)\n\t\t\tSo(w.Code, ShouldEqual, http.StatusOK)\n\t\t\tresponseBytes, err := ioutil.ReadAll(w.Body)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\tresponseString := string(responseBytes)\n\t\t\t// check that the encoded data in the jwt was properly returned as json\n\t\t\tSo(responseString, ShouldEqual, `{\"text\":\"bar\"}`)\n\t\t})\n\t\tConvey(\"Authenticated GET to /protected path should return a 200 response if expected algorithm is correct\", func() {\n\t\t\texpectedAlgorithm := jwt.SigningMethodHS256\n\t\t\tw := makeAuthenticatedRequest(\"GET\", \"/protected\", jwt.MapClaims{\"foo\": \"bar\"}, expectedAlgorithm)\n\t\t\tSo(w.Code, ShouldEqual, http.StatusOK)\n\t\t\tresponseBytes, err := ioutil.ReadAll(w.Body)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\tresponseString := string(responseBytes)\n\t\t\t// check that the encoded data in the jwt was properly returned as json\n\t\t\tSo(responseString, ShouldEqual, `{\"text\":\"bar\"}`)\n\t\t})\n\t\tConvey(\"Authenticated GET to /protected path should return a 401 response if algorithm is not expected one\", func() {\n\t\t\texpectedAlgorithm := jwt.SigningMethodRS256\n\t\t\tw := makeAuthenticatedRequest(\"GET\", \"/protected\", jwt.MapClaims{\"foo\": \"bar\"}, expectedAlgorithm)\n\t\t\tSo(w.Code, ShouldEqual, http.StatusUnauthorized)\n\t\t\tresponseBytes, err := ioutil.ReadAll(w.Body)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\tresponseString := string(responseBytes)\n\t\t\t// check that the encoded data in the jwt was properly returned as json\n\t\t\tSo(strings.TrimSpace(responseString), ShouldEqual, \"Expected RS256 signing method but token specified HS256\")\n\t\t})\n\t})\n}", "func newKeyServerWithMocking(user upspin.UserName, ref string, data []byte) (*server, *storagetest.ExpectDownloadCapturePut) {\n\tmockGCP := &storagetest.ExpectDownloadCapturePut{\n\t\tRef: []string{ref},\n\t\tData: [][]byte{data},\n\t\tPutContents: make([][]byte, 0, 1),\n\t\tPutRef: make([]string, 0, 1),\n\t}\n\ts := &server{\n\t\tstorage: mockGCP,\n\t\tuser: user,\n\t\tlookupTXT: mockLookupTXT,\n\t\tlogger: &noopLogger{},\n\t\tcache: cache.NewLRU(10),\n\t\tnegCache: cache.NewLRU(10),\n\t}\n\treturn s, mockGCP\n}", "func (m *MockMachine) SignerKey() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"SignerKey\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func private(bits int) (k *rsa.PrivateKey, err error) {\n\t// Private Key generation\n\tif k, err = rsa.GenerateKey(rand.Reader, bits); err != nil {\n\t\treturn k, err\n\t}\n\n\t// Validate Private Key\n\treturn k, k.Validate()\n}", "func TestOnionFile(t *testing.T) {\n\tt.Parallel()\n\n\ttempDir, errr := ioutil.TempDir(\"\", \"onion_store\")\n\tif errr != nil {\n\t\tt.Fatalf(\"unable to create temp dir: %v\", errr)\n\t}\n\n\tprivateKey := []byte(\"hide_me_plz\")\n\tprivateKeyPath := filepath.Join(tempDir, \"secret\")\n\n\t// Create a new file-based onion store. A private key should not exist\n\t// yet.\n\tonionFile := NewOnionFile(privateKeyPath, 0600)\n\tif _, err := onionFile.PrivateKey(V2); !ErrNoPrivateKey.Is(err) {\n\t\tt.Fatalf(\"expected ErrNoPrivateKey, got \\\"%v\\\"\", err)\n\t}\n\n\t// Store the private key and ensure what's stored matches.\n\tif err := onionFile.StorePrivateKey(V2, privateKey); err != nil {\n\t\tt.Fatalf(\"unable to store private key: %v\", err)\n\t}\n\tstorePrivateKey, err := onionFile.PrivateKey(V2)\n\tif err != nil {\n\t\tt.Fatalf(\"unable to retrieve private key: %v\", err)\n\t}\n\tif !bytes.Equal(storePrivateKey, privateKey) {\n\t\tt.Fatalf(\"expected private key \\\"%v\\\", got \\\"%v\\\"\",\n\t\t\tstring(privateKey), string(storePrivateKey))\n\t}\n\n\t// Finally, delete the private key. We should no longer be able to\n\t// retrieve it.\n\tif err := onionFile.DeletePrivateKey(V2); err != nil {\n\t\tt.Fatalf(\"unable to delete private key: %v\", err)\n\t}\n\tif _, err := onionFile.PrivateKey(V2); !ErrNoPrivateKey.Is(err) {\n\t\tt.Fatal(\"found deleted private key\")\n\t}\n}", "func newPrivateKey() (crypto.Signer, error) {\n\treturn ecdsa.GenerateKey(ellipticCurve, crand.Reader)\n}", "func NewPrivateKey(keyType string) (interface{}, error) {\n\tswitch keyType {\n\tcase \"ecdsa256\":\n\t\treturn ecdsa.GenerateKey(elliptic.P256(), rand.Reader)\n\tcase \"ecdsa384\":\n\t\treturn ecdsa.GenerateKey(elliptic.P384(), rand.Reader)\n\tcase \"ecdsa521\":\n\t\treturn ecdsa.GenerateKey(elliptic.P521(), rand.Reader)\n\tcase \"ed25519\":\n\t\t_, privateKey, err := ed25519.GenerateKey(rand.Reader)\n\t\treturn privateKey, err\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unsupported key type: %v\", keyType)\n\t}\n}", "func (c CryptoServiceTester) TestCreateAndGetKey(t *testing.T) {\n\tcryptoService := c.cryptoServiceFactory()\n\n\t// Test Create\n\ttufKey, err := cryptoService.Create(c.role, c.gun, c.keyAlgo)\n\trequire.NoError(t, err, c.errorMsg(\"error creating key\"))\n\n\t// Test GetKey\n\tretrievedKey := cryptoService.GetKey(tufKey.ID())\n\trequire.NotNil(t, retrievedKey,\n\t\tc.errorMsg(\"Could not find key ID %s\", tufKey.ID()))\n\trequire.Equal(t, tufKey.Public(), retrievedKey.Public(),\n\t\tc.errorMsg(\"retrieved public key didn't match\"))\n\n\t// Test GetPrivateKey\n\tretrievedKey, alias, err := cryptoService.GetPrivateKey(tufKey.ID())\n\trequire.NoError(t, err)\n\trequire.Equal(t, tufKey.ID(), retrievedKey.ID(),\n\t\tc.errorMsg(\"retrieved private key didn't have the right ID\"))\n\trequire.Equal(t, c.role, alias)\n}", "func (_m *TranslationKeyStore) GetServerDecryptionPrivateKeys(id []byte) ([]*keys.PrivateKey, error) {\n\tret := _m.Called(id)\n\n\tvar r0 []*keys.PrivateKey\n\tif rf, ok := ret.Get(0).(func([]byte) []*keys.PrivateKey); ok {\n\t\tr0 = rf(id)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).([]*keys.PrivateKey)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func([]byte) error); ok {\n\t\tr1 = rf(id)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func GeneratePrivateKey() (*rsa.PrivateKey, error) {\n\treturn rsa.GenerateKey(rand.Reader, RSA_BITS)\n}", "func (m *MockAPIConfigFromFlags) APIKey() string {\n\tret := m.ctrl.Call(m, \"APIKey\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func NewPrivateKey() PEMPrivateKeyLoaderInterface {\n\treturn &PrivateKey{\n\t\tpemDecoder: pemDecoder.NewPEMDecoder(),\n\t\tx509Parser: x509parser.Newx509Parser(),\n\t}\n}", "func (o *Gojwt) GetRSAPrivKey()(*rsa.PrivateKey){\n return o.privRSAKey\n}", "func (m *MockapprunnerDescriber) IsPrivate() (bool, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"IsPrivate\")\n\tret0, _ := ret[0].(bool)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockisCryptoAsymApiReqSetupPrivateKeyEx_Key) Size() int {\n\tret := m.ctrl.Call(m, \"Size\")\n\tret0, _ := ret[0].(int)\n\treturn ret0\n}", "func (x *Ed25519Credentials) PrivateKey() PrivateKey {\n\n\treturn PrivateKey{\n\t\tAlgorithm: AlgorithmEd25519,\n\t\tPrivate: base64.URLEncoding.EncodeToString(x.Private[:]),\n\t}\n\n}", "func GeneratePrivateKey(bitSize int) (*rsa.PrivateKey, error) {\n\tprivateKey, err := rsa.GenerateKey(rand.Reader, bitSize)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = privateKey.Validate()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn privateKey, nil\n}", "func (m *MockAuthorizer) HashKey() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"HashKey\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func TestPrivateKopeio(t *testing.T) {\n\tnewIntegrationTest(\"privatekopeio.example.com\", \"privatekopeio\").\n\t\twithPrivate().\n\t\twithAddons(\n\t\t\tawsEBSCSIAddon,\n\t\t\tdnsControllerAddon,\n\t\t\tawsCCMAddon,\n\t\t\tkopeioNetworkingAddon,\n\t\t).\n\t\trunTestTerraformAWS(t)\n}", "func (o ProviderOutput) PrivateKey() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *Provider) pulumi.StringPtrOutput { return v.PrivateKey }).(pulumi.StringPtrOutput)\n}", "func Test_Crypto(t *testing.T) {\n\trequire := require.New(t)\n\n\tc := &sm2.Driver{}\n\n\tpriv, err := c.GenKey()\n\trequire.Nil(err)\n\tt.Logf(\"priv:%X, len:%d\", priv.Bytes(), len(priv.Bytes()))\n\n\tpub := priv.PubKey()\n\trequire.NotNil(pub)\n\tt.Logf(\"pub:%X, len:%d\", pub.Bytes(), len(pub.Bytes()))\n\n\tmsg := []byte(\"hello world\")\n\tsignature := priv.Sign(msg)\n\tt.Logf(\"sign:%X, len:%d\", signature.Bytes(), len(signature.Bytes()))\n\n\tok := pub.VerifyBytes(msg, signature)\n\trequire.Equal(true, ok)\n}", "func getPrivateKey(data []byte) ([]byte, error) {\n\tvar der []byte\n\tvar derKey []byte\n\tfor {\n\t\tpemBlock, rest := pem.Decode(data)\n\t\tif pemBlock == nil {\n\t\t\tbreak\n\t\t}\n\t\tif pemBlock.Type != certType {\n\t\t\tder = pemBlock.Bytes\n\t\t}\n\t\tdata = rest\n\t}\n\n\tif key, err := x509.ParsePKCS1PrivateKey(der); err == nil {\n\t\tderKey = x509.MarshalPKCS1PrivateKey(key)\n\t}\n\n\tif key, err := x509.ParsePKCS8PrivateKey(der); err == nil {\n\t\tswitch key := key.(type) {\n\t\tcase *rsa.PrivateKey:\n\t\t\tderKey = x509.MarshalPKCS1PrivateKey(key)\n\t\tcase *ecdsa.PrivateKey:\n\t\t\tderKey, err = x509.MarshalECPrivateKey(key)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\tdefault:\n\t\t\treturn nil, fmt.Errorf(\"unknown private key type found while getting key. Only rsa and ecdsa are supported\")\n\t\t}\n\t}\n\tif key, err := x509.ParseECPrivateKey(der); err == nil {\n\t\tderKey, err = x509.MarshalECPrivateKey(key)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tblock := &pem.Block{\n\t\tType: privateKeyType,\n\t\tBytes: derKey,\n\t}\n\n\treturn pem.EncodeToMemory(block), nil\n}", "func (m *MockPrivateNetworkDetector) IsPrivate(arg0 string) (bool, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"IsPrivate\", arg0)\n\tret0, _ := ret[0].(bool)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func loadPrivateKey() {\n\tif privateKeyData, err := ioutil.ReadFile(PrivateKeyFile); err != nil {\n\t\tlog.Print(\"Unable to read private key file from disk, creating\")\n\t\tcreatePrivateKey()\n\t} else {\n\t\tblock, _ := pem.Decode(privateKeyData)\n\t\tif block == nil {\n\t\t\tlog.Print(\"Unable to decode PEM encoded private key data, creating\")\n\t\t\tcreatePrivateKey()\n\t\t} else {\n\t\t\tprivateKey, err = x509.ParsePKCS1PrivateKey(block.Bytes)\n\t\t\tif err != nil {\n\t\t\t\tlog.Print(\"Unable to decode X509 private key data, creating\")\n\t\t\t\tcreatePrivateKey()\n\t\t\t} else {\n\t\t\t\tlog.Printf(\"Read private key\")\n\t\t\t}\n\t\t}\n\t}\n}", "func TestOnionFile(t *testing.T) {\n\tt.Parallel()\n\n\ttempDir, err := ioutil.TempDir(\"\", \"onion_store\")\n\trequire.NoError(t, err, \"unable to create temp dir\")\n\n\tprivateKey := []byte(\"hide_me_plz\")\n\tprivateKeyPath := filepath.Join(tempDir, \"secret\")\n\n\t// Create a new file-based onion store. A private key should not exist\n\t// yet.\n\tonionFile := NewOnionFile(privateKeyPath, 0600)\n\tif _, err := onionFile.PrivateKey(V2); err != ErrNoPrivateKey {\n\t\tt.Fatalf(\"expected ErrNoPrivateKey, got \\\"%v\\\"\", err)\n\t}\n\n\t// Store the private key and ensure what's stored matches.\n\tif err := onionFile.StorePrivateKey(V2, privateKey); err != nil {\n\t\tt.Fatalf(\"unable to store private key: %v\", err)\n\t}\n\tstorePrivateKey, err := onionFile.PrivateKey(V2)\n\trequire.NoError(t, err, \"unable to retrieve private key\")\n\tif !bytes.Equal(storePrivateKey, privateKey) {\n\t\tt.Fatalf(\"expected private key \\\"%v\\\", got \\\"%v\\\"\",\n\t\t\tstring(privateKey), string(storePrivateKey))\n\t}\n\n\t// Finally, delete the private key. We should no longer be able to\n\t// retrieve it.\n\tif err := onionFile.DeletePrivateKey(V2); err != nil {\n\t\tt.Fatalf(\"unable to delete private key: %v\", err)\n\t}\n\tif _, err := onionFile.PrivateKey(V2); err != ErrNoPrivateKey {\n\t\tt.Fatal(\"found deleted private key\")\n\t}\n}", "func connect(user, host string, port int) (*ssh.Session, error) {\n\tvar (\n\t\tauth []ssh.AuthMethod\n\t\taddr string\n\t\tclientConfig *ssh.ClientConfig\n\t\tclient *ssh.Client\n\t\tsession *ssh.Session\n\t\terr error\n\t)\n\tauth = make([]ssh.AuthMethod, 0)\n\ttestPrivateKeys, err := ssh.ParseRawPrivateKey([]byte(`-----BEGIN RSA PRIVATE KEY-----\nMIIEowIBAAKCAQEApnIg4Q/g2thAR3vAUw6EPjqgWIEJ7+FZ+AQZtHUc7b920VJI\n7JPmZ1xwdUArlCpQIMAt6mAwV9Z/C+Nc9qIpIeQwKaAd6YWVdr3jFyHLC9rqIT2g\nVifCDnMkSnV7Lvuu5QTvgURGOYpyUhUDJBdBY4YAu9q1ITy35oB0xLh1vUCwuDxI\noM5lMc+HsPjf4/SyfyAacBuoD7BvAJsxJ6xuXBaIlmWcw8o76O/Y5PGcYKPS9/bI\nrN8TrstuWILp2Nvi4WoxVMIQ98i1S6jM47arI+vNGlFrwolrCanH8GBj1NOBh4BF\nJwJisi0Z3+RrtxOVRtgZ9S/tKdK73X6EpbN4hwIDAQABAoIBAAuBRAiKgm5eGENY\nqHiVPkrW3pJ/iOJN31wnXGd+2NsOKvZZC7Vem8R1PUi9gMWjDxrUbdgPggfwSaPW\nuWxK1TEEhte5u5eSpjwo7/N/YHuXTCu0CMsrwFwjVVTYPgWHXBV0e+GhiIEdsr09\nupPaD6kDcDWL7o03lzaVlnyqi2jjXT6kUDyEFCbIAGtoxaYf3clT5e30FnyZhiCH\nm8/Qqv5M1wcVIVdsItHqMsQXQF34eT/Lg3r/Ui1bQcUldc6yYjGpC08EdDNKhGT2\nf2QwAv7UJ+GB8RNl12w3fAh3ReuiW8NEtDQ1nuSahkX5YlIWkqRDOd6Sjrg1ZkfW\nu0/zPZECgYEA2m+w90vb3ui7M/Q0AYJivo88YKhT3ismQs2+CkkgWJ7IohJj3VSh\nREljeAwEVEKv8G8lXgjTNKQ+B4sPFckIvIWGkwo7cuerIwn9n41K20oGb6gEl0jW\nmVbhv0dy6yfp8deBCOZB4YgonXWsuv4lw8DaUoakGxZgFfChjH0VvbUCgYEAwxGj\nrmq+RQWYYna9WWn2GPEJoX0SBU39pHQYBKfQ++pMIUrrryCjPvBNnIICng82RjTp\nMU8BvudvDCJgj3J79TDetBnwVt8/nAGIkleyuWzDMQwF7khBS9/TqUUqmH88GmOt\n40BPThCBx8YgKiPpmGYgPnUww1bqpvxKT9O0IssCgYEAjFH7qKD+mW9/8pwJXH7Z\n1/hDnQQE/E9TwM5SKmFXehZmZFbT+DaJckiCsXdmwIomY5nCs2mP490uS8I06pW+\nGvzbulF0ZxgTg+rDFl+5mq0u/UM9z8FmuhJp6mqHlDCLxGPf7EuePrctABm74FOr\nBtk4ZpM/kHcLOozd+lXQRZECgYBipWr26zgpQ3kaYh3DN9iiKFLMfak9UYFxRtxW\njl8a5hN1yqOBPqoPTAqTmROlxt+VhXBf5Spm1jbMFh5qrGSPTBVzUqK968wJIqVk\nDEFvj9bt2LyvEY8jxZ8OPNIbqExGtB3djEoOmj5nPoRJizu4O/0WWME+J5gmtfMG\nh3LTHQKBgDlITGqdIM4Pp54X5ppOW9S55yaAMBJUUhgUsJ73vEcQsBCZ8xkJXg/Q\nmuPfcFzSD/IgeFoWxYrJIk0CBov3ah+14z5YV1JoKIXAlL7V18f7Omaav8/bozOP\nx78MQ06CGEFRcD4LPMITxTDj6zDm1h7iPhG4m2c9Shy0rwpFmFdd\n-----END RSA PRIVATE KEY-----`))\n\tif err != nil {\n\t\tglog.Infoln(\"Unable to parse test key :\", err)\n\t}\n\ttestSingers, _ := ssh.NewSignerFromKey(testPrivateKeys)\n\n\tauth = append(auth, ssh.PublicKeys(testSingers))\n\tclientConfig = &ssh.ClientConfig{\n\t\tUser: user,\n\t\tAuth: auth,\n\t\t//\t\tTimeout: \t\t\t60 * time.Second,\n\t\tHostKeyCallback: func(hostname string, remote net.Addr, key ssh.PublicKey) error {\n\t\t\treturn nil\n\t\t},\n\t}\n\taddr = fmt.Sprintf(\"%s:%d\", host, port)\n\tif client, err = ssh.Dial(\"tcp\", addr, clientConfig); err != nil {\n\t\treturn nil, err\n\t}\n\tif session, err = client.NewSession(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn session, nil\n}", "func connect(user, host string, port int) (*ssh.Session, error) {\n\tvar (\n\t\tauth []ssh.AuthMethod\n\t\taddr string\n\t\tclientConfig *ssh.ClientConfig\n\t\tclient *ssh.Client\n\t\tsession *ssh.Session\n\t\terr error\n\t)\n\tauth = make([]ssh.AuthMethod, 0)\n\ttestPrivateKeys, err := ssh.ParseRawPrivateKey([]byte(`-----BEGIN RSA PRIVATE KEY-----\nMIIEowIBAAKCAQEApnIg4Q/g2thAR3vAUw6EPjqgWIEJ7+FZ+AQZtHUc7b920VJI\n7JPmZ1xwdUArlCpQIMAt6mAwV9Z/C+Nc9qIpIeQwKaAd6YWVdr3jFyHLC9rqIT2g\nVifCDnMkSnV7Lvuu5QTvgURGOYpyUhUDJBdBY4YAu9q1ITy35oB0xLh1vUCwuDxI\noM5lMc+HsPjf4/SyfyAacBuoD7BvAJsxJ6xuXBaIlmWcw8o76O/Y5PGcYKPS9/bI\nrN8TrstuWILp2Nvi4WoxVMIQ98i1S6jM47arI+vNGlFrwolrCanH8GBj1NOBh4BF\nJwJisi0Z3+RrtxOVRtgZ9S/tKdK73X6EpbN4hwIDAQABAoIBAAuBRAiKgm5eGENY\nqHiVPkrW3pJ/iOJN31wnXGd+2NsOKvZZC7Vem8R1PUi9gMWjDxrUbdgPggfwSaPW\nuWxK1TEEhte5u5eSpjwo7/N/YHuXTCu0CMsrwFwjVVTYPgWHXBV0e+GhiIEdsr09\nupPaD6kDcDWL7o03lzaVlnyqi2jjXT6kUDyEFCbIAGtoxaYf3clT5e30FnyZhiCH\nm8/Qqv5M1wcVIVdsItHqMsQXQF34eT/Lg3r/Ui1bQcUldc6yYjGpC08EdDNKhGT2\nf2QwAv7UJ+GB8RNl12w3fAh3ReuiW8NEtDQ1nuSahkX5YlIWkqRDOd6Sjrg1ZkfW\nu0/zPZECgYEA2m+w90vb3ui7M/Q0AYJivo88YKhT3ismQs2+CkkgWJ7IohJj3VSh\nREljeAwEVEKv8G8lXgjTNKQ+B4sPFckIvIWGkwo7cuerIwn9n41K20oGb6gEl0jW\nmVbhv0dy6yfp8deBCOZB4YgonXWsuv4lw8DaUoakGxZgFfChjH0VvbUCgYEAwxGj\nrmq+RQWYYna9WWn2GPEJoX0SBU39pHQYBKfQ++pMIUrrryCjPvBNnIICng82RjTp\nMU8BvudvDCJgj3J79TDetBnwVt8/nAGIkleyuWzDMQwF7khBS9/TqUUqmH88GmOt\n40BPThCBx8YgKiPpmGYgPnUww1bqpvxKT9O0IssCgYEAjFH7qKD+mW9/8pwJXH7Z\n1/hDnQQE/E9TwM5SKmFXehZmZFbT+DaJckiCsXdmwIomY5nCs2mP490uS8I06pW+\nGvzbulF0ZxgTg+rDFl+5mq0u/UM9z8FmuhJp6mqHlDCLxGPf7EuePrctABm74FOr\nBtk4ZpM/kHcLOozd+lXQRZECgYBipWr26zgpQ3kaYh3DN9iiKFLMfak9UYFxRtxW\njl8a5hN1yqOBPqoPTAqTmROlxt+VhXBf5Spm1jbMFh5qrGSPTBVzUqK968wJIqVk\nDEFvj9bt2LyvEY8jxZ8OPNIbqExGtB3djEoOmj5nPoRJizu4O/0WWME+J5gmtfMG\nh3LTHQKBgDlITGqdIM4Pp54X5ppOW9S55yaAMBJUUhgUsJ73vEcQsBCZ8xkJXg/Q\nmuPfcFzSD/IgeFoWxYrJIk0CBov3ah+14z5YV1JoKIXAlL7V18f7Omaav8/bozOP\nx78MQ06CGEFRcD4LPMITxTDj6zDm1h7iPhG4m2c9Shy0rwpFmFdd\n-----END RSA PRIVATE KEY-----`))\n\tif err != nil {\n\t\tglog.Infoln(\"Unable to parse test key :\", err)\n\t}\n\ttestSingers, _ := ssh.NewSignerFromKey(testPrivateKeys)\n\n\tauth = append(auth, ssh.PublicKeys(testSingers))\n\tclientConfig = &ssh.ClientConfig{\n\t\tUser: user,\n\t\tAuth: auth,\n\t\t//\t\tTimeout: \t\t\t60 * time.Second,\n\t\tHostKeyCallback: func(hostname string, remote net.Addr, key ssh.PublicKey) error {\n\t\t\treturn nil\n\t\t},\n\t}\n\taddr = fmt.Sprintf(\"%s:%d\", host, port)\n\tif client, err = ssh.Dial(\"tcp\", addr, clientConfig); err != nil {\n\t\treturn nil, err\n\t}\n\tif session, err = client.NewSession(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn session, nil\n}", "func GeneratePrivateKey(algorithm string) (k *PrivateKey, err error) {\n\tswitch algorithm {\n\tcase \"(ecdsa-sha2 (curve p256))\":\n\t\treturn GenerateP256Key()\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"Unknown algorithm '%s'\", algorithm)\n\t}\n}", "func NewCustomPrivateKey(decoder pemDecoder.PEMDecoderInterface, parser x509parser.X509ParserInterface) PEMPrivateKeyLoaderInterface {\n\treturn &PrivateKey{\n\t\tpemDecoder: decoder,\n\t\tx509Parser: parser,\n\t}\n}", "func LoadPrivateKey(basepath, name string) (*PrivateKey, error) {\n\tkeysdir := filepath.Join(basepath, \"keys\")\n\tprivateKeyPath := fmt.Sprintf(DefaultKeystoreFile, keysdir, name, PrivateType)\n\n\tprivateExists, err := checkFileStat(privateKeyPath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif !privateExists {\n\t\treturn nil, ErrKeyNotFound\n\t}\n\n\tprivateKeyData, err := ioutil.ReadFile(privateKeyPath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpemBlock, _ := pem.Decode(privateKeyData)\n\tecdsaPrivateKey, err := x509.ParseECPrivateKey(pemBlock.Bytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &PrivateKey{\n\t\tecdsaPrivateKey,\n\t}, nil\n}", "func connect(user, host string, port int) (*ssh.Client, error) {\n\tvar (\n\t\tauth \t\t\t[]ssh.AuthMethod\n\t\taddr \t\t\tstring\n\t\tclientConfig \t*ssh.ClientConfig\n\t\tclient \t\t\t*ssh.Client\n\t\terr \t\t\terror\n\t)\n\tauth = make([]ssh.AuthMethod, 0)\n\ttestPrivateKeys, err := ssh.ParseRawPrivateKey([]byte(`-----BEGIN RSA PRIVATE KEY-----\nMIIEowIBAAKCAQEApnIg4Q/g2thAR3vAUw6EPjqgWIEJ7+FZ+AQZtHUc7b920VJI\n7JPmZ1xwdUArlCpQIMAt6mAwV9Z/C+Nc9qIpIeQwKaAd6YWVdr3jFyHLC9rqIT2g\nVifCDnMkSnV7Lvuu5QTvgURGOYpyUhUDJBdBY4YAu9q1ITy35oB0xLh1vUCwuDxI\noM5lMc+HsPjf4/SyfyAacBuoD7BvAJsxJ6xuXBaIlmWcw8o76O/Y5PGcYKPS9/bI\nrN8TrstuWILp2Nvi4WoxVMIQ98i1S6jM47arI+vNGlFrwolrCanH8GBj1NOBh4BF\nJwJisi0Z3+RrtxOVRtgZ9S/tKdK73X6EpbN4hwIDAQABAoIBAAuBRAiKgm5eGENY\nqHiVPkrW3pJ/iOJN31wnXGd+2NsOKvZZC7Vem8R1PUi9gMWjDxrUbdgPggfwSaPW\nuWxK1TEEhte5u5eSpjwo7/N/YHuXTCu0CMsrwFwjVVTYPgWHXBV0e+GhiIEdsr09\nupPaD6kDcDWL7o03lzaVlnyqi2jjXT6kUDyEFCbIAGtoxaYf3clT5e30FnyZhiCH\nm8/Qqv5M1wcVIVdsItHqMsQXQF34eT/Lg3r/Ui1bQcUldc6yYjGpC08EdDNKhGT2\nf2QwAv7UJ+GB8RNl12w3fAh3ReuiW8NEtDQ1nuSahkX5YlIWkqRDOd6Sjrg1ZkfW\nu0/zPZECgYEA2m+w90vb3ui7M/Q0AYJivo88YKhT3ismQs2+CkkgWJ7IohJj3VSh\nREljeAwEVEKv8G8lXgjTNKQ+B4sPFckIvIWGkwo7cuerIwn9n41K20oGb6gEl0jW\nmVbhv0dy6yfp8deBCOZB4YgonXWsuv4lw8DaUoakGxZgFfChjH0VvbUCgYEAwxGj\nrmq+RQWYYna9WWn2GPEJoX0SBU39pHQYBKfQ++pMIUrrryCjPvBNnIICng82RjTp\nMU8BvudvDCJgj3J79TDetBnwVt8/nAGIkleyuWzDMQwF7khBS9/TqUUqmH88GmOt\n40BPThCBx8YgKiPpmGYgPnUww1bqpvxKT9O0IssCgYEAjFH7qKD+mW9/8pwJXH7Z\n1/hDnQQE/E9TwM5SKmFXehZmZFbT+DaJckiCsXdmwIomY5nCs2mP490uS8I06pW+\nGvzbulF0ZxgTg+rDFl+5mq0u/UM9z8FmuhJp6mqHlDCLxGPf7EuePrctABm74FOr\nBtk4ZpM/kHcLOozd+lXQRZECgYBipWr26zgpQ3kaYh3DN9iiKFLMfak9UYFxRtxW\njl8a5hN1yqOBPqoPTAqTmROlxt+VhXBf5Spm1jbMFh5qrGSPTBVzUqK968wJIqVk\nDEFvj9bt2LyvEY8jxZ8OPNIbqExGtB3djEoOmj5nPoRJizu4O/0WWME+J5gmtfMG\nh3LTHQKBgDlITGqdIM4Pp54X5ppOW9S55yaAMBJUUhgUsJ73vEcQsBCZ8xkJXg/Q\nmuPfcFzSD/IgeFoWxYrJIk0CBov3ah+14z5YV1JoKIXAlL7V18f7Omaav8/bozOP\nx78MQ06CGEFRcD4LPMITxTDj6zDm1h7iPhG4m2c9Shy0rwpFmFdd\n-----END RSA PRIVATE KEY-----`))\n\tif err != nil {\n\t\t// fmt.Println(\"Unable to parse test key :\", err)\n\t\treturn nil, err\n\t}\n\ttestSingers, _ := ssh.NewSignerFromKey(testPrivateKeys)\n\n\tauth = append(auth, ssh.PublicKeys(testSingers))\n\tclientConfig = &ssh.ClientConfig{\n\t\tUser: \t\t\t\tuser,\n\t\tAuth: \t\t\t\tauth,\n\t\tTimeout: \t\t\t30 * time.Second,\n\t\tHostKeyCallback: \tfunc(hostname string, remote net.Addr, key ssh.PublicKey) error {\n\t\t\treturn nil\n\t\t},\n\t}\n\taddr = fmt.Sprintf(\"%s:%d\", host, port)\n\tif client, err = ssh.Dial(\"tcp\", addr, clientConfig); err != nil {\n\t\treturn nil, err\n\t}\n\treturn client, nil\n}", "func (k *key) getPrivateKey() (*ecdsa.PrivateKey, error) {\n\tby, err := base64.StdEncoding.DecodeString(k.PrivateKeyB64)\n\tif err != nil {\n\t\treturn (*ecdsa.PrivateKey)(nil), err\n\t}\n\n\tblock, _ := pem.Decode([]byte(by))\n\ttempKey, err := x509.ParseECPrivateKey(block.Bytes)\n\tif err != nil {\n\t\treturn (*ecdsa.PrivateKey)(nil), err\n\t}\n\n\treturn tempKey, nil\n}", "func (m *MockisCryptoAsymApiRespSetupPrivateKey_KeyInfo) Size() int {\n\tret := m.ctrl.Call(m, \"Size\")\n\tret0, _ := ret[0].(int)\n\treturn ret0\n}", "func TestRSAKeyExport(t *testing.T) {\n\tkey, err := NewKeyFromPrivateKeyPEM([]byte(rsaPrivKeyAuthPEM))\n\tif err != nil {\n\t\tt.Fatal(\"Failed to parse certificate from PEM:\", err)\n\t}\n\n\tpemBytes, err := key.ExportPrivate()\n\tif err != nil {\n\t\tt.Fatal(\"Failed exporting PEM-format bytes:\", err)\n\t}\n\tif !bytes.Equal(pemBytes, []byte(rsaPrivKeyAuthPEM)) {\n\t\tt.Fatal(\"Failed exporting the same PEM-format bytes\")\n\t}\n}", "func mockChildPackages() {\n\n\t// Fake an AWS credentials file so that the mfile package will nehave as if it is happy\n\tsetFakeCredentials()\n\n\t// Fake out the creds package into using an apparently credentials response from AWS\n\tcreds.SetGetSessionTokenFunc(func(awsService *sts.STS, input *sts.GetSessionTokenInput) (*sts.GetSessionTokenOutput, error) {\n\t\treturn getSessionTokenOutput, nil\n\t})\n\n}", "func TestPrivateCalico(t *testing.T) {\n\tnewIntegrationTest(\"privatecalico.example.com\", \"privatecalico\").\n\t\twithPrivate().\n\t\twithDefaultAddons24().\n\t\twithAddons(calicoAddon).\n\t\trunTestTerraformAWS(t)\n}", "func fakePassphraseKey() (*Key, error) {\n\treturn NewFixedLengthKeyFromReader(bytes.NewReader(fakePassword), len(fakePassword))\n}", "func loadPrivateKeyBase64(base64key string) (*rsa.PrivateKey, error) {\n\tkeybytes, err := base64.StdEncoding.DecodeString(base64key)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"base64 decode failed, error=%s\\n\", err.Error())\n\t}\n\n\tprivatekey, err := x509.ParsePKCS1PrivateKey(keybytes)\n\tif err != nil {\n\t\treturn nil, errors.New(\"parse private key error!\")\n\t}\n\n\treturn privatekey, nil\n}", "func (o SslCertificateSelfManagedSslCertificateOutput) PrivateKey() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v SslCertificateSelfManagedSslCertificate) *string { return v.PrivateKey }).(pulumi.StringPtrOutput)\n}", "func PrivateKey(i int) *keys.PrivateKey {\n\twif := WIF(i)\n\tpriv, err := keys.NewPrivateKeyFromWIF(wif)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn priv\n}", "func (m *MockisCryptoAsymApiRespSetupPrivateKey_KeyInfo) EXPECT() *MockisCryptoAsymApiRespSetupPrivateKey_KeyInfoMockRecorder {\n\treturn m.recorder\n}", "func (d *identityManager) PrivateKey() []byte {\n\treturn d.key.PrivateKey\n}", "func NewPrivateKey() (*rsa.PrivateKey, error) {\n\treturn rsa.GenerateKey(rand.Reader, 2048)\n}", "func (m *MockC2Client) NewC2Key(arg0 context.Context, arg1 *pb.NewC2KeyRequest, arg2 ...grpc.CallOption) (*pb.NewC2KeyResponse, error) {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{arg0, arg1}\n\tfor _, a := range arg2 {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"NewC2Key\", varargs...)\n\tret0, _ := ret[0].(*pb.NewC2KeyResponse)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (_m *Keychain) GenerateKeyPair() ([]byte, []byte, error) {\n\tret := _m.Called()\n\n\tvar r0 []byte\n\tif rf, ok := ret.Get(0).(func() []byte); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).([]byte)\n\t\t}\n\t}\n\n\tvar r1 []byte\n\tif rf, ok := ret.Get(1).(func() []byte); ok {\n\t\tr1 = rf()\n\t} else {\n\t\tif ret.Get(1) != nil {\n\t\t\tr1 = ret.Get(1).([]byte)\n\t\t}\n\t}\n\n\tvar r2 error\n\tif rf, ok := ret.Get(2).(func() error); ok {\n\t\tr2 = rf()\n\t} else {\n\t\tr2 = ret.Error(2)\n\t}\n\n\treturn r0, r1, r2\n}", "func genPrivateKeyFile(c *cli.Context) {\n\tconfig, err := readConfig(c)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tout, err := os.Create(config.KeyFile)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer out.Close()\n\n\tprv, err := rsa.GenerateKey(rand.Reader, 2048)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\terr = pem.Encode(out, &pem.Block{\n\t\tType: \"RSA PRIVATE KEY\",\n\t\tBytes: x509.MarshalPKCS1PrivateKey(prv),\n\t})\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}", "func MakePrivateKey(keystr string) (*PrivateKey, error) {\n\tvar seedbuf [64]byte\n\tseed1 := md5.Sum([]byte(keystr))\n\tseed2 := md5.Sum([]byte(keystr + \"pad1\"))\n\tseed3 := md5.Sum([]byte(keystr + \"pad2\"))\n\tseed4 := md5.Sum([]byte(keystr + \"pad3\"))\n\n\tcopy(seedbuf[0:16], seed1[:])\n\tcopy(seedbuf[16:32], seed2[:])\n\tcopy(seedbuf[32:48], seed3[:])\n\tcopy(seedbuf[48:64], seed4[:])\n\n\tvar p, q big.Int\n\tsetBytesReverse(&p, seedbuf[0:28])\n\tsetBytesReverse(&q, seedbuf[28:64])\n\tp.SetBit(&p, 215, 1)\n\tq.SetBit(&q, 279, 1)\n\treturn newPrivateKey(p, q)\n}", "func (m *MockInternalServer) CryptoKeyRead(arg0 context.Context, arg1 *CryptoKeyReadRequestMsg) (*CryptoKeyReadResponseMsg, error) {\n\tret := m.ctrl.Call(m, \"CryptoKeyRead\", arg0, arg1)\n\tret0, _ := ret[0].(*CryptoKeyReadResponseMsg)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func readPrivateKey() ([]byte, error) {\n\tprivateKey, e := ioutil.ReadFile(\"keys/sample-key\")\n\treturn privateKey, e\n}", "func (m *MockProvider) KMSDecryptEnv(arg0, arg1 string) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"KMSDecryptEnv\", arg0, arg1)\n}", "func derivePrivateKey(masterKey *hdkeychain.ExtendedKey, path accounts.DerivationPath) (*hdkeychain.ExtendedKey, error) {\n\tvar err error\n\tkey := masterKey\n\tfor _, n := range path {\n\t\tkey, err = key.Derive(n)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn key, nil\n}", "func (m *MockisTlsCbKeyHandle_KeyOrHandle) isTlsCbKeyHandle_KeyOrHandle() {\n\tm.ctrl.Call(m, \"isTlsCbKeyHandle_KeyOrHandle\")\n}", "func TestPrepareKeyParam(t *testing.T) {\n\ttestKey := []byte(\"hide_me_plz\")\n\tdummyErr := errors.New(\"dummy\")\n\n\t// Create a dummy controller.\n\tcontroller := NewController(\"\", \"\", \"\")\n\n\t// Test that a V3 keyParam is used.\n\tcfg := AddOnionConfig{Type: V3}\n\tkeyParam, err := controller.prepareKeyparam(cfg)\n\n\trequire.Equal(t, \"NEW:ED25519-V3\", keyParam)\n\trequire.NoError(t, err)\n\n\t// Create a mock store which returns the test private key.\n\tstore := &mockStore{}\n\tstore.On(\"PrivateKey\", cfg.Type).Return(testKey, nil)\n\n\t// Check that the test private is returned.\n\tcfg = AddOnionConfig{Type: V3, Store: store}\n\tkeyParam, err = controller.prepareKeyparam(cfg)\n\n\trequire.Equal(t, string(testKey), keyParam)\n\trequire.NoError(t, err)\n\tstore.AssertExpectations(t)\n\n\t// Create a mock store which returns ErrNoPrivateKey.\n\tstore = &mockStore{}\n\tstore.On(\"PrivateKey\", cfg.Type).Return(nil, ErrNoPrivateKey)\n\n\t// Check that the V3 keyParam is returned.\n\tcfg = AddOnionConfig{Type: V3, Store: store}\n\tkeyParam, err = controller.prepareKeyparam(cfg)\n\n\trequire.Equal(t, \"NEW:ED25519-V3\", keyParam)\n\trequire.NoError(t, err)\n\tstore.AssertExpectations(t)\n\n\t// Create a mock store which returns an dummy error.\n\tstore = &mockStore{}\n\tstore.On(\"PrivateKey\", cfg.Type).Return(nil, dummyErr)\n\n\t// Check that an error is returned.\n\tcfg = AddOnionConfig{Type: V3, Store: store}\n\tkeyParam, err = controller.prepareKeyparam(cfg)\n\n\trequire.Empty(t, keyParam)\n\trequire.ErrorIs(t, dummyErr, err)\n\tstore.AssertExpectations(t)\n}" ]
[ "0.68074006", "0.6719014", "0.6577349", "0.65547884", "0.655193", "0.6528726", "0.6515265", "0.6143082", "0.6138266", "0.6138245", "0.61061144", "0.6056119", "0.6028489", "0.60039204", "0.5974573", "0.59328353", "0.5916291", "0.59109217", "0.58914673", "0.5878999", "0.5856995", "0.58433086", "0.58230954", "0.58085114", "0.5806728", "0.5799682", "0.57726014", "0.5769625", "0.5749321", "0.5724578", "0.5721102", "0.57134587", "0.5712279", "0.56964", "0.5672295", "0.5657177", "0.5648475", "0.56462467", "0.56270057", "0.5626836", "0.56223416", "0.5615756", "0.5611758", "0.5608551", "0.56056637", "0.55800116", "0.5574454", "0.55614334", "0.55532014", "0.5553097", "0.5552692", "0.5536929", "0.55350035", "0.5532509", "0.55265266", "0.5520351", "0.5513288", "0.55077684", "0.54937315", "0.5486681", "0.5478727", "0.54776084", "0.5460963", "0.5444375", "0.54392374", "0.5433454", "0.5430841", "0.5423373", "0.5422914", "0.5418141", "0.54171866", "0.54121315", "0.54108244", "0.54108244", "0.54070306", "0.5404635", "0.5401713", "0.5401309", "0.5397874", "0.5385876", "0.5377986", "0.5375789", "0.53714335", "0.5364523", "0.5363257", "0.53599155", "0.53580123", "0.53572154", "0.53565", "0.5352053", "0.5340172", "0.53392434", "0.5334272", "0.53339195", "0.5315815", "0.5314685", "0.5311443", "0.5308144", "0.5306758", "0.52939266" ]
0.7180571
0
PrivateKey indicates an expected call of PrivateKey
func (mr *MockClientMockRecorder) PrivateKey() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PrivateKey", reflect.TypeOf((*MockClient)(nil).PrivateKey)) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func PrivateKeyValidate(priv *rsa.PrivateKey,) error", "func (o *PipelineSshKeyPairAllOf) GetPrivateKeyOk() (*string, bool) {\n\tif o == nil || o.PrivateKey == nil {\n\t\treturn nil, false\n\t}\n\treturn o.PrivateKey, true\n}", "func (o *TppCertificateParams) GetPrivateKeyOk() (*string, bool) {\n\tif o == nil {\n\t\treturn nil, false\n\t}\n\treturn &o.PrivateKey, true\n}", "func validatePrivateKey(k *ecdsa.PrivateKey) bool {\n\tif k == nil || k.D == nil || k.D.Sign() == 0 {\n\t\treturn false\n\t}\n\treturn ValidatePublicKey(&k.PublicKey)\n}", "func (o *PipelineSshKeyPairAllOf) HasPrivateKey() bool {\n\tif o != nil && o.PrivateKey != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (c *HTTPClientMock) APIKeyPrivate() string {\n\treturn c.apiKeyPrivate\n}", "func (o *PipelineSshKeyPairAllOf) SetPrivateKey(v string) {\n\to.PrivateKey = &v\n}", "func (o SslCertificateSelfManagedSslCertificateResponseOutput) PrivateKey() pulumi.StringOutput {\n\treturn o.ApplyT(func(v SslCertificateSelfManagedSslCertificateResponse) string { return v.PrivateKey }).(pulumi.StringOutput)\n}", "func (k *Key) IsPrivate() bool {\n\treturn k.Key.IsPrivate()\n}", "func private(bits int) (k *rsa.PrivateKey, err error) {\n\t// Private Key generation\n\tif k, err = rsa.GenerateKey(rand.Reader, bits); err != nil {\n\t\treturn k, err\n\t}\n\n\t// Validate Private Key\n\treturn k, k.Validate()\n}", "func (o SslCertificateOutput) PrivateKey() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *SslCertificate) pulumi.StringOutput { return v.PrivateKey }).(pulumi.StringOutput)\n}", "func (o SslCertificateSelfManagedSslCertificateOutput) PrivateKey() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v SslCertificateSelfManagedSslCertificate) *string { return v.PrivateKey }).(pulumi.StringPtrOutput)\n}", "func (o SslCertOutput) PrivateKey() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *SslCert) pulumi.StringOutput { return v.PrivateKey }).(pulumi.StringOutput)\n}", "func (o SslCertificateSelfManagedSslCertificateResponsePtrOutput) PrivateKey() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *SslCertificateSelfManagedSslCertificateResponse) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.PrivateKey\n\t}).(pulumi.StringPtrOutput)\n}", "func (dtk *DcmTagKey) IsPrivate() bool {\n\treturn ((dtk.group & 1) != 0) && dtk.HasValidGroup()\n}", "func ExpectValidPrivateKeyData(csr *certificatesv1.CertificateSigningRequest, key crypto.Signer) error {\n\tcert, err := pki.DecodeX509CertificateBytes(csr.Status.Certificate)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tequal := func() (bool, error) {\n\t\tswitch pub := key.Public().(type) {\n\t\tcase *rsa.PublicKey:\n\t\t\treturn pub.Equal(cert.PublicKey), nil\n\t\tcase *ecdsa.PublicKey:\n\t\t\treturn pub.Equal(cert.PublicKey), nil\n\t\tcase ed25519.PublicKey:\n\t\t\treturn pub.Equal(cert.PublicKey), nil\n\t\tdefault:\n\t\t\treturn false, fmt.Errorf(\"Unrecognised public key type: %T\", key)\n\t\t}\n\t}\n\n\tok, err := equal()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif !ok {\n\t\treturn errors.New(\"Expected signed certificate's public key to match requester's private key\")\n\t}\n\n\treturn nil\n}", "func (p *Provider) IsPrivate() bool {\n\treturn p.key != nil\n}", "func (mr *MockapprunnerDescriberMockRecorder) IsPrivate() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"IsPrivate\", reflect.TypeOf((*MockapprunnerDescriber)(nil).IsPrivate))\n}", "func (o *TppCertificateParams) SetPrivateKey(v string) {\n\to.PrivateKey = v\n}", "func (o ProviderOutput) PrivateKey() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *Provider) pulumi.StringPtrOutput { return v.PrivateKey }).(pulumi.StringPtrOutput)\n}", "func (x *X509ParseDataMock) ParsePrivateKey(der []byte) (interface{}, error) {\n\tvar err error\n\tif x.ParsePrivateKeyFailed {\n\t\terr = fmt.Errorf(\"ParsePrivateKeyFailed was set to TRUE\")\n\t}\n\n\treturn der, err\n}", "func parsePrivateKey(privateKeyDecoded []byte, keyType Secret) (*rsa.PrivateKey, error) {\n\tswitch keyType {\n\tcase PKCS1:\n\t\treturn x509.ParsePKCS1PrivateKey(privateKeyDecoded)\n\tcase PKCS8:\n\t\tkeyParsed, err := x509.ParsePKCS8PrivateKey(privateKeyDecoded)\n\t\treturn keyParsed.(*rsa.PrivateKey), err\n\tdefault:\n\t\treturn &rsa.PrivateKey{}, fmt.Errorf(\"secretInfo PrivateKeyDataType unsupport\")\n\t}\n}", "func TestPrivateKey(t *testing.T) {\n\tconst jsonKey = `{\"keys\":\n [\n {\"kty\":\"EC\",\n \"crv\":\"P-256\",\n \"x\":\"MKBCTNIcKUSDii11ySs3526iDZ8AiTo7Tu6KPAqv7D4\",\n \"y\":\"4Etl6SRW2YiLUrN5vfvVHuhp7x8PxltmWWlbbM4IFyM\",\n \"d\":\"870MB6gfuTJ4HtUnUvYMyJpr5eUZNP4Bk43bVdj3eAE\",\n \"use\":\"enc\",\n \"kid\":\"1\"},\n\n {\"kty\":\"RSA\",\n \"n\":\"0vx7agoebGcQSuuPiLJXZptN9nndrQmbXEps2aiAFbWhM78LhWx4cbbfAAtVT86zwu1RK7aPFFxuhDR1L6tSoc_BJECPebWKRXjBZCiFV4n3oknjhMstn64tZ_2W-5JsGY4Hc5n9yBXArwl93lqt7_RN5w6Cf0h4QyQ5v-65YGjQR0_FDW2QvzqY368QQMicAtaSqzs8KJZgnYb9c7d0zgdAZHzu6qMQvRL5hajrn1n91CbOpbISD08qNLyrdkt-bFTWhAI4vMQFh6WeZu0fM4lFd2NcRwr3XPksINHaQ-G_xBniIqbw0Ls1jF44-csFCur-kEgU8awapJzKnqDKgw\",\n \"e\":\"AQAB\",\n \"d\":\"X4cTteJY_gn4FYPsXB8rdXix5vwsg1FLN5E3EaG6RJoVH-HLLKD9M7dx5oo7GURknchnrRweUkC7hT5fJLM0WbFAKNLWY2vv7B6NqXSzUvxT0_YSfqijwp3RTzlBaCxWp4doFk5N2o8Gy_nHNKroADIkJ46pRUohsXywbReAdYaMwFs9tv8d_cPVY3i07a3t8MN6TNwm0dSawm9v47UiCl3Sk5ZiG7xojPLu4sbg1U2jx4IBTNBznbJSzFHK66jT8bgkuqsk0GjskDJk19Z4qwjwbsnn4j2WBii3RL-Us2lGVkY8fkFzme1z0HbIkfz0Y6mqnOYtqc0X4jfcKoAC8Q\",\n \"p\":\"83i-7IvMGXoMXCskv73TKr8637FiO7Z27zv8oj6pbWUQyLPQBQxtPVnwD20R-60eTDmD2ujnMt5PoqMrm8RfmNhVWDtjjMmCMjOpSXicFHj7XOuVIYQyqVWlWEh6dN36GVZYk93N8Bc9vY41xy8B9RzzOGVQzXvNEvn7O0nVbfs\",\n \"q\":\"3dfOR9cuYq-0S-mkFLzgItgMEfFzB2q3hWehMuG0oCuqnb3vobLyumqjVZQO1dIrdwgTnCdpYzBcOfW5r370AFXjiWft_NGEiovonizhKpo9VVS78TzFgxkIdrecRezsZ-1kYd_s1qDbxtkDEgfAITAG9LUnADun4vIcb6yelxk\",\n \"dp\":\"G4sPXkc6Ya9y8oJW9_ILj4xuppu0lzi_H7VTkS8xj5SdX3coE0oimYwxIi2emTAue0UOa5dpgFGyBJ4c8tQ2VF402XRugKDTP8akYhFo5tAA77Qe_NmtuYZc3C3m3I24G2GvR5sSDxUyAN2zq8Lfn9EUms6rY3Ob8YeiKkTiBj0\",\n \"dq\":\"s9lAH9fggBsoFR8Oac2R_E2gw282rT2kGOAhvIllETE1efrA6huUUvMfBcMpn8lqeW6vzznYY5SSQF7pMdC_agI3nG8Ibp1BUb0JUiraRNqUfLhcQb_d9GF4Dh7e74WbRsobRonujTYN1xCaP6TO61jvWrX-L18txXw494Q_cgk\",\n \"qi\":\"GyM_p6JrXySiz1toFgKbWV-JdI3jQ4ypu9rbMWx3rQJBfmt0FoYzgUIZEVFEcOqwemRN81zoDAaa-Bk0KWNGDjJHZDdDmFhW3AN7lI-puxk_mHZGJ11rxyR8O55XLSe3SPmRfKwZI6yU24ZxvQKFYItdldUKGzO6Ia6zTKhAVRU\",\n \"alg\":\"RS256\",\n \"kid\":\"2011-04-29\"}\n ]\n }`\n\n\tjwt, err := Unmarshal([]byte(jsonKey))\n\tif err != nil {\n\t\tt.Fatal(\"Unmarshal: \", err)\n\t} else if len(jwt.Keys) != 2 {\n\t\tt.Fatalf(\"Expected 2 keys, got %d\", len(jwt.Keys))\n\t}\n\n\tkeys := make([]crypto.PrivateKey, len(jwt.Keys))\n\tfor ii, jwt := range jwt.Keys {\n\t\tkeys[ii], err = jwt.DecodePrivateKey()\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Failed to decode key %d: %v\", ii, err)\n\t\t}\n\t}\n\n\tif key0, ok := keys[0].(*ecdsa.PrivateKey); !ok {\n\t\tt.Fatalf(\"Expected ECDSA key[0], got %T\", keys[0])\n\t} else if key1, ok := keys[1].(*rsa.PrivateKey); !ok {\n\t\tt.Fatalf(\"Expected RSA key[1], got %T\", keys[1])\n\t} else if key0.Curve != elliptic.P256() {\n\t\tt.Fatalf(\"Key[0] is not using P-256 curve\")\n\t} else if !bytes.Equal(key0.X.Bytes(), []byte{0x30, 0xa0, 0x42, 0x4c, 0xd2,\n\t\t0x1c, 0x29, 0x44, 0x83, 0x8a, 0x2d, 0x75, 0xc9, 0x2b, 0x37, 0xe7, 0x6e, 0xa2,\n\t\t0xd, 0x9f, 0x0, 0x89, 0x3a, 0x3b, 0x4e, 0xee, 0x8a, 0x3c, 0xa, 0xaf, 0xec, 0x3e}) {\n\t\tt.Fatalf(\"Bad key[0].X, got %v\", key0.X.Bytes())\n\t} else if !bytes.Equal(key0.Y.Bytes(), []byte{0xe0, 0x4b, 0x65, 0xe9, 0x24,\n\t\t0x56, 0xd9, 0x88, 0x8b, 0x52, 0xb3, 0x79, 0xbd, 0xfb, 0xd5, 0x1e, 0xe8,\n\t\t0x69, 0xef, 0x1f, 0xf, 0xc6, 0x5b, 0x66, 0x59, 0x69, 0x5b, 0x6c, 0xce,\n\t\t0x8, 0x17, 0x23}) {\n\t\tt.Fatalf(\"Bad key[0].Y, got %v\", key0.Y.Bytes())\n\t} else if !bytes.Equal(key0.D.Bytes(), []byte{0xf3, 0xbd, 0xc, 0x7, 0xa8,\n\t\t0x1f, 0xb9, 0x32, 0x78, 0x1e, 0xd5, 0x27, 0x52, 0xf6, 0xc, 0xc8, 0x9a,\n\t\t0x6b, 0xe5, 0xe5, 0x19, 0x34, 0xfe, 0x1, 0x93, 0x8d, 0xdb, 0x55, 0xd8,\n\t\t0xf7, 0x78, 0x1}) {\n\t\tt.Fatalf(\"Bad key[0].D, got %v\", key0.D.Bytes())\n\t} else if key1.E != 0x10001 {\n\t\tt.Fatalf(\"Bad key[1].E: %d\", key1.E)\n\t} else if !bytes.Equal(key1.N.Bytes(), []byte{0xd2, 0xfc, 0x7b, 0x6a, 0xa, 0x1e,\n\t\t0x6c, 0x67, 0x10, 0x4a, 0xeb, 0x8f, 0x88, 0xb2, 0x57, 0x66, 0x9b, 0x4d, 0xf6,\n\t\t0x79, 0xdd, 0xad, 0x9, 0x9b, 0x5c, 0x4a, 0x6c, 0xd9, 0xa8, 0x80, 0x15, 0xb5,\n\t\t0xa1, 0x33, 0xbf, 0xb, 0x85, 0x6c, 0x78, 0x71, 0xb6, 0xdf, 0x0, 0xb, 0x55,\n\t\t0x4f, 0xce, 0xb3, 0xc2, 0xed, 0x51, 0x2b, 0xb6, 0x8f, 0x14, 0x5c, 0x6e, 0x84,\n\t\t0x34, 0x75, 0x2f, 0xab, 0x52, 0xa1, 0xcf, 0xc1, 0x24, 0x40, 0x8f, 0x79, 0xb5,\n\t\t0x8a, 0x45, 0x78, 0xc1, 0x64, 0x28, 0x85, 0x57, 0x89, 0xf7, 0xa2, 0x49, 0xe3,\n\t\t0x84, 0xcb, 0x2d, 0x9f, 0xae, 0x2d, 0x67, 0xfd, 0x96, 0xfb, 0x92, 0x6c, 0x19,\n\t\t0x8e, 0x7, 0x73, 0x99, 0xfd, 0xc8, 0x15, 0xc0, 0xaf, 0x9, 0x7d, 0xde, 0x5a,\n\t\t0xad, 0xef, 0xf4, 0x4d, 0xe7, 0xe, 0x82, 0x7f, 0x48, 0x78, 0x43, 0x24, 0x39,\n\t\t0xbf, 0xee, 0xb9, 0x60, 0x68, 0xd0, 0x47, 0x4f, 0xc5, 0xd, 0x6d, 0x90, 0xbf,\n\t\t0x3a, 0x98, 0xdf, 0xaf, 0x10, 0x40, 0xc8, 0x9c, 0x2, 0xd6, 0x92, 0xab, 0x3b,\n\t\t0x3c, 0x28, 0x96, 0x60, 0x9d, 0x86, 0xfd, 0x73, 0xb7, 0x74, 0xce, 0x7, 0x40,\n\t\t0x64, 0x7c, 0xee, 0xea, 0xa3, 0x10, 0xbd, 0x12, 0xf9, 0x85, 0xa8, 0xeb, 0x9f,\n\t\t0x59, 0xfd, 0xd4, 0x26, 0xce, 0xa5, 0xb2, 0x12, 0xf, 0x4f, 0x2a, 0x34, 0xbc,\n\t\t0xab, 0x76, 0x4b, 0x7e, 0x6c, 0x54, 0xd6, 0x84, 0x2, 0x38, 0xbc, 0xc4, 0x5, 0x87,\n\t\t0xa5, 0x9e, 0x66, 0xed, 0x1f, 0x33, 0x89, 0x45, 0x77, 0x63, 0x5c, 0x47, 0xa,\n\t\t0xf7, 0x5c, 0xf9, 0x2c, 0x20, 0xd1, 0xda, 0x43, 0xe1, 0xbf, 0xc4, 0x19, 0xe2,\n\t\t0x22, 0xa6, 0xf0, 0xd0, 0xbb, 0x35, 0x8c, 0x5e, 0x38, 0xf9, 0xcb, 0x5, 0xa, 0xea,\n\t\t0xfe, 0x90, 0x48, 0x14, 0xf1, 0xac, 0x1a, 0xa4, 0x9c, 0xca, 0x9e, 0xa0, 0xca, 0x83}) {\n\t\tt.Fatalf(\"Bad key[1].N, got %v\", key1.N.Bytes())\n\t} else if !bytes.Equal(key1.D.Bytes(), []byte{0x5f, 0x87, 0x13, 0xb5, 0xe2, 0x58,\n\t\t0xfe, 0x9, 0xf8, 0x15, 0x83, 0xec, 0x5c, 0x1f, 0x2b, 0x75, 0x78, 0xb1, 0xe6,\n\t\t0xfc, 0x2c, 0x83, 0x51, 0x4b, 0x37, 0x91, 0x37, 0x11, 0xa1, 0xba, 0x44, 0x9a,\n\t\t0x15, 0x1f, 0xe1, 0xcb, 0x2c, 0xa0, 0xfd, 0x33, 0xb7, 0x71, 0xe6, 0x8a, 0x3b,\n\t\t0x19, 0x44, 0x64, 0x9d, 0xc8, 0x67, 0xad, 0x1c, 0x1e, 0x52, 0x40, 0xbb, 0x85,\n\t\t0x3e, 0x5f, 0x24, 0xb3, 0x34, 0x59, 0xb1, 0x40, 0x28, 0xd2, 0xd6, 0x63, 0x6b,\n\t\t0xef, 0xec, 0x1e, 0x8d, 0xa9, 0x74, 0xb3, 0x52, 0xfc, 0x53, 0xd3, 0xf6, 0x12,\n\t\t0x7e, 0xa8, 0xa3, 0xc2, 0x9d, 0xd1, 0x4f, 0x39, 0x41, 0x68, 0x2c, 0x56, 0xa7,\n\t\t0x87, 0x68, 0x16, 0x4e, 0x4d, 0xda, 0x8f, 0x6, 0xcb, 0xf9, 0xc7, 0x34, 0xaa,\n\t\t0xe8, 0x0, 0x32, 0x24, 0x27, 0x8e, 0xa9, 0x45, 0x4a, 0x21, 0xb1, 0x7c, 0xb0,\n\t\t0x6d, 0x17, 0x80, 0x75, 0x86, 0x8c, 0xc0, 0x5b, 0x3d, 0xb6, 0xff, 0x1d, 0xfd,\n\t\t0xc3, 0xd5, 0x63, 0x78, 0xb4, 0xed, 0xad, 0xed, 0xf0, 0xc3, 0x7a, 0x4c, 0xdc,\n\t\t0x26, 0xd1, 0xd4, 0x9a, 0xc2, 0x6f, 0x6f, 0xe3, 0xb5, 0x22, 0xa, 0x5d, 0xd2,\n\t\t0x93, 0x96, 0x62, 0x1b, 0xbc, 0x68, 0x8c, 0xf2, 0xee, 0xe2, 0xc6, 0xe0, 0xd5,\n\t\t0x4d, 0xa3, 0xc7, 0x82, 0x1, 0x4c, 0xd0, 0x73, 0x9d, 0xb2, 0x52, 0xcc, 0x51,\n\t\t0xca, 0xeb, 0xa8, 0xd3, 0xf1, 0xb8, 0x24, 0xba, 0xab, 0x24, 0xd0, 0x68, 0xec,\n\t\t0x90, 0x32, 0x64, 0xd7, 0xd6, 0x78, 0xab, 0x8, 0xf0, 0x6e, 0xc9, 0xe7, 0xe2,\n\t\t0x3d, 0x96, 0x6, 0x28, 0xb7, 0x44, 0xbf, 0x94, 0xb3, 0x69, 0x46, 0x56, 0x46,\n\t\t0x3c, 0x7e, 0x41, 0x73, 0x99, 0xed, 0x73, 0xd0, 0x76, 0xc8, 0x91, 0xfc, 0xf4,\n\t\t0x63, 0xa9, 0xaa, 0x9c, 0xe6, 0x2d, 0xa9, 0xcd, 0x17, 0xe2, 0x37, 0xdc, 0x2a,\n\t\t0x80, 0x2, 0xf1}) {\n\t\tt.Fatalf(\"Bad key[1].D, got %v\", key1.D.Bytes())\n\t}\n}", "func (a *Account) GetPrivateKey() crypto.PrivateKey { return a.key }", "func (o SslCertificateSelfManagedSslCertificatePtrOutput) PrivateKey() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *SslCertificateSelfManagedSslCertificate) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.PrivateKey\n\t}).(pulumi.StringPtrOutput)\n}", "func PrivateKeyFile(usage Usage, version scrypto.KeyVersion) string {\n\treturn fmt.Sprintf(\"%s-v%d.key\", usage, version)\n}", "func TestGenPrivateKey(t *testing.T) {\n\t// test that calling by default generates an RSA private key\n\ttpl := `{{genPrivateKey \"\"}}`\n\tout, err := runRaw(tpl, nil)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tif !strings.Contains(out, \"RSA PRIVATE KEY\") {\n\t\tt.Error(\"Expected RSA PRIVATE KEY\")\n\t}\n\t// test all acceptable arguments\n\ttpl = `{{genPrivateKey \"rsa\"}}`\n\tout, err = runRaw(tpl, nil)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tif !strings.Contains(out, \"RSA PRIVATE KEY\") {\n\t\tt.Error(\"Expected RSA PRIVATE KEY\")\n\t}\n\ttpl = `{{genPrivateKey \"dsa\"}}`\n\tout, err = runRaw(tpl, nil)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tif !strings.Contains(out, \"DSA PRIVATE KEY\") {\n\t\tt.Error(\"Expected DSA PRIVATE KEY\")\n\t}\n\ttpl = `{{genPrivateKey \"ecdsa\"}}`\n\tout, err = runRaw(tpl, nil)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tif !strings.Contains(out, \"EC PRIVATE KEY\") {\n\t\tt.Error(\"Expected EC PRIVATE KEY\")\n\t}\n\ttpl = `{{genPrivateKey \"ed25519\"}}`\n\tout, err = runRaw(tpl, nil)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tif !strings.Contains(out, \"PRIVATE KEY\") {\n\t\tt.Error(\"Expected PRIVATE KEY\")\n\t}\n\t// test bad\n\ttpl = `{{genPrivateKey \"bad\"}}`\n\tout, err = runRaw(tpl, nil)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tif out != \"Unknown type bad\" {\n\t\tt.Error(\"Expected type 'bad' to be an unknown crypto algorithm\")\n\t}\n\t// ensure that we can base64 encode the string\n\ttpl = `{{genPrivateKey \"rsa\" | b64enc}}`\n\t_, err = runRaw(tpl, nil)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n}", "func GeneratePrivateKey() (privateKey PrivateKey, err error) {\n\t_, privateKey, err = GenerateKey()\n\n\treturn\n}", "func (e *Domain) Private() *PrivateKey {\n\tif e.ClearPrivateKey == nil {\n\t\te.decrypt_privatekey()\n\t}\n\treturn e.ClearPrivateKey\n}", "func (c CryptoServiceTester) TestGetPrivateKeyPasswordInvalid(t *testing.T) {\n\ttempBaseDir, err := ioutil.TempDir(\"\", \"cs-test-\")\n\trequire.NoError(t, err, \"failed to create a temporary directory: %s\", err)\n\tdefer os.RemoveAll(tempBaseDir)\n\n\t// Do not use c.cryptoServiceFactory(), we need a KeyFileStore.\n\tretriever := passphrase.ConstantRetriever(\"password\")\n\tstore, err := trustmanager.NewKeyFileStore(tempBaseDir, retriever)\n\trequire.NoError(t, err)\n\tcryptoService := NewCryptoService(store)\n\tpubKey, err := cryptoService.Create(c.role, c.gun, c.keyAlgo)\n\trequire.NoError(t, err, \"error generating key: %s\", err)\n\n\t// cryptoService's FileKeyStore caches the unlocked private key, so to test\n\t// private key unlocking we need a new instance.\n\tstore, err = trustmanager.NewKeyFileStore(tempBaseDir, giveUpPassphraseRetriever)\n\trequire.NoError(t, err)\n\tcryptoService = NewCryptoService(store)\n\n\t_, _, err = cryptoService.GetPrivateKey(pubKey.ID())\n\trequire.EqualError(t, err, trustmanager.ErrPasswordInvalid{}.Error())\n}", "func parsePrivateKey(der []byte) (crypto.PrivateKey, error) {\n if key, err := x509.ParsePKCS1PrivateKey(der); err == nil {\n return key, nil\n }\n if key, err := x509.ParsePKCS8PrivateKey(der); err == nil {\n switch key := key.(type) {\n case *rsa.PrivateKey, *ecdsa.PrivateKey:\n return key, nil\n default:\n return nil, errors.New(\"crypto/tls: found unknown private key type in PKCS#8 wrapping\")\n }\n }\n if key, err := x509.ParseECPrivateKey(der); err == nil {\n return key, nil\n }\n\n return nil, errors.New(\"crypto/tls: failed to parse private key\")\n}", "func (e *EtcdCert) PrivateKeyPath() string { return path.Join(e.BaseDir, etcdKeyFileName) }", "func ExportPrivateKey(key *rsa.PrivateKey) []byte {\n\tkeyBytes := x509.MarshalPKCS1PrivateKey(key)\n\treturn pem.EncodeToMemory(\n\t\t&pem.Block{\n\t\t\tType: \"RSA PRIVATE KEY\",\n\t\t\tBytes: keyBytes,\n\t\t},\n\t)\n}", "func GeneratePrivateKey() *PrivateKey {\n\tpriv := new(PrivateKey)\n\tseckey := NewSeckey()\n\tpriv.seckey = seckey\n\treturn priv\n}", "func (m *MockClient) PrivateKey() core.Key {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"PrivateKey\")\n\tret0, _ := ret[0].(core.Key)\n\treturn ret0\n}", "func (o *InlineResponse200115) GetPrivateOk() (*string, bool) {\n\tif o == nil || o.Private == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Private, true\n}", "func (c CertificateKey) Private() string {\n\treturn c.private\n}", "func BitcoinPrivateKey() string {\n\treturn \"5\" + Password(true, true, true, false, false, 50)\n}", "func EvalPrivateKey(s sexprs.Sexp) (k PrivateKey, err error) {\n\tl, ok := s.(sexprs.List)\n\tif !ok {\n\t\treturn k, fmt.Errorf(\"Key S-expression must be a list\")\n\t}\n\tif !privateKeyAtom.Equal(l[0]) {\n\t\treturn k, fmt.Errorf(\"Key S-expression must start with 'private-key'\")\n\t}\n\tif len(l) != 2 {\n\t\treturn k, fmt.Errorf(\"Key S-expression must have two elements\")\n\t}\n\treturn evalECDSAPrivateKey(l[1])\n\tpanic(\"Can't reach here\")\n}", "func encodePrivateKey(private *rsa.PrivateKey) []byte {\n\treturn pem.EncodeToMemory(&pem.Block{\n\t\tBytes: x509.MarshalPKCS1PrivateKey(private),\n\t\tHeaders: nil,\n\t\tType: \"RSA PRIVATE KEY\",\n\t})\n}", "func (d *DocsCrypto) ExportPrivate(out io.Writer) error {\n\td.Info(\"Exporting private key\")\n\tif err := pem.Encode(out, &pem.Block{\n\t\tType: \"PRIVATE KEY\",\n\t\tBytes: x509.MarshalPKCS1PrivateKey(d.GetPrivate()),\n\t}); err != nil {\n\t\td.Error(err)\n\t\treturn errExportPrivateKey\n\t}\n\treturn nil\n}", "func PrivateKeyPublic(priv *rsa.PrivateKey,) crypto.PublicKey", "func (o *InlineResponse20049Post) GetPrivateOk() (*string, bool) {\n\tif o == nil || o.Private == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Private, true\n}", "func (o *LinkPublicIpRequest) GetPrivateIpOk() (*string, bool) {\n\tif o == nil || o.PrivateIp == nil {\n\t\treturn nil, false\n\t}\n\treturn o.PrivateIp, true\n}", "func (mr *MockapprunnerClientMockRecorder) PrivateURL(vicARN interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"PrivateURL\", reflect.TypeOf((*MockapprunnerClient)(nil).PrivateURL), vicARN)\n}", "func (p PrivateKey) Equal(x crypto.PrivateKey) bool {\n\txx, ok := x.(PrivateKey)\n\tif !ok {\n\t\treturn false\n\t}\n\treturn bytes.Equal(p, xx)\n}", "func MarshalPrivateKey(key crypto.PrivateKey, comment string) (*pem.Block, error) {\n\treturn marshalOpenSSHPrivateKey(key, comment, unencryptedOpenSSHMarshaler)\n}", "func PrivateKey(p *big.Int) *big.Int {\n\t// handle range requirement and generate random number within that range\n\tnum := big.NewInt(0)\n\tnum = num.Add(p, big.NewInt(-2))\n\trandNum, _ := rand.Int(rand.Reader, num)\n\n\tresult := randNum.Add(randNum, big.NewInt(2))\n\treturn result\n}", "func parsePrivateKey(der []byte) (crypto.PrivateKey, error) {\n\tif key, err := x509.ParsePKCS1PrivateKey(der); err == nil {\n\t\treturn key, nil\n\t}\n\tif key, err := x509.ParsePKCS8PrivateKey(der); err == nil {\n\t\tswitch key := key.(type) {\n\t\tcase *rsa.PrivateKey, *ecdsa.PrivateKey:\n\t\t\treturn key, nil\n\t\tdefault:\n\t\t\treturn nil, errors.New(\"crypto/tls: found unknown private key type in PKCS#8 wrapping\")\n\t\t}\n\t}\n\tif key, err := x509.ParseECPrivateKey(der); err == nil {\n\t\treturn key, nil\n\t}\n\n\treturn nil, errors.New(\"crypto/tls: failed to parse private key\")\n}", "func PrivateKeySign(priv *rsa.PrivateKey, rand io.Reader, digest []byte, opts crypto.SignerOpts) ([]byte, error)", "func (cfg *Config) PrivateKey() hotstuff.PrivateKey {\n\treturn cfg.privKey\n}", "func (k *PrivateKey) Equal(x crypto.PrivateKey) bool {\n\txx, ok := x.(*PrivateKey)\n\tif !ok {\n\t\treturn false\n\t}\n\treturn k.curve == xx.curve &&\n\t\tsubtle.ConstantTimeCompare(k.privateKey, xx.privateKey) == 1\n}", "func ValidUnencryptedPrivateKey(file string) error {\n\t// Check private key before use it\n\tfi, err := os.Stat(file)\n\tif err != nil {\n\t\t// Abort if key not accessible\n\t\treturn err\n\t}\n\n\tbuffer, err := ioutil.ReadFile(file)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tisEncrypted, err := isEncrypted(buffer)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Parse SSH key error\")\n\t}\n\n\tif isEncrypted {\n\t\treturn fmt.Errorf(\"Encrypted SSH key is not permitted\")\n\t}\n\n\t_, err = ssh.ParsePrivateKey(buffer)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Parse SSH key error: %v\", err)\n\t}\n\n\tif runtime.GOOS != \"windows\" {\n\t\tmode := fi.Mode()\n\n\t\t// Private key file should have strict permissions\n\t\tperm := mode.Perm()\n\t\tif perm&0400 == 0 {\n\t\t\treturn fmt.Errorf(\"'%s' is not readable\", file)\n\t\t}\n\t\tif perm&0077 != 0 {\n\t\t\treturn fmt.Errorf(\"permissions %#o for '%s' are too open. Permissions should be set to 0600.\", perm, file)\n\t\t}\n\t}\n\n\treturn nil\n}", "func generatePrivateKey(bitSize int) (*rsa.PrivateKey, error) {\n\t// Private Key generation\n\tprivateKey, err := rsa.GenerateKey(rand.Reader, bitSize)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Validate Private Key\n\terr = privateKey.Validate()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn privateKey, nil\n}", "func GeneratePrivateKey(algo ...Algorithm) (PrivateKey, error) {\n\tif len(algo) != 0 {\n\t\tswitch algo[0] {\n\t\tcase KeyAlgoSecp256k1:\n\t\t\treturn GenerateSECP256K1PrivateKey()\n\t\tdefault:\n\t\t\treturn GenerateSM2PrivateKey()\n\t\t}\n\t}\n\treturn GenerateSM2PrivateKey()\n}", "func (o *SecurityCertificateCollectionGetParams) SetPrivateKey(privateKey *string) {\n\to.PrivateKey = privateKey\n}", "func (o *PipelineSshKeyPairAllOf) GetPrivateKey() string {\n\tif o == nil || o.PrivateKey == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.PrivateKey\n}", "func (o *FileversionFileversion) GetPrivateOk() (*bool, bool) {\n\tif o == nil || o.Private == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Private, true\n}", "func parsePrivateKey(der []byte) (crypto.Signer, error) {\n\tif key, err := x509.ParsePKCS1PrivateKey(der); err == nil {\n\t\treturn key, nil\n\t}\n\tif key, err := x509.ParsePKCS8PrivateKey(der); err == nil {\n\t\tswitch key := key.(type) {\n\t\tcase *rsa.PrivateKey:\n\t\t\treturn key, nil\n\t\tcase *ecdsa.PrivateKey:\n\t\t\treturn key, nil\n\t\tdefault:\n\t\t\treturn nil, errors.New(\"autocertLego: unknown private key type in PKCS#8 wrapping\")\n\t\t}\n\t}\n\tif key, err := x509.ParseECPrivateKey(der); err == nil {\n\t\treturn key, nil\n\t}\n\n\treturn nil, errors.New(\"autocertLego: failed to parse private key\")\n}", "func ParsePKCS8PrivateKey(der []byte) (key interface{}, err error) {\n\tvar privKey pkcs8\n\tif _, err := asn1.Unmarshal(der, &privKey); err != nil {\n\t\treturn nil, err\n\t}\n\tswitch {\n\tcase privKey.Algo.Algorithm.Equal(oidPublicKeyRSA):\n\t\tkey, err = ParsePKCS1PrivateKey(privKey.PrivateKey)\n\t\tif err != nil {\n\t\t\treturn nil, errors.New(\"x509: failed to parse RSA private key embedded in PKCS#8: \" + err.Error())\n\t\t}\n\t\treturn key, nil\n\n\tcase privKey.Algo.Algorithm.Equal(oidPublicKeyECDSA):\n\t\tbytes := privKey.Algo.Parameters.FullBytes\n\t\tnamedCurveOID := new(asn1.ObjectIdentifier)\n\t\tif _, err := asn1.Unmarshal(bytes, namedCurveOID); err != nil {\n\t\t\tnamedCurveOID = nil\n\t\t}\n\t\tif namedCurveOID.Equal(oidNamedCurveSm2) {\n\t\t\tkey, err = parseSM2PrivateKey(namedCurveOID, privKey.PrivateKey)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, errors.New(\"x509: failed to parse sm2 private key embedded in PKCS#8: \" + err.Error())\n\t\t\t}\n\t\t} else {\n\t\t\tkey, err = parseECPrivateKey(namedCurveOID, privKey.PrivateKey)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, errors.New(\"x509: failed to parse EC private key embedded in PKCS#8: \" + err.Error())\n\t\t\t}\n\t\t}\n\t\treturn key, nil\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"x509: PKCS#8 wrapping contained private key with unknown algorithm: %v\", privKey.Algo.Algorithm)\n\t}\n}", "func (e *EtcdClientCert) PrivateKeyPath() string { return path.Join(e.BaseDir, etcdClientKeyFileName) }", "func PrivateIndicator(psi []byte) bool {\n\treturn psi[2+PointerField(psi)]&0x40 != 0\n}", "func parsePrivateKey(der []byte) (crypto.PrivateKey, error) {\n\tif key, err := gmx509.ParsePKCS8SM2PrivateKey(der); err == nil {\n\t\treturn key, nil\n\t}\n\n\tif key, err := gmx509.ParseSM2PrivateKey(der); err == nil {\n\t\treturn key, nil\n\t}\n\n\treturn nil, errors.New(\"tls: failed to parse private key\")\n}", "func (mr *MockPrivateNetworkDetectorMockRecorder) IsPrivate(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"IsPrivate\", reflect.TypeOf((*MockPrivateNetworkDetector)(nil).IsPrivate), arg0)\n}", "func (grc *GitRemoteConfiguration) SetPrivateKey(privateKey *string) {\n\tgrc.PrivateKey = privateKey\n}", "func (o *PublicIp) GetPrivateIpOk() (string, bool) {\n\tif o == nil || o.PrivateIp == nil {\n\t\tvar ret string\n\t\treturn ret, false\n\t}\n\treturn *o.PrivateIp, true\n}", "func PrivateKey(pemData []byte) func(*Server) error {\n\treturn func(s *Server) error {\n\t\tprivKey, err := ssh.ParseRawPrivateKey(pemData)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\thostKey, err := ssh.NewSignerFromKey(privKey)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\ts.SSH.AddHostKey(hostKey)\n\n\t\ts.SSH.PublicKeyCallback = func(c ssh.ConnMetadata, key ssh.PublicKey) (*ssh.Permissions, error) {\n\t\t\thost, _, _ := net.SplitHostPort(c.RemoteAddr().String())\n\t\t\tlog.Printf(\"Authenticating user %s from IP %s\", c.User(), host)\n\t\t\tif c.User() == s.Uid {\n\t\t\t\tname, err := getUserFromKey(string(ssh.MarshalAuthorizedKey(key)))\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Printf(\"Auth failed from IP %s with error %v\", host, err)\n\t\t\t\t\treturn nil, errors.New(\"public key rejected\")\n\t\t\t\t}\n\t\t\t\treturn &ssh.Permissions{Extensions: map[string]string{\"key-id\": name, \"ip\": host}}, nil\n\t\t\t} else {\n\t\t\t\treturn nil, errors.New(\"Invalid user\")\n\t\t\t}\n\t\t}\n\n\t\treturn nil\n\t}\n}", "func (kt KeyType) PrivateKey() string {\n\treturn kt.KeyBaseName\n}", "func (o *PublicIp) GetPrivateIpOk() (*string, bool) {\n\tif o == nil || o.PrivateIp == nil {\n\t\treturn nil, false\n\t}\n\treturn o.PrivateIp, true\n}", "func IsPkcs11PrivateKey(yamlstr []byte) bool {\n\t_, err := ParsePkcs11KeyFile(yamlstr)\n\treturn err == nil\n}", "func (c *Crypto) PrivateKeyPath() string {\n\treturn c.privateKeyPath\n}", "func (o *InlineResponse20034Milestone) GetPrivateOk() (*bool, bool) {\n\tif o == nil || o.Private == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Private, true\n}", "func (p *PrivateKey) PrivateKey() *ecdsa.PrivateKey {\n\treturn p.privateKey\n}", "func (sc Credential) parsePrivateKey(privateKey string) (ssh.AuthMethod, error) {\n\tsigner, err := ssh.ParsePrivateKey([]byte(privateKey))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"parse private key failed: %v\", err)\n\t}\n\n\treturn ssh.PublicKeys(signer), nil\n}", "func (dtk *DcmTagKey) IsPrivateReservation() bool {\n\treturn dtk.IsPrivate() && dtk.element >= 0x10 && dtk.element <= 0xFF\n}", "func PrivateKey(keyFile string) (gossh.AuthMethod, error) {\n\tsigner, err := KeyFile(keyFile)\n\tif err != nil {\n\t\tdlog.Common.Debug(keyFile, err)\n\t\treturn nil, err\n\t}\n\treturn gossh.AuthMethod(signer), nil\n}", "func VerifyPrivKey(ctx *Context, seckey []byte) (int, error) {\n\tif len(seckey) < 1 {\n\t\treturn 0, errors.New(PrivateKeyNullError)\n\t}\n\tresult := int(C.secp256k1_ec_seckey_verify(ctx.ctx, cBuf(seckey[:])))\n\tif result != 1 {\n\t\treturn result, errors.New(PrivateKeyInvalidError)\n\t}\n\n\treturn result, nil\n}", "func GeneratePrivateKey(bitSize int) (*rsa.PrivateKey, error) {\n\tprivateKey, err := rsa.GenerateKey(rand.Reader, bitSize)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = privateKey.Validate()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn privateKey, nil\n}", "func (d *identityManager) PrivateKey() []byte {\n\treturn d.key.PrivateKey\n}", "func GeneratePrivateKey(algorithm string) (k *PrivateKey, err error) {\n\tswitch algorithm {\n\tcase \"(ecdsa-sha2 (curve p256))\":\n\t\treturn GenerateP256Key()\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"Unknown algorithm '%s'\", algorithm)\n\t}\n}", "func TestPrivateCalico(t *testing.T) {\n\tnewIntegrationTest(\"privatecalico.example.com\", \"privatecalico\").\n\t\twithPrivate().\n\t\twithDefaultAddons24().\n\t\twithAddons(calicoAddon).\n\t\trunTestTerraformAWS(t)\n}", "func GeneratePrivateKey() []byte {\n\tvar privateKeyBytes32 [32]byte\n\tsecp256k1.Start()\nLoop:\n\tfor {\n\t\tfor i := 0; i < size; i++ {\n\t\t\t//This is not \"cryptographically random\"\n\t\t\tprivateKeyBytes32[i] = byte(util.RandInt(0, math.MaxUint8))\n\t\t}\n\t\tok := secp256k1.Seckey_verify(privateKeyBytes32)\n\t\tif ok {\n\t\t\tbreak Loop\n\t\t}\n\t}\n\tsecp256k1.Stop()\n\treturn privateKeyBytes32[:]\n}", "func NewPrivateKey(name ndn.Name, key *rsa.PrivateKey) (keychain.PrivateKeyKeyLocatorChanger, error) {\n\tif !keychain.IsKeyName(name) {\n\t\treturn nil, keychain.ErrKeyName\n\t}\n\tvar pvt privateKey\n\tpvt.name = name\n\tpvt.key = key\n\treturn &pvt, nil\n}", "func (o *InlineResponse200115) HasPrivate() bool {\n\tif o != nil && o.Private != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (mr *MockisCryptoAsymApiReqSetupPrivateKeyEx_KeyMockRecorder) isCryptoAsymApiReqSetupPrivateKeyEx_Key() *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"isCryptoAsymApiReqSetupPrivateKeyEx_Key\", reflect.TypeOf((*MockisCryptoAsymApiReqSetupPrivateKeyEx_Key)(nil).isCryptoAsymApiReqSetupPrivateKeyEx_Key))\n}", "func (x *Ed25519Credentials) PrivateKey() PrivateKey {\n\n\treturn PrivateKey{\n\t\tAlgorithm: AlgorithmEd25519,\n\t\tPrivate: base64.URLEncoding.EncodeToString(x.Private[:]),\n\t}\n\n}", "func newPrivateKey() (crypto.Signer, error) {\n\treturn ecdsa.GenerateKey(ellipticCurve, crand.Reader)\n}", "func GeneratePrivateKey() (string, error) {\n\t// Private Key generation\n\tprivateKey, err := rsa.GenerateKey(rand.Reader, 4096)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn fmt.Sprintf(\"%x\", privateKey.D.Bytes()), nil\n}", "func PrivateKey(p *big.Int) *big.Int {\n\tkey := new(big.Int)\n\tlimit := new(big.Int).Sub(p, big.NewInt(2))\n\tseed := rand.New(rand.NewSource(time.Now().UnixNano()))\n\treturn key.Rand(seed, limit).Add(key, big.NewInt(2))\n}", "func (c *Client) Private(id *key.Identity) ([]byte, error) {\n\tephScalar := key.KeyGroup.Scalar()\n\tephPoint := key.KeyGroup.Point().Mul(ephScalar, nil)\n\tephBuff, err := ephPoint.MarshalBinary()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tobj, err := ecies.Encrypt(key.KeyGroup, id.Key, ephBuff, EciesHash)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresp, err := c.client.PrivateRand(context.TODO(), id, &drand.PrivateRandRequest{Request: obj})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn ecies.Decrypt(key.KeyGroup, ephScalar, resp.GetResponse(), EciesHash)\n}", "func (c CryptoServiceTester) TestSignNoMatchingKeys(t *testing.T) {\n\tcryptoService := c.cryptoServiceFactory()\n\n\tprivKey, err := utils.GenerateECDSAKey(rand.Reader)\n\trequire.NoError(t, err, c.errorMsg(\"error creating key\"))\n\n\t// Test Sign\n\t_, _, err = cryptoService.GetPrivateKey(privKey.ID())\n\trequire.Error(t, err, c.errorMsg(\"Should not have found private key\"))\n}", "func PrivateKey(username string, path string, keyCallBack ssh.HostKeyCallback) (ssh.ClientConfig, error) {\n\tprivateKey, err := ioutil.ReadFile(path)\n\n\tif err != nil {\n\t\treturn ssh.ClientConfig{}, err\n\t}\n\n\tsigner, err := ssh.ParsePrivateKey(privateKey)\n\n\tif err != nil {\n\t\treturn ssh.ClientConfig{}, err\n\t}\n\n\treturn ssh.ClientConfig{\n\t\tUser: username,\n\t\tAuth: []ssh.AuthMethod{\n\t\t\tssh.PublicKeys(signer),\n\t\t},\n\t\tHostKeyCallback: keyCallBack,\n\t}, nil\n}", "func (o *InlineResponse20033Milestones) GetPrivateOk() (*bool, bool) {\n\tif o == nil || o.Private == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Private, true\n}", "func PrivateKeyPath(path string) GitOptions {\n\treturn func(o *options) error {\n\t\to.privateKeyPath = path\n\t\treturn nil\n\t}\n}", "func GeneratePrivateKey() (*rsa.PrivateKey, error) {\n\treturn rsa.GenerateKey(rand.Reader, RSA_BITS)\n}", "func (u *walletIdentity) PrivateKey() core.Key {\n\treturn u.privateKey\n}", "func ParsePrivateKey(derBlob []byte) (parsedPrivateKey interface{}, keyType string, err error) {\n // First check if it is an RSA key\n parsedPrivateKey, err = x509.ParsePKCS1PrivateKey(derBlob)\n // If we get an error, it might be an EC key or malformed\n if err != nil {\n parsedPrivateKey, err = x509.ParseECPrivateKey(derBlob)\n if err != nil {\n return nil, \"\", err // if we encounter an error then the key is malformed (or not EC/RSA)\n }\n // Because we have a return inside the if, this is essentially the else part\n // If ParseECPrivateKey was sucessfulthen it's an EC key\n keyType = \"EC\"\n return parsedPrivateKey, keyType, err // no naked returns\n }\n // If ParsePKCS1PrivateKey was successful then it's an RSA key\n keyType = \"RSA\"\n return parsedPrivateKey, keyType, err\n\n // I could do a bunch of if-else and do only one return in the end, but I think this is more readable\n}", "func PrivateKey(i int) *keys.PrivateKey {\n\twif := WIF(i)\n\tpriv, err := keys.NewPrivateKeyFromWIF(wif)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn priv\n}", "func generateBadPrivateKeyPEM(fileName string) (err error) {\n\tprivateKey, err := rsa.GenerateKey(rand.Reader, 2048)\n\tif err != nil {\n\t\treturn\n\t}\n\tblock := &pem.Block{\n\t\tType: \"RSA PRIVATE KEY\",\n\t\tBytes: x509.MarshalPKCS1PrivateKey(privateKey),\n\t}\n\tprivateKeyPem := pem.EncodeToMemory(block)\n\trand.Read(privateKeyPem[256:280])\n\terr = ioutil.WriteFile(fileName, privateKeyPem, 0600)\n\treturn\n}", "func loadPrivateKey(data []byte) (interface{}, error) {\n\tinput := data\n\n\tblock, _ := pem.Decode(data)\n\tif block != nil {\n\t\tinput = block.Bytes\n\t}\n\n\tvar priv interface{}\n\tpriv, err0 := x509.ParsePKCS1PrivateKey(input)\n\tif err0 == nil {\n\t\treturn priv, nil\n\t}\n\n\tpriv, err1 := x509.ParsePKCS8PrivateKey(input)\n\tif err1 == nil {\n\t\treturn priv, nil\n\t}\n\n\tpriv, err2 := x509.ParseECPrivateKey(input)\n\tif err2 == nil {\n\t\treturn priv, nil\n\t}\n\n\tjwk, err3 := loadJSONWebKey(input, false)\n\tif err3 == nil {\n\t\treturn jwk, nil\n\t}\n\n\treturn nil, errors.New(\"parse error, invalid private key\")\n}" ]
[ "0.74063396", "0.68982327", "0.6687545", "0.6668617", "0.66394156", "0.66042066", "0.64109045", "0.638909", "0.63769555", "0.63654226", "0.6331232", "0.63108945", "0.62955505", "0.6252219", "0.62332714", "0.62081003", "0.6194143", "0.61720526", "0.6162626", "0.615435", "0.6106912", "0.6082185", "0.6060096", "0.60243565", "0.60225546", "0.6019319", "0.60106575", "0.60028917", "0.59775865", "0.5976882", "0.59591585", "0.5956278", "0.59397644", "0.59376615", "0.59355694", "0.59212554", "0.59182316", "0.5911493", "0.5908458", "0.59029955", "0.5902306", "0.5899213", "0.58631855", "0.58623135", "0.5856833", "0.5852401", "0.58291155", "0.58238226", "0.58188146", "0.5815099", "0.5809223", "0.5794308", "0.5781084", "0.5778822", "0.5772396", "0.5770165", "0.5767622", "0.57620513", "0.575981", "0.5758252", "0.57578725", "0.575045", "0.574964", "0.57455385", "0.5741559", "0.57392246", "0.57344276", "0.57340366", "0.5725218", "0.5720856", "0.57112366", "0.5708488", "0.5703925", "0.56982327", "0.5680302", "0.56794786", "0.56763875", "0.5670087", "0.5664905", "0.5662157", "0.56618077", "0.5661026", "0.56563795", "0.56559265", "0.5647018", "0.56387275", "0.56345147", "0.56340253", "0.56291234", "0.5627926", "0.5625346", "0.56224155", "0.562175", "0.5621056", "0.5617049", "0.5616278", "0.5614861", "0.56016046", "0.5600104", "0.55974275" ]
0.70924914
1
PublicVersion mocks base method
func (m *MockClient) PublicVersion() msp.Identity { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "PublicVersion") ret0, _ := ret[0].(msp.Identity) return ret0 }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func TestVersion(t *testing.T) {\n\t//fmt.Println(\"EliteProvision [\" + Version() + \"]\")\n}", "func newVersionCheckerMock(version string, tags []string) *VersionChecker {\n\n\tfixedAppVersion := fixVersion(version)\n\n\treturn &VersionChecker{\n\t\tfixedAppVersion: fixedAppVersion,\n\t\tversionSource: &versionCheckerMock{\n\t\t\ttags: tags,\n\t\t\tfixVersionStrFunc: fixVersion,\n\t\t\ttagFilterFunc: versionFilterFunc(fixedAppVersion),\n\t\t},\n\t}\n}", "func TestGetVersions4A(t *testing.T) {\n}", "func (m *MockShootClients) Version() *version.Info {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Version\")\n\tret0, _ := ret[0].(*version.Info)\n\treturn ret0\n}", "func (m *MockRemotePeer) Version() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Version\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func (m *MockEventLogger) Version() uint64 {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Version\")\n\tret0, _ := ret[0].(uint64)\n\treturn ret0\n}", "func (_m *MockAggregate) incrementVersion() {\n\t_m.Called()\n}", "func (m *MockMachine) Version() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Version\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func (_m *MockAggregate) setVersion(_a0 int) {\n\t_m.Called(_a0)\n}", "func (m *MockManager) UpdateVersion() {\n\tm.ctrl.Call(m, \"UpdateVersion\")\n}", "func (m *MockFullNode) Version(arg0 context.Context) (types0.Version, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Version\", arg0)\n\tret0, _ := ret[0].(types0.Version)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func TestVersion(t *testing.T) {\n\t// Get Vault client\n\tvaultClientConfig := vault.DefaultConfig()\n\tvaultClientConfig.Address = vaultAddress\n\tv, err := vault.NewClient(vaultClientConfig)\n\tif err != nil {\n\t\tt.Fatalf(err.Error())\n\t}\n\tv.SetToken(\"root\")\n\tvl := v.Logical()\n\n\t// Get Pachyderm version from plugin\n\tsecret, err := vl.Read(\"/pachyderm/version\")\n\tif err != nil {\n\t\tt.Fatalf(err.Error())\n\t}\n\tif _, ok := secret.Data[\"client-version\"]; !ok {\n\t\tt.Fatalf(\"could not get client version from Pachyderm plugin\")\n\t}\n\tif _, ok := secret.Data[\"server-version\"]; !ok {\n\t\tt.Fatalf(\"could not get server version from Pachyderm plugin\")\n\t}\n\n\t// Test client-only endpoint\n\tsecret, err = vl.Read(\"/pachyderm/version/client-only\")\n\tif _, ok := secret.Data[\"client-version\"]; !ok {\n\t\tt.Fatalf(\"could not get client version from Pachyderm plugin (client-only)\")\n\t}\n\tif _, ok := secret.Data[\"server-version\"]; ok {\n\t\tt.Fatalf(\"got unexpected server version from Pachyderm plugin (client-only)\")\n\t}\n}", "func (m *MockqueueTaskInfo) GetVersion() int64 {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetVersion\")\n\tret0, _ := ret[0].(int64)\n\treturn ret0\n}", "func (m *MockqueueTask) GetVersion() int64 {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetVersion\")\n\tret0, _ := ret[0].(int64)\n\treturn ret0\n}", "func TestGetVersion(t *testing.T) {\n\tassert := assert.New(t)\n\n\tmockedTpmProvider := new(tpmprovider.MockedTpmProvider)\n\tmockedTpmProvider.On(\"Close\").Return(nil)\n\tmockedTpmProvider.On(\"NvIndexExists\", mock.Anything).Return(false, nil)\n\tmockedTpmProvider.On(\"NvRelease\", mock.Anything, mock.Anything).Return(nil)\n\tmockedTpmProvider.On(\"NvDefine\", mock.Anything, mock.Anything, mock.Anything).Return(nil)\n\tmockedTpmProvider.On(\"NvWrite\", mock.Anything, mock.Anything, mock.Anything).Return(nil)\n\n\tmockedTpmFactory := tpmprovider.MockedTpmFactory{TpmProvider: mockedTpmProvider}\n\n\ttrustAgentService, err := CreateTrustAgentService(CreateTestConfig(), mockedTpmFactory)\n\n\ttrustAgentService.router.HandleFunc(\"/version\", errorHandler(getVersion())).Methods(\"GET\")\n\n\t// test request\n\trequest, err := http.NewRequest(\"GET\", \"/version\", nil)\n\tassert.NoError(err)\n\n\trecorder := httptest.NewRecorder()\n\tresponse := recorder.Result()\n\ttrustAgentService.router.ServeHTTP(recorder, request)\n\tassert.Equal(http.StatusOK, response.StatusCode)\n\tfmt.Printf(\"Version: %s\\n\", recorder.Body.String())\n\tassert.NotEmpty(recorder.Body.String())\n}", "func TestVersion(t *testing.T) {\n\tvers := Version()\n\tif len(vers) == 0 {\n\t\tt.Error(\"version string is not present\")\n\t}\n}", "func TestDaemon_Version(t *testing.T) {\n\td, start, clean, _, _, _ := mockDaemon(t)\n\tstart()\n\tdefer clean()\n\n\tctx := context.Background()\n\tv, err := d.Version(ctx)\n\tif err != nil {\n\t\tt.Fatalf(\"Error: %s\", err.Error())\n\t}\n\tif v != testVersion {\n\t\tt.Fatalf(\"Expected %v but got %v\", testVersion, v)\n\t}\n}", "func (m *Mock) Version() string {\n\treturn defaultMockVersion\n}", "func (m *MockTask) GetVersion() int64 {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetVersion\")\n\tret0, _ := ret[0].(int64)\n\treturn ret0\n}", "func TestGetVersion(t *testing.T) {\n\ttests := []struct {\n\t\tversion string\n\t\tcommit string\n\t\tdate string\n\t\texpect string\n\t\tshortOutput bool\n\t}{\n\t\t{\n\t\t\t\"a\",\n\t\t\t\"b\",\n\t\t\t\"c\",\n\t\t\t\"waver version: a from commit b built on c\",\n\t\t\tfalse,\n\t\t}, {\n\t\t\t\"v0.12.4\",\n\t\t\t\"5b1a61f9b58e3778986c99b1282840ce64329614\",\n\t\t\t\"Thu May 21 16:48:18 PDT 2020\",\n\t\t\t\"waver version: v0.12.4 from commit 5b1a61f9b58e3778986c99b1282840ce64329614 built on Thu May 21 16:48:18 PDT 2020\",\n\t\t\tfalse,\n\t\t}, {\n\t\t\t\"v0.12.4-rc5\",\n\t\t\t\"5b1a61f9b58\",\n\t\t\t\"1590105848\",\n\t\t\t\"waver version: v0.12.4-rc5 from commit 5b1a61f9b58 built on 1590105848\",\n\t\t\tfalse,\n\t\t}, {\n\t\t\t\"v0.12.4-rc5\",\n\t\t\t\"5b1a61f9b58\",\n\t\t\t\"1590105848\",\n\t\t\t\"5b1a61f9b58\",\n\t\t\ttrue,\n\t\t},\n\t}\n\n\t// save the current global variables so they can be set back after testing\n\toldVal := version\n\toldCommit := commit\n\toldDate := date\n\n\tfor _, test := range tests {\n\t\t// run through each test, should not be run in parallel.\n\t\tversion = test.version\n\t\tcommit = test.commit\n\t\tdate = test.date\n\n\t\t// build the new Cobra command and configure stdout and args\n\t\tv := Get(test.shortOutput)\n\n\t\t// assert output string matches expectations\n\t\tassert.Equal(t, test.expect, v)\n\t}\n\n\t// put the original build values back after tests have run\n\tversion = oldVal\n\tcommit = oldCommit\n\tdate = oldDate\n}", "func (m *MockEventLogger) VersionInitial() uint64 {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"VersionInitial\")\n\tret0, _ := ret[0].(uint64)\n\treturn ret0\n}", "func (_m *MockAggregate) Version() int {\n\tret := _m.Called()\n\n\tvar r0 int\n\tif rf, ok := ret.Get(0).(func() int); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tr0 = ret.Get(0).(int)\n\t}\n\n\treturn r0\n}", "func Test_LatestVersion(t *testing.T) {\n\tmockServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Header().Set(\"Content-Type\", \"text/plain\")\n\t\tw.WriteHeader(http.StatusOK)\n\t\tw.Write([]byte(\"0.6.1\\n\"))\n\t}))\n\tdefer mockServer.Close()\n\n\tversion, err := latestVersion(mockServer.URL)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\ttestVersion := semver.New(\"0.6.1\")\n\tif !version.Equal(*testVersion) {\n\t\tt.Error(\"Version equality check failed.\")\n\t}\n}", "func TestVersion(t *testing.T) {\n\tfor _, v := range versionTests {\n\t\tp, e := model.ParseVersion(v[0])\n\t\tassert.Nil(t, e, \"Should have parsed %s\", v)\n\t\tassert.Equal(t, p.String(), v[1], \"Should be equal %s==%s\", p.String(), v)\n\t}\n}", "func (s *suite) Test_QueryNextVersion_happy_path(c *C) {\n\tserver := NewMockServer().WithBody(`1.0`).Start(c)\n\tdefer server.Stop()\n\n\tunit := NewRemoteInventory(server.URL, \"token\", \"\", \"\", false)\n\tversion, err := unit.QueryNextVersion(\"query-project\", \"name\", \"1.@\")\n\tserver.ExpectCalled(c, true, queryNextVersionURL)\n\tc.Assert(err, IsNil)\n\tc.Assert(version, Equals, \"1.0\")\n}", "func TestVersionStorage(openStorage func() storage.ChunkStorage, closeStorage func(storage.ChunkStorage),\n\tresetStorage func(), t *testing.T) {\n\tassert := testifyAssert.New(t)\n\n\tvar s storage.ChunkStorage = nil\n\n\ttest := func(name string, run func()) {\n\t\tt.Logf(\"subtest: %s\", name)\n\t\tresetStorage()\n\t\ts = openStorage()\n\t\tdefer func() {\n\t\t\tif s != nil {\n\t\t\t\tcloseStorage(s)\n\t\t\t\ts = nil\n\t\t\t}\n\t\t}()\n\t\trun()\n\t}\n\n\treopen := func() {\n\t\tcloseStorage(s)\n\t\t// no reset\n\t\ts = openStorage()\n\t}\n\n\ttest(\"empty by default\", func() {\n\t\tchunks, err := s.ListChunksWithLatest()\n\t\tassert.NoError(err)\n\t\tassert.Empty(chunks)\n\t})\n\n\ttest(\"cannot get nonexistent latest\", func() {\n\t\t_, err := s.GetLatestVersion(71)\n\t\tassert.Error(err)\n\t})\n\n\ttest(\"cannot delete nonexistent version\", func() {\n\t\terr := s.DeleteLatestVersion(71)\n\t\tassert.Error(err)\n\t})\n\n\ttest(\"write single version\", func() {\n\t\tassert.NoError(s.SetLatestVersion(71, 3))\n\n\t\tchunks, err := s.ListChunksWithLatest()\n\t\tassert.NoError(err)\n\t\tassert.Equal([]apis.ChunkNum{71}, chunks)\n\n\t\tdata, err := s.GetLatestVersion(71)\n\t\tassert.NoError(err)\n\t\tassert.Equal(apis.Version(3), data)\n\t})\n\n\ttest(\"write single version corrolaries\", func() {\n\t\tassert.NoError(s.SetLatestVersion(71, 3))\n\n\t\tchunks, err := s.ListChunksWithLatest()\n\t\tassert.NoError(err)\n\t\tassert.Equal([]apis.ChunkNum{71}, chunks)\n\n\t\t_, err = s.GetLatestVersion(72)\n\t\tassert.Error(err)\n\n\t\t_, err = s.GetLatestVersion(70)\n\t\tassert.Error(err)\n\t})\n\n\ttest(\"write single version durability\", func() {\n\t\tassert.NoError(s.SetLatestVersion(71, 3))\n\n\t\treopen()\n\n\t\tchunks, err := s.ListChunksWithLatest()\n\t\tassert.NoError(err)\n\t\tassert.Equal([]apis.ChunkNum{71}, chunks)\n\n\t\tdata, err := s.GetLatestVersion(71)\n\t\tassert.NoError(err)\n\t\tassert.Equal(apis.Version(3), data)\n\t})\n\n\ttest(\"updating versions\", func() {\n\t\tassert.NoError(s.SetLatestVersion(71, 1))\n\t\tassert.NoError(s.SetLatestVersion(71, 3))\n\n\t\tdata, err := s.GetLatestVersion(71)\n\t\tassert.NoError(err)\n\t\tassert.Equal(apis.Version(3), data)\n\n\t\tassert.NoError(s.SetLatestVersion(72, 6))\n\t\tassert.NoError(s.SetLatestVersion(71, 2))\n\n\t\tchunks, err := s.ListChunksWithLatest()\n\t\tassert.NoError(err)\n\t\tsortChunkNums(chunks)\n\t\tassert.Equal([]apis.ChunkNum{71, 72}, chunks)\n\n\t\tdata, err = s.GetLatestVersion(71)\n\t\tassert.NoError(err)\n\t\tassert.Equal(apis.Version(2), data)\n\n\t\tdata, err = s.GetLatestVersion(72)\n\t\tassert.NoError(err)\n\t\tassert.Equal(apis.Version(6), data)\n\t})\n\n\ttest(\"updating versions with durability\", func() {\n\t\tassert.NoError(s.SetLatestVersion(71, 1))\n\t\tassert.NoError(s.SetLatestVersion(71, 3))\n\n\t\treopen()\n\n\t\tdata, err := s.GetLatestVersion(71)\n\t\tassert.NoError(err)\n\t\tassert.Equal(apis.Version(3), data)\n\n\t\tassert.NoError(s.SetLatestVersion(72, 6))\n\t\tassert.NoError(s.SetLatestVersion(71, 2))\n\n\t\tchunks, err := s.ListChunksWithLatest()\n\t\tassert.NoError(err)\n\t\tsortChunkNums(chunks)\n\t\tassert.Equal([]apis.ChunkNum{71, 72}, chunks)\n\n\t\tdata, err = s.GetLatestVersion(71)\n\t\tassert.NoError(err)\n\t\tassert.Equal(apis.Version(2), data)\n\n\t\tdata, err = s.GetLatestVersion(72)\n\t\tassert.NoError(err)\n\t\tassert.Equal(apis.Version(6), data)\n\t})\n\n\ttest(\"delete subset of versions\", func() {\n\t\tassert.NoError(s.SetLatestVersion(71, 2))\n\t\tassert.NoError(s.SetLatestVersion(72, 6))\n\n\t\tassert.NoError(s.DeleteLatestVersion(71))\n\n\t\tversions, err := s.ListChunksWithLatest()\n\t\tassert.NoError(err)\n\t\tassert.Equal([]apis.ChunkNum{72}, versions)\n\n\t\tassert.Error(s.DeleteLatestVersion(71))\n\t})\n\n\ttest(\"delete subset of versions with durabilitiy\", func() {\n\t\tassert.NoError(s.SetLatestVersion(71, 2))\n\t\tassert.NoError(s.SetLatestVersion(72, 6))\n\n\t\treopen()\n\n\t\tassert.NoError(s.DeleteLatestVersion(71))\n\n\t\treopen()\n\n\t\tversions, err := s.ListChunksWithLatest()\n\t\tassert.NoError(err)\n\t\tassert.Equal([]apis.ChunkNum{72}, versions)\n\n\t\tassert.Error(s.DeleteLatestVersion(71))\n\t})\n\n\ttest(\"delete all versions\", func() {\n\t\tassert.NoError(s.SetLatestVersion(71, 2))\n\t\tassert.NoError(s.SetLatestVersion(72, 6))\n\n\t\tassert.NoError(s.DeleteLatestVersion(71))\n\t\tassert.NoError(s.DeleteLatestVersion(72))\n\n\t\tversions, err := s.ListChunksWithLatest()\n\t\tassert.NoError(err)\n\t\tassert.Empty(versions)\n\n\t\t_, err = s.GetLatestVersion(71)\n\t\tassert.Error(err)\n\t})\n}", "func TestVersion(t *testing.T) {\n\tassert := audit.NewTestingAssertion(t, true)\n\t// Setup the test server.\n\tmux := newMultiplexer(assert)\n\tts := restaudit.StartServer(mux, assert)\n\tdefer ts.Close()\n\terr := mux.Register(\"test\", \"json\", NewTestHandler(\"json\", assert))\n\tassert.Nil(err)\n\t// Perform test requests.\n\treq := restaudit.NewRequest(\"GET\", \"/base/test/json/4711?foo=0815\")\n\treq.AddHeader(restaudit.HeaderAccept, restaudit.ApplicationJSON)\n\tresp := ts.DoRequest(req)\n\tresp.AssertStatusEquals(200)\n\tresp.AssertHeaderEquals(\"Version\", \"1.0.0\")\n\n\treq = restaudit.NewRequest(\"GET\", \"/base/test/json/4711?foo=0815\")\n\treq.AddHeader(restaudit.HeaderAccept, restaudit.ApplicationJSON)\n\treq.AddHeader(\"Version\", \"2\")\n\tresp = ts.DoRequest(req)\n\tresp.AssertStatusEquals(200)\n\tresp.AssertHeaderEquals(\"Version\", \"2.0.0\")\n\n\treq = restaudit.NewRequest(\"GET\", \"/base/test/json/4711?foo=0815\")\n\treq.AddHeader(restaudit.HeaderAccept, restaudit.ApplicationJSON)\n\treq.AddHeader(\"Version\", \"3.0\")\n\tresp = ts.DoRequest(req)\n\tresp.AssertStatusEquals(200)\n\tresp.AssertHeaderEquals(\"Version\", \"4.0.0-alpha\")\n}", "func (m *MockPacketHandler) GetVersion() protocol.VersionNumber {\n\tret := m.ctrl.Call(m, \"GetVersion\")\n\tret0, _ := ret[0].(protocol.VersionNumber)\n\treturn ret0\n}", "func NewObjectVersioner(t mockConstructorTestingTNewObjectVersioner) *ObjectVersioner {\n\tmock := &ObjectVersioner{}\n\tmock.Mock.Test(t)\n\n\tt.Cleanup(func() { mock.AssertExpectations(t) })\n\n\treturn mock\n}", "func (m *MockKernelData) FullVersion(arg0 *v1.NodeList) (string, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"FullVersion\", arg0)\n\tret0, _ := ret[0].(string)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func TestGetVersion(t *testing.T) {\n\n\tversion, err := GetVersion()\n\n\tif err != nil{\n\t\tt.Error(err)\n\t}\n\n\tif version != \"v1\"{\n\t\tt.Errorf(\"app version not match: %s, expect: %s.\", version, \"v1\")\n\t}\n\n\tfmt.Println(version)\n}", "func MockMinimalRelease(t *testing.T) *Release {\n\tvar r Release\n\terr := json.Unmarshal([]byte(`\n {\n \"release_id\": \"rr\",\n \"project_name\": \"project\",\n \"config_name\": \"config\",\n \"ami\": \"ami-123456\",\n \"subnets\": [\"subnet-1\"],\n \"user_data\": \"echo DATE\",\n \"services\": {\n \"web\": {\n \"instance_type\": \"t2.small\",\n \"security_groups\": [\"web-sg\"]\n }\n }\n }\n `), &r)\n\n\tassert.NoError(t, err)\n\tr.CreatedAt = to.Timep(time.Now())\n\n\treturn &r\n}", "func (m *MockTask) SetVersion(version int64) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"SetVersion\", version)\n}", "func (_m *U2FDevice) Version() (string, error) {\n\tret := _m.Called()\n\n\tvar r0 string\n\tif rf, ok := ret.Get(0).(func() string); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tr0 = ret.Get(0).(string)\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func() error); ok {\n\t\tr1 = rf()\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (m *MockFullNode) StateNetworkVersion(arg0 context.Context, arg1 types0.TipSetKey) (network.Version, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"StateNetworkVersion\", arg0, arg1)\n\tret0, _ := ret[0].(network.Version)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func TestGetVersion(t *testing.T) {\n\tv := \"0.0.0\"\n\tmaj, min, patch := getVersion(v)\n\n\tif maj != 0 && min != 0 && patch != 0 {\n\t\tt.Error(\"maj, min or patch are not set to 0\", maj, min, patch)\n\t}\n\n\tv = \"1.2.4\"\n\n\tmaj, min, patch = getVersion(v)\n\n\tif maj != 1 && min != 2 && patch != 4 {\n\t\tt.Error(\"maj, min or patch are not set to 1, 2, 4\", maj, min, patch)\n\t}\n}", "func (_m *System) Version() (types.Text, error) {\n\tret := _m.Called()\n\n\tvar r0 types.Text\n\tif rf, ok := ret.Get(0).(func() types.Text); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tr0 = ret.Get(0).(types.Text)\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func() error); ok {\n\t\tr1 = rf()\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func TestHandleGetVersion(t *testing.T) {\n\tsv := ServerVersion{Version:\"v1\", IP:\"127.0.0.1\", Port:8080}\n\n\tmux := http.NewServeMux()\n\tmux.HandleFunc(\"/version\", sv.handGetVersion)\n\n\twriter := httptest.NewRecorder()\n\treq, _ := http.NewRequest(\"GET\", \"/version\", nil)\n\tmux.ServeHTTP(writer, req)\n\n\tfmt.Println(writer.Body.String())\n}", "func TestClientVersion(t *testing.T) {\n\t// t.SkipNow()\n\tet := testutil.GetETH()\n\n\tclientVersion, err := et.ClientVersion()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tt.Log(\"clientVersion:\", clientVersion)\n}", "func TestVersion(t *testing.T) {\n\n\ttests := []struct {\n\t\tInput driver.Version\n\t\tMajor int\n\t\tMinor int\n\t\tSub string\n\t\tSubInt int\n\t\tSubIsInt bool\n\t}{\n\t\t{\"1.2.3\", 1, 2, \"3\", 3, true},\n\t\t{\"\", 0, 0, \"\", 0, false},\n\t\t{\"1.2.3a\", 1, 2, \"3a\", 0, false},\n\t\t{\"13.12\", 13, 12, \"\", 0, false},\n\t}\n\n\tfor _, test := range tests {\n\t\tif v := test.Input.Major(); v != test.Major {\n\t\t\tt.Errorf(\"Major failed for '%s', expected %d, got %d\", test.Input, test.Major, v)\n\t\t}\n\t\tif v := test.Input.Minor(); v != test.Minor {\n\t\t\tt.Errorf(\"Minor failed for '%s', expected %d, got %d\", test.Input, test.Minor, v)\n\t\t}\n\t\tif v := test.Input.Sub(); v != test.Sub {\n\t\t\tt.Errorf(\"Sub failed for '%s', expected '%s', got '%s'\", test.Input, test.Sub, v)\n\t\t}\n\t\tif v, vIsInt := test.Input.SubInt(); vIsInt != test.SubIsInt || v != test.SubInt {\n\t\t\tt.Errorf(\"SubInt failed for '%s', expected (%d,%v), got (%d,%v)\", test.Input, test.SubInt, test.SubIsInt, v, vIsInt)\n\t\t}\n\t}\n}", "func (m *MockClusterVersionBuilder) New(arg0 client.Client) clusterversion.ClusterVersion {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"New\", arg0)\n\tret0, _ := ret[0].(clusterversion.ClusterVersion)\n\treturn ret0\n}", "func (m *MockVersionInfoDao) GetVersionByDeployVersion(version, serviceID string) (*model.VersionInfo, error) {\n\tret := m.ctrl.Call(m, \"GetVersionByDeployVersion\", version, serviceID)\n\tret0, _ := ret[0].(*model.VersionInfo)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func MockKernelVersion(version string) (restore func()) {\n\told := KernelVersion\n\tKernelVersion = func() string { return version }\n\treturn func() {\n\t\tKernelVersion = old\n\t}\n}", "func TestMakeUpVersion(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\tmajor uint8\n\t\tminor uint8\n\t\tfix uint8\n\t\twant uint32\n\t}{\n\t\t{\n\t\t\tname: \"MakeUpversionTest\",\n\t\t\tmajor: FixVersion,\n\t\t\tminor: MinorVersion,\n\t\t\tfix: FixVersion,\n\t\t\twant: 16843008,\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tif got := makeUpVersion(tt.major, tt.minor, tt.fix); got != tt.want {\n\t\t\t\tt.Errorf(\"makeUpVersion() = %v, majorVersion %v\", got, tt.want)\n\t\t\t}\n\t\t})\n\t}\n}", "func Test_ExecuteVersion(t *testing.T) {\n\tfor _, v := range versiontests {\n\t\tt.Run(v.desc, func(t *testing.T) {\n\t\t\t// fakeout the output for the tests\n\t\t\tout := &testhelpers.FakeOut{}\n\t\t\tcommonOpts := opts.NewCommonOptionsWithTerm(clients.NewFactory(), os.Stdin, out, os.Stderr)\n\n\t\t\t// Set batchmode to true for tests\n\t\t\tcommonOpts.BatchMode = true\n\t\t\tcommand := version.NewCmdVersion(commonOpts)\n\n\t\t\tswitch v.short {\n\t\t\tcase true:\n\t\t\t\tcommand.SetArgs([]string{\"--short\"})\n\t\t\t\terr := command.Execute()\n\t\t\t\tassert.NoError(t, err, \"could not execute version\")\n\t\t\t\tassert.Contains(t, out.GetOutput(), \"Version\")\n\t\t\t\tassert.NotContains(t, out.GetOutput(), \"Commit\")\n\t\t\t\tassert.NotContains(t, out.GetOutput(), \"Build date\")\n\t\t\t\tassert.NotContains(t, out.GetOutput(), \"Go version\")\n\t\t\t\tassert.NotContains(t, out.GetOutput(), \"Git tree state\")\n\t\t\tdefault:\n\t\t\t\terr := command.Execute()\n\t\t\t\tassert.NoError(t, err, \"could not execute version\")\n\t\t\t\tassert.Contains(t, out.GetOutput(), \"Version\")\n\t\t\t\tassert.Contains(t, out.GetOutput(), \"Commit\")\n\t\t\t\tassert.Contains(t, out.GetOutput(), \"Build date\")\n\t\t\t\tassert.Contains(t, out.GetOutput(), \"Go version\")\n\t\t\t\tassert.Contains(t, out.GetOutput(), \"Git tree state\")\n\t\t\t}\n\t\t})\n\t}\n}", "func (m *MockCredHub) GetLatestVersion(arg0 string) (credentials.Credential, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetLatestVersion\", arg0)\n\tret0, _ := ret[0].(credentials.Credential)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockVersionInfoDao) GetLatestScsVersion(sid string) (*model.VersionInfo, error) {\n\tret := m.ctrl.Call(m, \"GetLatestScsVersion\", sid)\n\tret0, _ := ret[0].(*model.VersionInfo)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func TestAPIVersionsSimple(t *testing.T) {\n\tv201, err := semver.Make(\"2.0.1\")\n\tassert.Nil(t, err)\n\tv300, err := semver.Make(\"3.0.0\")\n\tassert.Nil(t, err)\n\tv312, err := semver.Make(\"3.1.2\")\n\tassert.Nil(t, err)\n\tv314, err := semver.Make(\"3.1.4\")\n\tassert.Nil(t, err)\n\tv317, err := semver.Make(\"3.1.7\")\n\tassert.Nil(t, err)\n\tv400, err := semver.Make(\"4.0.0\")\n\tassert.Nil(t, err)\n\n\tassert.True(t, v312.LT(v314))\n\tassert.True(t, v312.LT(v317))\n\n\tsingleRange, err := semver.ParseRange(\"3.1.4\")\n\tassert.True(t, singleRange(v314))\n\n\tmultiRange, err := semver.ParseRange(\">=3.1.4 <=3.1.8\")\n\tassert.True(t, multiRange(v317))\n\tassert.False(t, multiRange(v312))\n\tassert.False(t, multiRange(v400))\n\n\tanotherRange, err := semver.ParseRange(\">=3.1.0\")\n\tassert.True(t, anotherRange(v400))\n\tassert.False(t, anotherRange(v300))\n\tassert.False(t, anotherRange(v201))\n\n}", "func ReleaseMock(opts *MockReleaseOptions) *release.Release {\n\tdate := time.Unix(242085845, 0).UTC()\n\n\tname := opts.Name\n\tif name == \"\" {\n\t\tname = \"testrelease-\" + string(rand.Intn(100))\n\t}\n\n\tversion := 1\n\tif opts.Version != 0 {\n\t\tversion = opts.Version\n\t}\n\n\tnamespace := opts.Namespace\n\tif namespace == \"\" {\n\t\tnamespace = \"default\"\n\t}\n\n\tch := opts.Chart\n\tif opts.Chart == nil {\n\t\tch = &chart.Chart{\n\t\t\tMetadata: &chart.Metadata{\n\t\t\t\tName: \"foo\",\n\t\t\t\tVersion: \"0.1.0-beta.1\",\n\t\t\t},\n\t\t\tTemplates: []*chart.File{\n\t\t\t\t{Name: \"templates/foo.tpl\", Data: []byte(MockManifest)},\n\t\t\t},\n\t\t}\n\t}\n\n\tscode := release.StatusDeployed\n\tif len(opts.Status) > 0 {\n\t\tscode = opts.Status\n\t}\n\n\treturn &release.Release{\n\t\tName: name,\n\t\tInfo: &release.Info{\n\t\t\tFirstDeployed: date,\n\t\t\tLastDeployed: date,\n\t\t\tStatus: scode,\n\t\t\tDescription: \"Release mock\",\n\t\t},\n\t\tChart: ch,\n\t\tConfig: map[string]interface{}{\"name\": \"value\"},\n\t\tVersion: version,\n\t\tNamespace: namespace,\n\t\tHooks: []*release.Hook{\n\t\t\t{\n\t\t\t\tName: \"pre-install-hook\",\n\t\t\t\tKind: \"Job\",\n\t\t\t\tPath: \"pre-install-hook.yaml\",\n\t\t\t\tManifest: MockHookTemplate,\n\t\t\t\tLastRun: date,\n\t\t\t\tEvents: []release.HookEvent{release.HookPreInstall},\n\t\t\t},\n\t\t},\n\t\tManifest: MockManifest,\n\t}\n}", "func (m *MockDeployedVersionFinder) OpenSourceVersion(ctx context.Context, installNamespace string) (string, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"OpenSourceVersion\", ctx, installNamespace)\n\tret0, _ := ret[0].(string)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (r *versionResolver) BaseVersion(ctx context.Context, obj *restModel.APIVersion) (*restModel.APIVersion, error) {\n\tbaseVersion, err := model.VersionFindOne(model.BaseVersionByProjectIdAndRevision(*obj.Project, *obj.Revision))\n\tif baseVersion == nil || err != nil {\n\t\treturn nil, nil\n\t}\n\n\tapiVersion := restModel.APIVersion{}\n\tapiVersion.BuildFromService(*baseVersion)\n\treturn &apiVersion, nil\n}", "func _getMock(url string) (content []byte, err error) {\n\tvar idnum = crc32.ChecksumIEEE([]byte(url))%uint32(5) + 1\n\tvar response = fmt.Sprintf(mockResponseTemplate, idnum, idnum, \"no message\", 200)\n\treturn []byte(response), nil\n}", "func (_m *MockAggregate) OriginalVersion() int {\n\tret := _m.Called()\n\n\tvar r0 int\n\tif rf, ok := ret.Get(0).(func() int); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tr0 = ret.Get(0).(int)\n\t}\n\n\treturn r0\n}", "func (mock *PluginerMock) VersionCalls() []struct {\n} {\n\tvar calls []struct {\n\t}\n\tmock.lockVersion.RLock()\n\tcalls = mock.calls.Version\n\tmock.lockVersion.RUnlock()\n\treturn calls\n}", "func (m *MockSignerDecrypter) Public() crypto.PublicKey {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Public\")\n\tret0, _ := ret[0].(crypto.PublicKey)\n\treturn ret0\n}", "func (r *MockRepoManager) mockNextRollRev(hash string) {\n\tr.mtx.Lock()\n\tdefer r.mtx.Unlock()\n\tr.skiaHead = hash\n}", "func (m *MockKernelData) PatchVersion(kernelFullVersion string) (string, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"PatchVersion\", kernelFullVersion)\n\tret0, _ := ret[0].(string)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func TestVersion(t *testing.T) {\n\tt.Parallel()\n\n\ttree := writeTree(t, \"\")\n\n\t// There's not much we can robustly assert about the actual version.\n\twant := debug.Version() // e.g. \"master\"\n\n\t// basic\n\t{\n\t\tres := gopls(t, tree, \"version\")\n\t\tres.checkExit(true)\n\t\tres.checkStdout(want)\n\t}\n\n\t// -json flag\n\t{\n\t\tres := gopls(t, tree, \"version\", \"-json\")\n\t\tres.checkExit(true)\n\t\tvar v debug.ServerVersion\n\t\tif res.toJSON(&v) {\n\t\t\tif v.Version != want {\n\t\t\t\tt.Errorf(\"expected Version %q, got %q (%v)\", want, v.Version, res)\n\t\t\t}\n\t\t}\n\t}\n}", "func TestSetGetGoodArgsFull(t *testing.T) {\n\tfmt.Println(\"Entering the test method for SetGetGoodArgsFull\")\n\tprovcc := new(SimpleAsset)\n\tstub := shim.NewMockStub(\"ANY_PARAM\", provcc)\n\n\t// Testing the init. It always return true. No parameters in init. \n\t\n\tcheckInit(t, stub, [][]byte{[]byte(\"init\")})\n\n\tres := stub.MockInvoke(\"1\", [][]byte{[]byte(\"set\"), []byte(\"S52fkpF2rCEArSuwqyDA9tVjawUdrkGzbNQLaa7xJfA=\"),\n\t[]byte(\"agentInfo.atype\"),[]byte(\"1.2.3.4\"),\n\t[]byte(\"agentInfo.id\"),[]byte(\"agentidentifier\"),\n\t[]byte(\"agentinfo.name\"),[]byte(\"7.8.9\"),\n\t[]byte(\"agentinfo.idp\"),[]byte(\"urn:tiani-spirit:sts\"),\n\t[]byte(\"locationInfo.id\"),[]byte(\"urn:oid:1.2.3\"),\n\t[]byte(\"locationInfo.name\"),[]byte(\"General Hospital\"),\n\t[]byte(\"locationInfo.locality\"),[]byte(\"Nashville, TN\"),\n\t[]byte(\"locationInfo.docid\"),[]byte(\"1.2.3\"),\n\t[]byte(\"action\"),[]byte(\"ex:CREATE\"),\n\t[]byte(\"date\"),[]byte(\"2017-11-21T10:29:49.816Z\"),\n\t[]byte(\"digest1\"),[]byte(\"E0nioxbCYD5AlzGWXDDDl0Gt5AAKv3ppKt4XMhE1rfo\"),\n\t[]byte(\"digest2\"),[]byte(\"xLrbWN5QJBJUAsdevfrxGlN3o0p8VZMnFFnV9iMll5o\"),\n\t[]byte(\"digest3\"),[]byte(\"THIS_IS_DIGEST_3\"),\n\t[]byte(\"digest4\"),[]byte(\"THIS_IS_DIGEST_4\")})\n\n\tif res.Status != shim.OK {\n\t\tfmt.Println(\"Invoke failed\", string(res.Message))\n\t\tt.FailNow()\n\t}\n\t\n\tresGet := stub.MockInvoke(\"1\", [][]byte{[]byte(\"get\"), []byte(\"S52fkpF2rCEArSuwqyDA9tVjawUdrkGzbNQLaa7xJfA=\")})\n\tif resGet.Status != shim.OK {\n\t\tfmt.Println(\"Invoke failed\", string(resGet.Message))\n\t\tt.FailNow()\n\t}\n}", "func (m *MockUpstreamIntf) ServerPublicKey() []byte {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ServerPublicKey\")\n\tret0, _ := ret[0].([]byte)\n\treturn ret0\n}", "func Test12(t *testing.T) {\n\tcustommutatingBaseCollection := mutatingBaseCollectionVersions.DeepCopy()\n\tnewCollection := mutatingBaseCollectionVersions.DeepCopy()\n\tcustommutatingBaseCollection.Spec.Version = \"1.2.3\"\n\tnewCollection.Spec.Version = \"1.2.4\"\n\tcustommutatingBaseCollection.Spec.Versions[0].Version = \"1.2.4\"\n\tnewCollection.Spec.Versions[0].Version = \"1.2.4\"\n\n\terr := processUpdate(custommutatingBaseCollection, newCollection)\n\tif err != nil {\n\t\tt.Fatal(\"Unexpected error during mutation.\", err)\n\t}\n\n\texpectedversion0 := kabanerov1alpha1.CollectionVersion{\n\t\tDesiredState: \"active\",\n\t\tRepositoryUrl: \"https://github.com/some/collection/kabanero-index.yaml\",\n\t\tVersion: \"1.2.4\"}\n\n\tif newCollection.Spec.Versions[0] != expectedversion0 {\n\t\tt.Fatal(\"New collection.Spec.Versions[0] values do not match expected collection.Spec.Versions[0] values. New versions[0]: \", newCollection.Spec.Versions[0], \"Expected versions[0]: \", expectedversion0)\n\t}\n\n\tif newCollection.Spec.RepositoryUrl != \"https://github.com/some/collection/kabanero-index.yaml\" {\n\t\tt.Fatal(\"New collection.Spec.RepositoryUrl values do not match expected value of https://github.com/some/collection/kabanero-index.yaml. RepositoryUrl found: \", newCollection.Spec.RepositoryUrl)\n\t}\n\tif newCollection.Spec.Version != \"1.2.4\" {\n\t\tt.Fatal(\"New collection.Spec.Version values do not match expected value of 1.2.3. Version found: \", newCollection.Spec.Version)\n\t}\n\tif newCollection.Spec.DesiredState != \"active\" {\n\t\tt.Fatal(\"New collection.Spec.DesiredState values do not match expected value of active. DesiredStateme found: \", newCollection.Spec.DesiredState)\n\t}\n}", "func TestDerivedArtifactsCreate(t *testing.T) {\n\tctx := context.Background()\n\tregistryClient, err := connection.NewClient(ctx)\n\tif err != nil {\n\t\tt.Logf(\"Failed to create client: %+v\", err)\n\t\tt.FailNow()\n\t}\n\tdefer registryClient.Close()\n\n\t// Setup\n\tdeleteProject(ctx, registryClient, t, \"controller-test\")\n\tcreateProject(ctx, registryClient, t, \"controller-test\")\n\tcreateApi(ctx, registryClient, t, \"projects/controller-test\", \"petstore\")\n\t// Version 1.0.0\n\tcreateVersion(ctx, registryClient, t, \"projects/controller-test/apis/petstore\", \"1.0.0\")\n\tcreateSpec(ctx, registryClient, t, \"projects/controller-test/apis/petstore/versions/1.0.0\", \"openapi.yaml\", gzipOpenAPIv3)\n\tcreateUpdateArtifact(ctx, registryClient, t, \"projects/controller-test/apis/petstore/versions/1.0.0/specs/openapi.yaml/artifacts/lint-gnostic\")\n\tcreateUpdateArtifact(ctx, registryClient, t, \"projects/controller-test/apis/petstore/versions/1.0.0/specs/openapi.yaml/artifacts/complexity\")\n\t// Version 1.0.1\n\tcreateVersion(ctx, registryClient, t, \"projects/controller-test/apis/petstore\", \"1.0.1\")\n\tcreateSpec(ctx, registryClient, t, \"projects/controller-test/apis/petstore/versions/1.0.1\", \"openapi.yaml\", gzipOpenAPIv3)\n\tcreateUpdateArtifact(ctx, registryClient, t, \"projects/controller-test/apis/petstore/versions/1.0.1/specs/openapi.yaml/artifacts/lint-gnostic\")\n\tcreateUpdateArtifact(ctx, registryClient, t, \"projects/controller-test/apis/petstore/versions/1.0.1/specs/openapi.yaml/artifacts/complexity\")\n\t// Version 1.1.0\n\tcreateVersion(ctx, registryClient, t, \"projects/controller-test/apis/petstore\", \"1.1.0\")\n\tcreateSpec(ctx, registryClient, t, \"projects/controller-test/apis/petstore/versions/1.1.0\", \"openapi.yaml\", gzipOpenAPIv3)\n\tcreateUpdateArtifact(ctx, registryClient, t, \"projects/controller-test/apis/petstore/versions/1.1.0/specs/openapi.yaml/artifacts/lint-gnostic\")\n\tcreateUpdateArtifact(ctx, registryClient, t, \"projects/controller-test/apis/petstore/versions/1.1.0/specs/openapi.yaml/artifacts/complexity\")\n\n\t// Test the manifest\n\tmanifest := manifests[2]\n\tactions, err := ProcessManifest(ctx, registryClient, \"controller-test\", manifest)\n\tif err != nil {\n\t\tlog.Printf(err.Error())\n\t}\n\texpectedActions := []string{\n\t\tfmt.Sprintf(\n\t\t\t\"compute score %s %s\",\n\t\t\t\"projects/controller-test/apis/petstore/versions/1.0.0/specs/openapi.yaml/artifacts/lint-gnostic\",\n\t\t\t\"projects/controller-test/apis/petstore/versions/1.0.0/specs/openapi.yaml/artifacts/complexity\"),\n\t\tfmt.Sprintf(\n\t\t\t\"compute score %s %s\",\n\t\t\t\"projects/controller-test/apis/petstore/versions/1.0.1/specs/openapi.yaml/artifacts/lint-gnostic\",\n\t\t\t\"projects/controller-test/apis/petstore/versions/1.0.1/specs/openapi.yaml/artifacts/complexity\"),\n\t\tfmt.Sprintf(\n\t\t\t\"compute score %s %s\",\n\t\t\t\"projects/controller-test/apis/petstore/versions/1.1.0/specs/openapi.yaml/artifacts/lint-gnostic\",\n\t\t\t\"projects/controller-test/apis/petstore/versions/1.1.0/specs/openapi.yaml/artifacts/complexity\"),\n\t}\n\tif diff := cmp.Diff(expectedActions, actions, sortStrings); diff != \"\" {\n\t\tt.Errorf(\"ProcessManifest(%+v) returned unexpected diff (-want +got):\\n%s\", manifest, diff)\n\t}\n\n\tdeleteProject(ctx, registryClient, t, \"controller-test\")\n}", "func TestGetSemverVersisonWithStandardVersion(t *testing.T) {\n\tversion.Map[\"version\"] = \"1.2.1\"\n\tresult, err := version.GetSemverVersion()\n\texpectedResult := semver.Version{Major: 1, Minor: 2, Patch: 1}\n\tassert.NoError(t, err, \"GetSemverVersion should exit without failure\")\n\tassert.Exactly(t, expectedResult, result)\n}", "func TestSetGoodArgsFull(t *testing.T) {\n\tfmt.Println(\"Entering the test method for SetGoodArgsFull\")\n\tprovcc := new(SimpleAsset)\n\tstub := shim.NewMockStub(\"ANY_PARAM\", provcc)\n\n\t// Testing the init. It always return true. No parameters in init. \n\t\n\tcheckInit(t, stub, [][]byte{[]byte(\"init\")})\n\n\tres := stub.MockInvoke(\"1\", [][]byte{[]byte(\"set\"), []byte(\"S52fkpF2rCEArSuwqyDA9tVjawUdrkGzbNQLaa7xJfA=\"),\n\t[]byte(\"agentInfo.atype\"),[]byte(\"1.2.3.4\"),\n\t[]byte(\"agentInfo.id\"),[]byte(\"agentidentifier\"),\n\t[]byte(\"agentinfo.name\"),[]byte(\"7.8.9\"),\n\t[]byte(\"agentinfo.idp\"),[]byte(\"urn:tiani-spirit:sts\"),\n\t[]byte(\"locationInfo.id\"),[]byte(\"urn:oid:1.2.3\"),\n\t[]byte(\"locationInfo.name\"),[]byte(\"General Hospital\"),\n\t[]byte(\"locationInfo.locality\"),[]byte(\"Nashville, TN\"),\n\t[]byte(\"locationInfo.docid\"),[]byte(\"1.2.3\"),\n\t[]byte(\"action\"),[]byte(\"ex:CREATE\"),\n\t[]byte(\"date\"),[]byte(\"2018-11-10T12:15:55.028Z\"),\n\t[]byte(\"digest1\"),[]byte(\"E0nioxbCYD5AlzGWXDDDl0Gt5AAKv3ppKt4XMhE1rfo\"),\n\t[]byte(\"digest3\"),[]byte(\"xLrbWN5QJBJUAsdevfrxGlN3o0p8VZMnFFnV9iMll5o\")})\n\n\tif res.Status != shim.OK {\n\t\tfmt.Println(\"Invoke failed\", string(res.Message))\n\t\tt.FailNow()\n\t}\n\t\n}", "func (m *MockContext) GetNamespaceNotificationVersion() int64 {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetNamespaceNotificationVersion\")\n\tret0, _ := ret[0].(int64)\n\treturn ret0\n}", "func (m *MockClusterServer) GetVersion(arg0 context.Context, arg1 *GetVersionRequest) (*ClusterVersion, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetVersion\", arg0, arg1)\n\tret0, _ := ret[0].(*ClusterVersion)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockModuleService) UpdateModuleByVersion(arg0 *models.Module) (*models.Module, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"UpdateModuleByVersion\", arg0)\n\tret0, _ := ret[0].(*models.Module)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockVersion) GetVersion(keyName string) (string, error) {\n\targs := m.Called()\n\treturn args.String(0), args.Error(1)\n}", "func TestRootMetadataUpconversionPublic(t *testing.T) {\n\tconfig := MakeTestConfigOrBust(t, \"alice\", \"bob\")\n\tdefer config.Shutdown()\n\n\ttlfID := tlf.FakeID(1, true)\n\th := parseTlfHandleOrBust(t, config, \"alice,bob,charlie@twitter\", true)\n\trmd, err := makeInitialRootMetadata(InitialExtraMetadataVer, tlfID, h)\n\trequire.NoError(t, err)\n\trequire.Equal(t, rmd.LatestKeyGeneration(), PublicKeyGen)\n\trequire.Equal(t, rmd.Revision(), MetadataRevision(1))\n\trequire.Equal(t, rmd.Version(), InitialExtraMetadataVer)\n\n\t// set some dummy numbers\n\tdiskUsage, refBytes, unrefBytes := uint64(12345), uint64(4321), uint64(1234)\n\trmd.SetDiskUsage(diskUsage)\n\trmd.SetRefBytes(refBytes)\n\trmd.SetUnrefBytes(unrefBytes)\n\n\t// override the metadata version\n\tconfig.metadataVersion = SegregatedKeyBundlesVer\n\n\t// create an MDv3 successor\n\trmd2, err := rmd.MakeSuccessor(context.Background(), config, fakeMdID(1), true)\n\trequire.NoError(t, err)\n\trequire.Equal(t, rmd2.LatestKeyGeneration(), PublicKeyGen)\n\trequire.Equal(t, rmd2.Revision(), MetadataRevision(2))\n\trequire.Equal(t, rmd2.Version(), SegregatedKeyBundlesVer)\n\n\t// compare numbers\n\trequire.Equal(t, diskUsage, rmd2.DiskUsage())\n\t// we expect this and the below to be zero this time because the folder is public.\n\t// they aren't reset in the private version because the private metadata isn't\n\t// initialized therefor it's considered unreadable.\n\trequire.Equal(t, uint64(0), rmd2.RefBytes())\n\trequire.Equal(t, uint64(0), rmd2.UnrefBytes())\n\n\t// create and compare bare tlf handles (this verifies unresolved+resolved writer sets are identical)\n\trmd.tlfHandle, rmd2.tlfHandle = nil, nil // avoid a panic due to the handle already existing\n\thandle, err := rmd.MakeBareTlfHandle()\n\trequire.NoError(t, err)\n\thandle2, err := rmd2.MakeBareTlfHandle()\n\trequire.NoError(t, err)\n\trequire.Equal(t, handle, handle2)\n}", "func (m *MockChefIngesterServer) GetVersion(arg0 context.Context, arg1 *VersionRequest) (*Version, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetVersion\", arg0, arg1)\n\tret0, _ := ret[0].(*Version)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func buildMockVulnClientKey(version string, os string, packages []string) string {\n\tpkgs := strings.Join(packages, \"\")\n\treturn strings.Join([]string{version, os, pkgs}, \"/\")\n}", "func TestSetupReplaceMock(t *testing.T) {\n\tt.SkipNow()\n\tstudent, mocks, err := MockCluster(false, nil, t)\n\tif err != nil {\n\t\tt.Error(\"Couldn't set up mock cluster\", err)\n\t}\n\n\t// Create a new impl for an rpc function\n\tdenyVote := func(ctx context.Context, req *RequestVoteRequest) (*RequestVoteReply, error) {\n\t\treturn &RequestVoteReply{Term: req.Term, VoteGranted: false}, nil\n\t}\n\n\t// replace the existing impl\n\tmocks[0].RequestVote = denyVote\n\tmocks[1].RequestVote = denyVote\n\n\tmocks[0].JoinCluster()\n\tmocks[1].JoinCluster()\n\n\ttime.Sleep(DefaultConfig().ElectionTimeout * 4)\n\n\tt.Log(\"Student node is:\", student.State)\n\n\tif student.State != CANDIDATE_STATE {\n\t\tt.Error(\"student state was not candidate, was:\", student.State)\n\t}\n\n\t// test as part of an rpc function\n\tmocks[0].RequestVote = func(ctx context.Context, req *RequestVoteRequest) (*RequestVoteReply, error) {\n\t\tt.Logf(\"Mock 0 recieved request vote: last_idx: %v term: %v\", req.GetLastLogIndex(), req.GetLastLogTerm())\n\t\tif req.GetLastLogIndex() != 0 || req.GetLastLogTerm() != 0 {\n\t\t\tt.Errorf(\"Student node failed to request vote correctly: last_idx: %v term: %v\", req.GetLastLogIndex(), req.GetLastLogTerm())\n\t\t}\n\n\t\tif term := student.GetCurrentTerm(); req.GetTerm() != term {\n\t\t\tt.Errorf(\"Student node sent the wrong term: (sent %v, expecting %v)\", req.GetTerm(), term)\n\t\t}\n\t\treturn denyVote(ctx, req)\n\t}\n\n\ttime.Sleep(DefaultConfig().ElectionTimeout * 5)\n}", "func (m *mockStore) GetCurrentVersion() (time.Time, error) {\n\treturn m.version, nil\n}", "func init() {\n\tsrClient = CreateMockSchemaRegistryClient(\"mock://testingUrl\")\n\n\t// Test Schema and Value Schema creation\n\t_, _ = srClient.CreateSchema(\"test1\", schema, Avro, false)\n\t_, _ = srClient.CreateSchema(\"test1\", schema, Avro, true)\n\t// Test version upgrades for key and value and more registration\n\t_, _ = srClient.CreateSchema(\"test1\", schema2, Avro, false)\n\t_, _ = srClient.CreateSchema(\"test1\", schema2, Avro, true)\n\n\t// Test version upgrades for key and value and more registration (arbitrary subject)\n\t_, _ = srClient.CreateSchemaWithArbitrarySubject(\"test1_arb\", schema3, Avro)\n\t_, _ = srClient.CreateSchemaWithArbitrarySubject(\"test1_arb\", schema4, Avro)\n}", "func (m *MockModuleService) GetModuleByVersion(arg0, arg1 string) (*models.Module, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetModuleByVersion\", arg0, arg1)\n\tret0, _ := ret[0].(*models.Module)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func newAPIVersionAssert(t *testing.T, s string) *kubernetes.APIVersion {\n\tv, err := kubernetes.NewAPIVersion(s)\n\tif err != nil {\n\t\tt.Errorf(\"Creating an APIVersion with '%s' should work\", s)\n\t}\n\treturn v\n}", "func TestPeersService_Version(t *testing.T) {\n\tclient, mux, _, teardown := setupTest()\n\tdefer teardown()\n\n\tmux.HandleFunc(\"/peers/version\", func(writer http.ResponseWriter, request *http.Request) {\n\t\ttestMethod(t, request, \"GET\")\n\t\tfmt.Fprint(writer,\n\t\t\t`{\n\t\t\t \"version\": \"2.0.0\",\n\t\t\t \"success\": true\n\t\t\t}`)\n\t})\n\n\tresponseStruct, response, err := client.Peers.Version(context.Background())\n\ttestGeneralError(t, \"Peers.Version\", err)\n\ttestResponseUrl(t, \"Peers.Version\", response, \"/api/peers/version\")\n\ttestResponseStruct(t, \"Peers.Version\", responseStruct, &PeersVersion{\n\t\tSuccess: true,\n\t\tVersion: \"2.0.0\",\n\t})\n}", "func TestSonobuoyVersion(t *testing.T) {\n\terr, stdout, stderr := runSonobuoyCommand(t, \"version\")\n\n\tif err != nil {\n\t\tt.Errorf(\"Sonobuoy exited with an error: %q\\n\", err)\n\t\tt.Log(stderr.String())\n\t\tt.FailNow()\n\t}\n\n\tlines := strings.Split(stdout.String(), \"\\n\")\n\tfor _, line := range lines {\n\t\tversionComponents := strings.Split(line, \":\")\n\t\t// If a Kubeconfig is not provided, a warning is included that the API version check is skipped.\n\t\t// Only check lines where a split on \":\" actually happened.\n\t\tif len(versionComponents) == 2 && strings.TrimSpace(versionComponents[1]) == \"\" {\n\t\t\tt.Errorf(\"expected value for %v to be set, but was empty\", versionComponents[0])\n\t\t}\n\t}\n}", "func MockPrepareRelease(release *Release) {\n\trelease.SetDefaultRegionAccount(to.Strp(\"region\"), to.Strp(\"account\"))\n\trelease.SetDefaults()\n\trelease.SetUUID()\n}", "func (_m *MockBackend) ProtocolVersion() string {\n\tret := _m.Called()\n\n\tvar r0 string\n\tif rf, ok := ret.Get(0).(func() string); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tr0 = ret.Get(0).(string)\n\t}\n\n\treturn r0\n}", "func (m *MockProductCatalog) UpdateVersionForEditor(arg0 context.Context, arg1 db.UpdateVersionForEditorParams) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"UpdateVersionForEditor\", arg0, arg1)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func Test_CheckVersion(t *testing.T) {\n\tt.Run(\"Outdated version\", Test(&TestConfig{\n\t\tCommands: NewCommands(fakeCommand),\n\t\tBuildInfo: BuildInfo{\n\t\t\tVersion: version.Must(version.NewSemver(\"v1.20\")),\n\t\t},\n\t\tBeforeFunc: deleteLatestVersionUpdateFile,\n\t\tCmd: \"scw plop\",\n\t\tCheck: TestCheckCombine(\n\t\t\tTestCheckGolden(),\n\t\t\tTestCheckExitCode(0),\n\t\t),\n\t\tDisableParallel: true,\n\t}))\n\n\tt.Run(\"Up to date version\", Test(&TestConfig{\n\t\tCommands: NewCommands(fakeCommand),\n\t\tBuildInfo: BuildInfo{\n\t\t\tVersion: version.Must(version.NewSemver(\"v99.99\")),\n\t\t},\n\t\tBeforeFunc: deleteLatestVersionUpdateFile,\n\t\tCmd: \"scw plop -D\",\n\t\tCheck: TestCheckCombine(\n\t\t\tTestCheckGolden(),\n\t\t\tTestCheckExitCode(0),\n\t\t),\n\t\tDisableParallel: true,\n\t}))\n\n\tt.Run(\"Already checked\", Test(&TestConfig{\n\t\tCommands: NewCommands(fakeCommand),\n\t\tBuildInfo: BuildInfo{\n\t\t\tVersion: version.Must(version.NewSemver(\"v1.0\")),\n\t\t},\n\t\tBeforeFunc: func(ctx *BeforeFuncCtx) error {\n\t\t\tif createAndCloseFile(getLatestVersionUpdateFilePath()) {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\treturn fmt.Errorf(\"failed to create latestVersionUpdateFile\")\n\t\t},\n\t\tCmd: \"scw plop -D\",\n\t\tCheck: TestCheckCombine(\n\t\t\tTestCheckGolden(),\n\t\t\tTestCheckExitCode(0),\n\t\t),\n\t\tDisableParallel: true,\n\t}))\n}", "func TestSimpleIncrement(t *testing.T) {\n\tv := Version{\n\t\tMajor: 1,\n\t\tMinor: 9,\n\t}\n\tif v.String() != \"1.9.0\" {\n\t\tt.Fatalf(`Expected \"1.9.0\", got \"%s\"`, v.String())\n\t}\n\tv = v.NextMinor()\n\tif v.String() != \"1.10.0\" {\n\t\tt.Fatalf(`Expected \"1.10.0\", got \"%s\"`, v.String())\n\t}\n\tv = v.NextMinor()\n\tif v.String() != \"1.11.0\" {\n\t\tt.Fatalf(`Expected \"1.11.0\", got \"%s\"`, v.String())\n\t}\n}", "func Mock() Cluster { return mockCluster{} }", "func (m *MockKeystore) Get(key string) (keystoreregistry.KeyValueVersion, error) {\n\tret := m.ctrl.Call(m, \"Get\", key)\n\tret0, _ := ret[0].(keystoreregistry.KeyValueVersion)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (_m *LambdaAPI) PublishVersion(_a0 *lambda.PublishVersionInput) (*lambda.FunctionConfiguration, error) {\n\tret := _m.Called(_a0)\n\n\tvar r0 *lambda.FunctionConfiguration\n\tif rf, ok := ret.Get(0).(func(*lambda.PublishVersionInput) *lambda.FunctionConfiguration); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*lambda.FunctionConfiguration)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(*lambda.PublishVersionInput) error); ok {\n\t\tr1 = rf(_a0)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (m *MockVersionInfoDao) GetVersionByEventID(eventID string) (*model.VersionInfo, error) {\n\tret := m.ctrl.Call(m, \"GetVersionByEventID\", eventID)\n\tret0, _ := ret[0].(*model.VersionInfo)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func mockVoteTx(publicKeys [][]byte) *types.Transaction {\n\tcandidateVotes := make([]outputpayload.CandidateVotes, 0, len(publicKeys))\n\tfor _, pk := range publicKeys {\n\t\tcandidateVotes = append(candidateVotes,\n\t\t\toutputpayload.CandidateVotes{pk, 0})\n\t}\n\toutput := &types.Output{\n\t\tValue: 100,\n\t\tType: types.OTVote,\n\t\tPayload: &outputpayload.VoteOutput{\n\t\t\tVersion: 0,\n\t\t\tContents: []outputpayload.VoteContent{\n\t\t\t\t{outputpayload.Delegate, candidateVotes},\n\t\t\t},\n\t\t},\n\t}\n\n\treturn &types.Transaction{\n\t\tVersion: types.TxVersion09,\n\t\tTxType: types.TransferAsset,\n\t\tOutputs: []*types.Output{output},\n\t}\n}", "func TestSuccessfullyUpdateVersion(t *testing.T) {\n\tids, err := helpers.GetIDsAndTimestamps()\n\tif err != nil {\n\t\tlog.ErrorC(\"unable to generate mongo timestamp\", err, nil)\n\t\tt.FailNow()\n\t}\n\n\tdatasetAPI := httpexpect.New(t, cfg.DatasetAPIURL)\n\n\tneo4JStore, err := neo4j.NewDatastore(cfg.Neo4jAddr, \"\", neo4j.GenericHierarchyCPIHTestData)\n\tif err != nil {\n\t\tt.Errorf(\"unable to connect to neo4j. error: [%v]\\n\", err)\n\t\tlog.ErrorC(\"unable to connect to neo4j\", err, nil)\n\t\tt.FailNow()\n\t}\n\n\tConvey(\"Given an unpublished dataset, edition and version\", t, func() {\n\t\tedition := \"2018\"\n\t\tversion := \"2\"\n\n\t\tdocs, err := setupResources(ids.DatasetAssociated, ids.EditionUnpublished, edition, ids.InstanceEditionConfirmed, ids.UniqueTimestamp, 1)\n\t\tif err != nil {\n\t\t\tlog.ErrorC(\"Was unable to setup test data\", err, nil)\n\t\t\tt.FailNow()\n\t\t}\n\n\t\tcount, err := neo4JStore.CreateInstanceNode(ids.InstanceEditionConfirmed)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"failed to create neo4j instance node: [%v]\\n error: [%v]\\n\", ids.InstanceEditionConfirmed, err)\n\t\t\tt.FailNow()\n\t\t}\n\t\tSo(count, ShouldEqual, 1)\n\n\t\tConvey(\"When a PUT request to update meta data against the version resource\", func() {\n\t\t\tConvey(\"Then version resource is updated and returns a status ok (200)\", func() {\n\n\t\t\t\tdatasetAPI.PUT(\"/datasets/{id}/editions/{edition}/versions/{version}\", ids.DatasetAssociated, edition, version).\n\t\t\t\t\tWithHeader(florenceTokenName, florenceToken).\n\t\t\t\t\tWithBytes([]byte(validPUTUpdateVersionMetaDataJSON)).\n\t\t\t\t\tExpect().Status(http.StatusOK)\n\n\t\t\t\tupdatedVersion, err := mongo.GetVersion(cfg.MongoDB, \"instances\", \"_id\", ids.InstanceEditionConfirmed)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.ErrorC(\"Unable to retrieve updated version document\", err, nil)\n\t\t\t\t\tos.Exit(1)\n\t\t\t\t}\n\n\t\t\t\t// Check version has been updated\n\t\t\t\tSo(updatedVersion.ID, ShouldEqual, ids.InstanceEditionConfirmed)\n\t\t\t\tSo(updatedVersion.ReleaseDate, ShouldEqual, \"2018-11-11\")\n\t\t\t\tSo(len(*updatedVersion.UsageNotes), ShouldEqual, 2)\n\n\t\t\t\tSo((*updatedVersion.UsageNotes)[0].Title, ShouldEqual, \"Coefficients of variation\")\n\n\t\t\t\talert := mongo.Alert{\n\t\t\t\t\tDescription: \"All data entries (observations) for Plymouth have been updated\",\n\t\t\t\t\tDate: \"2017-04-05\",\n\t\t\t\t\tType: \"Correction\",\n\t\t\t\t}\n\n\t\t\t\talertList := &[]mongo.Alert{alert}\n\n\t\t\t\tSo(updatedVersion.Alerts, ShouldResemble, alertList)\n\n\t\t\t\tlatestChange := mongo.LatestChange{\n\t\t\t\t\tDescription: \"change to the period frequency from quarterly to monthly\",\n\t\t\t\t\tName: \"Changes to the period frequency\",\n\t\t\t\t\tType: \"Summary of Changes\",\n\t\t\t\t}\n\n\t\t\t\tlatestChangesList := []mongo.LatestChange{latestChange}\n\n\t\t\t\tSo(updatedVersion.LatestChanges, ShouldResemble, latestChangesList)\n\n\t\t\t\tSo(updatedVersion.Links.Spatial.HRef, ShouldEqual, \"http://ons.gov.uk/new-geography-list\")\n\n\t\t\t\t// Check self link does not update - the only link that can be updated is `spatial`\n\t\t\t\tSo(updatedVersion.Links.Self.HRef, ShouldNotEqual, \"http://bogus/bad-link\")\n\n\t\t\t\ttemporal := mongo.TemporalFrequency{\n\t\t\t\t\tStartDate: \"2014-11-11\",\n\t\t\t\t\tEndDate: \"2017-11-11\",\n\t\t\t\t\tFrequency: \"monthly\",\n\t\t\t\t}\n\n\t\t\t\ttemporalList := []mongo.TemporalFrequency{temporal}\n\n\t\t\t\tSo(updatedVersion.Temporal, ShouldResemble, temporalList)\n\t\t\t})\n\t\t})\n\n\t\tConvey(\"When a PUT request to update version resource with a collection id and state of associated\", func() {\n\t\t\tConvey(\"Then the dataset and version resources are updated and returns a status ok (200)\", func() {\n\n\t\t\t\tdatasetAPI.PUT(\"/datasets/{id}/editions/{edition}/versions/{version}\", ids.DatasetAssociated, edition, version).\n\t\t\t\t\tWithHeader(florenceTokenName, florenceToken).\n\t\t\t\t\tWithBytes([]byte(validPUTUpdateVersionToAssociatedJSON)).\n\t\t\t\t\tExpect().Status(http.StatusOK)\n\n\t\t\t\tupdatedVersion, err := mongo.GetVersion(cfg.MongoDB, \"instances\", \"_id\", ids.InstanceEditionConfirmed)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.ErrorC(\"Unable to retrieve updated version document\", err, nil)\n\t\t\t\t\tos.Exit(1)\n\t\t\t\t}\n\n\t\t\t\t// Check version has been updated\n\t\t\t\tSo(updatedVersion.ID, ShouldEqual, ids.InstanceEditionConfirmed)\n\t\t\t\tSo(updatedVersion.CollectionID, ShouldEqual, \"45454545\")\n\t\t\t\tSo(updatedVersion.State, ShouldEqual, \"associated\")\n\n\t\t\t\tupdatedDataset, err := mongo.GetDataset(cfg.MongoDB, collection, \"_id\", ids.DatasetAssociated)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.ErrorC(\"Unable to retrieve updated version document\", err, nil)\n\t\t\t\t\tos.Exit(1)\n\t\t\t\t}\n\n\t\t\t\t// Check dataset has been updated\n\t\t\t\tSo(updatedDataset.ID, ShouldEqual, ids.DatasetAssociated)\n\t\t\t\tSo(updatedDataset.Next.CollectionID, ShouldEqual, \"45454545\")\n\t\t\t\tSo(updatedDataset.Next.State, ShouldEqual, \"associated\")\n\t\t\t})\n\t\t})\n\n\t\tConvey(\"When a PUT request to update version resource with a collection id and state of published\", func() {\n\t\t\tConvey(\"Then the dataset, edition and version resources are updated and returns a status ok (200)\", func() {\n\n\t\t\t\tdatasetAPI.PUT(\"/datasets/{id}/editions/{edition}/versions/{version}\", ids.DatasetAssociated, edition, version).\n\t\t\t\t\tWithHeader(florenceTokenName, florenceToken).\n\t\t\t\t\tWithBytes([]byte(validPUTUpdateVersionToPublishedWithCollectionIDJSON)).\n\t\t\t\t\tExpect().Status(http.StatusOK)\n\n\t\t\t\tupdatedVersion, err := mongo.GetVersion(cfg.MongoDB, \"instances\", \"_id\", ids.InstanceEditionConfirmed)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.ErrorC(\"Unable to retrieve updated version document\", err, nil)\n\t\t\t\t\tos.Exit(1)\n\t\t\t\t}\n\n\t\t\t\t// Check version has been updated, and CollectionID removed\n\t\t\t\tSo(updatedVersion.ID, ShouldEqual, ids.InstanceEditionConfirmed)\n\t\t\t\tSo(updatedVersion.CollectionID, ShouldBeEmpty)\n\t\t\t\tSo(updatedVersion.State, ShouldEqual, \"published\")\n\n\t\t\t\tlog.Debug(\"edition id\", log.Data{\"edition_id\": ids.EditionUnpublished})\n\n\t\t\t\tupdatedEdition, err := mongo.GetEdition(cfg.MongoDB, \"editions\", \"_id\", ids.EditionUnpublished)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.ErrorC(\"Unable to retrieve updated version document\", err, nil)\n\t\t\t\t\tos.Exit(1)\n\t\t\t\t}\n\n\t\t\t\t// Check edition has been updated\n\t\t\t\tSo(updatedEdition.ID, ShouldEqual, ids.EditionUnpublished)\n\t\t\t\tSo(updatedEdition.Next.State, ShouldEqual, \"published\")\n\t\t\t\tSo(updatedEdition.Current, ShouldNotBeNil)\n\t\t\t\tSo(updatedEdition.Current.State, ShouldEqual, \"published\")\n\n\t\t\t\tupdatedDataset, err := mongo.GetDataset(cfg.MongoDB, collection, \"_id\", ids.DatasetAssociated)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.ErrorC(\"Unable to retrieve updated version document\", err, nil)\n\t\t\t\t\tos.Exit(1)\n\t\t\t\t}\n\n\t\t\t\t// Check dataset has been updated, and CollectionID removed\n\t\t\t\tSo(updatedDataset.ID, ShouldEqual, ids.DatasetAssociated)\n\t\t\t\tSo(updatedDataset.Current.CollectionID, ShouldBeEmpty)\n\t\t\t\tSo(updatedDataset.Current.State, ShouldEqual, \"published\")\n\n\t\t\t\tinstanceProps, err := neo4JStore.GetInstanceProperties(ids.InstanceEditionConfirmed)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.ErrorC(\"failed to get properties from neo4j instance node\", err, nil)\n\t\t\t\t\tt.FailNow()\n\t\t\t\t}\n\n\t\t\t\tSo(instanceProps[\"is_published\"], ShouldBeTrue)\n\t\t\t})\n\t\t})\n\n\t\tif err := mongo.Teardown(docs...); err != nil {\n\t\t\tif err != mgo.ErrNotFound {\n\t\t\t\tlog.ErrorC(\"Was unable to remove test data\", err, nil)\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t}\n\n\t\tif err := neo4JStore.CleanUpInstance(ids.InstanceEditionConfirmed); err != nil {\n\t\t\tt.Errorf(\"failed to cleanup neo4j instances: [%v]\\n error: [%v]\\n\", ids.InstanceEditionConfirmed, err)\n\t\t\tt.FailNow()\n\t\t}\n\t})\n\n\tConvey(\"Given an unpublished dataset, edition and a version that has been associated\", t, func() {\n\t\tedition := \"2018\"\n\t\tversion := \"2\"\n\n\t\tdocs, err := setupResources(ids.DatasetAssociated, ids.EditionUnpublished, edition, ids.InstanceAssociated, ids.UniqueTimestamp, 2)\n\t\tif err != nil {\n\t\t\tlog.ErrorC(\"Was unable to setup test data\", err, nil)\n\t\t\tos.Exit(1)\n\t\t}\n\n\t\tcount, err := neo4JStore.CreateInstanceNode(ids.InstanceAssociated)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"failed to create neo4j instance node: [%v]\\n error: [%v]\\n\", ids.InstanceAssociated, err)\n\t\t\tt.FailNow()\n\t\t}\n\t\tSo(count, ShouldEqual, 1)\n\n\t\t// TODO Remove skipped tests when code has been refactored (and hence fixed)\n\t\t// 1 test skipped\n\t\tSkipConvey(\"When a PUT request to update version resource to remove collection id\", func() {\n\t\t\tConvey(\"Then the dataset and version resources are updated accordingly and returns a status ok (200)\", func() {\n\n\t\t\t\tdatasetAPI.PUT(\"/datasets/{id}/editions/{edition}/versions/{version}\", ids.DatasetAssociated, edition, version).\n\t\t\t\t\tWithHeader(florenceTokenName, florenceToken).\n\t\t\t\t\tWithBytes([]byte(validPUTUpdateVersionFromAssociatedToEditionConfirmedJSON)).\n\t\t\t\t\tExpect().Status(http.StatusOK)\n\n\t\t\t\tupdatedVersion, err := mongo.GetVersion(cfg.MongoDB, \"instances\", \"_id\", ids.InstanceAssociated)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.ErrorC(\"Unable to retrieve updated version document\", err, nil)\n\t\t\t\t\tos.Exit(1)\n\t\t\t\t}\n\n\t\t\t\t// Check version has been updated\n\t\t\t\tSo(updatedVersion.ID, ShouldEqual, ids.InstanceAssociated)\n\t\t\t\tSo(updatedVersion.CollectionID, ShouldEqual, \"\")\n\t\t\t\tSo(updatedVersion.State, ShouldEqual, \"edition-confirmed\")\n\n\t\t\t\tupdatedDataset, err := mongo.GetDataset(cfg.MongoDB, collection, \"_id\", ids.DatasetAssociated)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.ErrorC(\"Unable to retrieve updated version document\", err, nil)\n\t\t\t\t\tos.Exit(1)\n\t\t\t\t}\n\n\t\t\t\t// Check dataset has been updated\n\t\t\t\tSo(updatedDataset.ID, ShouldEqual, ids.DatasetAssociated)\n\t\t\t\tSo(updatedDataset.Next.CollectionID, ShouldEqual, \"\")\n\t\t\t\tSo(updatedDataset.Next.State, ShouldEqual, \"edition-confirmed\")\n\t\t\t})\n\t\t})\n\n\t\tConvey(\"When a PUT request to update version resource with a state of published\", func() {\n\t\t\tConvey(\"Then the dataset, edition and version resources are updated and returns a status ok (200)\", func() {\n\n\t\t\t\tdatasetAPI.PUT(\"/datasets/{id}/editions/{edition}/versions/{version}\", ids.DatasetAssociated, edition, version).\n\t\t\t\t\tWithHeader(florenceTokenName, florenceToken).\n\t\t\t\t\tWithBytes([]byte(validPUTUpdateVersionToPublishedJSON)).\n\t\t\t\t\tExpect().Status(http.StatusOK)\n\n\t\t\t\tupdatedVersion, err := mongo.GetVersion(cfg.MongoDB, \"instances\", \"_id\", ids.InstanceAssociated)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.ErrorC(\"Unable to retrieve updated version document\", err, nil)\n\t\t\t\t\tos.Exit(1)\n\t\t\t\t}\n\n\t\t\t\t// Check version has been updated\n\t\t\t\tSo(updatedVersion.ID, ShouldEqual, ids.InstanceAssociated)\n\t\t\t\tSo(updatedVersion.State, ShouldEqual, \"published\")\n\n\t\t\t\tupdatedEdition, err := mongo.GetEdition(cfg.MongoDB, \"editions\", \"_id\", ids.EditionUnpublished)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.ErrorC(\"Unable to retrieve updated version document\", err, nil)\n\t\t\t\t\tos.Exit(1)\n\t\t\t\t}\n\n\t\t\t\t// Check edition has been updated\n\t\t\t\tSo(updatedEdition.ID, ShouldEqual, ids.EditionUnpublished)\n\t\t\t\tSo(updatedEdition.Next.State, ShouldEqual, \"published\")\n\t\t\t\tSo(updatedEdition.Current, ShouldNotBeNil)\n\t\t\t\tSo(updatedEdition.Current.State, ShouldEqual, \"published\")\n\t\t\t\tSo(updatedEdition.Current.Links.LatestVersion.ID, ShouldEqual, \"2\")\n\t\t\t\tSo(updatedEdition.Current.Links.LatestVersion.HRef, ShouldEqual, cfg.DatasetAPIURL+\"/datasets/\"+ids.DatasetAssociated+\"/editions/2018/versions/2\")\n\n\t\t\t\tupdatedDataset, err := mongo.GetDataset(cfg.MongoDB, collection, \"_id\", ids.DatasetAssociated)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.ErrorC(\"Unable to retrieve updated version document\", err, nil)\n\t\t\t\t\tos.Exit(1)\n\t\t\t\t}\n\n\t\t\t\t// Check dataset has been updated, next sub document should be copied across to current sub doc\n\t\t\t\tSo(updatedDataset.ID, ShouldEqual, ids.DatasetAssociated)\n\t\t\t\tSo(updatedDataset.Current.State, ShouldEqual, \"published\")\n\t\t\t\tSo(updatedDataset.Next.State, ShouldEqual, \"published\") // Check next subdoc still exists\n\t\t\t\tSo(updatedDataset, ShouldResemble, expectedDatasetResource(ids.DatasetAssociated, 0))\n\t\t\t})\n\t\t})\n\n\t\tif err := mongo.Teardown(docs...); err != nil {\n\t\t\tif err != mgo.ErrNotFound {\n\t\t\t\tlog.ErrorC(\"Was unable to remove test data\", err, nil)\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t}\n\n\t\tif err := neo4JStore.CleanUpInstance(ids.InstanceAssociated); err != nil {\n\t\t\tt.Errorf(\"failed to cleanup neo4j instances: [%v]\\n error: [%v]\\n\", ids.InstanceAssociated, err)\n\t\t\tt.FailNow()\n\t\t}\n\t})\n\n\tConvey(\"Given a published dataset and edition, and a version that has been associated\", t, func() {\n\t\tedition := \"2017\"\n\t\tversion := \"2\"\n\n\t\tdocs, err := setupResources(ids.DatasetPublished, ids.EditionPublished, edition, ids.InstanceAssociated, ids.UniqueTimestamp, 3)\n\t\tif err != nil {\n\t\t\tlog.ErrorC(\"Was unable to setup test data\", err, nil)\n\t\t\tos.Exit(1)\n\t\t}\n\n\t\tcount, err := neo4JStore.CreateInstanceNode(ids.InstanceAssociated)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"failed to create neo4j instance node: [%v]\\n error: [%v]\\n\", ids.InstanceAssociated, err)\n\t\t\tt.Fail()\n\t\t}\n\t\tSo(count, ShouldEqual, 1)\n\n\t\tConvey(\"When a PUT request to update version resource with a state of published\", func() {\n\t\t\tConvey(\"Then the dataset, edition and version resources are updated and returns a status ok (200)\", func() {\n\n\t\t\t\tdatasetAPI.PUT(\"/datasets/{id}/editions/{edition}/versions/{version}\", ids.DatasetPublished, edition, version).\n\t\t\t\t\tWithHeader(florenceTokenName, florenceToken).\n\t\t\t\t\tWithBytes([]byte(validPUTUpdateVersionToPublishedJSON)).\n\t\t\t\t\tExpect().Status(http.StatusOK)\n\n\t\t\t\tupdatedVersion, err := mongo.GetVersion(cfg.MongoDB, \"instances\", \"_id\", ids.InstanceAssociated)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.ErrorC(\"Unable to retrieve updated version document\", err, nil)\n\t\t\t\t\tos.Exit(1)\n\t\t\t\t}\n\n\t\t\t\t// Check version has been updated\n\t\t\t\tSo(updatedVersion.ID, ShouldEqual, ids.InstanceAssociated)\n\t\t\t\tSo(updatedVersion.State, ShouldEqual, \"published\")\n\n\t\t\t\tupdatedEdition, err := mongo.GetEdition(cfg.MongoDB, \"editions\", \"_id\", ids.EditionPublished)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.ErrorC(\"Unable to retrieve updated version document\", err, nil)\n\t\t\t\t\tos.Exit(1)\n\t\t\t\t}\n\n\t\t\t\t// Check edition has been updated\n\t\t\t\tSo(updatedEdition.ID, ShouldEqual, ids.EditionPublished)\n\t\t\t\tSo(updatedEdition.Next.State, ShouldEqual, \"published\")\n\t\t\t\tSo(updatedEdition.Current, ShouldNotBeNil)\n\t\t\t\tSo(updatedEdition.Current.State, ShouldEqual, \"published\")\n\t\t\t\tSo(updatedEdition.Current.Links.LatestVersion.ID, ShouldEqual, \"2\")\n\t\t\t\tSo(updatedEdition.Current.Links.LatestVersion.HRef, ShouldEqual, cfg.DatasetAPIURL+\"/datasets/\"+ids.DatasetPublished+\"/editions/2017/versions/2\")\n\n\t\t\t\tupdatedDataset, err := mongo.GetDataset(cfg.MongoDB, collection, \"_id\", ids.DatasetPublished)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.ErrorC(\"Unable to retrieve updated version document\", err, nil)\n\t\t\t\t\tos.Exit(1)\n\t\t\t\t}\n\n\t\t\t\t// Check dataset has been updated, next sub document should be copied across to current sub doc\n\t\t\t\tSo(updatedDataset.ID, ShouldEqual, ids.DatasetPublished)\n\t\t\t\tSo(updatedDataset.Current.State, ShouldEqual, \"published\")\n\t\t\t\tSo(updatedDataset.Next.State, ShouldEqual, \"published\") // Check next subdoc still exists\n\t\t\t\tSo(updatedDataset, ShouldResemble, expectedDatasetResource(ids.DatasetPublished, 1))\n\t\t\t})\n\t\t})\n\n\t\tif err := mongo.Teardown(docs...); err != nil {\n\t\t\tif err != mgo.ErrNotFound {\n\t\t\t\tlog.ErrorC(\"Was unable to remove test data\", err, nil)\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t}\n\n\t\tif err := neo4JStore.CleanUpInstance(ids.InstanceAssociated); err != nil {\n\t\t\tt.Errorf(\"failed to cleanup neo4j instances: [%v]\\n error: [%v]\\n\", ids.InstanceAssociated, err)\n\t\t\tt.FailNow()\n\t\t}\n\t})\n}", "func (m *MockInterface) ClusterGenevaLoggingConfigVersion() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ClusterGenevaLoggingConfigVersion\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func Test11(t *testing.T) {\n\tcustommutatingBaseCollection := mutatingBaseCollectionVersions.DeepCopy()\n\tnewCollection := mutatingBaseCollectionVersions.DeepCopy()\n\tcustommutatingBaseCollection.Spec.Version = \"1.2.4\"\n\tnewCollection.Spec.Version = \"1.2.4\"\n\tcustommutatingBaseCollection.Spec.Versions[0].Version = \"2.0.0\"\n\tnewCollection.Spec.Versions[0].Version = \"2.0.1\"\n\n\terr := processUpdate(custommutatingBaseCollection, newCollection)\n\tif err != nil {\n\t\tt.Fatal(\"Unexpected error during mutation.\", err)\n\t}\n\n\tif newCollection.Spec.RepositoryUrl != \"https://github.com/some/collection/kabanero-index.yaml\" {\n\t\tt.Fatal(\"New collection.Spec.RepositoryUrl values do not match expected value of https://github.com/some/collection/kabanero-index.yaml. RepositoryUrl found: \", newCollection.Spec.RepositoryUrl)\n\t}\n\tif newCollection.Spec.Version != \"2.0.1\" {\n\t\tt.Fatal(\"New collection.Spec.Version values do not match expected value of 1.2.3. Version found: \", newCollection.Spec.Version)\n\t}\n\tif newCollection.Spec.DesiredState != \"active\" {\n\t\tt.Fatal(\"New collection.Spec.DesiredState values do not match expected value of active. DesiredStateme found: \", newCollection.Spec.DesiredState)\n\t}\n}", "func TestSetGoodArgs(t *testing.T) {\n\tfmt.Println(\"Entering the test method for SetGoodArgs\")\n\tprovcc := new(SimpleAsset)\n\tstub := shim.NewMockStub(\"ANY_PARAM\", provcc)\n\n\t// Testing the init. It always return true. No parameters in init. \n\t\n\tcheckInit(t, stub, [][]byte{[]byte(\"init\")})\n\n\tres := stub.MockInvoke(\"1\", [][]byte{[]byte(\"set\"), []byte(\"S52fkpF2rCEArSuwqyDA9tVjawUdrkGzbNQLaa7xJfA=\"),\n\t[]byte(\"agentInfo.atype\"),[]byte(\"1.2.3.4\"),\n\t[]byte(\"agentInfo.id\"),[]byte(\"agentidentifier\"),\n\t[]byte(\"agentinfo.name\"),[]byte(\"7.8.9\"),\n\t[]byte(\"agentinfo.idp\"),[]byte(\"urn:tiani-spirit:sts\"),\n\t[]byte(\"locationInfo.id\"),[]byte(\"urn:oid:1.2.3\"),\n\t[]byte(\"locationInfo.name\"),[]byte(\"General Hospital\"),\n\t[]byte(\"locationInfo.locality\"),[]byte(\"Nashville, TN\"),\n\t[]byte(\"locationInfo.docid\"),[]byte(\"1.2.3\"),\n\t[]byte(\"action\"),[]byte(\"ex:CREATE\"),\n\t[]byte(\"date\"),[]byte(\"2018-11-10T12:15:55.028Z\")})\n\n\tif res.Status != shim.OK {\n\t\tfmt.Println(\"Invoke failed\", string(res.Message))\n\t\tt.FailNow()\n\t}\n\t\n}", "func Test4(t *testing.T) {\n\tnewCollection := mutatingBaseCollectionVersions.DeepCopy()\n\tnewCollection.Spec.RepositoryUrl = \"https://github.com/some/collection/alternate-kabanero-index.yaml\"\n\tnewCollection.Spec.Version = \"4.5.6\"\n\tnewCollection.Spec.DesiredState = \"inactive\"\n\terr := processUpdate(&mutatingBaseCollection, newCollection)\n\tif err != nil {\n\t\tt.Fatal(\"Unexpected error during mutation.\", err)\n\t}\n\n\texpectedversion0 := kabanerov1alpha1.CollectionVersion{\n\t\tRepositoryUrl: \"https://github.com/some/collection/alternate-kabanero-index.yaml\",\n\t\tVersion: \"4.5.6\",\n\t\tDesiredState: \"inactive\"}\n\n\tif newCollection.Spec.Versions[0] != expectedversion0 {\n\t\tt.Fatal(\"New collection.Spec.Versions[0] values do not match expected collection.Spec.Versions[0] values. New versions[0]: \", newCollection.Spec.Versions[0], \"Expected versions[0]: \", expectedversion0)\n\t}\n}", "func TestVersionSemVer(t *testing.T) {\n\tt.Logf(\"Testing version semantic (%s)\", Version)\n\tdetails := strings.Split(Version, \".\")\n\tif len(details) != 3 {\n\t\tt.Errorf(\"Version should provide major, minor and path informations: %s\", Version)\n\t}\n\tif _, err := strconv.ParseInt(details[0], 2, 0); err != nil {\n\t\tt.Errorf(err.Error())\n\t}\n\tif _, err := strconv.ParseInt(details[1], 2, 0); err != nil {\n\t\tt.Errorf(err.Error())\n\t}\n\n\tpatch := strings.Split(details[2], \"-\")\n\tif _, err := strconv.ParseInt(patch[0], 2, 0); err != nil {\n\t\tt.Errorf(err.Error())\n\t}\n\tif len(patch) > 2 {\n\t\tt.Error(\"last version part only provides patch number and pre-release info\")\n\n\t}\n}", "func TestTestVersion(t *testing.T) {\n\tif testVersion != targetTestVersion {\n\t\tt.Fatalf(\"Found testVersion = %v, want %v\", testVersion, targetTestVersion)\n\t}\n}", "func (m *MockDatasetClient) GetVersion(ctx context.Context, userAuthToken, serviceAuthToken, downloadServiceToken, collectionID, datasetID, edition, version string) (dataset.Version, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetVersion\", ctx, userAuthToken, serviceAuthToken, downloadServiceToken, collectionID, datasetID, edition, version)\n\tret0, _ := ret[0].(dataset.Version)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockManager) GetLoadedAppnetVersion() (string, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetLoadedAppnetVersion\")\n\tret0, _ := ret[0].(string)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func TestSingleCommit4A(t *testing.T) {\n}", "func Test10(t *testing.T) {\n\tcustommutatingBaseCollection := mutatingBaseCollectionVersions.DeepCopy()\n\tnewCollection := mutatingBaseCollectionVersions.DeepCopy()\n\tcustommutatingBaseCollection.Spec.Version = \"1.2.4\"\n\tnewCollection.Spec.Version = \"1.2.5\"\n\tcustommutatingBaseCollection.Spec.Versions[0].Version = \"2.0.0\"\n\tnewCollection.Spec.Versions[0].Version = \"2.0.0\"\n\n\terr := processUpdate(custommutatingBaseCollection, newCollection)\n\tif err != nil {\n\t\tt.Fatal(\"Unexpected error during mutation.\", err)\n\t}\n\n\texpectedversion0 := kabanerov1alpha1.CollectionVersion{\n\t\tDesiredState: \"active\",\n\t\tRepositoryUrl: \"https://github.com/some/collection/kabanero-index.yaml\",\n\t\tVersion: \"1.2.5\"}\n\n\tif newCollection.Spec.Versions[0] != expectedversion0 {\n\t\tt.Fatal(\"New collection.Spec.Versions[0] values do not match expected collection.Spec.Versions[0] values. New versions[0]: \", newCollection.Spec.Versions[0], \"Expected versions[0]: \", expectedversion0)\n\t}\n}", "func TestMakePublicService(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\tsks *v1alpha1.ServerlessService\n\t\twant *corev1.Service\n\t}{{\n\t\tname: \"HTTP - serve\",\n\t\tsks: &v1alpha1.ServerlessService{\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tNamespace: \"melon\",\n\t\t\t\tName: \"collie\",\n\t\t\t\tUID: \"1982\",\n\t\t\t\t// Those labels are propagated from the Revision->PA.\n\t\t\t\tLabels: map[string]string{\n\t\t\t\t\tserving.RevisionLabelKey: \"collie\",\n\t\t\t\t\tserving.RevisionUID: \"1982\",\n\t\t\t\t},\n\t\t\t},\n\t\t\tSpec: v1alpha1.ServerlessServiceSpec{\n\t\t\t\tProtocolType: networking.ProtocolHTTP1,\n\t\t\t\tMode: v1alpha1.SKSOperationModeServe,\n\t\t\t},\n\t\t},\n\t\twant: &corev1.Service{\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tNamespace: \"melon\",\n\t\t\t\tName: \"collie\",\n\t\t\t\tLabels: map[string]string{\n\t\t\t\t\t// Those should be propagated.\n\t\t\t\t\tserving.RevisionLabelKey: \"collie\",\n\t\t\t\t\tserving.RevisionUID: \"1982\",\n\t\t\t\t\tnetworking.SKSLabelKey: \"collie\",\n\t\t\t\t\tnetworking.ServiceTypeKey: \"Public\",\n\t\t\t\t},\n\t\t\t\tAnnotations: map[string]string{},\n\t\t\t\tOwnerReferences: []metav1.OwnerReference{{\n\t\t\t\t\tAPIVersion: v1alpha1.SchemeGroupVersion.String(),\n\t\t\t\t\tKind: \"ServerlessService\",\n\t\t\t\t\tName: \"collie\",\n\t\t\t\t\tUID: \"1982\",\n\t\t\t\t\tController: ptr.Bool(true),\n\t\t\t\t\tBlockOwnerDeletion: ptr.Bool(true),\n\t\t\t\t}},\n\t\t\t},\n\t\t\tSpec: corev1.ServiceSpec{\n\t\t\t\tPorts: []corev1.ServicePort{{\n\t\t\t\t\tName: networking.ServicePortNameHTTP1,\n\t\t\t\t\tProtocol: corev1.ProtocolTCP,\n\t\t\t\t\tPort: networking.ServiceHTTPPort,\n\t\t\t\t\tTargetPort: intstr.FromInt(networking.BackendHTTPPort),\n\t\t\t\t}},\n\t\t\t},\n\t\t},\n\t}, {\n\t\tname: \"HTTP - proxy\",\n\t\tsks: &v1alpha1.ServerlessService{\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tNamespace: \"melon\",\n\t\t\t\tName: \"collie\",\n\t\t\t\tUID: \"1982\",\n\t\t\t\t// Those labels are propagated from the Revision->PA.\n\t\t\t\tLabels: map[string]string{\n\t\t\t\t\tserving.RevisionLabelKey: \"collie\",\n\t\t\t\t\tserving.RevisionUID: \"1982\",\n\t\t\t\t},\n\t\t\t},\n\t\t\tSpec: v1alpha1.ServerlessServiceSpec{\n\t\t\t\tMode: v1alpha1.SKSOperationModeProxy,\n\t\t\t\tProtocolType: networking.ProtocolHTTP1,\n\t\t\t},\n\t\t},\n\t\twant: &corev1.Service{\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tNamespace: \"melon\",\n\t\t\t\tName: \"collie\",\n\t\t\t\tLabels: map[string]string{\n\t\t\t\t\t// Those should be propagated.\n\t\t\t\t\tserving.RevisionLabelKey: \"collie\",\n\t\t\t\t\tserving.RevisionUID: \"1982\",\n\t\t\t\t\tnetworking.SKSLabelKey: \"collie\",\n\t\t\t\t\tnetworking.ServiceTypeKey: \"Public\",\n\t\t\t\t},\n\t\t\t\tAnnotations: map[string]string{},\n\t\t\t\tOwnerReferences: []metav1.OwnerReference{{\n\t\t\t\t\tAPIVersion: v1alpha1.SchemeGroupVersion.String(),\n\t\t\t\t\tKind: \"ServerlessService\",\n\t\t\t\t\tName: \"collie\",\n\t\t\t\t\tUID: \"1982\",\n\t\t\t\t\tController: ptr.Bool(true),\n\t\t\t\t\tBlockOwnerDeletion: ptr.Bool(true),\n\t\t\t\t}},\n\t\t\t},\n\t\t\tSpec: corev1.ServiceSpec{\n\t\t\t\tPorts: []corev1.ServicePort{{\n\t\t\t\t\tName: networking.ServicePortNameHTTP1,\n\t\t\t\t\tProtocol: corev1.ProtocolTCP,\n\t\t\t\t\tPort: networking.ServiceHTTPPort,\n\t\t\t\t\tTargetPort: intstr.FromInt(networking.BackendHTTPPort),\n\t\t\t\t}},\n\t\t\t},\n\t\t},\n\t}, {\n\t\tname: \"HTTP2 - serve\",\n\t\tsks: &v1alpha1.ServerlessService{\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tNamespace: \"siamese\",\n\t\t\t\tName: \"dream\",\n\t\t\t\tUID: \"1988\",\n\t\t\t\t// Those labels are propagated from the Revision->PA.\n\t\t\t\tLabels: map[string]string{\n\t\t\t\t\tserving.RevisionLabelKey: \"dream\",\n\t\t\t\t\tserving.RevisionUID: \"1988\",\n\t\t\t\t},\n\t\t\t\tAnnotations: map[string]string{\n\t\t\t\t\t\"cherub\": \"rock\",\n\t\t\t\t},\n\t\t\t},\n\t\t\tSpec: v1alpha1.ServerlessServiceSpec{\n\t\t\t\tProtocolType: networking.ProtocolH2C,\n\t\t\t\tMode: v1alpha1.SKSOperationModeServe,\n\t\t\t},\n\t\t},\n\t\twant: &corev1.Service{\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tNamespace: \"siamese\",\n\t\t\t\tName: \"dream\",\n\t\t\t\tLabels: map[string]string{\n\t\t\t\t\t// Those should be propagated.\n\t\t\t\t\tserving.RevisionLabelKey: \"dream\",\n\t\t\t\t\tserving.RevisionUID: \"1988\",\n\t\t\t\t\tnetworking.SKSLabelKey: \"dream\",\n\t\t\t\t\tnetworking.ServiceTypeKey: \"Public\",\n\t\t\t\t},\n\t\t\t\tAnnotations: map[string]string{\n\t\t\t\t\t\"cherub\": \"rock\",\n\t\t\t\t},\n\t\t\t\tOwnerReferences: []metav1.OwnerReference{{\n\t\t\t\t\tAPIVersion: v1alpha1.SchemeGroupVersion.String(),\n\t\t\t\t\tKind: \"ServerlessService\",\n\t\t\t\t\tName: \"dream\",\n\t\t\t\t\tUID: \"1988\",\n\t\t\t\t\tController: ptr.Bool(true),\n\t\t\t\t\tBlockOwnerDeletion: ptr.Bool(true),\n\t\t\t\t}},\n\t\t\t},\n\t\t\tSpec: corev1.ServiceSpec{\n\t\t\t\tPorts: []corev1.ServicePort{{\n\t\t\t\t\tName: networking.ServicePortNameH2C,\n\t\t\t\t\tProtocol: corev1.ProtocolTCP,\n\t\t\t\t\tPort: networking.ServiceHTTP2Port,\n\t\t\t\t\tTargetPort: intstr.FromInt(networking.BackendHTTP2Port),\n\t\t\t\t}},\n\t\t\t},\n\t\t},\n\t}, {\n\t\tname: \"HTTP2 - serve - no backends\",\n\t\tsks: &v1alpha1.ServerlessService{\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tNamespace: \"siamese\",\n\t\t\t\tName: \"dream\",\n\t\t\t\tUID: \"1988\",\n\t\t\t\t// Those labels are propagated from the Revision->PA.\n\t\t\t\tLabels: map[string]string{\n\t\t\t\t\tserving.RevisionLabelKey: \"dream\",\n\t\t\t\t\tserving.RevisionUID: \"1988\",\n\t\t\t\t},\n\t\t\t\tAnnotations: map[string]string{\n\t\t\t\t\t\"cherub\": \"rock\",\n\t\t\t\t},\n\t\t\t},\n\t\t\tSpec: v1alpha1.ServerlessServiceSpec{\n\t\t\t\tProtocolType: networking.ProtocolH2C,\n\t\t\t\tMode: v1alpha1.SKSOperationModeServe,\n\t\t\t},\n\t\t},\n\t\twant: &corev1.Service{\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tNamespace: \"siamese\",\n\t\t\t\tName: \"dream\",\n\t\t\t\tLabels: map[string]string{\n\t\t\t\t\t// Those should be propagated.\n\t\t\t\t\tserving.RevisionLabelKey: \"dream\",\n\t\t\t\t\tserving.RevisionUID: \"1988\",\n\t\t\t\t\tnetworking.SKSLabelKey: \"dream\",\n\t\t\t\t\tnetworking.ServiceTypeKey: \"Public\",\n\t\t\t\t},\n\t\t\t\tAnnotations: map[string]string{\n\t\t\t\t\t\"cherub\": \"rock\",\n\t\t\t\t},\n\t\t\t\tOwnerReferences: []metav1.OwnerReference{{\n\t\t\t\t\tAPIVersion: v1alpha1.SchemeGroupVersion.String(),\n\t\t\t\t\tKind: \"ServerlessService\",\n\t\t\t\t\tName: \"dream\",\n\t\t\t\t\tUID: \"1988\",\n\t\t\t\t\tController: ptr.Bool(true),\n\t\t\t\t\tBlockOwnerDeletion: ptr.Bool(true),\n\t\t\t\t}},\n\t\t\t},\n\t\t\tSpec: corev1.ServiceSpec{\n\t\t\t\tPorts: []corev1.ServicePort{{\n\t\t\t\t\tName: networking.ServicePortNameH2C,\n\t\t\t\t\tProtocol: corev1.ProtocolTCP,\n\t\t\t\t\tPort: networking.ServiceHTTP2Port,\n\t\t\t\t\tTargetPort: intstr.FromInt(networking.BackendHTTP2Port),\n\t\t\t\t}},\n\t\t\t},\n\t\t},\n\t}, {\n\t\tname: \"HTTP2 - proxy\",\n\t\tsks: &v1alpha1.ServerlessService{\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tNamespace: \"siamese\",\n\t\t\t\tName: \"dream\",\n\t\t\t\tUID: \"1988\",\n\t\t\t\t// Those labels are propagated from the Revision->PA.\n\t\t\t\tLabels: map[string]string{\n\t\t\t\t\tserving.RevisionLabelKey: \"dream\",\n\t\t\t\t\tserving.RevisionUID: \"1988\",\n\t\t\t\t},\n\t\t\t\tAnnotations: map[string]string{\n\t\t\t\t\t\"cherub\": \"rock\",\n\t\t\t\t},\n\t\t\t},\n\t\t\tSpec: v1alpha1.ServerlessServiceSpec{\n\t\t\t\tProtocolType: networking.ProtocolH2C,\n\t\t\t\tMode: v1alpha1.SKSOperationModeProxy,\n\t\t\t},\n\t\t},\n\t\twant: &corev1.Service{\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tNamespace: \"siamese\",\n\t\t\t\tName: \"dream\",\n\t\t\t\tLabels: map[string]string{\n\t\t\t\t\t// Those should be propagated.\n\t\t\t\t\tserving.RevisionLabelKey: \"dream\",\n\t\t\t\t\tserving.RevisionUID: \"1988\",\n\t\t\t\t\tnetworking.SKSLabelKey: \"dream\",\n\t\t\t\t\tnetworking.ServiceTypeKey: \"Public\",\n\t\t\t\t},\n\t\t\t\tAnnotations: map[string]string{\n\t\t\t\t\t\"cherub\": \"rock\",\n\t\t\t\t},\n\t\t\t\tOwnerReferences: []metav1.OwnerReference{{\n\t\t\t\t\tAPIVersion: v1alpha1.SchemeGroupVersion.String(),\n\t\t\t\t\tKind: \"ServerlessService\",\n\t\t\t\t\tName: \"dream\",\n\t\t\t\t\tUID: \"1988\",\n\t\t\t\t\tController: ptr.Bool(true),\n\t\t\t\t\tBlockOwnerDeletion: ptr.Bool(true),\n\t\t\t\t}},\n\t\t\t},\n\t\t\tSpec: corev1.ServiceSpec{\n\t\t\t\tPorts: []corev1.ServicePort{{\n\t\t\t\t\tName: networking.ServicePortNameH2C,\n\t\t\t\t\tProtocol: corev1.ProtocolTCP,\n\t\t\t\t\tPort: networking.ServiceHTTP2Port,\n\t\t\t\t\tTargetPort: intstr.FromInt(networking.BackendHTTP2Port),\n\t\t\t\t}},\n\t\t\t},\n\t\t},\n\t}}\n\n\tfor _, test := range tests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tgot := MakePublicService(test.sks)\n\t\t\tif diff := cmp.Diff(test.want, got); diff != \"\" {\n\t\t\t\tt.Errorf(\"Public K8s Service mismatch (-want, +got) = %v\", diff)\n\t\t\t}\n\t\t})\n\t}\n}" ]
[ "0.68449587", "0.6694633", "0.66058457", "0.6596282", "0.6554341", "0.6468374", "0.6429601", "0.64212376", "0.6420173", "0.636126", "0.63060135", "0.6267418", "0.624314", "0.624108", "0.61913735", "0.61460763", "0.6129149", "0.60969746", "0.6089816", "0.6028361", "0.60138357", "0.5991385", "0.5922671", "0.58900845", "0.58796644", "0.587578", "0.5841241", "0.5830459", "0.5807635", "0.580407", "0.5754645", "0.5702492", "0.56809115", "0.5612201", "0.55279845", "0.5525852", "0.54962116", "0.54956686", "0.549302", "0.54763865", "0.5454105", "0.5445004", "0.5420968", "0.5396739", "0.5394302", "0.5393103", "0.5365037", "0.53603274", "0.5350917", "0.53377414", "0.53178996", "0.5316433", "0.53113383", "0.5311231", "0.52907914", "0.5278949", "0.5277283", "0.52748245", "0.52744323", "0.5262264", "0.52491844", "0.5247745", "0.5236845", "0.52323794", "0.5231651", "0.52288467", "0.522506", "0.5222593", "0.5219", "0.5215394", "0.52131665", "0.5204031", "0.51984966", "0.51905954", "0.51881397", "0.51871705", "0.5183752", "0.51734525", "0.5169144", "0.5169089", "0.51680225", "0.51469404", "0.51450187", "0.5134941", "0.51341605", "0.51332", "0.5129681", "0.51283544", "0.512565", "0.51244485", "0.5124119", "0.5120538", "0.5118445", "0.509746", "0.50913787", "0.5090675", "0.5089528", "0.50892943", "0.5083952", "0.50821096" ]
0.71553564
0
PublicVersion indicates an expected call of PublicVersion
func (mr *MockClientMockRecorder) PublicVersion() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PublicVersion", reflect.TypeOf((*MockClient)(nil).PublicVersion)) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func isBadVersion(version int) bool{\n return false\n}", "func (m *MockClient) PublicVersion() msp.Identity {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"PublicVersion\")\n\tret0, _ := ret[0].(msp.Identity)\n\treturn ret0\n}", "func TestVersion(t *testing.T) {\n\t//fmt.Println(\"EliteProvision [\" + Version() + \"]\")\n}", "func TestVersion(t *testing.T) {\n\tvers := Version()\n\tif len(vers) == 0 {\n\t\tt.Error(\"version string is not present\")\n\t}\n}", "func Public(statusCode int, err error) error {\n\treturn Value{\n\t\tPublic: true,\n\t\tStatusCode: statusCode,\n\t\tErr: err,\n\t}\n}", "func TestRootMetadataLatestKeyGenerationPublic(t *testing.T) {\n\ttlfID := tlf.FakeID(0, true)\n\th := makeFakeTlfHandle(t, 14, true, nil, nil)\n\trmd, err := makeInitialRootMetadata(defaultClientMetadataVer, tlfID, h)\n\trequire.NoError(t, err)\n\n\tif rmd.LatestKeyGeneration() != PublicKeyGen {\n\t\tt.Errorf(\"Expected key generation to be public (%d)\", PublicKeyGen)\n\t}\n}", "func MyFunc() {\n\tfmt.Println(\"Checking package public func\")\n}", "func isBadVersion(version int) bool{\n\treturn true\n}", "func (CreatedV1) Version() uint64 {\n\treturn 1\n}", "func (b *GroupsEditBuilder) PublicDate(v string) *GroupsEditBuilder {\n\tb.Params[\"public_date\"] = v\n\treturn b\n}", "func TestGetSemverVersisonWithNonStandardVersion(t *testing.T) {\n\tversion.Map[\"version\"] = \"1.3.153-dev+7a8285f4\"\n\tresult, err := version.GetSemverVersion()\n\n\tprVersions := []semver.PRVersion{{VersionStr: \"dev\"}}\n\tbuilds := []string{\"7a8285f4\"}\n\texpectedResult := semver.Version{Major: 1, Minor: 3, Patch: 153, Pre: prVersions, Build: builds}\n\tassert.NoError(t, err, \"GetSemverVersion should exit without failure\")\n\tassert.Exactly(t, expectedResult, result)\n}", "func TestVersion(t *testing.T) {\n\tfor _, v := range versionTests {\n\t\tp, e := model.ParseVersion(v[0])\n\t\tassert.Nil(t, e, \"Should have parsed %s\", v)\n\t\tassert.Equal(t, p.String(), v[1], \"Should be equal %s==%s\", p.String(), v)\n\t}\n}", "func (mr *MockSignerDecrypterMockRecorder) Public() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Public\", reflect.TypeOf((*MockSignerDecrypter)(nil).Public))\n}", "func (u *walletIdentity) PublicVersion() msp.Identity {\n\treturn u\n}", "func (o *APICheck) Version() int {\n\n\treturn 1\n}", "func NewPublic(msg string) error {\n\treturn &publicError{publicMessage: msg}\n}", "func (standardGo) Version() float64 {\n\treturn 0\n}", "func PublicWrap(err error, publicMsg string) error {\n\tif err == nil {\n\t\treturn nil\n\t}\n\treturn &publicError{cause: err, publicMessage: publicMsg}\n}", "func UnmarshalPublicCertificateVersion(m map[string]json.RawMessage, result interface{}) (err error) {\n\tobj := new(PublicCertificateVersion)\n\terr = core.UnmarshalPrimitive(m, \"auto_rotated\", &obj.AutoRotated)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalPrimitive(m, \"created_by\", &obj.CreatedBy)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalPrimitive(m, \"created_at\", &obj.CreatedAt)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalPrimitive(m, \"downloaded\", &obj.Downloaded)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalPrimitive(m, \"id\", &obj.ID)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalPrimitive(m, \"secret_name\", &obj.SecretName)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalPrimitive(m, \"secret_type\", &obj.SecretType)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalPrimitive(m, \"secret_group_id\", &obj.SecretGroupID)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalPrimitive(m, \"payload_available\", &obj.PayloadAvailable)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalPrimitive(m, \"alias\", &obj.Alias)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalPrimitive(m, \"version_custom_metadata\", &obj.VersionCustomMetadata)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalPrimitive(m, \"secret_id\", &obj.SecretID)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalPrimitive(m, \"expiration_date\", &obj.ExpirationDate)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalPrimitive(m, \"serial_number\", &obj.SerialNumber)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalModel(m, \"validity\", &obj.Validity, UnmarshalCertificateValidity)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalPrimitive(m, \"certificate\", &obj.Certificate)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalPrimitive(m, \"intermediate\", &obj.Intermediate)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalPrimitive(m, \"private_key\", &obj.PrivateKey)\n\tif err != nil {\n\t\treturn\n\t}\n\treflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj))\n\treturn\n}", "func TestAPIVersionsSimple(t *testing.T) {\n\tv201, err := semver.Make(\"2.0.1\")\n\tassert.Nil(t, err)\n\tv300, err := semver.Make(\"3.0.0\")\n\tassert.Nil(t, err)\n\tv312, err := semver.Make(\"3.1.2\")\n\tassert.Nil(t, err)\n\tv314, err := semver.Make(\"3.1.4\")\n\tassert.Nil(t, err)\n\tv317, err := semver.Make(\"3.1.7\")\n\tassert.Nil(t, err)\n\tv400, err := semver.Make(\"4.0.0\")\n\tassert.Nil(t, err)\n\n\tassert.True(t, v312.LT(v314))\n\tassert.True(t, v312.LT(v317))\n\n\tsingleRange, err := semver.ParseRange(\"3.1.4\")\n\tassert.True(t, singleRange(v314))\n\n\tmultiRange, err := semver.ParseRange(\">=3.1.4 <=3.1.8\")\n\tassert.True(t, multiRange(v317))\n\tassert.False(t, multiRange(v312))\n\tassert.False(t, multiRange(v400))\n\n\tanotherRange, err := semver.ParseRange(\">=3.1.0\")\n\tassert.True(t, anotherRange(v400))\n\tassert.False(t, anotherRange(v300))\n\tassert.False(t, anotherRange(v201))\n\n}", "func (o *SyntheticsBrowserTest) GetPublicIdOk() (*string, bool) {\n\tif o == nil || o.PublicId == nil {\n\t\treturn nil, false\n\t}\n\treturn o.PublicId, true\n}", "func (c *HTTPClientMock) APIKeyPublic() string {\n\treturn c.apiKeyPublic\n}", "func (mr *MockCandidatePropertyGetterMockRecorder) IsPublic() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"IsPublic\", reflect.TypeOf((*MockCandidatePropertyGetter)(nil).IsPublic))\n}", "func isBeforeV1(version string) bool {\r\n\treturn semver.IsValid(version) && semver.Compare(version, \"v1.0.0\") < 0\r\n}", "func (p Reviewer) Version() (int, int, int) {\n return 0,0,0\n}", "func (o *NiaapiNewReleaseDetailAllOf) GetVersionOk() (*string, bool) {\n\tif o == nil || o.Version == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Version, true\n}", "func CheckPublic(url string) (bool, error) {\n\tcode, _, err := fetchPage(url)\n\tif err != nil {\n\t\treturn true, err\n\t}\n\tif code/100 == 4 {\n\t\treturn false, nil\n\t}\n\n\treturn true, nil\n}", "func TestVersion(t *testing.T) {\n\t// Get Vault client\n\tvaultClientConfig := vault.DefaultConfig()\n\tvaultClientConfig.Address = vaultAddress\n\tv, err := vault.NewClient(vaultClientConfig)\n\tif err != nil {\n\t\tt.Fatalf(err.Error())\n\t}\n\tv.SetToken(\"root\")\n\tvl := v.Logical()\n\n\t// Get Pachyderm version from plugin\n\tsecret, err := vl.Read(\"/pachyderm/version\")\n\tif err != nil {\n\t\tt.Fatalf(err.Error())\n\t}\n\tif _, ok := secret.Data[\"client-version\"]; !ok {\n\t\tt.Fatalf(\"could not get client version from Pachyderm plugin\")\n\t}\n\tif _, ok := secret.Data[\"server-version\"]; !ok {\n\t\tt.Fatalf(\"could not get server version from Pachyderm plugin\")\n\t}\n\n\t// Test client-only endpoint\n\tsecret, err = vl.Read(\"/pachyderm/version/client-only\")\n\tif _, ok := secret.Data[\"client-version\"]; !ok {\n\t\tt.Fatalf(\"could not get client version from Pachyderm plugin (client-only)\")\n\t}\n\tif _, ok := secret.Data[\"server-version\"]; ok {\n\t\tt.Fatalf(\"got unexpected server version from Pachyderm plugin (client-only)\")\n\t}\n}", "func (o *SparseAPICheck) Version() int {\n\n\treturn 1\n}", "func _isValidFileVersion(v FileVersion) bool {\n\tif v.Format == nil {\n\t\treturn false\n\t}\n\tif v.Link == \"\" {\n\t\treturn false\n\t}\n\treturn true\n}", "func IsPublic(request *http.Request) bool {\n\tif request == nil {\n\t\treturn true\n\t}\n\t//when condition is true then it is public\n\treturn request.Header.Get(headerXPublic) == \"true\"\n}", "func IsPubliclyKnown(publicPath string) bool {\n\treturn publicKnownFiles[publicPath] != false\n}", "func TestGetVersions4A(t *testing.T) {\n}", "func version() {\n fmt.Printf(\"v%s\\ncommit=%s\\n\", versionNumber, commitId)\n}", "func (cmr *ConsumerMetadataRequest) Version() int16 {\n\treturn 0\n}", "func (api *PrivateExtensionAPI) checkIfPublicContract(toExtend common.Address) (bool, error) {\n\t// check if the passed contract is public contract\n\tchain := api.privacyService.stateFetcher.chainAccessor\n\tpublicStateDb, _, err := chain.StateAtPSI(chain.CurrentBlock().Root(), types.DefaultPrivateStateIdentifier)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\treturn publicStateDb != nil && publicStateDb.Exist(toExtend), nil\n}", "func ValidateTransactionVersion(transactionVersion uint32) (bool) {\n if transactionVersion == 1 { //current transaction version\n return true\n }\n return false\n}", "func (c Initializer) VerifyServedVersion(client *kube.Client, expectedVersion string, result *verifier.Result) error {\n\tapiClient := client.ExtClient.ApiextensionsV1()\n\tif err := c.verifyServedVersion(apiClient, c.Operator.Name, expectedVersion, result); err != nil {\n\t\treturn err\n\t}\n\tif err := c.verifyServedVersion(apiClient, c.OperatorVersion.Name, expectedVersion, result); err != nil {\n\t\treturn err\n\t}\n\tif err := c.verifyServedVersion(apiClient, c.Instance.Name, expectedVersion, result); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (a *Client) VersionNoop(params *VersionNoopParams, authInfo runtime.ClientAuthInfoWriter) (*VersionNoopOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewVersionNoopParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"version_noop\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/version\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"http\", \"https\"},\n\t\tParams: params,\n\t\tReader: &VersionNoopReader{formats: a.formats},\n\t\tAuthInfo: authInfo,\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsuccess, ok := result.(*VersionNoopOK)\n\tif ok {\n\t\treturn success, nil\n\t}\n\t// unexpected success response\n\t// safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue\n\tmsg := fmt.Sprintf(\"unexpected success response for version_noop: API contract not enforced by server. Client expected to get an error, but got: %T\", result)\n\tpanic(msg)\n}", "func PublicFunc() string {\n\treturn \"foo\"\n}", "func (p *Peer) VersionKnown() bool {\n\tp.flagsMtx.Lock()\n\tversionKnown := p.versionKnown\n\tp.flagsMtx.Unlock()\n\n\treturn versionKnown\n}", "func TestVersion(t *testing.T) {\n\tassert := audit.NewTestingAssertion(t, true)\n\t// Setup the test server.\n\tmux := newMultiplexer(assert)\n\tts := restaudit.StartServer(mux, assert)\n\tdefer ts.Close()\n\terr := mux.Register(\"test\", \"json\", NewTestHandler(\"json\", assert))\n\tassert.Nil(err)\n\t// Perform test requests.\n\treq := restaudit.NewRequest(\"GET\", \"/base/test/json/4711?foo=0815\")\n\treq.AddHeader(restaudit.HeaderAccept, restaudit.ApplicationJSON)\n\tresp := ts.DoRequest(req)\n\tresp.AssertStatusEquals(200)\n\tresp.AssertHeaderEquals(\"Version\", \"1.0.0\")\n\n\treq = restaudit.NewRequest(\"GET\", \"/base/test/json/4711?foo=0815\")\n\treq.AddHeader(restaudit.HeaderAccept, restaudit.ApplicationJSON)\n\treq.AddHeader(\"Version\", \"2\")\n\tresp = ts.DoRequest(req)\n\tresp.AssertStatusEquals(200)\n\tresp.AssertHeaderEquals(\"Version\", \"2.0.0\")\n\n\treq = restaudit.NewRequest(\"GET\", \"/base/test/json/4711?foo=0815\")\n\treq.AddHeader(restaudit.HeaderAccept, restaudit.ApplicationJSON)\n\treq.AddHeader(\"Version\", \"3.0\")\n\tresp = ts.DoRequest(req)\n\tresp.AssertStatusEquals(200)\n\tresp.AssertHeaderEquals(\"Version\", \"4.0.0-alpha\")\n}", "func TestClientVersion(t *testing.T) {\n\t// t.SkipNow()\n\tet := testutil.GetETH()\n\n\tclientVersion, err := et.ClientVersion()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tt.Log(\"clientVersion:\", clientVersion)\n}", "func (o *NetworkElementSummaryAllOf) GetVersionOk() (*string, bool) {\n\tif o == nil || o.Version == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Version, true\n}", "func (k *EnterpriseCertSigner) Public(ignored struct{}, publicKey *[]byte) (err error) {\n\tif len(k.cert.Certificate) == 0 {\n\t\treturn nil\n\t}\n\tcert, err := x509.ParseCertificate(k.cert.Certificate[0])\n\tif err != nil {\n\t\treturn err\n\t}\n\t*publicKey, err = x509.MarshalPKIXPublicKey(cert.PublicKey)\n\treturn err\n}", "func mustMakePubliclyViewableParams(fsc *frontendServerConfig) publicparams.Matcher {\n\tvar publiclyViewableParams publicparams.Matcher\n\tvar err error\n\n\t// Load the publiclyViewable params if configured and disable querying for issues.\n\tif len(fsc.PubliclyAllowableParams) > 0 {\n\t\tif publiclyViewableParams, err = publicparams.MatcherFromRules(fsc.PubliclyAllowableParams); err != nil {\n\t\t\tsklog.Fatalf(\"Could not load list of public params: %s\", err)\n\t\t}\n\t}\n\n\t// Check if this is public instance. If so, make sure we have a non-nil Matcher.\n\tif fsc.IsPublicView && publiclyViewableParams == nil {\n\t\tsklog.Fatal(\"A non-empty map of publiclyViewableParams must be provided if is public view.\")\n\t}\n\n\treturn publiclyViewableParams\n}", "func (s NodeKeySignature) UnverifiedWrappingPublic() (pub ed25519.PublicKey, ok bool) {\n\treturn s.wrappingPublic()\n}", "func (o SparseAPIChecksList) Version() int {\n\n\treturn 1\n}", "func (a *Client) Version(params *VersionParams) (*VersionOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewVersionParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"Version\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/version\",\n\t\tProducesMediaTypes: []string{\"text/plain\"},\n\t\tConsumesMediaTypes: []string{\"text/plain\"},\n\t\tSchemes: []string{\"http\", \"https\"},\n\t\tParams: params,\n\t\tReader: &VersionReader{formats: a.formats},\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsuccess, ok := result.(*VersionOK)\n\tif ok {\n\t\treturn success, nil\n\t}\n\t// unexpected success response\n\tunexpectedSuccess := result.(*VersionDefault)\n\treturn nil, runtime.NewAPIError(\"unexpected success response: content available as default response in error\", unexpectedSuccess, unexpectedSuccess.Code())\n}", "func (o *KanbanViewView) GetPublicOk() (*bool, bool) {\n\tif o == nil || IsNil(o.Public) {\n\t\treturn nil, false\n\t}\n\treturn o.Public, true\n}", "func (FirstNameUpdatedV1) Version() uint64 {\n\treturn 1\n}", "func (o *NSQProducer) GetVersionOk() (*string, bool) {\n\tif o == nil || o.Version == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Version, true\n}", "func (HeaderV2) Version() int { return 2 }", "func (o *GridViewUpdate) GetPublicOk() (*bool, bool) {\n\tif o == nil || IsNil(o.Public) {\n\t\treturn nil, false\n\t}\n\treturn o.Public, true\n}", "func (o *SparseEnforcerReport) Version() int {\n\n\treturn 1\n}", "func (o *SparseOAUTHKey) Version() int {\n\n\treturn 1\n}", "func Version(remote, detail bool) {\n\n\tdefer func() {\n\t\tif err := recover(); err != nil {\n\t\t\tmsg := fmt.Sprintf(\"'%v' an error has occurred. please check. \\nError: \", \"gnvm version -r\")\n\t\t\tError(ERROR, msg, err)\n\t\t\tos.Exit(0)\n\t\t}\n\t}()\n\n\tlocalVersion, arch := config.VERSION, \"32 bit\"\n\tif runtime.GOARCH == \"amd64\" {\n\t\tarch = \"64 bit\"\n\t}\n\n\tcp := CP{Red, true, None, true, \"Kenshin Wang\"}\n\tcp1 := CP{Red, true, None, true, \"fallenwood\"}\n\tP(DEFAULT, \"Current version %v %v.\", localVersion, arch, \"\\n\")\n\tP(DEFAULT, \"Copyright (C) 2014-2016 %v <kenshin@ksria.com>\", cp, \"\\n\")\n\tP(DEFAULT, \"Copyright (C) 2022 %v <fallenwood@foxmail.com>\", cp1, \"\\n\")\n\tcp.FgColor, cp.Value = Blue, \"https://github.com/fallenwood/gnvm\"\n\tP(DEFAULT, \"See %v for more information.\", cp, \"\\n\")\n\n\tif !remote {\n\t\treturn\n\t}\n\n\tcode, res, err := curl.Get(\"http://ksria.com/gnvm/CHANGELOG.md\")\n\tif code != 0 {\n\t\tpanic(err)\n\t}\n\tdefer res.Body.Close()\n\n\tversionFunc := func(content string, line int) bool {\n\t\tif content != \"\" && line == 1 {\n\t\t\tarr := strings.Fields(content)\n\t\t\tif len(arr) == 2 {\n\n\t\t\t\tcp := CP{Red, true, None, true, arr[0][1:]}\n\t\t\t\tP(DEFAULT, \"Latest version %v, publish data %v\", cp, arr[1], \"\\n\")\n\n\t\t\t\tlatestVersion, msg := arr[0][1:], \"\"\n\t\t\t\tlocalArr, latestArr := strings.Split(localVersion, \".\"), strings.Split(latestVersion, \".\")\n\n\t\t\t\tswitch {\n\t\t\t\tcase latestArr[0] > localArr[0]:\n\t\t\t\t\tmsg = \"must be upgraded.\"\n\t\t\t\tcase latestArr[1] > localArr[1]:\n\t\t\t\t\tmsg = \"suggest to upgrade.\"\n\t\t\t\tcase latestArr[2] > localArr[2]:\n\t\t\t\t\tmsg = \"optional upgrade.\"\n\t\t\t\t}\n\n\t\t\t\tif msg != \"\" {\n\t\t\t\t\tP(NOTICE, msg+\" Please download latest %v from %v\", \"gnvm.exe\", \"https://github.com/kenshin/gnvm\", \"\\n\")\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\t\tif line > 2 && detail {\n\t\t\tP(DEFAULT, content)\n\t\t}\n\n\t\treturn false\n\t}\n\n\tif err := curl.ReadLine(res.Body, versionFunc); err != nil && err != io.EOF {\n\t\tpanic(err)\n\t}\n}", "func TestGetSemverVersisonWithStandardVersion(t *testing.T) {\n\tversion.Map[\"version\"] = \"1.2.1\"\n\tresult, err := version.GetSemverVersion()\n\texpectedResult := semver.Version{Major: 1, Minor: 2, Patch: 1}\n\tassert.NoError(t, err, \"GetSemverVersion should exit without failure\")\n\tassert.Exactly(t, expectedResult, result)\n}", "func firstBadVersion(n int) int {\n\treturn sort.Search(n+1, func(i int) bool { return isBadVersion(i) })\n}", "func (o SparsePokesList) Version() int {\n\n\treturn 1\n}", "func (o SparseOAUTHKeysList) Version() int {\n\n\treturn 1\n}", "func (_m *MockAggregate) setVersion(_a0 int) {\n\t_m.Called(_a0)\n}", "func (c Initializer) verifyServedVersion(client crdclient.CustomResourceDefinitionsGetter, crdName, version string, result *verifier.Result) error {\n\texistingCrd, err := c.getCrdForVerify(client, crdName, result)\n\tif err != nil || existingCrd == nil {\n\t\treturn err\n\t}\n\tif healthy, msg, err := status.IsHealthy(existingCrd); !healthy || err != nil {\n\t\tif !healthy {\n\t\t\tresult.AddErrors(msg)\n\t\t} else {\n\t\t\tresult.AddErrors(err.Error())\n\t\t}\n\t\treturn nil\n\t}\n\n\tvar expectedVersion *apiextv1.CustomResourceDefinitionVersion\n\tvar allNames = []string{}\n\tfor _, v := range existingCrd.Spec.Versions {\n\t\tv := v\n\t\tallNames = append(allNames, v.Name)\n\t\tif v.Name == version {\n\t\t\texpectedVersion = &v\n\t\t\tbreak\n\t\t}\n\t}\n\tif expectedVersion == nil {\n\t\tresult.AddErrors(fmt.Sprintf(\"Expected API version %s was not found for %s, api-server only supports %v. Please update your KUDO CLI.\", version, crdName, allNames))\n\t\treturn nil\n\t}\n\tif !expectedVersion.Served {\n\t\tresult.AddErrors(fmt.Sprintf(\"Expected API version %s for %s is known to api-server, but is not served. Please update your KUDO CLI.\", version, crdName))\n\t}\n\treturn nil\n}", "func (o *OAUTHKey) Version() int {\n\n\treturn 1\n}", "func ParsePublicHeader(b *bytes.Reader, packetSentBy protocol.Perspective, version protocol.VersionNumber) (*PublicHeader, error) {\n\theader := &PublicHeader{}\n\n\t// First byte\n\tpublicFlagByte, err := b.ReadByte()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\theader.ResetFlag = publicFlagByte&0x02 > 0\n\theader.VersionFlag = publicFlagByte&0x01 > 0\n\tif version == protocol.VersionUnknown && !(header.VersionFlag || header.ResetFlag) {\n\t\treturn nil, ErrPacketWithUnknownVersion\n\t}\n\n\t// TODO: activate this check once Chrome sends the correct value\n\t// see https://github.com/lucas-clemente/quic-go/issues/232\n\t// if publicFlagByte&0x04 > 0 {\n\t// \treturn nil, errors.New(\"diversification nonces should only be sent by servers\")\n\t// }\n\n\theader.TruncateConnectionID = publicFlagByte&0x08 == 0\n\tif header.TruncateConnectionID && packetSentBy == protocol.PerspectiveClient {\n\t\treturn nil, errReceivedTruncatedConnectionID\n\t}\n\n\tif header.hasPacketNumber(packetSentBy) {\n\t\tswitch publicFlagByte & 0x30 {\n\t\tcase 0x30:\n\t\t\theader.PacketNumberLen = protocol.PacketNumberLen6\n\t\tcase 0x20:\n\t\t\theader.PacketNumberLen = protocol.PacketNumberLen4\n\t\tcase 0x10:\n\t\t\theader.PacketNumberLen = protocol.PacketNumberLen2\n\t\tcase 0x00:\n\t\t\theader.PacketNumberLen = protocol.PacketNumberLen1\n\t\t}\n\t}\n\n\theader.MultipathFlag = publicFlagByte&0x40 > 0\n\n\t// Connection ID\n\tif !header.TruncateConnectionID {\n\t\tvar connID uint64\n\t\t// always write the connection ID in little endian\n\t\tconnID, err = utils.LittleEndian.ReadUint64(b)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\theader.ConnectionID = protocol.ConnectionID(connID)\n\t\tif header.ConnectionID == 0 {\n\t\t\treturn nil, errInvalidConnectionID\n\t\t}\n\t}\n\n\tif packetSentBy == protocol.PerspectiveServer && publicFlagByte&0x04 > 0 {\n\t\t// TODO: remove the if once the Google servers send the correct value\n\t\t// assume that a packet doesn't contain a diversification nonce if the version flag or the reset flag is set, no matter what the public flag says\n\t\t// see https://github.com/lucas-clemente/quic-go/issues/232\n\t\tif !header.VersionFlag && !header.ResetFlag {\n\t\t\theader.DiversificationNonce = make([]byte, 32)\n\t\t\tif _, err := io.ReadFull(b, header.DiversificationNonce); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t}\n\n\t// Version (optional)\n\tif !header.ResetFlag && header.VersionFlag {\n\t\tif packetSentBy == protocol.PerspectiveServer { // parse the version negotiaton packet\n\t\t\tif b.Len()%4 != 0 {\n\t\t\t\treturn nil, qerr.InvalidVersionNegotiationPacket\n\t\t\t}\n\t\t\theader.SupportedVersions = make([]protocol.VersionNumber, 0)\n\t\t\tfor {\n\t\t\t\tvar versionTag uint32\n\t\t\t\tversionTag, err = utils.LittleEndian.ReadUint32(b)\n\t\t\t\tif err != nil {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tv := protocol.VersionTagToNumber(versionTag)\n\t\t\t\theader.SupportedVersions = append(header.SupportedVersions, v)\n\t\t\t}\n\t\t\t// a version negotiation packet doesn't have a packet number\n\t\t\treturn header, nil\n\t\t}\n\t\t// packet was sent by the client. Read the version number\n\t\tvar versionTag uint32\n\t\tversionTag, err = utils.LittleEndian.ReadUint32(b)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\theader.VersionNumber = protocol.VersionTagToNumber(versionTag)\n\t\tversion = header.VersionNumber\n\t}\n\n\t// Path ID\n\tif header.MultipathFlag {\n\t\tpathID, err := b.ReadByte()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\theader.PathID = protocol.PathID(pathID)\n\t} else {\n\t\theader.PathID = 0\n\t}\n\n\t// Packet number\n\tif header.hasPacketNumber(packetSentBy) {\n\t\tpacketNumber, err := utils.GetByteOrder(version).ReadUintN(b, uint8(header.PacketNumberLen))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\theader.PacketNumber = protocol.PacketNumber(packetNumber)\n\t}\n\n\treturn header, nil\n}", "func (o *EnforcerReport) Version() int {\n\n\treturn 1\n}", "func (a Asset) version() string {\n\tvar versionRegexp = regexp.MustCompile(`^v\\d+`)\n\tversion := a.Version\n\tif version == 0 &&\n\t\ta.Config.URL.ForceVersion &&\n\t\tfilepath.Dir(a.PublicID) != \".\" &&\n\t\t!isURL(a.PublicID) &&\n\t\t!versionRegexp.MatchString(a.PublicID) {\n\t\tversion = 1\n\t}\n\n\tif version != 0 {\n\t\treturn fmt.Sprintf(\"v%d\", version)\n\t}\n\n\treturn \"\"\n}", "func firstBadVersion(n int) int {\n\treturn sort.Search(n, func(version int) bool { return isBadVersion(version) })\n}", "func (d Document) Version() int { return d.version }", "func (o APIChecksList) Version() int {\n\n\treturn 1\n}", "func (a *Client) Version(params *VersionParams) (*VersionOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewVersionParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"Version\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/version\",\n\t\tProducesMediaTypes: []string{\"text/plain\"},\n\t\tConsumesMediaTypes: []string{\"text/plain\"},\n\t\tSchemes: []string{\"http\", \"https\"},\n\t\tParams: params,\n\t\tReader: &VersionReader{formats: a.formats},\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn result.(*VersionOK), nil\n\n}", "func (_m *MockAggregate) incrementVersion() {\n\t_m.Called()\n}", "func (o *SyntheticsTriggerCITestRunResult) GetPublicIdOk() (*string, bool) {\n\tif o == nil || o.PublicId == nil {\n\t\treturn nil, false\n\t}\n\treturn o.PublicId, true\n}", "func isV1(version string) bool {\r\n\tif !semver.IsValid(version) || isBeforeV1(version) {\r\n\t\treturn false\r\n\t}\r\n\treturn semver.Major(version) == \"v1\"\r\n}", "func TestVersionSemVer(t *testing.T) {\n\tt.Logf(\"Testing version semantic (%s)\", Version)\n\tdetails := strings.Split(Version, \".\")\n\tif len(details) != 3 {\n\t\tt.Errorf(\"Version should provide major, minor and path informations: %s\", Version)\n\t}\n\tif _, err := strconv.ParseInt(details[0], 2, 0); err != nil {\n\t\tt.Errorf(err.Error())\n\t}\n\tif _, err := strconv.ParseInt(details[1], 2, 0); err != nil {\n\t\tt.Errorf(err.Error())\n\t}\n\n\tpatch := strings.Split(details[2], \"-\")\n\tif _, err := strconv.ParseInt(patch[0], 2, 0); err != nil {\n\t\tt.Errorf(err.Error())\n\t}\n\tif len(patch) > 2 {\n\t\tt.Error(\"last version part only provides patch number and pre-release info\")\n\n\t}\n}", "func newPublicAddress(public *PublicKey, version, stream uint64) (*publicAddress, error) {\n\n\tid := &publicAddress{\n\t\tPublicKey: *public,\n\t\tversion: version,\n\t\tstream: stream,\n\t}\n\n\t// Check whether the address can be generated without an error.\n\t_, err := id.address()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn id, nil\n}", "func (h *PublicHeader) Write(b *bytes.Buffer, version protocol.VersionNumber, pers protocol.Perspective) error {\n\tpublicFlagByte := uint8(0x00)\n\n\tif h.VersionFlag && h.ResetFlag {\n\t\treturn errResetAndVersionFlagSet\n\t}\n\n\tif h.VersionFlag {\n\t\tpublicFlagByte |= 0x01\n\t}\n\tif h.ResetFlag {\n\t\tpublicFlagByte |= 0x02\n\t}\n\tif !h.TruncateConnectionID {\n\t\tpublicFlagByte |= 0x08\n\t}\n\n\tif len(h.DiversificationNonce) > 0 {\n\t\tif len(h.DiversificationNonce) != 32 {\n\t\t\treturn errors.New(\"invalid diversification nonce length\")\n\t\t}\n\t\tpublicFlagByte |= 0x04\n\t}\n\n\t// only set PacketNumberLen bits if a packet number will be written\n\tif h.hasPacketNumber(pers) {\n\t\tswitch h.PacketNumberLen {\n\t\tcase protocol.PacketNumberLen1:\n\t\t\tpublicFlagByte |= 0x00\n\t\tcase protocol.PacketNumberLen2:\n\t\t\tpublicFlagByte |= 0x10\n\t\tcase protocol.PacketNumberLen4:\n\t\t\tpublicFlagByte |= 0x20\n\t\tcase protocol.PacketNumberLen6:\n\t\t\tpublicFlagByte |= 0x30\n\t\t}\n\t}\n\n\tif h.MultipathFlag {\n\t\tpublicFlagByte |= 0x40\n\t}\n\n\tb.WriteByte(publicFlagByte)\n\n\tif !h.TruncateConnectionID {\n\t\t// always read the connection ID in little endian\n\t\tutils.LittleEndian.WriteUint64(b, uint64(h.ConnectionID))\n\t}\n\n\tif h.VersionFlag && pers == protocol.PerspectiveClient {\n\t\tutils.LittleEndian.WriteUint32(b, protocol.VersionNumberToTag(h.VersionNumber))\n\t}\n\n\tif len(h.DiversificationNonce) > 0 {\n\t\tb.Write(h.DiversificationNonce)\n\t}\n\n\tif h.MultipathFlag {\n\t\tb.WriteByte(uint8(h.PathID))\n\t}\n\n\t// if we're a server, and the VersionFlag is set, we must not include anything else in the packet\n\tif !h.hasPacketNumber(pers) {\n\t\treturn nil\n\t}\n\n\tswitch h.PacketNumberLen {\n\tcase protocol.PacketNumberLen1:\n\t\tb.WriteByte(uint8(h.PacketNumber))\n\tcase protocol.PacketNumberLen2:\n\t\tutils.GetByteOrder(version).WriteUint16(b, uint16(h.PacketNumber))\n\tcase protocol.PacketNumberLen4:\n\t\tutils.GetByteOrder(version).WriteUint32(b, uint32(h.PacketNumber))\n\tcase protocol.PacketNumberLen6:\n\t\tutils.GetByteOrder(version).WriteUint48(b, uint64(h.PacketNumber)&(1<<48-1))\n\tdefault:\n\t\treturn errors.New(\"PublicHeader: PacketNumberLen not set\")\n\t}\n\n\treturn nil\n}", "func (c *Client) PublicURL() string {\n\treturn c.Scheme + \"://\" + c.Subdomain + \".\" + c.APIHost\n}", "func (me TrestrictionType) IsPublic() bool { return me.String() == \"public\" }", "func TestPublicIdentityMarshalling(t *testing.T) {\n\tid, err := GenerateIdentity()\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to generate new identity: %v\", err)\n\t}\n\tpub := id.Public()\n\toriginal, _ := json.Marshal(pub)\n\n\tpub = new(PublicIdentity)\n\tif err = json.Unmarshal(original, pub); err != nil {\n\t\tt.Fatalf(\"Failed to parse encoded identity: %v\", err)\n\t}\n\tparsed, _ := json.Marshal(pub)\n\n\tif !bytes.Equal(original, parsed) {\n\t\tt.Fatalf(\"Encode-parse-encode mismatch: have\\n %s\\n want\\n %s\", parsed, original)\n\t}\n}", "func validateSignatureVersion(signature nbv1.S3SignatureVersion, nsStoreName string) error {\n\tif signature != \"\" &&\n\t\tsignature != nbv1.S3SignatureVersionV2 &&\n\t\tsignature != nbv1.S3SignatureVersionV4 {\n\t\treturn util.NewPersistentError(\"InvalidSignatureVersion\",\n\t\t\tfmt.Sprintf(\"Invalid s3 signature version %q for namespace store %q\",\n\t\t\t\tsignature, nsStoreName))\n\t}\n\treturn nil\n}", "func TestGetVersion(t *testing.T) {\n\n\tversion, err := GetVersion()\n\n\tif err != nil{\n\t\tt.Error(err)\n\t}\n\n\tif version != \"v1\"{\n\t\tt.Errorf(\"app version not match: %s, expect: %s.\", version, \"v1\")\n\t}\n\n\tfmt.Println(version)\n}", "func (o *SparseSSHAuthority) Version() int {\n\n\treturn 1\n}", "func Test4(t *testing.T) {\n\tnewCollection := mutatingBaseCollectionVersions.DeepCopy()\n\tnewCollection.Spec.RepositoryUrl = \"https://github.com/some/collection/alternate-kabanero-index.yaml\"\n\tnewCollection.Spec.Version = \"4.5.6\"\n\tnewCollection.Spec.DesiredState = \"inactive\"\n\terr := processUpdate(&mutatingBaseCollection, newCollection)\n\tif err != nil {\n\t\tt.Fatal(\"Unexpected error during mutation.\", err)\n\t}\n\n\texpectedversion0 := kabanerov1alpha1.CollectionVersion{\n\t\tRepositoryUrl: \"https://github.com/some/collection/alternate-kabanero-index.yaml\",\n\t\tVersion: \"4.5.6\",\n\t\tDesiredState: \"inactive\"}\n\n\tif newCollection.Spec.Versions[0] != expectedversion0 {\n\t\tt.Fatal(\"New collection.Spec.Versions[0] values do not match expected collection.Spec.Versions[0] values. New versions[0]: \", newCollection.Spec.Versions[0], \"Expected versions[0]: \", expectedversion0)\n\t}\n}", "func (ut *jSONDataVersion) Publicize() *JSONDataVersion {\n\tvar pub JSONDataVersion\n\tif ut.Data != nil {\n\t\tpub.Data = make([]*JSONDataRow, len(ut.Data))\n\t\tfor i2, elem2 := range ut.Data {\n\t\t\tpub.Data[i2] = elem2.Publicize()\n\t\t}\n\t}\n\tif ut.Meta != nil {\n\t\tpub.Meta = ut.Meta.Publicize()\n\t}\n\treturn &pub\n}", "func TestVersion(t *testing.T) {\n\tt.Parallel()\n\n\ttree := writeTree(t, \"\")\n\n\t// There's not much we can robustly assert about the actual version.\n\twant := debug.Version() // e.g. \"master\"\n\n\t// basic\n\t{\n\t\tres := gopls(t, tree, \"version\")\n\t\tres.checkExit(true)\n\t\tres.checkStdout(want)\n\t}\n\n\t// -json flag\n\t{\n\t\tres := gopls(t, tree, \"version\", \"-json\")\n\t\tres.checkExit(true)\n\t\tvar v debug.ServerVersion\n\t\tif res.toJSON(&v) {\n\t\t\tif v.Version != want {\n\t\t\t\tt.Errorf(\"expected Version %q, got %q (%v)\", want, v.Version, res)\n\t\t\t}\n\t\t}\n\t}\n}", "func SetPublicRPC(v bool) {\n\tpublicRPC = v\n}", "func (r *Repository) VersionOnCommit(n int) {\n\tr.createVersion = n\n}", "func (api *API) Version(request *restful.Request, response *restful.Response) {\n\tglog.V(2).Infof(\"Returning version information\")\n\tif err := response.WriteHeaderAndEntity(http.StatusOK, version.Info); err != nil {\n\t\tapi.writeError(http.StatusInternalServerError, err.Error(), response)\n\t}\n}", "func (h *Headers) IsPublic() bool {\n\treturn h.public\n}", "func (ut *jSONDataMetaStationFirmware) Publicize() *JSONDataMetaStationFirmware {\n\tvar pub JSONDataMetaStationFirmware\n\tif ut.Build != nil {\n\t\tpub.Build = *ut.Build\n\t}\n\tif ut.Hash != nil {\n\t\tpub.Hash = *ut.Hash\n\t}\n\tif ut.Number != nil {\n\t\tpub.Number = *ut.Number\n\t}\n\tif ut.Timestamp != nil {\n\t\tpub.Timestamp = *ut.Timestamp\n\t}\n\tif ut.Version != nil {\n\t\tpub.Version = *ut.Version\n\t}\n\treturn &pub\n}", "func TestMakeUpVersion(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\tmajor uint8\n\t\tminor uint8\n\t\tfix uint8\n\t\twant uint32\n\t}{\n\t\t{\n\t\t\tname: \"MakeUpversionTest\",\n\t\t\tmajor: FixVersion,\n\t\t\tminor: MinorVersion,\n\t\t\tfix: FixVersion,\n\t\t\twant: 16843008,\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tif got := makeUpVersion(tt.major, tt.minor, tt.fix); got != tt.want {\n\t\t\t\tt.Errorf(\"makeUpVersion() = %v, majorVersion %v\", got, tt.want)\n\t\t\t}\n\t\t})\n\t}\n}", "func GetPublicRPC() bool {\n\treturn publicRPC\n}", "func isPublic(name string) bool {\n\tup := bytes.ToUpper([]byte(name))\n\treturn []byte(name)[0] == up[0]\n}", "func (*CreateMsgBeginRedelegate) Version() int {\n\treturn 1\n}", "func Test_LatestVersion(t *testing.T) {\n\tmockServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Header().Set(\"Content-Type\", \"text/plain\")\n\t\tw.WriteHeader(http.StatusOK)\n\t\tw.Write([]byte(\"0.6.1\\n\"))\n\t}))\n\tdefer mockServer.Close()\n\n\tversion, err := latestVersion(mockServer.URL)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\ttestVersion := semver.New(\"0.6.1\")\n\tif !version.Equal(*testVersion) {\n\t\tt.Error(\"Version equality check failed.\")\n\t}\n}", "func (o *WorkflowServiceItemDefinitionAllOf) GetVersionOk() (*int64, bool) {\n\tif o == nil || o.Version == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Version, true\n}", "func UnmarshalPublicCertificateVersionPrototype(m map[string]json.RawMessage, result interface{}) (err error) {\n\tobj := new(PublicCertificateVersionPrototype)\n\terr = core.UnmarshalModel(m, \"rotation\", &obj.Rotation, UnmarshalPublicCertificateRotationObject)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalPrimitive(m, \"custom_metadata\", &obj.CustomMetadata)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalPrimitive(m, \"version_custom_metadata\", &obj.VersionCustomMetadata)\n\tif err != nil {\n\t\treturn\n\t}\n\treflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj))\n\treturn\n}", "func isPseudoVersion(v string) bool {\n\treturn strings.Count(v, \"-\") >= 2 && semver.IsValid(v) && pseudoVersionRE.MatchString(v)\n}", "func (_Ownable *OwnableCaller) Version(opts *bind.CallOpts) ([32]byte, error) {\n\tvar out []interface{}\n\terr := _Ownable.contract.Call(opts, &out, \"version\")\n\n\tif err != nil {\n\t\treturn *new([32]byte), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new([32]byte)).(*[32]byte)\n\n\treturn out0, err\n\n}" ]
[ "0.61684936", "0.6067962", "0.5954322", "0.56574756", "0.56270444", "0.5623315", "0.5601342", "0.55662715", "0.5558212", "0.55543554", "0.5481111", "0.5477666", "0.54693365", "0.5434321", "0.53901994", "0.53724116", "0.53723973", "0.5360367", "0.535976", "0.52923805", "0.52780044", "0.5277057", "0.5272688", "0.52699256", "0.5267909", "0.5260384", "0.5259272", "0.5250905", "0.5238036", "0.52307075", "0.52202463", "0.52156854", "0.5210286", "0.5207732", "0.52056354", "0.51854193", "0.51811355", "0.51791453", "0.5177025", "0.5155246", "0.5148725", "0.5138737", "0.51287735", "0.51203746", "0.51124495", "0.5104366", "0.510272", "0.5102522", "0.51004106", "0.5098157", "0.5087884", "0.50832486", "0.50766474", "0.50695086", "0.50678176", "0.5067324", "0.5066465", "0.5066371", "0.5062982", "0.50506365", "0.5029783", "0.5029084", "0.50217336", "0.50180423", "0.50176835", "0.50146174", "0.5009847", "0.50089717", "0.5008543", "0.50028145", "0.4993251", "0.49932057", "0.49889424", "0.4988213", "0.49814606", "0.49794278", "0.49746805", "0.4971921", "0.49714547", "0.49712712", "0.49657676", "0.49591282", "0.49584255", "0.49557737", "0.4950456", "0.49467114", "0.49450764", "0.49391055", "0.4937133", "0.49343324", "0.4923709", "0.49216372", "0.49201915", "0.492004", "0.49167982", "0.49019912", "0.49018592", "0.4900548", "0.49001485", "0.48970452" ]
0.70306873
0
Serialize mocks base method
func (m *MockClient) Serialize() ([]byte, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Serialize") ret0, _ := ret[0].([]byte) ret1, _ := ret[1].(error) return ret0, ret1 }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (m *MockManager) SerializeUpstream(arg0 string) error {\n\tret := m.ctrl.Call(m, \"SerializeUpstream\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockManager) SerializeNamespace(arg0 string) error {\n\tret := m.ctrl.Call(m, \"SerializeNamespace\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockManager) SerializeUpstreamContents(arg0 *state.UpstreamContents) error {\n\tret := m.ctrl.Call(m, \"SerializeUpstreamContents\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *VirtualEndpoint) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.Entity.Serialize(writer)\n if err != nil {\n return err\n }\n if m.GetAuditEvents() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetAuditEvents()))\n for i, v := range m.GetAuditEvents() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"auditEvents\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetBulkActions() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetBulkActions()))\n for i, v := range m.GetBulkActions() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"bulkActions\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetCloudPCs() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetCloudPCs()))\n for i, v := range m.GetCloudPCs() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"cloudPCs\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"crossCloudGovernmentOrganizationMapping\", m.GetCrossCloudGovernmentOrganizationMapping())\n if err != nil {\n return err\n }\n }\n if m.GetDeviceImages() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetDeviceImages()))\n for i, v := range m.GetDeviceImages() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"deviceImages\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetExternalPartnerSettings() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetExternalPartnerSettings()))\n for i, v := range m.GetExternalPartnerSettings() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"externalPartnerSettings\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetFrontLineServicePlans() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetFrontLineServicePlans()))\n for i, v := range m.GetFrontLineServicePlans() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"frontLineServicePlans\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetGalleryImages() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetGalleryImages()))\n for i, v := range m.GetGalleryImages() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"galleryImages\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetOnPremisesConnections() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetOnPremisesConnections()))\n for i, v := range m.GetOnPremisesConnections() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"onPremisesConnections\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"organizationSettings\", m.GetOrganizationSettings())\n if err != nil {\n return err\n }\n }\n if m.GetProvisioningPolicies() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetProvisioningPolicies()))\n for i, v := range m.GetProvisioningPolicies() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"provisioningPolicies\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"reports\", m.GetReports())\n if err != nil {\n return err\n }\n }\n if m.GetServicePlans() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetServicePlans()))\n for i, v := range m.GetServicePlans() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"servicePlans\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetSharedUseServicePlans() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetSharedUseServicePlans()))\n for i, v := range m.GetSharedUseServicePlans() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"sharedUseServicePlans\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetSnapshots() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetSnapshots()))\n for i, v := range m.GetSnapshots() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"snapshots\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetSupportedRegions() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetSupportedRegions()))\n for i, v := range m.GetSupportedRegions() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"supportedRegions\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetUserSettings() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetUserSettings()))\n for i, v := range m.GetUserSettings() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"userSettings\", cast)\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (m *MockManager) SerializeShipMetadata(arg0 api.ShipAppMetadata, arg1 string) error {\n\tret := m.ctrl.Call(m, \"SerializeShipMetadata\", arg0, arg1)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (_m *MockWriteBufferJsonBased) WriteSerializable(ctx context.Context, serializable Serializable) error {\n\tret := _m.Called(ctx, serializable)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(context.Context, Serializable) error); ok {\n\t\tr0 = rf(ctx, serializable)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func TestSer(t *testing.T) {\n\tt.Skip()\n}", "func (b *mockEncoder) Encode(value interface{}) (data []byte, err error) {\n\treturn json.Marshal(value)\n}", "func serialize(toMarshal interface{}) *bytes.Buffer {\n\tjsonStr, _ := json.Marshal(toMarshal)\n\treturn bytes.NewBuffer(jsonStr)\n}", "func TestMsgSerialize(t *testing.T) {\n handler := new(CmdMsgHandler)\n cmd := new(CmdMsg)\n cmd.Cmd = CMD_ENV\n cmd.Data = \"\"\n\n b, err := handler.SerializeMsg(cmd)\n if err != nil {\n t.Fatal(err)\n }\n\n obj, err := handler.DeserializeMsg(b, 255)\n if err != nil {\n t.Fatal(err)\n }\n\n newCmd, ok := obj.(*CmdMsg)\n if !ok {\n t.Fatal(\"Invalid type received %T\", obj)\n }\n\n if cmd.Cmd != newCmd.Cmd {\n t.Fatalf(\n \"Cmd mismatch: %s vs %s\", \n cmd.Cmd, \n newCmd.Cmd,\n )\n }\n\n if cmd.Data != newCmd.Data {\n t.Fatalf(\n \"Data mismatch: %s vs %s\", \n cmd.Data, \n newCmd.Data,\n ) }\n\n log.Printf(\"TestMsgSerialize: passed\")\n}", "func TestTxSerialize(t *testing.T) {\n\tnoTx := NewNativeMsgTx(1, nil, nil)\n\tnoTxEncoded := []byte{\n\t\t0x01, 0x00, 0x00, 0x00, // Version\n\t\t0x00, // Varint for number of input transactions\n\t\t0x00, // Varint for number of output transactions\n\t\t0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Lock time\n\t\t0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n\t\t0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n\t\t0x00, 0x00, 0x00, 0x00, // Sub Network ID\n\t}\n\n\tregistryTx := NewRegistryMsgTx(1, nil, nil, 16)\n\tregistryTxEncoded := []byte{\n\t\t0x01, 0x00, 0x00, 0x00, // Version\n\t\t0x00, // Varint for number of input transactions\n\t\t0x00, // Varint for number of output transactions\n\t\t0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Lock time\n\t\t0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n\t\t0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n\t\t0x00, 0x00, 0x00, 0x00, // Sub Network ID\n\t\t0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Gas\n\t\t0x77, 0x56, 0x36, 0xb4, 0x89, 0x32, 0xe9, 0xa8,\n\t\t0xbb, 0x67, 0xe6, 0x54, 0x84, 0x36, 0x93, 0x8d,\n\t\t0x9f, 0xc5, 0x62, 0x49, 0x79, 0x5c, 0x0d, 0x0a,\n\t\t0x86, 0xaf, 0x7c, 0x5d, 0x54, 0x45, 0x4c, 0x4b, // Payload hash\n\t\t0x08, // Payload length varint\n\t\t0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Payload / Gas limit\n\t}\n\n\tsubnetworkTx := NewSubnetworkMsgTx(1, nil, nil, &subnetworkid.SubnetworkID{0xff}, 5, []byte{0, 1, 2})\n\n\tsubnetworkTxEncoded := []byte{\n\t\t0x01, 0x00, 0x00, 0x00, // Version\n\t\t0x00, // Varint for number of input transactions\n\t\t0x00, // Varint for number of output transactions\n\t\t0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Lock time\n\t\t0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n\t\t0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n\t\t0x00, 0x00, 0x00, 0x00, // Sub Network ID\n\t\t0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Gas\n\t\t0x35, 0xf9, 0xf2, 0x93, 0x0e, 0xa3, 0x44, 0x61,\n\t\t0x88, 0x22, 0x79, 0x5e, 0xee, 0xc5, 0x68, 0xae,\n\t\t0x67, 0xab, 0x29, 0x87, 0xd8, 0xb1, 0x9e, 0x45,\n\t\t0x91, 0xe1, 0x05, 0x27, 0xba, 0xa1, 0xdf, 0x3d, // Payload hash\n\t\t0x03, // Payload length varint\n\t\t0x00, 0x01, 0x02, // Payload\n\t}\n\n\ttests := []struct {\n\t\tname string\n\t\tin *MsgTx // Message to encode\n\t\tout *MsgTx // Expected decoded message\n\t\tbuf []byte // Serialized data\n\t\tscriptPubKeyLocs []int // Expected output script locations\n\t}{\n\t\t// No transactions.\n\t\t{\n\t\t\t\"noTx\",\n\t\t\tnoTx,\n\t\t\tnoTx,\n\t\t\tnoTxEncoded,\n\t\t\tnil,\n\t\t},\n\n\t\t// Registry Transaction.\n\t\t{\n\t\t\t\"registryTx\",\n\t\t\tregistryTx,\n\t\t\tregistryTx,\n\t\t\tregistryTxEncoded,\n\t\t\tnil,\n\t\t},\n\n\t\t// Sub Network Transaction.\n\t\t{\n\t\t\t\"subnetworkTx\",\n\t\t\tsubnetworkTx,\n\t\t\tsubnetworkTx,\n\t\t\tsubnetworkTxEncoded,\n\t\t\tnil,\n\t\t},\n\n\t\t// Multiple transactions.\n\t\t{\n\t\t\t\"multiTx\",\n\t\t\tmultiTx,\n\t\t\tmultiTx,\n\t\t\tmultiTxEncoded,\n\t\t\tmultiTxScriptPubKeyLocs,\n\t\t},\n\t}\n\n\tt.Logf(\"Running %d tests\", len(tests))\n\tfor i, test := range tests {\n\t\t// Serialize the transaction.\n\t\tvar buf bytes.Buffer\n\t\terr := test.in.Serialize(&buf)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Serialize %s: error %v\", test.name, err)\n\t\t\tcontinue\n\t\t}\n\t\tif !bytes.Equal(buf.Bytes(), test.buf) {\n\t\t\tt.Errorf(\"Serialize %s:\\n got: %s want: %s\", test.name,\n\t\t\t\tspew.Sdump(buf.Bytes()), spew.Sdump(test.buf))\n\t\t\tcontinue\n\t\t}\n\n\t\t// Deserialize the transaction.\n\t\tvar tx MsgTx\n\t\trbuf := bytes.NewReader(test.buf)\n\t\terr = tx.Deserialize(rbuf)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Deserialize #%d error %v\", i, err)\n\t\t\tcontinue\n\t\t}\n\t\tif !reflect.DeepEqual(&tx, test.out) {\n\t\t\tt.Errorf(\"Deserialize #%d\\n got: %s want: %s\", i,\n\t\t\t\tspew.Sdump(&tx), spew.Sdump(test.out))\n\t\t\tcontinue\n\t\t}\n\n\t\t// Ensure the public key script locations are accurate.\n\t\tscriptPubKeyLocs := test.in.ScriptPubKeyLocs()\n\t\tif !reflect.DeepEqual(scriptPubKeyLocs, test.scriptPubKeyLocs) {\n\t\t\tt.Errorf(\"ScriptPubKeyLocs #%d\\n got: %s want: %s\", i,\n\t\t\t\tspew.Sdump(scriptPubKeyLocs),\n\t\t\t\tspew.Sdump(test.scriptPubKeyLocs))\n\t\t\tcontinue\n\t\t}\n\t\tfor j, loc := range scriptPubKeyLocs {\n\t\t\twantScriptPubKey := test.in.TxOut[j].ScriptPubKey\n\t\t\tgotScriptPubKey := test.buf[loc : loc+len(wantScriptPubKey)]\n\t\t\tif !bytes.Equal(gotScriptPubKey, wantScriptPubKey) {\n\t\t\t\tt.Errorf(\"ScriptPubKeyLocs #%d:%d\\n unexpected \"+\n\t\t\t\t\t\"script got: %s want: %s\", i, j,\n\t\t\t\t\tspew.Sdump(gotScriptPubKey),\n\t\t\t\t\tspew.Sdump(wantScriptPubKey))\n\t\t\t}\n\t\t}\n\t}\n}", "func (m *MockManager) SerializeConfig(arg0 []api.Asset, arg1 api.ReleaseMetadata, arg2 map[string]interface{}) error {\n\tret := m.ctrl.Call(m, \"SerializeConfig\", arg0, arg1, arg2)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func TestCanMarshalFileInstanceToJSON(t *testing.T) {\n\tfi := &FileInstance{\n\t\tID: 505,\n\t\tRepoPullID: 17,\n\t\tFileHashID: 923,\n\t\tPath: \"/test/somefile_test.go\",\n\t}\n\n\tjs, err := json.Marshal(fi)\n\tif err != nil {\n\t\tt.Fatalf(\"got non-nil error: %v\", err)\n\t}\n\n\t// read back in as empty interface to check values\n\t// should be a map whose keys are strings, values are empty interface values\n\t// per https://blog.golang.org/json-and-go\n\tvar mapGot interface{}\n\terr = json.Unmarshal(js, &mapGot)\n\tif err != nil {\n\t\tt.Fatalf(\"got non-nil error: %v\", err)\n\t}\n\tmGot := mapGot.(map[string]interface{})\n\n\t// check for expected values\n\tif float64(fi.ID) != mGot[\"id\"].(float64) {\n\t\tt.Errorf(\"expected %v, got %v\", float64(fi.ID), mGot[\"id\"].(float64))\n\t}\n\tif float64(fi.RepoPullID) != mGot[\"repopull_id\"].(float64) {\n\t\tt.Errorf(\"expected %v, got %v\", float64(fi.RepoPullID), mGot[\"repopull_id\"].(float64))\n\t}\n\tif float64(fi.FileHashID) != mGot[\"filehash_id\"].(float64) {\n\t\tt.Errorf(\"expected %v, got %v\", float64(fi.FileHashID), mGot[\"filehash_id\"].(float64))\n\t}\n\tif fi.Path != mGot[\"path\"].(string) {\n\t\tt.Errorf(\"expected %v, got %v\", fi.Path, mGot[\"path\"].(string))\n\t}\n}", "func AssertSerialize(t *testing.T, dialect jet.Dialect, serializer jet.Serializer, query string, args ...interface{}) {\n\tout := jet.SQLBuilder{Dialect: dialect}\n\tjet.Serialize(serializer, jet.SelectStatementType, &out)\n\n\t//fmt.Println(out.Buff.String())\n\n\tAssertDeepEqual(t, out.Buff.String(), query)\n\n\tif len(args) > 0 {\n\t\tAssertDeepEqual(t, out.Args, args)\n\t}\n}", "func (_m *MockWriteBufferXmlBased) WriteSerializable(ctx context.Context, serializable Serializable) error {\n\tret := _m.Called(ctx, serializable)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(context.Context, Serializable) error); ok {\n\t\tr0 = rf(ctx, serializable)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func TestJsonEncode(t *testing.T) {\n\tt.Parallel()\n\n\t// Set up a mock struct for testing\n\ttype TestStruct struct {\n\t\tTestKey string `json:\"test_key\"`\n\t\tTestKeyTwo string `json:\"test_key_two\"`\n\t\tnotAllowed string\n\t}\n\n\t// Base model and test model\n\tvar model = new(TestStruct)\n\tvar modelTest = new(TestStruct)\n\tvar allowedFields = []string{\"test_key\", \"test_key_two\"} // notice omitted: notAllowed\n\n\t// Set the testing data\n\tmodel.TestKey = \"TestValue1\"\n\tmodel.TestKeyTwo = \"TestValue2\"\n\tmodel.notAllowed = \"PrivateValue\"\n\n\t// Set the buffer and encoder\n\tvar b bytes.Buffer\n\tenc := json.NewEncoder(&b)\n\n\t// Run the encoder\n\terr := JSONEncode(enc, model, allowedFields)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// Now unmarshal and test\n\tif err = json.Unmarshal(b.Bytes(), &modelTest); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// Test for our fields and values now\n\tif modelTest.TestKey != \"TestValue1\" {\n\t\tt.Fatal(\"TestKey does not have the right value! Encoding failed.\", modelTest.TestKey)\n\t} else if modelTest.TestKeyTwo != \"TestValue2\" {\n\t\tt.Fatal(\"TestKeyTwo does not have the right value! Encoding failed.\", modelTest.TestKeyTwo)\n\t} else if modelTest.notAllowed == \"PrivateValue\" {\n\t\tt.Fatal(\"Field not removed! notAllowed does not have the right value! Encoding failed.\", modelTest.notAllowed)\n\t}\n}", "func (m *MockManager) SerializeReleaseName(arg0 string) error {\n\tret := m.ctrl.Call(m, \"SerializeReleaseName\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (_e *MockWriteBufferJsonBased_Expecter) WriteSerializable(ctx interface{}, serializable interface{}) *MockWriteBufferJsonBased_WriteSerializable_Call {\n\treturn &MockWriteBufferJsonBased_WriteSerializable_Call{Call: _e.mock.On(\"WriteSerializable\", ctx, serializable)}\n}", "func TestRecordSerialization(t *testing.T) {\n\tcommon.Log(\"test\", \"\\n\\nTestRecordSerialization\")\n\tindexFile, err := os.OpenFile(config.Base.IndexPrefix+\"_record_persistence_test\", os.O_RDWR|os.O_CREATE, 0666)\n\tcommon.FaceIt(err)\n\tdefer indexFile.Close()\n\n\trecord := common.Record{}\n\tslots := record.Slots()\n\tfor i := 0; i < len(slots); i++ {\n\t\t*slots[i] = uint64(i + 1)\n\t}\n\n\tindexFile.Seek(0, os.SEEK_SET)\n\tindexFile.Write(record.Serialize())\n\n\tindexFile.Seek(0, os.SEEK_SET)\n\treadRecord := common.Record{}\n\treadRecord.Deserialize(indexFile)\n\n\treadSlots := readRecord.Slots()\n\tfor i := 0; i < len(slots); i++ {\n\t\tif *slots[i] != *readSlots[i] {\n\t\t\tt.Fatalf(\"deserialized field %d ne expected %d\", *readSlots[i], *slots[i])\n\t\t}\n\t}\n}", "func (m *MockConn) WriteJSON(v interface{}) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"WriteJSON\", v)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (_m *MockTestTransportInstance) Write(data []byte) error {\n\tret := _m.Called(data)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func([]byte) error); ok {\n\t\tr0 = rf(data)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (m *MockManager) SerializeHelmValues(arg0, arg1 string) error {\n\tret := m.ctrl.Call(m, \"SerializeHelmValues\", arg0, arg1)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *Synchronization) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.Entity.Serialize(writer)\n if err != nil {\n return err\n }\n if m.GetJobs() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetJobs()))\n for i, v := range m.GetJobs() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"jobs\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetSecrets() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetSecrets()))\n for i, v := range m.GetSecrets() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"secrets\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetTemplates() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetTemplates()))\n for i, v := range m.GetTemplates() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"templates\", cast)\n if err != nil {\n return err\n }\n }\n return nil\n}", "func MockWire(hash []byte, round uint64, step uint8, keys []key.ConsensusKeys, p *user.Provisioners, i ...int) *bytes.Buffer {\n\tev := MockAgreementEvent(hash, round, step, keys, p, i...)\n\n\tbuf := new(bytes.Buffer)\n\tif err := header.Marshal(buf, ev.Header); err != nil {\n\t\tpanic(err)\n\t}\n\n\tif err := Marshal(buf, *ev); err != nil {\n\t\tpanic(err)\n\t}\n\treturn buf\n}", "func Serialize(input interface{}) (msg []byte, err error) {\n\tbuffer, err := json.Marshal(input)\n\treturn buffer, err\n\n\t// TODO: Do we really need wire here?\n\t/*\n\t\tvar count int\n\n\t\tbuffer := new(bytes.Buffer)\n\n\t\twire.WriteBinary(input, buffer, &count, &err)\n\n\t\treturn buffer.Bytes(), err\n\t*/\n}", "func (m *MockManager) SerializeContentSHA(arg0 string) error {\n\tret := m.ctrl.Call(m, \"SerializeContentSHA\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *Drive) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.BaseItem.Serialize(writer)\n if err != nil {\n return err\n }\n if m.GetBundles() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetBundles())\n err = writer.WriteCollectionOfObjectValues(\"bundles\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"driveType\", m.GetDriveType())\n if err != nil {\n return err\n }\n }\n if m.GetFollowing() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetFollowing())\n err = writer.WriteCollectionOfObjectValues(\"following\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetItems() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetItems())\n err = writer.WriteCollectionOfObjectValues(\"items\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"list\", m.GetList())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"owner\", m.GetOwner())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"quota\", m.GetQuota())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"root\", m.GetRoot())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"sharePointIds\", m.GetSharePointIds())\n if err != nil {\n return err\n }\n }\n if m.GetSpecial() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetSpecial())\n err = writer.WriteCollectionOfObjectValues(\"special\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"system\", m.GetSystem())\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (m *MockSnapshot) MarshalJSON() ([]byte, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"MarshalJSON\")\n\tret0, _ := ret[0].([]byte)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockRemoteSnapshot) MarshalJSON() ([]byte, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"MarshalJSON\")\n\tret0, _ := ret[0].([]byte)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func TestEncode(t *testing.T) {\n\tvar err error\n\tassert := assert.New(t)\n\n\tauthor := bio{\n\t\tFirstname: \"Bastien\",\n\t\tLastname: \"Gysler\",\n\t\tHobbies: []string{\"DJ\", \"Running\", \"Tennis\"},\n\t\tMisc: map[string]string{\n\t\t\t\"lineSeparator\": \"\\u2028\",\n\t\t\t\"Nationality\": \"Swiss\",\n\t\t\t\"City\": \"Zürich\",\n\t\t\t\"foo\": \"\",\n\t\t\t\"bar\": \"\\\"quoted text\\\"\",\n\t\t\t\"esc\": \"escaped \\\\ sanitized\",\n\t\t\t\"r\": \"\\r return line\",\n\t\t\t\"default\": \"< >\",\n\t\t\t\"runeError\": \"\\uFFFD\",\n\t\t},\n\t}\n\n\t// Build document\n\troot := &Node{}\n\troot.AddChild(\"firstname\", &Node{\n\t\tData: author.Firstname,\n\t})\n\troot.AddChild(\"lastname\", &Node{\n\t\tData: author.Lastname,\n\t})\n\n\tfor _, h := range author.Hobbies {\n\t\troot.AddChild(\"hobbies\", &Node{\n\t\t\tData: h,\n\t\t})\n\t}\n\n\tmisc := &Node{}\n\tfor k, v := range author.Misc {\n\t\tmisc.AddChild(k, &Node{\n\t\t\tData: v,\n\t\t})\n\t}\n\troot.AddChild(\"misc\", misc)\n\tvar enc *Encoder\n\n\t// Convert to JSON string\n\tbuf := new(bytes.Buffer)\n\tenc = NewEncoder(buf)\n\n\terr = enc.Encode(nil)\n\tassert.NoError(err)\n\n\tenc.SetAttributePrefix(\"test\")\n\tenc.SetContentPrefix(\"test2\")\n\t// err = enc.EncodeWithCustomPrefixes(root, \"test3\", \"test4\")\n\tenc.CustomPrefixesOption(\"test3\", \"test4\")\n\terr = enc.Encode(root)\n\tassert.NoError(err)\n\n\terr = enc.Encode(root)\n\tassert.NoError(err)\n\n\t// Build SimpleJSON\n\tsj, err := sj.NewJson(buf.Bytes())\n\tres, err := sj.Map()\n\tassert.NoError(err)\n\n\t// Assertions\n\tassert.Equal(author.Firstname, res[\"firstname\"])\n\tassert.Equal(author.Lastname, res[\"lastname\"])\n\n\tresHobbies, err := sj.Get(\"hobbies\").StringArray()\n\tassert.NoError(err)\n\tassert.Equal(author.Hobbies, resHobbies)\n\n\tresMisc, err := sj.Get(\"misc\").Map()\n\tassert.NoError(err)\n\tfor k, v := range resMisc {\n\t\tassert.Equal(author.Misc[k], v)\n\t}\n\n\tenc.err = fmt.Errorf(\"Testing if error provided is returned\")\n\tassert.Error(enc.Encode(nil))\n}", "func (m *List) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.BaseItem.Serialize(writer)\n if err != nil {\n return err\n }\n if m.GetColumns() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetColumns())\n err = writer.WriteCollectionOfObjectValues(\"columns\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetContentTypes() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetContentTypes())\n err = writer.WriteCollectionOfObjectValues(\"contentTypes\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"displayName\", m.GetDisplayName())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"drive\", m.GetDrive())\n if err != nil {\n return err\n }\n }\n if m.GetItems() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetItems())\n err = writer.WriteCollectionOfObjectValues(\"items\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"list\", m.GetList())\n if err != nil {\n return err\n }\n }\n if m.GetOperations() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetOperations())\n err = writer.WriteCollectionOfObjectValues(\"operations\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"sharepointIds\", m.GetSharepointIds())\n if err != nil {\n return err\n }\n }\n if m.GetSubscriptions() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetSubscriptions())\n err = writer.WriteCollectionOfObjectValues(\"subscriptions\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"system\", m.GetSystem())\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (m *MockManager) SerializeAppMetadata(arg0 api.ReleaseMetadata) error {\n\tret := m.ctrl.Call(m, \"SerializeAppMetadata\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockSerialInterface) Marshal(v interface{}) ([]byte, error) {\n\tret := m.ctrl.Call(m, \"Marshal\", v)\n\tret0, _ := ret[0].([]byte)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (_e *MockWriteBufferXmlBased_Expecter) WriteSerializable(ctx interface{}, serializable interface{}) *MockWriteBufferXmlBased_WriteSerializable_Call {\n\treturn &MockWriteBufferXmlBased_WriteSerializable_Call{Call: _e.mock.On(\"WriteSerializable\", ctx, serializable)}\n}", "func (m *SimulationAutomationRun) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.Entity.Serialize(writer)\n if err != nil {\n return err\n }\n {\n err = writer.WriteTimeValue(\"endDateTime\", m.GetEndDateTime())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"simulationId\", m.GetSimulationId())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteTimeValue(\"startDateTime\", m.GetStartDateTime())\n if err != nil {\n return err\n }\n }\n if m.GetStatus() != nil {\n cast := (*m.GetStatus()).String()\n err = writer.WriteStringValue(\"status\", &cast)\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (m *ExternalConnection) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.Entity.Serialize(writer)\n if err != nil {\n return err\n }\n {\n err = writer.WriteObjectValue(\"configuration\", m.GetConfiguration())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"description\", m.GetDescription())\n if err != nil {\n return err\n }\n }\n if m.GetGroups() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetGroups())\n err = writer.WriteCollectionOfObjectValues(\"groups\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetItems() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetItems())\n err = writer.WriteCollectionOfObjectValues(\"items\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"name\", m.GetName())\n if err != nil {\n return err\n }\n }\n if m.GetOperations() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetOperations())\n err = writer.WriteCollectionOfObjectValues(\"operations\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"schema\", m.GetSchema())\n if err != nil {\n return err\n }\n }\n return nil\n}", "func TestJsonEncodeSubstruct(t *testing.T) {\n\tt.Parallel()\n\n\t// Set up a new mock substruct\n\ttype TestSubStruct struct {\n\t\tTestSubKey string `json:\"test_sub_key\"`\n\t}\n\t// Set up a mock struct for testing\n\ttype TestStruct struct {\n\t\tTestKey string `json:\"test_key\"`\n\t\tTestKeyTwo TestSubStruct `json:\"test_key_two\"`\n\t\tNotAllowed string `json:\"not_allowed\"`\n\t}\n\n\t// Base model and test model\n\tvar model = new(TestStruct)\n\tvar modelTest = new(TestStruct)\n\tvar allowedFields = []string{\"test_key\", \"test_key_two\"} // notice omitted: notAllowed\n\n\t// Set the testing data\n\tmodel.TestKey = \"TestValue1\"\n\tmodel.TestKeyTwo.TestSubKey = \"TestSubValue\"\n\tmodel.NotAllowed = \"PrivateValue\"\n\n\t// Set the buffer and encoder\n\tvar b bytes.Buffer\n\tenc := json.NewEncoder(&b)\n\n\t// Run the encoder\n\terr := JSONEncode(enc, model, allowedFields)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// Now unmarshal and test\n\tif err = json.Unmarshal(b.Bytes(), &modelTest); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// Test for our fields and values now\n\tif modelTest.TestKey != \"TestValue1\" {\n\t\tt.Fatal(\"TestKey does not have the right value! Encoding failed.\", modelTest.TestKey)\n\t} else if modelTest.TestKeyTwo.TestSubKey != \"TestSubValue\" {\n\t\tt.Fatal(\"TestKeyTwo does not have the right value! Encoding failed.\", modelTest.TestKeyTwo)\n\t} else if modelTest.NotAllowed == \"PrivateValue\" {\n\t\tt.Fatal(\"Field not removed! notAllowed does not have the right value! Encoding failed.\", modelTest.NotAllowed)\n\t}\n\n}", "func (self *ResTransaction)Serialize()[]byte{\n data, err := json.Marshal(self)\n if err != nil {\n fmt.Println(err)\n }\n return data\n}", "func (m *CloudCommunications) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.Entity.Serialize(writer)\n if err != nil {\n return err\n }\n if m.GetCalls() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetCalls()))\n for i, v := range m.GetCalls() {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n err = writer.WriteCollectionOfObjectValues(\"calls\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetOnlineMeetings() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetOnlineMeetings()))\n for i, v := range m.GetOnlineMeetings() {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n err = writer.WriteCollectionOfObjectValues(\"onlineMeetings\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetPresences() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetPresences()))\n for i, v := range m.GetPresences() {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n err = writer.WriteCollectionOfObjectValues(\"presences\", cast)\n if err != nil {\n return err\n }\n }\n return nil\n}", "func encodeMockEvent(e models.Event) ([]byte, error) {\n\tbyteBuffer, err := cbor.Marshal(e)\n\tif err != nil {\n\t\treturn []byte{}, err\n\t}\n\treturn byteBuffer, nil\n}", "func (m *Printer) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.PrinterBase.Serialize(writer)\n if err != nil {\n return err\n }\n if m.GetConnectors() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetConnectors()))\n for i, v := range m.GetConnectors() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"connectors\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteBoolValue(\"hasPhysicalDevice\", m.GetHasPhysicalDevice())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteBoolValue(\"isShared\", m.GetIsShared())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteTimeValue(\"lastSeenDateTime\", m.GetLastSeenDateTime())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteTimeValue(\"registeredDateTime\", m.GetRegisteredDateTime())\n if err != nil {\n return err\n }\n }\n if m.GetShares() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetShares()))\n for i, v := range m.GetShares() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"shares\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetTaskTriggers() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetTaskTriggers()))\n for i, v := range m.GetTaskTriggers() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"taskTriggers\", cast)\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (m *MockPKG) Encode() ([]byte, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Encode\")\n\tret0, _ := ret[0].([]byte)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func TestObjectSerialize(t *testing.T) {\n\n\tjo := NewJavaTcObject(1)\n\tclz := NewJavaTcClassDesc(\"com.david.test.serialize.D\", 1, 0x02)\n\tjfa := NewJavaField(TC_PRIM_INTEGER, \"a\", 1)\n\tjfb := NewJavaField(TC_OBJ_OBJECT, \"b\", \"abcdefg\")\n\tjfb.FieldObjectClassName = \"java.lang.String\"\n\tclz.AddField(jfa)\n\tclz.AddField(jfb)\n\tclz.SortFields()\n\n\tjo.AddClassDesc(clz)\n\n\tvar f *os.File\n\tvar err error\n\n\tif f, err = os.OpenFile(\"d:\\\\tmp\\\\serialize-go.data\", os.O_CREATE|os.O_TRUNC, 0755); err != nil {\n\t\tt.Fatalf(\"got error when open file %v\\n\", err)\n\t}\n\tdefer f.Close()\n\n\tif err = SerializeJavaEntity(f, jo); err != nil {\n\t\tt.Fatalf(\"SerializeJavaEntity got %v\\n\", err)\n\t} else {\n\t\tt.Logf(\"SerializeJavaEntity succeed!\\n\")\n\t}\n}", "func (s *BaseEvent) SerialiseToString() (string,error) {\n if err := s.serialisePart1(); err != nil { return \"\",err }\n if err := s.serialisePart2(); err != nil { return \"\",err }\n if err := s.serialiseSysParams(); err != nil { return \"\",err }\n if err := s.serialiseExecParams(); err != nil { return \"\",err }\n\n // construct the payload - 4 payloads all of type 1 which is a json payload\n // this can later be rewritten to make it possible for a derived class to add extra blocks\n payloadLen := BLOCK_HEADER_LEN+len(s.part1Json)+len(s.part2Json)+len(s.sysParamsJson)+len(s.execParamsJson)\n if payloadLen > MAX_HEADER_BLOCK_LEN {\n s.errString = fmt.Sprintf(\"SerialiseToString MAX_HEADER_BLOCK_LEN exceeded: payloadLen:%u, jsonPart1:%u, jsonPart2:%u, jsonSysParams:%u, jsonExecParams:%u\",payloadLen,len(s.part1Json),len(s.part2Json),len(s.sysParamsJson),len(s.execParamsJson) )\n return \"\",s\n } // if\n payloadHeader := fmt.Sprintf( \"%s%s:%06d\\n%02d,1,%06d,1,%06d,1,%06d,1,%06d\\n\",FRAME_HEADER,PROTOCOL_VERSION_NUMBER,payloadLen,4,len(s.part1Json),len(s.part2Json),len(s.sysParamsJson),len(s.execParamsJson) )\n// strSerialised := payloadHeader + \"\\n\" + string(s.part1Json) + \"\\n\" + string(s.part2Json) + \"\\n\" + string(s.sysParamsJson) + \"\\n\" + string(s.execParamsJson)\n strSerialised := payloadHeader + string(s.part1Json) + string(s.part2Json) + string(s.sysParamsJson) + string(s.execParamsJson)\n\n Log.Print( \"BaseEvent SerialiseToString:\", strSerialised )\n return strSerialised,nil;\n}", "func (m *SolutionsRoot) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n if m.GetBusinessScenarios() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetBusinessScenarios()))\n for i, v := range m.GetBusinessScenarios() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err := writer.WriteCollectionOfObjectValues(\"businessScenarios\", cast)\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"@odata.type\", m.GetOdataType())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteObjectValue(\"virtualEvents\", m.GetVirtualEvents())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteAdditionalData(m.GetAdditionalData())\n if err != nil {\n return err\n }\n }\n return nil\n}", "func NewMockWriteBufferJsonBased(t interface {\n\tmock.TestingT\n\tCleanup(func())\n}) *MockWriteBufferJsonBased {\n\tmock := &MockWriteBufferJsonBased{}\n\tmock.Mock.Test(t)\n\n\tt.Cleanup(func() { mock.AssertExpectations(t) })\n\n\treturn mock\n}", "func mockTokenAsString(t *testing.T) string {\n\ttoken := mockToken(t)\n\treturn token.Encode()\n}", "func (m *MockisWRingGetEntriesResponse_WRingSlotInfo) MarshalTo(arg0 []byte) (int, error) {\n\tret := m.ctrl.Call(m, \"MarshalTo\", arg0)\n\tret0, _ := ret[0].(int)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *Set) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.Entity.Serialize(writer)\n if err != nil {\n return err\n }\n if m.GetChildren() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetChildren()))\n for i, v := range m.GetChildren() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"children\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteTimeValue(\"createdDateTime\", m.GetCreatedDateTime())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"description\", m.GetDescription())\n if err != nil {\n return err\n }\n }\n if m.GetLocalizedNames() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetLocalizedNames()))\n for i, v := range m.GetLocalizedNames() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"localizedNames\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"parentGroup\", m.GetParentGroup())\n if err != nil {\n return err\n }\n }\n if m.GetProperties() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetProperties()))\n for i, v := range m.GetProperties() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"properties\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetRelations() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetRelations()))\n for i, v := range m.GetRelations() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"relations\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetTerms() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetTerms()))\n for i, v := range m.GetTerms() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"terms\", cast)\n if err != nil {\n return err\n }\n }\n return nil\n}", "func MockPayload(content string) string {\n\tdata := make(map[string]interface{})\n\tdata[\"content\"] = content\n\n\tres, err := json.Marshal(data)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn string(res)\n}", "func TestDeploymentSerialization(t *testing.T) {\n\tres := resource.NewState(\n\t\ttokens.Type(\"Test\"),\n\t\tresource.NewURN(\n\t\t\ttokens.QName(\"test\"),\n\t\t\ttokens.PackageName(\"resource/test\"),\n\t\t\ttokens.Type(\"\"),\n\t\t\ttokens.Type(\"Test\"),\n\t\t\ttokens.QName(\"resource-x\"),\n\t\t),\n\t\ttrue,\n\t\tfalse,\n\t\tresource.ID(\"test-resource-x\"),\n\t\tresource.NewPropertyMapFromMap(map[string]interface{}{\n\t\t\t\"in-nil\": nil,\n\t\t\t\"in-bool\": true,\n\t\t\t\"in-float64\": float64(1.5),\n\t\t\t\"in-string\": \"lumilumilo\",\n\t\t\t\"in-array\": []interface{}{\"a\", true, float64(32)},\n\t\t\t\"in-empty-array\": []interface{}{},\n\t\t\t\"in-map\": map[string]interface{}{\n\t\t\t\t\"a\": true,\n\t\t\t\t\"b\": float64(88),\n\t\t\t\t\"c\": \"c-see-saw\",\n\t\t\t\t\"d\": \"d-dee-daw\",\n\t\t\t},\n\t\t\t\"in-empty-map\": map[string]interface{}{},\n\t\t}),\n\t\tresource.NewPropertyMapFromMap(map[string]interface{}{\n\t\t\t\"out-nil\": nil,\n\t\t\t\"out-bool\": false,\n\t\t\t\"out-float64\": float64(76),\n\t\t\t\"out-string\": \"loyolumiloom\",\n\t\t\t\"out-array\": []interface{}{false, \"zzxx\"},\n\t\t\t\"out-empty-array\": []interface{}{},\n\t\t\t\"out-map\": map[string]interface{}{\n\t\t\t\t\"x\": false,\n\t\t\t\t\"y\": \"z-zee-zaw\",\n\t\t\t\t\"z\": float64(999.9),\n\t\t\t},\n\t\t\t\"out-empty-map\": map[string]interface{}{},\n\t\t}),\n\t\t\"\",\n\t\tfalse,\n\t\tfalse,\n\t\t[]resource.URN{\n\t\t\tresource.URN(\"foo:bar:baz\"),\n\t\t\tresource.URN(\"foo:bar:boo\"),\n\t\t},\n\t\t[]string{},\n\t\t\"\",\n\t\tnil,\n\t\tfalse,\n\t\tnil,\n\t\tnil,\n\t\tnil,\n\t\t\"\",\n\t)\n\n\tdep, err := SerializeResource(res, config.NopEncrypter, false /* showSecrets */)\n\tassert.NoError(t, err)\n\n\t// assert some things about the deployment record:\n\tassert.NotNil(t, dep)\n\tassert.NotNil(t, dep.ID)\n\tassert.Equal(t, resource.ID(\"test-resource-x\"), dep.ID)\n\tassert.Equal(t, tokens.Type(\"Test\"), dep.Type)\n\tassert.Equal(t, 2, len(dep.Dependencies))\n\tassert.Equal(t, resource.URN(\"foo:bar:baz\"), dep.Dependencies[0])\n\tassert.Equal(t, resource.URN(\"foo:bar:boo\"), dep.Dependencies[1])\n\n\t// assert some things about the inputs:\n\tassert.NotNil(t, dep.Inputs)\n\tassert.Nil(t, dep.Inputs[\"in-nil\"])\n\tassert.NotNil(t, dep.Inputs[\"in-bool\"])\n\tassert.True(t, dep.Inputs[\"in-bool\"].(bool))\n\tassert.NotNil(t, dep.Inputs[\"in-float64\"])\n\tassert.Equal(t, float64(1.5), dep.Inputs[\"in-float64\"].(float64))\n\tassert.NotNil(t, dep.Inputs[\"in-string\"])\n\tassert.Equal(t, \"lumilumilo\", dep.Inputs[\"in-string\"].(string))\n\tassert.NotNil(t, dep.Inputs[\"in-array\"])\n\tassert.Equal(t, 3, len(dep.Inputs[\"in-array\"].([]interface{})))\n\tassert.Equal(t, \"a\", dep.Inputs[\"in-array\"].([]interface{})[0])\n\tassert.Equal(t, true, dep.Inputs[\"in-array\"].([]interface{})[1])\n\tassert.Equal(t, float64(32), dep.Inputs[\"in-array\"].([]interface{})[2])\n\tassert.NotNil(t, dep.Inputs[\"in-empty-array\"])\n\tassert.Equal(t, 0, len(dep.Inputs[\"in-empty-array\"].([]interface{})))\n\tassert.NotNil(t, dep.Inputs[\"in-map\"])\n\tinmap := dep.Inputs[\"in-map\"].(map[string]interface{})\n\tassert.Equal(t, 4, len(inmap))\n\tassert.NotNil(t, inmap[\"a\"])\n\tassert.Equal(t, true, inmap[\"a\"].(bool))\n\tassert.NotNil(t, inmap[\"b\"])\n\tassert.Equal(t, float64(88), inmap[\"b\"].(float64))\n\tassert.NotNil(t, inmap[\"c\"])\n\tassert.Equal(t, \"c-see-saw\", inmap[\"c\"].(string))\n\tassert.NotNil(t, inmap[\"d\"])\n\tassert.Equal(t, \"d-dee-daw\", inmap[\"d\"].(string))\n\tassert.NotNil(t, dep.Inputs[\"in-empty-map\"])\n\tassert.Equal(t, 0, len(dep.Inputs[\"in-empty-map\"].(map[string]interface{})))\n\n\t// assert some things about the outputs:\n\tassert.NotNil(t, dep.Outputs)\n\tassert.Nil(t, dep.Outputs[\"out-nil\"])\n\tassert.NotNil(t, dep.Outputs[\"out-bool\"])\n\tassert.False(t, dep.Outputs[\"out-bool\"].(bool))\n\tassert.NotNil(t, dep.Outputs[\"out-float64\"])\n\tassert.Equal(t, float64(76), dep.Outputs[\"out-float64\"].(float64))\n\tassert.NotNil(t, dep.Outputs[\"out-string\"])\n\tassert.Equal(t, \"loyolumiloom\", dep.Outputs[\"out-string\"].(string))\n\tassert.NotNil(t, dep.Outputs[\"out-array\"])\n\tassert.Equal(t, 2, len(dep.Outputs[\"out-array\"].([]interface{})))\n\tassert.Equal(t, false, dep.Outputs[\"out-array\"].([]interface{})[0])\n\tassert.Equal(t, \"zzxx\", dep.Outputs[\"out-array\"].([]interface{})[1])\n\tassert.NotNil(t, dep.Outputs[\"out-empty-array\"])\n\tassert.Equal(t, 0, len(dep.Outputs[\"out-empty-array\"].([]interface{})))\n\tassert.NotNil(t, dep.Outputs[\"out-map\"])\n\toutmap := dep.Outputs[\"out-map\"].(map[string]interface{})\n\tassert.Equal(t, 3, len(outmap))\n\tassert.NotNil(t, outmap[\"x\"])\n\tassert.Equal(t, false, outmap[\"x\"].(bool))\n\tassert.NotNil(t, outmap[\"y\"])\n\tassert.Equal(t, \"z-zee-zaw\", outmap[\"y\"].(string))\n\tassert.NotNil(t, outmap[\"z\"])\n\tassert.Equal(t, float64(999.9), outmap[\"z\"].(float64))\n\tassert.NotNil(t, dep.Outputs[\"out-empty-map\"])\n\tassert.Equal(t, 0, len(dep.Outputs[\"out-empty-map\"].(map[string]interface{})))\n}", "func Serialize(o interface{}) ([]byte, error) {\n\tautil.TODO(\"CBOR-serialization\")\n\treturn nil, nil\n}", "func (m *User) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.DirectoryObject.Serialize(writer)\n if err != nil {\n return err\n }\n {\n err = writer.WriteStringValue(\"aboutMe\", m.GetAboutMe())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteBoolValue(\"accountEnabled\", m.GetAccountEnabled())\n if err != nil {\n return err\n }\n }\n if m.GetActivities() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetActivities())\n err = writer.WriteCollectionOfObjectValues(\"activities\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"ageGroup\", m.GetAgeGroup())\n if err != nil {\n return err\n }\n }\n if m.GetAgreementAcceptances() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetAgreementAcceptances())\n err = writer.WriteCollectionOfObjectValues(\"agreementAcceptances\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetAppRoleAssignments() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetAppRoleAssignments())\n err = writer.WriteCollectionOfObjectValues(\"appRoleAssignments\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetAssignedLicenses() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetAssignedLicenses())\n err = writer.WriteCollectionOfObjectValues(\"assignedLicenses\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetAssignedPlans() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetAssignedPlans())\n err = writer.WriteCollectionOfObjectValues(\"assignedPlans\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"authentication\", m.GetAuthentication())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"authorizationInfo\", m.GetAuthorizationInfo())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteTimeValue(\"birthday\", m.GetBirthday())\n if err != nil {\n return err\n }\n }\n if m.GetBusinessPhones() != nil {\n err = writer.WriteCollectionOfStringValues(\"businessPhones\", m.GetBusinessPhones())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"calendar\", m.GetCalendar())\n if err != nil {\n return err\n }\n }\n if m.GetCalendarGroups() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetCalendarGroups())\n err = writer.WriteCollectionOfObjectValues(\"calendarGroups\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetCalendars() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetCalendars())\n err = writer.WriteCollectionOfObjectValues(\"calendars\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetCalendarView() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetCalendarView())\n err = writer.WriteCollectionOfObjectValues(\"calendarView\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetChats() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetChats())\n err = writer.WriteCollectionOfObjectValues(\"chats\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"city\", m.GetCity())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"companyName\", m.GetCompanyName())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"consentProvidedForMinor\", m.GetConsentProvidedForMinor())\n if err != nil {\n return err\n }\n }\n if m.GetContactFolders() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetContactFolders())\n err = writer.WriteCollectionOfObjectValues(\"contactFolders\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetContacts() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetContacts())\n err = writer.WriteCollectionOfObjectValues(\"contacts\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"country\", m.GetCountry())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteTimeValue(\"createdDateTime\", m.GetCreatedDateTime())\n if err != nil {\n return err\n }\n }\n if m.GetCreatedObjects() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetCreatedObjects())\n err = writer.WriteCollectionOfObjectValues(\"createdObjects\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"creationType\", m.GetCreationType())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"department\", m.GetDepartment())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteInt32Value(\"deviceEnrollmentLimit\", m.GetDeviceEnrollmentLimit())\n if err != nil {\n return err\n }\n }\n if m.GetDeviceManagementTroubleshootingEvents() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetDeviceManagementTroubleshootingEvents())\n err = writer.WriteCollectionOfObjectValues(\"deviceManagementTroubleshootingEvents\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetDirectReports() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetDirectReports())\n err = writer.WriteCollectionOfObjectValues(\"directReports\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"displayName\", m.GetDisplayName())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"drive\", m.GetDrive())\n if err != nil {\n return err\n }\n }\n if m.GetDrives() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetDrives())\n err = writer.WriteCollectionOfObjectValues(\"drives\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteTimeValue(\"employeeHireDate\", m.GetEmployeeHireDate())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"employeeId\", m.GetEmployeeId())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"employeeOrgData\", m.GetEmployeeOrgData())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"employeeType\", m.GetEmployeeType())\n if err != nil {\n return err\n }\n }\n if m.GetEvents() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetEvents())\n err = writer.WriteCollectionOfObjectValues(\"events\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetExtensions() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetExtensions())\n err = writer.WriteCollectionOfObjectValues(\"extensions\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"externalUserState\", m.GetExternalUserState())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteTimeValue(\"externalUserStateChangeDateTime\", m.GetExternalUserStateChangeDateTime())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"faxNumber\", m.GetFaxNumber())\n if err != nil {\n return err\n }\n }\n if m.GetFollowedSites() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetFollowedSites())\n err = writer.WriteCollectionOfObjectValues(\"followedSites\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"givenName\", m.GetGivenName())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteTimeValue(\"hireDate\", m.GetHireDate())\n if err != nil {\n return err\n }\n }\n if m.GetIdentities() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetIdentities())\n err = writer.WriteCollectionOfObjectValues(\"identities\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetImAddresses() != nil {\n err = writer.WriteCollectionOfStringValues(\"imAddresses\", m.GetImAddresses())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"inferenceClassification\", m.GetInferenceClassification())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"insights\", m.GetInsights())\n if err != nil {\n return err\n }\n }\n if m.GetInterests() != nil {\n err = writer.WriteCollectionOfStringValues(\"interests\", m.GetInterests())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteBoolValue(\"isResourceAccount\", m.GetIsResourceAccount())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"jobTitle\", m.GetJobTitle())\n if err != nil {\n return err\n }\n }\n if m.GetJoinedTeams() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetJoinedTeams())\n err = writer.WriteCollectionOfObjectValues(\"joinedTeams\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteTimeValue(\"lastPasswordChangeDateTime\", m.GetLastPasswordChangeDateTime())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"legalAgeGroupClassification\", m.GetLegalAgeGroupClassification())\n if err != nil {\n return err\n }\n }\n if m.GetLicenseAssignmentStates() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetLicenseAssignmentStates())\n err = writer.WriteCollectionOfObjectValues(\"licenseAssignmentStates\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetLicenseDetails() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetLicenseDetails())\n err = writer.WriteCollectionOfObjectValues(\"licenseDetails\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"mail\", m.GetMail())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"mailboxSettings\", m.GetMailboxSettings())\n if err != nil {\n return err\n }\n }\n if m.GetMailFolders() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetMailFolders())\n err = writer.WriteCollectionOfObjectValues(\"mailFolders\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"mailNickname\", m.GetMailNickname())\n if err != nil {\n return err\n }\n }\n if m.GetManagedAppRegistrations() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetManagedAppRegistrations())\n err = writer.WriteCollectionOfObjectValues(\"managedAppRegistrations\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetManagedDevices() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetManagedDevices())\n err = writer.WriteCollectionOfObjectValues(\"managedDevices\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"manager\", m.GetManager())\n if err != nil {\n return err\n }\n }\n if m.GetMemberOf() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetMemberOf())\n err = writer.WriteCollectionOfObjectValues(\"memberOf\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetMessages() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetMessages())\n err = writer.WriteCollectionOfObjectValues(\"messages\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"mobilePhone\", m.GetMobilePhone())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"mySite\", m.GetMySite())\n if err != nil {\n return err\n }\n }\n if m.GetOauth2PermissionGrants() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetOauth2PermissionGrants())\n err = writer.WriteCollectionOfObjectValues(\"oauth2PermissionGrants\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"officeLocation\", m.GetOfficeLocation())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"onenote\", m.GetOnenote())\n if err != nil {\n return err\n }\n }\n if m.GetOnlineMeetings() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetOnlineMeetings())\n err = writer.WriteCollectionOfObjectValues(\"onlineMeetings\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"onPremisesDistinguishedName\", m.GetOnPremisesDistinguishedName())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"onPremisesDomainName\", m.GetOnPremisesDomainName())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"onPremisesExtensionAttributes\", m.GetOnPremisesExtensionAttributes())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"onPremisesImmutableId\", m.GetOnPremisesImmutableId())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteTimeValue(\"onPremisesLastSyncDateTime\", m.GetOnPremisesLastSyncDateTime())\n if err != nil {\n return err\n }\n }\n if m.GetOnPremisesProvisioningErrors() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetOnPremisesProvisioningErrors())\n err = writer.WriteCollectionOfObjectValues(\"onPremisesProvisioningErrors\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"onPremisesSamAccountName\", m.GetOnPremisesSamAccountName())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"onPremisesSecurityIdentifier\", m.GetOnPremisesSecurityIdentifier())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteBoolValue(\"onPremisesSyncEnabled\", m.GetOnPremisesSyncEnabled())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"onPremisesUserPrincipalName\", m.GetOnPremisesUserPrincipalName())\n if err != nil {\n return err\n }\n }\n if m.GetOtherMails() != nil {\n err = writer.WriteCollectionOfStringValues(\"otherMails\", m.GetOtherMails())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"outlook\", m.GetOutlook())\n if err != nil {\n return err\n }\n }\n if m.GetOwnedDevices() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetOwnedDevices())\n err = writer.WriteCollectionOfObjectValues(\"ownedDevices\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetOwnedObjects() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetOwnedObjects())\n err = writer.WriteCollectionOfObjectValues(\"ownedObjects\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"passwordPolicies\", m.GetPasswordPolicies())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"passwordProfile\", m.GetPasswordProfile())\n if err != nil {\n return err\n }\n }\n if m.GetPastProjects() != nil {\n err = writer.WriteCollectionOfStringValues(\"pastProjects\", m.GetPastProjects())\n if err != nil {\n return err\n }\n }\n if m.GetPeople() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetPeople())\n err = writer.WriteCollectionOfObjectValues(\"people\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"photo\", m.GetPhoto())\n if err != nil {\n return err\n }\n }\n if m.GetPhotos() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetPhotos())\n err = writer.WriteCollectionOfObjectValues(\"photos\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"planner\", m.GetPlanner())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"postalCode\", m.GetPostalCode())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"preferredDataLocation\", m.GetPreferredDataLocation())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"preferredLanguage\", m.GetPreferredLanguage())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"preferredName\", m.GetPreferredName())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"presence\", m.GetPresence())\n if err != nil {\n return err\n }\n }\n if m.GetProvisionedPlans() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetProvisionedPlans())\n err = writer.WriteCollectionOfObjectValues(\"provisionedPlans\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetProxyAddresses() != nil {\n err = writer.WriteCollectionOfStringValues(\"proxyAddresses\", m.GetProxyAddresses())\n if err != nil {\n return err\n }\n }\n if m.GetRegisteredDevices() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetRegisteredDevices())\n err = writer.WriteCollectionOfObjectValues(\"registeredDevices\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetResponsibilities() != nil {\n err = writer.WriteCollectionOfStringValues(\"responsibilities\", m.GetResponsibilities())\n if err != nil {\n return err\n }\n }\n if m.GetSchools() != nil {\n err = writer.WriteCollectionOfStringValues(\"schools\", m.GetSchools())\n if err != nil {\n return err\n }\n }\n if m.GetScopedRoleMemberOf() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetScopedRoleMemberOf())\n err = writer.WriteCollectionOfObjectValues(\"scopedRoleMemberOf\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"securityIdentifier\", m.GetSecurityIdentifier())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"settings\", m.GetSettings())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteBoolValue(\"showInAddressList\", m.GetShowInAddressList())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteTimeValue(\"signInSessionsValidFromDateTime\", m.GetSignInSessionsValidFromDateTime())\n if err != nil {\n return err\n }\n }\n if m.GetSkills() != nil {\n err = writer.WriteCollectionOfStringValues(\"skills\", m.GetSkills())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"state\", m.GetState())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"streetAddress\", m.GetStreetAddress())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"surname\", m.GetSurname())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"teamwork\", m.GetTeamwork())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"todo\", m.GetTodo())\n if err != nil {\n return err\n }\n }\n if m.GetTransitiveMemberOf() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetTransitiveMemberOf())\n err = writer.WriteCollectionOfObjectValues(\"transitiveMemberOf\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"usageLocation\", m.GetUsageLocation())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"userPrincipalName\", m.GetUserPrincipalName())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"userType\", m.GetUserType())\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (m *Workbook) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.Entity.Serialize(writer)\n if err != nil {\n return err\n }\n {\n err = writer.WriteObjectValue(\"application\", m.GetApplication())\n if err != nil {\n return err\n }\n }\n if m.GetComments() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetComments())\n err = writer.WriteCollectionOfObjectValues(\"comments\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"functions\", m.GetFunctions())\n if err != nil {\n return err\n }\n }\n if m.GetNames() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetNames())\n err = writer.WriteCollectionOfObjectValues(\"names\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetOperations() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetOperations())\n err = writer.WriteCollectionOfObjectValues(\"operations\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetTables() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetTables())\n err = writer.WriteCollectionOfObjectValues(\"tables\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetWorksheets() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetWorksheets())\n err = writer.WriteCollectionOfObjectValues(\"worksheets\", cast)\n if err != nil {\n return err\n }\n }\n return nil\n}", "func newMockEncodeDataFunc(mockStore *mock.NodeStore) func(chunk Chunk) []byte {\n\treturn func(chunk Chunk) []byte {\n\t\tif err := mockStore.Put(chunk.Address(), encodeData(chunk)); err != nil {\n\t\t\tlog.Error(fmt.Sprintf(\"%T: Chunk %v put: %v\", mockStore, chunk.Address().Log(), err))\n\t\t}\n\t\treturn chunk.Address()[:]\n\t}\n}", "func (m *ManagementTemplateStep) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.Entity.Serialize(writer)\n if err != nil {\n return err\n }\n {\n err = writer.WriteObjectValue(\"acceptedVersion\", m.GetAcceptedVersion())\n if err != nil {\n return err\n }\n }\n if m.GetCategory() != nil {\n cast := (*m.GetCategory()).String()\n err = writer.WriteStringValue(\"category\", &cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"createdByUserId\", m.GetCreatedByUserId())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteTimeValue(\"createdDateTime\", m.GetCreatedDateTime())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"description\", m.GetDescription())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"displayName\", m.GetDisplayName())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"lastActionByUserId\", m.GetLastActionByUserId())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteTimeValue(\"lastActionDateTime\", m.GetLastActionDateTime())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"managementTemplate\", m.GetManagementTemplate())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"portalLink\", m.GetPortalLink())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteInt32Value(\"priority\", m.GetPriority())\n if err != nil {\n return err\n }\n }\n if m.GetVersions() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetVersions()))\n for i, v := range m.GetVersions() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"versions\", cast)\n if err != nil {\n return err\n }\n }\n return nil\n}", "func testJSONMarshal(t *testing.T, v interface{}, want string) {\n\tj, err := json.Marshal(v)\n\tif err != nil {\n\t\tt.Errorf(\"Unable to marshal JSON for %v\", v)\n\t}\n\n\tw := new(bytes.Buffer)\n\terr = json.Compact(w, []byte(want))\n\tif err != nil {\n\t\tt.Errorf(\"String is not valid json: %s\", want)\n\t}\n\n\tif w.String() != string(j) {\n\t\tt.Errorf(\"json.Marshal(%q) returned %s, want %s\", v, j, w)\n\t}\n\n\t// now go the other direction and make sure things unmarshal as expected\n\tu := reflect.ValueOf(v).Interface()\n\tif err := json.Unmarshal([]byte(want), u); err != nil {\n\t\tt.Errorf(\"Unable to unmarshal JSON for %v: %v\", want, err)\n\t}\n\n\tif !reflect.DeepEqual(v, u) {\n\t\tt.Errorf(\"json.Unmarshal(%q) returned %s, want %s\", want, u, v)\n\t}\n}", "func (m *IdentityProviderBase) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.Entity.Serialize(writer)\n if err != nil {\n return err\n }\n {\n err = writer.WriteStringValue(\"displayName\", m.GetDisplayName())\n if err != nil {\n return err\n }\n }\n return nil\n}", "func TestMarshal(t *testing.T) {\n\tpb := PassBytes(\"def\")\n\tpbRawBytes, err := json.Marshal(pb)\n\tif err != nil {\n\t\tt.Fatalf(\"cannot marshal PassBytes: %v\", err)\n\t}\n\n\t// check if pbRawBytes can be successfully unmarshalled into *PassBytes\n\tvar pbUnmarshalled PassBytes\n\terr = json.Unmarshal(pbRawBytes, &pbUnmarshalled)\n\tif err != nil {\n\t\tt.Fatalf(\"cannot unmarshal the rawbytes of a PassBytes: %v\", err)\n\t}\n\n\tif !bytes.Equal(pb, pbUnmarshalled) {\n\t\tt.Fatalf(\"expected original passbytes %x to equal unmarshalled passbytes %s\", pb, pbUnmarshalled)\n\t}\n}", "func testJSONMarshal(t *testing.T, v interface{}, want string) {\n\tj, err := json.Marshal(v)\n\tif err != nil {\n\t\tt.Errorf(\"Unable to marshal JSON for %v\", v)\n\t}\n\n\tw := new(bytes.Buffer)\n\terr = json.Compact(w, []byte(want))\n\tif err != nil {\n\t\tt.Errorf(\"String is not valid json: %s\", want)\n\t}\n\n\tif w.String() != string(j) {\n\t\tt.Errorf(\"json.Marshal(%q) returned %s, want %s\", v, j, w)\n\t}\n\n\t// now go the other direction and make sure things unmarshal as expected\n\tu := reflect.ValueOf(v).Interface()\n\tif err := json.Unmarshal([]byte(want), u); err != nil {\n\t\tt.Errorf(\"Unable to unmarshal JSON for %v\", want)\n\t}\n\n\tif !reflect.DeepEqual(v, u) {\n\t\tt.Errorf(\"json.Unmarshal(%q) returned %s, want %s\", want, u, v)\n\t}\n}", "func (c *cacheableStoreMock) Write() error {\n\treturn c.err\n}", "func (m *AuditLogRoot) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.Entity.Serialize(writer)\n if err != nil {\n return err\n }\n if m.GetDirectoryAudits() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetDirectoryAudits())\n err = writer.WriteCollectionOfObjectValues(\"directoryAudits\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetProvisioning() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetProvisioning())\n err = writer.WriteCollectionOfObjectValues(\"provisioning\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetSignIns() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetSignIns())\n err = writer.WriteCollectionOfObjectValues(\"signIns\", cast)\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (m *MockEncoder) Encode(message *message.Message) ([]byte, error) {\n\tret := m.ctrl.Call(m, \"Encode\", message)\n\tret0, _ := ret[0].([]byte)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *BookingBusiness) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.Entity.Serialize(writer)\n if err != nil {\n return err\n }\n {\n err = writer.WriteObjectValue(\"address\", m.GetAddress())\n if err != nil {\n return err\n }\n }\n if m.GetAppointments() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetAppointments()))\n for i, v := range m.GetAppointments() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"appointments\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetBusinessHours() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetBusinessHours()))\n for i, v := range m.GetBusinessHours() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"businessHours\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"businessType\", m.GetBusinessType())\n if err != nil {\n return err\n }\n }\n if m.GetCalendarView() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetCalendarView()))\n for i, v := range m.GetCalendarView() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"calendarView\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetCustomers() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetCustomers()))\n for i, v := range m.GetCustomers() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"customers\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetCustomQuestions() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetCustomQuestions()))\n for i, v := range m.GetCustomQuestions() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"customQuestions\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"defaultCurrencyIso\", m.GetDefaultCurrencyIso())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"displayName\", m.GetDisplayName())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"email\", m.GetEmail())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"languageTag\", m.GetLanguageTag())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"phone\", m.GetPhone())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"schedulingPolicy\", m.GetSchedulingPolicy())\n if err != nil {\n return err\n }\n }\n if m.GetServices() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetServices()))\n for i, v := range m.GetServices() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"services\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetStaffMembers() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetStaffMembers()))\n for i, v := range m.GetStaffMembers() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"staffMembers\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"webSiteUrl\", m.GetWebSiteUrl())\n if err != nil {\n return err\n }\n }\n return nil\n}", "func TestParentsSubHeaderSerialize(t *testing.T) {\n\n\t// NOTE(cedric): This is the same hash defined in github.com/soteria-dag/soterd/chaincfg package.\n\t// We re-define it here, because the chaincfg package imports the wire package,\n\t// and golang doesn't allow for circular imports in tests.\n\t// (wire -> chaincfg -> wire -> ...)\n\t// 5f2694c9f5d5808adf308c62995154d29596c36c554b15d3d95cdd6bebaf6cb2\n\tvar simNetGenesisHash = chainhash.Hash([chainhash.HashSize]byte{\n\t\t0xb2, 0x6c, 0xaf, 0xeb, 0x6b, 0xdd, 0x5c, 0xd9,\n\t\t0xd3, 0x15, 0x4b, 0x55, 0x6c, 0xc3, 0x96, 0x95,\n\t\t0xd2, 0x54, 0x51, 0x99, 0x62, 0x8c, 0x30, 0xdf,\n\t\t0x8a, 0x80, 0xd5, 0xf5, 0xc9, 0x94, 0x26, 0x5f,\n\t})\n\n\tparents := []*Parent{\n\t\t&Parent{\n\t\t\tHash: simNetGenesisHash,\n\t\t\tData: [32]byte{}},\n\t}\n\n\tpsh := ParentSubHeader{\n\t\tVersion: int32(0),\n\t\tSize: int32(len(parents)),\n\t\tParents: parents}\n\n\tencodedHeader := []byte{\n\t\t0x00, 0x00, 0x00, 0x00, // Version\n\n\t\t0x01, 0x00, 0x00, 0x00, // Size\n\n\t\t0xb2, 0x6c, 0xaf, 0xeb, 0x6b, 0xdd, 0x5c, 0xd9, // Parents -> Hash\n\t\t0xd3, 0x15, 0x4b, 0x55, 0x6c, 0xc3, 0x96, 0x95,\n\t\t0xd2, 0x54, 0x51, 0x99, 0x62, 0x8c, 0x30, 0xdf,\n\t\t0x8a, 0x80, 0xd5, 0xf5, 0xc9, 0x94, 0x26, 0x5f,\n\n\t\t0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Parents -> Data\n\t\t0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n\t\t0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n\t\t0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n\t}\n\n\ttests := []struct {\n\t\theader *ParentSubHeader // Data to encode\n\t\tdecodedHeader *ParentSubHeader // Expected decoded type\n\t\tencoded []byte // Serialized data\n\t}{\n\t\t{\n\t\t\theader: &psh,\n\t\t\tdecodedHeader: &psh,\n\t\t\tencoded: encodedHeader,\n\t\t},\n\t}\n\n\tfor i, test := range tests {\n\t\t// Serialize header\n\t\tvar buf bytes.Buffer\n\t\terr := test.header.Serialize(&buf)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Test #%d Serialize error %v\", i, err)\n\t\t\tcontinue\n\t\t}\n\t\tif !bytes.Equal(buf.Bytes(), test.encoded) {\n\t\t\tt.Errorf(\"Test #%d\\n got: %s want: %s\",\n\t\t\t\ti,\n\t\t\t\tspew.Sdump(buf.Bytes()),\n\t\t\t\tspew.Sdump(test.encoded))\n\t\t\tcontinue\n\t\t}\n\n\t\t// Deserialize header\n\t\tvar h ParentSubHeader\n\t\trbuf := bytes.NewReader(test.encoded)\n\t\terr = h.Deserialize(rbuf)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Test #%d Deserialize error %v\", i, err)\n\t\t\tcontinue\n\t\t}\n\t\tif !reflect.DeepEqual(&h, test.decodedHeader) {\n\t\t\tt.Errorf(\"Test #%d\\n got: %s want: %s\",\n\t\t\t\ti,\n\t\t\t\tspew.Sdump(&h),\n\t\t\t\tspew.Sdump(test.decodedHeader))\n\t\t\tcontinue\n\t\t}\n\t}\n\n\tvar buf bytes.Buffer\n\terr := psh.Serialize(&buf)\n\tif err != nil {\n\t\tt.Errorf(\"Serialize error %v\", err)\n\t}\n}", "func serialize(src interface{}) ([]byte, error) {\n\tbuf := new(bytes.Buffer)\n\tenc := gob.NewEncoder(buf)\n\tif err := enc.Encode(src); err != nil {\n\t\treturn nil, err\n\t}\n\treturn buf.Bytes(), nil\n}", "func testMarshalJSON(t *testing.T, cmd interface{}) {\n\tjsonCmd, err := json.Marshal(cmd)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tfmt.Println(string(jsonCmd))\n}", "func (m *AttackSimulationRoot) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.Entity.Serialize(writer)\n if err != nil {\n return err\n }\n if m.GetSimulationAutomations() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetSimulationAutomations())\n err = writer.WriteCollectionOfObjectValues(\"simulationAutomations\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetSimulations() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetSimulations())\n err = writer.WriteCollectionOfObjectValues(\"simulations\", cast)\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (m *MockAPI) Marshal(arg0 interface{}) ([]byte, error) {\n\tret := m.ctrl.Call(m, \"Marshal\", arg0)\n\tret0, _ := ret[0].([]byte)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *Planner) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.Entity.Serialize(writer)\n if err != nil {\n return err\n }\n if m.GetBuckets() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetBuckets())\n err = writer.WriteCollectionOfObjectValues(\"buckets\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetPlans() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetPlans())\n err = writer.WriteCollectionOfObjectValues(\"plans\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetTasks() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetTasks())\n err = writer.WriteCollectionOfObjectValues(\"tasks\", cast)\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (m *AdministrativeUnit) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.DirectoryObject.Serialize(writer)\n if err != nil {\n return err\n }\n {\n err = writer.WriteStringValue(\"description\", m.GetDescription())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"displayName\", m.GetDisplayName())\n if err != nil {\n return err\n }\n }\n if m.GetExtensions() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetExtensions())\n err = writer.WriteCollectionOfObjectValues(\"extensions\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetMembers() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetMembers())\n err = writer.WriteCollectionOfObjectValues(\"members\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetScopedRoleMembers() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetScopedRoleMembers())\n err = writer.WriteCollectionOfObjectValues(\"scopedRoleMembers\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"visibility\", m.GetVisibility())\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (m *NestedTestAllTypes) Marshal() []byte {\n\twriter := jspb.NewWriter()\n\tm.MarshalToWriter(writer)\n\treturn writer.GetResult()\n}", "func (m *MockYamlInterface) Marshal(in interface{}) ([]byte, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Marshal\", in)\n\tret0, _ := ret[0].([]byte)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func RunJSONSerializationTestForManagementPolicyBaseBlob(subject ManagementPolicyBaseBlob) string {\n\t// Serialize to JSON\n\tbin, err := json.Marshal(subject)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Deserialize back into memory\n\tvar actual ManagementPolicyBaseBlob\n\terr = json.Unmarshal(bin, &actual)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Check for outcome\n\tmatch := cmp.Equal(subject, actual, cmpopts.EquateEmpty())\n\tif !match {\n\t\tactualFmt := pretty.Sprint(actual)\n\t\tsubjectFmt := pretty.Sprint(subject)\n\t\tresult := diff.Diff(subjectFmt, actualFmt)\n\t\treturn result\n\t}\n\n\treturn \"\"\n}", "func (JSONPresenter) Serialize(object interface{}) []byte {\n\tserial, err := json.Marshal(object)\n\n\tif err != nil {\n\t\tlog.Printf(\"failed to serialize: \\\"%s\\\"\", err)\n\t}\n\n\treturn serial\n}", "func Serialize(data interface{}) string {\n\tval, _ := json.Marshal(data)\n\treturn string(val);\n}", "func (s *Serializer) Serialize(p svermaker.ProjectVersion) error {\n\ts.SerializerInvoked = true\n\treturn s.SerializerFn(p)\n}", "func TestCompatibility(t *testing.T) {\n\ttestcases := map[string]struct {\n\t\t// fixture holds a representation of a LoggingConfiguration struct in JSON format.\n\t\tfixture string\n\t\t// baseConfig is the struct that Unmarshal writes into.\n\t\tbaseConfig LoggingConfiguration\n\t\t// expectAllFields enables a reflection check to ensure that the\n\t\t// result has all fields set.\n\t\texpectAllFields bool\n\t\t// expectConfig is the intended result.\n\t\texpectConfig LoggingConfiguration\n\t}{\n\t\t\"defaults\": {\n\t\t\t// No changes when nothing is specified.\n\t\t\tfixture: \"{}\",\n\t\t\tbaseConfig: *NewLoggingConfiguration(),\n\t\t\texpectConfig: *NewLoggingConfiguration(),\n\t\t},\n\t\t\"all-fields\": {\n\t\t\t// The JSON fixture includes all fields. The result\n\t\t\t// must have all fields as non-empty when starting with\n\t\t\t// an empty base, otherwise the fixture is incomplete\n\t\t\t// and must be updated for the test case to pass.\n\t\t\tfixture: `{\n\t\"format\": \"json\",\n\t\"flushFrequency\": 1,\n\t\"verbosity\": 5,\n\t\"vmodule\": [\n\t\t{\"filePattern\": \"someFile\", \"verbosity\": 10},\n\t\t{\"filePattern\": \"anotherFile\", \"verbosity\": 1}\n\t],\n\t\"options\": {\n\t\t\"json\": {\n\t\t\t\"splitStream\": true,\n\t\t\t\"infoBufferSize\": \"1024\"\n\t\t}\n\t}\n}\n`,\n\t\t\tbaseConfig: LoggingConfiguration{},\n\t\t\texpectAllFields: true,\n\t\t\texpectConfig: LoggingConfiguration{\n\t\t\t\tFormat: JSONLogFormat,\n\t\t\t\tFlushFrequency: TimeOrMetaDuration{Duration: metav1.Duration{Duration: time.Nanosecond}},\n\t\t\t\tVerbosity: VerbosityLevel(5),\n\t\t\t\tVModule: VModuleConfiguration{\n\t\t\t\t\t{\n\t\t\t\t\t\tFilePattern: \"someFile\",\n\t\t\t\t\t\tVerbosity: VerbosityLevel(10),\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tFilePattern: \"anotherFile\",\n\t\t\t\t\t\tVerbosity: VerbosityLevel(1),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tOptions: FormatOptions{\n\t\t\t\t\tJSON: JSONOptions{\n\t\t\t\t\t\tSplitStream: true,\n\t\t\t\t\t\tInfoBufferSize: resource.QuantityValue{\n\t\t\t\t\t\t\tQuantity: *resource.NewQuantity(1024, resource.DecimalSI),\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\tfor name, tc := range testcases {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\t// Beware, not a deep copy. Different test cases must\n\t\t\t// not share anything.\n\t\t\tconfig := tc.baseConfig\n\t\t\tif strictErr, err := json.UnmarshalStrict([]byte(tc.fixture), &config); err != nil {\n\t\t\t\tt.Fatalf(\"unexpected unmarshal error: %v\", err)\n\t\t\t} else if strictErr != nil {\n\t\t\t\tt.Fatalf(\"unexpected strict unmarshal error: %v\", strictErr)\n\t\t\t}\n\t\t\t// This sets the internal \"s\" field just like unmarshaling does.\n\t\t\t// Required for assert.Equal to pass.\n\t\t\t_ = tc.expectConfig.Options.JSON.InfoBufferSize.String()\n\t\t\tassert.Equal(t, tc.expectConfig, config)\n\t\t\tif tc.expectAllFields {\n\t\t\t\tnotZeroRecursive(t, config, \"LoggingConfiguration\")\n\t\t\t}\n\t\t})\n\t}\n}", "func (rs *Restake) Serialize() []byte {\n\treturn byteutil.Must(proto.Marshal(rs.Proto()))\n}", "func RunJSONSerializationTestForPartnerInfo(subject PartnerInfo) string {\n\t// Serialize to JSON\n\tbin, err := json.Marshal(subject)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Deserialize back into memory\n\tvar actual PartnerInfo\n\terr = json.Unmarshal(bin, &actual)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Check for outcome\n\tmatch := cmp.Equal(subject, actual, cmpopts.EquateEmpty())\n\tif !match {\n\t\tactualFmt := pretty.Sprint(actual)\n\t\tsubjectFmt := pretty.Sprint(subject)\n\t\tresult := diff.Diff(subjectFmt, actualFmt)\n\t\treturn result\n\t}\n\n\treturn \"\"\n}", "func (m *Directory) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.Entity.Serialize(writer)\n if err != nil {\n return err\n }\n if m.GetAdministrativeUnits() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetAdministrativeUnits()))\n for i, v := range m.GetAdministrativeUnits() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"administrativeUnits\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetAttributeSets() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetAttributeSets()))\n for i, v := range m.GetAttributeSets() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"attributeSets\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetCustomSecurityAttributeDefinitions() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetCustomSecurityAttributeDefinitions()))\n for i, v := range m.GetCustomSecurityAttributeDefinitions() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"customSecurityAttributeDefinitions\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetDeletedItems() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetDeletedItems()))\n for i, v := range m.GetDeletedItems() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"deletedItems\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetFederationConfigurations() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetFederationConfigurations()))\n for i, v := range m.GetFederationConfigurations() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"federationConfigurations\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetOnPremisesSynchronization() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetOnPremisesSynchronization()))\n for i, v := range m.GetOnPremisesSynchronization() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"onPremisesSynchronization\", cast)\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (m *MockisCryptoApiRequest_CryptoApiReq) MarshalTo(arg0 []byte) (int, error) {\n\tret := m.ctrl.Call(m, \"MarshalTo\", arg0)\n\tret0, _ := ret[0].(int)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockisCryptoApiResponse_CryptoApiResp) MarshalTo(arg0 []byte) (int, error) {\n\tret := m.ctrl.Call(m, \"MarshalTo\", arg0)\n\tret0, _ := ret[0].(int)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockisTlsProxyFlowConfig_Keys) MarshalTo(arg0 []byte) (int, error) {\n\tret := m.ctrl.Call(m, \"MarshalTo\", arg0)\n\tret0, _ := ret[0].(int)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func TestMarshal(t *testing.T) {\n\ttype mTest struct {\n\t\tB bool\n\t\tF float64\n\t\tS string\n\t}\n\tobjs := mTest{false, 1.0, \"foo\"}\n\trecv := mTest{}\n\tb, err := Marshal(objs)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\terr = Unmarshal(b, &recv)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif objs != recv {\n\t\tt.Error(\"input\", objs, \"does not match output\", recv)\n\t}\n}", "func (m *MockEncoder) Encode(arg0 Marshaler) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Encode\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func TestSerializeTimestampRFC3339(t *testing.T) {\n\tt.Parallel()\n\n\tcreated := time.Now().UTC()\n\tmodified := created.Add(time.Hour)\n\n\tdeployment, err := makeUntypedDeploymentTimestamp(\"b\", \"123abc\",\n\t\t\"v1:C7H2a7/Ietk=:v1:yfAd1zOi6iY9DRIB:dumdsr+H89VpHIQWdB01XEFqYaYjAg==\", &created, &modified)\n\tassert.NoError(t, err)\n\n\tcreatedStr := created.Format(time.RFC3339Nano)\n\tmodifiedStr := modified.Format(time.RFC3339Nano)\n\tassert.Contains(t, string(deployment.Deployment), createdStr)\n\tassert.Contains(t, string(deployment.Deployment), modifiedStr)\n}", "func (g *Generic) Serialize() ([]byte, error) {\n\tlog.Println(\"DEPRECATED: MarshalBinary instead\")\n\treturn g.MarshalBinary()\n}", "func (m *ReportRoot) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.Entity.Serialize(writer)\n if err != nil {\n return err\n }\n if m.GetAppCredentialSignInActivities() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetAppCredentialSignInActivities()))\n for i, v := range m.GetAppCredentialSignInActivities() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"appCredentialSignInActivities\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetApplicationSignInDetailedSummary() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetApplicationSignInDetailedSummary()))\n for i, v := range m.GetApplicationSignInDetailedSummary() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"applicationSignInDetailedSummary\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"authenticationMethods\", m.GetAuthenticationMethods())\n if err != nil {\n return err\n }\n }\n if m.GetCredentialUserRegistrationDetails() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetCredentialUserRegistrationDetails()))\n for i, v := range m.GetCredentialUserRegistrationDetails() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"credentialUserRegistrationDetails\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetDailyPrintUsage() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetDailyPrintUsage()))\n for i, v := range m.GetDailyPrintUsage() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"dailyPrintUsage\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetDailyPrintUsageByPrinter() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetDailyPrintUsageByPrinter()))\n for i, v := range m.GetDailyPrintUsageByPrinter() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"dailyPrintUsageByPrinter\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetDailyPrintUsageByUser() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetDailyPrintUsageByUser()))\n for i, v := range m.GetDailyPrintUsageByUser() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"dailyPrintUsageByUser\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetDailyPrintUsageSummariesByPrinter() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetDailyPrintUsageSummariesByPrinter()))\n for i, v := range m.GetDailyPrintUsageSummariesByPrinter() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"dailyPrintUsageSummariesByPrinter\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetDailyPrintUsageSummariesByUser() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetDailyPrintUsageSummariesByUser()))\n for i, v := range m.GetDailyPrintUsageSummariesByUser() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"dailyPrintUsageSummariesByUser\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetMonthlyPrintUsageByPrinter() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetMonthlyPrintUsageByPrinter()))\n for i, v := range m.GetMonthlyPrintUsageByPrinter() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"monthlyPrintUsageByPrinter\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetMonthlyPrintUsageByUser() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetMonthlyPrintUsageByUser()))\n for i, v := range m.GetMonthlyPrintUsageByUser() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"monthlyPrintUsageByUser\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetMonthlyPrintUsageSummariesByPrinter() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetMonthlyPrintUsageSummariesByPrinter()))\n for i, v := range m.GetMonthlyPrintUsageSummariesByPrinter() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"monthlyPrintUsageSummariesByPrinter\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetMonthlyPrintUsageSummariesByUser() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetMonthlyPrintUsageSummariesByUser()))\n for i, v := range m.GetMonthlyPrintUsageSummariesByUser() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"monthlyPrintUsageSummariesByUser\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"security\", m.GetSecurity())\n if err != nil {\n return err\n }\n }\n if m.GetServicePrincipalSignInActivities() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetServicePrincipalSignInActivities()))\n for i, v := range m.GetServicePrincipalSignInActivities() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"servicePrincipalSignInActivities\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"sla\", m.GetSla())\n if err != nil {\n return err\n }\n }\n if m.GetUserCredentialUsageDetails() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetUserCredentialUsageDetails()))\n for i, v := range m.GetUserCredentialUsageDetails() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"userCredentialUsageDetails\", cast)\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (m *MockisCryptoAsymApiRespSetupPrivateKey_KeyInfo) MarshalTo(arg0 []byte) (int, error) {\n\tret := m.ctrl.Call(m, \"MarshalTo\", arg0)\n\tret0, _ := ret[0].(int)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func TestTxSerializeSize(t *testing.T) {\n\t// Empty tx message.\n\tnoTx := NewNativeMsgTx(1, nil, nil)\n\n\ttests := []struct {\n\t\tin *MsgTx // Tx to encode\n\t\tsize int // Expected serialized size\n\t}{\n\t\t// No inputs or outpus.\n\t\t{noTx, 34},\n\n\t\t// Transcaction with an input and an output.\n\t\t{multiTx, 238},\n\t}\n\n\tt.Logf(\"Running %d tests\", len(tests))\n\tfor i, test := range tests {\n\t\tserializedSize := test.in.SerializeSize()\n\t\tif serializedSize != test.size {\n\t\t\tt.Errorf(\"MsgTx.SerializeSize: #%d got: %d, want: %d\", i,\n\t\t\t\tserializedSize, test.size)\n\t\t\tcontinue\n\t\t}\n\t}\n}", "func TestEncoderAndDecoder(t *testing.T) {\n\tbuf := new(bytes.Buffer)\n\n\tinPb := &example.A{\n\t\tDescription: \"hello world!\",\n\t\tNumber: 1,\n\t}\n\t// UUID is 16 byte long\n\tfor i := 0; i < 16; i++ {\n\t\tinPb.Id = append(inPb.Id, byte(i))\n\t}\n\n\tbytes, err := proto.Marshal(inPb)\n\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tmsg := NewMessage(0, bytes)\n\n\te := NewMsgEncoder(buf)\n\te.Encode(msg)\n\n\toutMsg := NewEmptyMessage()\n\n\td := NewMsgDecoder(buf)\n\td.Decode(outMsg)\n\n\tif !reflect.DeepEqual(msg, outMsg) {\n\t\tt.Fatal(\"Messages are not equal!\")\n\t}\n\n\toutPb := new(example.A)\n\n\tproto.Unmarshal(outMsg.bytes, outPb)\n\n\tif !reflect.DeepEqual(outPb, inPb) {\n\t\tt.Fatal(\"Protos are not equal!\")\n\t}\n}", "func TestEncodeRequest(t *testing.T) {\n\tassert := assert.New(t)\n\treq := NewRequest(\"GET\", \"url.com\", *auth)\n\treq.RequestBody = TestStructRequest{\"hi\"}\n\terr := req.EncodeRequestBody()\n\tassert.Nil(err)\n\tassert.NotNil(req.RequestReader)\n}", "func (m *ItemItemsItemWorkbookFunctionsRandBetweenPostRequestBody) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n {\n err := writer.WriteObjectValue(\"bottom\", m.GetBottom())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteObjectValue(\"top\", m.GetTop())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteAdditionalData(m.GetAdditionalData())\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (_e *MockTestTransportInstance_Expecter) Write(data interface{}) *MockTestTransportInstance_Write_Call {\n\treturn &MockTestTransportInstance_Write_Call{Call: _e.mock.On(\"Write\", data)}\n}", "func (m *MockisKey_KeyInfo) MarshalTo(arg0 []byte) (int, error) {\n\tret := m.ctrl.Call(m, \"MarshalTo\", arg0)\n\tret0, _ := ret[0].(int)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (defaultStorage) Serialize() (string, error) {\n\tpanic(noConfigStorage)\n}", "func (m *MockSerialInterface) MarshalIndent(v interface{}, prefix, indent string) ([]byte, error) {\n\tret := m.ctrl.Call(m, \"MarshalIndent\", v, prefix, indent)\n\tret0, _ := ret[0].([]byte)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *TestAllTypes) Marshal() []byte {\n\twriter := jspb.NewWriter()\n\tm.MarshalToWriter(writer)\n\treturn writer.GetResult()\n}", "func (m *IncomingContext) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n {\n err := writer.WriteStringValue(\"observedParticipantId\", m.GetObservedParticipantId())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"@odata.type\", m.GetOdataType())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteObjectValue(\"onBehalfOf\", m.GetOnBehalfOf())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"sourceParticipantId\", m.GetSourceParticipantId())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteObjectValue(\"transferor\", m.GetTransferor())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteAdditionalData(m.GetAdditionalData())\n if err != nil {\n return err\n }\n }\n return nil\n}" ]
[ "0.62063146", "0.6125965", "0.59509856", "0.59343916", "0.5882502", "0.58464044", "0.5813615", "0.58003867", "0.5799796", "0.5747636", "0.57350713", "0.57124287", "0.5706793", "0.5704014", "0.5584812", "0.55754673", "0.55690277", "0.553161", "0.55240047", "0.54972166", "0.5480678", "0.54798055", "0.54794204", "0.54451835", "0.5438735", "0.5425565", "0.5417792", "0.5417056", "0.54002035", "0.53773385", "0.53608507", "0.5346168", "0.5312921", "0.5310518", "0.53060704", "0.52969956", "0.5286789", "0.5280638", "0.5279902", "0.52739006", "0.52705145", "0.52516925", "0.5239422", "0.52273726", "0.5222874", "0.52126867", "0.52122545", "0.5200322", "0.51980704", "0.519339", "0.5190785", "0.5179167", "0.5175347", "0.51496935", "0.51428896", "0.5107871", "0.5104998", "0.51041126", "0.51011175", "0.50977796", "0.50928175", "0.5082243", "0.507926", "0.5076437", "0.5070648", "0.5063702", "0.5049136", "0.50397664", "0.50224316", "0.50151986", "0.5012291", "0.49927437", "0.4991275", "0.49873492", "0.49781007", "0.49778247", "0.49739733", "0.49738604", "0.49706036", "0.49685606", "0.4967178", "0.49665055", "0.496533", "0.49619576", "0.4949805", "0.49496174", "0.49473584", "0.4943221", "0.4943046", "0.49297753", "0.49276695", "0.4925806", "0.49249887", "0.49244455", "0.4924187", "0.49196076", "0.49148664", "0.49059066", "0.49027625", "0.4900397" ]
0.62714547
0
Serialize indicates an expected call of Serialize
func (mr *MockClientMockRecorder) Serialize() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Serialize", reflect.TypeOf((*MockClient)(nil).Serialize)) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (mr *MockManagerMockRecorder) SerializeNamespace(arg0 interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"SerializeNamespace\", reflect.TypeOf((*MockManager)(nil).SerializeNamespace), arg0)\n}", "func (e *Event) IsSerialized() bool {\n\treturn int32(e.GetType())&int32(EVENT_TYPE_SERIALIZED) != 0\n}", "func (s *Serializer) Serialize(p svermaker.ProjectVersion) error {\n\ts.SerializerInvoked = true\n\treturn s.SerializerFn(p)\n}", "func (mr *MockManagerMockRecorder) SerializeConfig(arg0, arg1, arg2 interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"SerializeConfig\", reflect.TypeOf((*MockManager)(nil).SerializeConfig), arg0, arg1, arg2)\n}", "func (mr *MockManagerMockRecorder) SerializeUpstream(arg0 interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"SerializeUpstream\", reflect.TypeOf((*MockManager)(nil).SerializeUpstream), arg0)\n}", "func (mr *MockManagerMockRecorder) SerializeAppMetadata(arg0 interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"SerializeAppMetadata\", reflect.TypeOf((*MockManager)(nil).SerializeAppMetadata), arg0)\n}", "func (mr *MockManagerMockRecorder) SerializeShipMetadata(arg0, arg1 interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"SerializeShipMetadata\", reflect.TypeOf((*MockManager)(nil).SerializeShipMetadata), arg0, arg1)\n}", "func Serialize(o interface{}) ([]byte, error) {\n\tautil.TODO(\"CBOR-serialization\")\n\treturn nil, nil\n}", "func (_mr *MockEncoderMockRecorder) Encode(arg0, arg1, arg2 interface{}) *gomock.Call {\n\treturn _mr.mock.ctrl.RecordCallWithMethodType(_mr.mock, \"Encode\", reflect.TypeOf((*MockEncoder)(nil).Encode), arg0, arg1, arg2)\n}", "func AssertSerialize(t *testing.T, dialect jet.Dialect, serializer jet.Serializer, query string, args ...interface{}) {\n\tout := jet.SQLBuilder{Dialect: dialect}\n\tjet.Serialize(serializer, jet.SelectStatementType, &out)\n\n\t//fmt.Println(out.Buff.String())\n\n\tAssertDeepEqual(t, out.Buff.String(), query)\n\n\tif len(args) > 0 {\n\t\tAssertDeepEqual(t, out.Args, args)\n\t}\n}", "func (mr *MockEncoderMockRecorder) Encode(message interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Encode\", reflect.TypeOf((*MockEncoder)(nil).Encode), message)\n}", "func (mr *MockEncoderMockRecorder) Encode(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Encode\", reflect.TypeOf((*MockEncoder)(nil).Encode), arg0)\n}", "func (mr *MockManagerMockRecorder) SerializeReleaseName(arg0 interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"SerializeReleaseName\", reflect.TypeOf((*MockManager)(nil).SerializeReleaseName), arg0)\n}", "func TestSer(t *testing.T) {\n\tt.Skip()\n}", "func (e *InvalidPageSizeError) Serialize() []byte {\n\tg, _ := json.Marshal(map[string]interface{}{\n\t\t\"code\": \"ERR-008\",\n\t\t\"error\": \"InvalidPageSizeError\",\n\t\t\"description\": e.Error(),\n\t\t\"success\": false,\n\t})\n\n\treturn g\n}", "func TestRecordSerialization(t *testing.T) {\n\tcommon.Log(\"test\", \"\\n\\nTestRecordSerialization\")\n\tindexFile, err := os.OpenFile(config.Base.IndexPrefix+\"_record_persistence_test\", os.O_RDWR|os.O_CREATE, 0666)\n\tcommon.FaceIt(err)\n\tdefer indexFile.Close()\n\n\trecord := common.Record{}\n\tslots := record.Slots()\n\tfor i := 0; i < len(slots); i++ {\n\t\t*slots[i] = uint64(i + 1)\n\t}\n\n\tindexFile.Seek(0, os.SEEK_SET)\n\tindexFile.Write(record.Serialize())\n\n\tindexFile.Seek(0, os.SEEK_SET)\n\treadRecord := common.Record{}\n\treadRecord.Deserialize(indexFile)\n\n\treadSlots := readRecord.Slots()\n\tfor i := 0; i < len(slots); i++ {\n\t\tif *slots[i] != *readSlots[i] {\n\t\t\tt.Fatalf(\"deserialized field %d ne expected %d\", *readSlots[i], *slots[i])\n\t\t}\n\t}\n}", "func (mr *MockSerialInterfaceMockRecorder) Marshal(v interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Marshal\", reflect.TypeOf((*MockSerialInterface)(nil).Marshal), v)\n}", "func (m *ActionResultPart) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n {\n err := writer.WriteObjectValue(\"error\", m.GetError())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"@odata.type\", m.GetOdataType())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteAdditionalData(m.GetAdditionalData())\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (m *VirtualEndpoint) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.Entity.Serialize(writer)\n if err != nil {\n return err\n }\n if m.GetAuditEvents() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetAuditEvents()))\n for i, v := range m.GetAuditEvents() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"auditEvents\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetBulkActions() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetBulkActions()))\n for i, v := range m.GetBulkActions() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"bulkActions\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetCloudPCs() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetCloudPCs()))\n for i, v := range m.GetCloudPCs() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"cloudPCs\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"crossCloudGovernmentOrganizationMapping\", m.GetCrossCloudGovernmentOrganizationMapping())\n if err != nil {\n return err\n }\n }\n if m.GetDeviceImages() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetDeviceImages()))\n for i, v := range m.GetDeviceImages() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"deviceImages\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetExternalPartnerSettings() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetExternalPartnerSettings()))\n for i, v := range m.GetExternalPartnerSettings() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"externalPartnerSettings\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetFrontLineServicePlans() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetFrontLineServicePlans()))\n for i, v := range m.GetFrontLineServicePlans() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"frontLineServicePlans\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetGalleryImages() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetGalleryImages()))\n for i, v := range m.GetGalleryImages() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"galleryImages\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetOnPremisesConnections() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetOnPremisesConnections()))\n for i, v := range m.GetOnPremisesConnections() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"onPremisesConnections\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"organizationSettings\", m.GetOrganizationSettings())\n if err != nil {\n return err\n }\n }\n if m.GetProvisioningPolicies() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetProvisioningPolicies()))\n for i, v := range m.GetProvisioningPolicies() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"provisioningPolicies\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"reports\", m.GetReports())\n if err != nil {\n return err\n }\n }\n if m.GetServicePlans() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetServicePlans()))\n for i, v := range m.GetServicePlans() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"servicePlans\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetSharedUseServicePlans() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetSharedUseServicePlans()))\n for i, v := range m.GetSharedUseServicePlans() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"sharedUseServicePlans\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetSnapshots() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetSnapshots()))\n for i, v := range m.GetSnapshots() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"snapshots\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetSupportedRegions() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetSupportedRegions()))\n for i, v := range m.GetSupportedRegions() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"supportedRegions\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetUserSettings() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetUserSettings()))\n for i, v := range m.GetUserSettings() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"userSettings\", cast)\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (mr *MockManagerMockRecorder) SerializeUpstreamContents(arg0 interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"SerializeUpstreamContents\", reflect.TypeOf((*MockManager)(nil).SerializeUpstreamContents), arg0)\n}", "func SerializePanic(in interface{}) []byte {\n\tbytes, err := Serialize(in)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn bytes\n}", "func (_e *MockWriteBufferJsonBased_Expecter) WriteSerializable(ctx interface{}, serializable interface{}) *MockWriteBufferJsonBased_WriteSerializable_Call {\n\treturn &MockWriteBufferJsonBased_WriteSerializable_Call{Call: _e.mock.On(\"WriteSerializable\", ctx, serializable)}\n}", "func (defaultStorage) Serialize() (string, error) {\n\tpanic(noConfigStorage)\n}", "func (_e *MockWriteBufferXmlBased_Expecter) WriteSerializable(ctx interface{}, serializable interface{}) *MockWriteBufferXmlBased_WriteSerializable_Call {\n\treturn &MockWriteBufferXmlBased_WriteSerializable_Call{Call: _e.mock.On(\"WriteSerializable\", ctx, serializable)}\n}", "func TestMarshal(t *testing.T) {\n\ttype mTest struct {\n\t\tB bool\n\t\tF float64\n\t\tS string\n\t}\n\tobjs := mTest{false, 1.0, \"foo\"}\n\trecv := mTest{}\n\tb, err := Marshal(objs)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\terr = Unmarshal(b, &recv)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif objs != recv {\n\t\tt.Error(\"input\", objs, \"does not match output\", recv)\n\t}\n}", "func (mr *MockManagerMockRecorder) SerializeHelmValues(arg0, arg1 interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"SerializeHelmValues\", reflect.TypeOf((*MockManager)(nil).SerializeHelmValues), arg0, arg1)\n}", "func (m *IncomingContext) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n {\n err := writer.WriteStringValue(\"observedParticipantId\", m.GetObservedParticipantId())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"@odata.type\", m.GetOdataType())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteObjectValue(\"onBehalfOf\", m.GetOnBehalfOf())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"sourceParticipantId\", m.GetSourceParticipantId())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteObjectValue(\"transferor\", m.GetTransferor())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteAdditionalData(m.GetAdditionalData())\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (req *PutRequest) serialize(w proto.Writer, serialVersion int16) (err error) {\n\treturn req.serializeInternal(w, serialVersion, true)\n}", "func (m *AgreementAcceptance) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.Entity.Serialize(writer)\n if err != nil {\n return err\n }\n {\n err = writer.WriteStringValue(\"agreementFileId\", m.GetAgreementFileId())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"agreementId\", m.GetAgreementId())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"deviceDisplayName\", m.GetDeviceDisplayName())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"deviceId\", m.GetDeviceId())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"deviceOSType\", m.GetDeviceOSType())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"deviceOSVersion\", m.GetDeviceOSVersion())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteTimeValue(\"expirationDateTime\", m.GetExpirationDateTime())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteTimeValue(\"recordedDateTime\", m.GetRecordedDateTime())\n if err != nil {\n return err\n }\n }\n if m.GetState() != nil {\n cast := (*m.GetState()).String()\n err = writer.WriteStringValue(\"state\", &cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"userDisplayName\", m.GetUserDisplayName())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"userEmail\", m.GetUserEmail())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"userId\", m.GetUserId())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"userPrincipalName\", m.GetUserPrincipalName())\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (mr *MockSerialMockRecorder) Write(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Write\", reflect.TypeOf((*MockSerial)(nil).Write), arg0)\n}", "func (JSONIndent) IsMarshal7951Arg() {}", "func (m *User) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.DirectoryObject.Serialize(writer)\n if err != nil {\n return err\n }\n {\n err = writer.WriteStringValue(\"aboutMe\", m.GetAboutMe())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteBoolValue(\"accountEnabled\", m.GetAccountEnabled())\n if err != nil {\n return err\n }\n }\n if m.GetActivities() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetActivities())\n err = writer.WriteCollectionOfObjectValues(\"activities\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"ageGroup\", m.GetAgeGroup())\n if err != nil {\n return err\n }\n }\n if m.GetAgreementAcceptances() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetAgreementAcceptances())\n err = writer.WriteCollectionOfObjectValues(\"agreementAcceptances\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetAppRoleAssignments() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetAppRoleAssignments())\n err = writer.WriteCollectionOfObjectValues(\"appRoleAssignments\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetAssignedLicenses() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetAssignedLicenses())\n err = writer.WriteCollectionOfObjectValues(\"assignedLicenses\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetAssignedPlans() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetAssignedPlans())\n err = writer.WriteCollectionOfObjectValues(\"assignedPlans\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"authentication\", m.GetAuthentication())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"authorizationInfo\", m.GetAuthorizationInfo())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteTimeValue(\"birthday\", m.GetBirthday())\n if err != nil {\n return err\n }\n }\n if m.GetBusinessPhones() != nil {\n err = writer.WriteCollectionOfStringValues(\"businessPhones\", m.GetBusinessPhones())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"calendar\", m.GetCalendar())\n if err != nil {\n return err\n }\n }\n if m.GetCalendarGroups() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetCalendarGroups())\n err = writer.WriteCollectionOfObjectValues(\"calendarGroups\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetCalendars() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetCalendars())\n err = writer.WriteCollectionOfObjectValues(\"calendars\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetCalendarView() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetCalendarView())\n err = writer.WriteCollectionOfObjectValues(\"calendarView\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetChats() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetChats())\n err = writer.WriteCollectionOfObjectValues(\"chats\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"city\", m.GetCity())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"companyName\", m.GetCompanyName())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"consentProvidedForMinor\", m.GetConsentProvidedForMinor())\n if err != nil {\n return err\n }\n }\n if m.GetContactFolders() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetContactFolders())\n err = writer.WriteCollectionOfObjectValues(\"contactFolders\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetContacts() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetContacts())\n err = writer.WriteCollectionOfObjectValues(\"contacts\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"country\", m.GetCountry())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteTimeValue(\"createdDateTime\", m.GetCreatedDateTime())\n if err != nil {\n return err\n }\n }\n if m.GetCreatedObjects() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetCreatedObjects())\n err = writer.WriteCollectionOfObjectValues(\"createdObjects\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"creationType\", m.GetCreationType())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"department\", m.GetDepartment())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteInt32Value(\"deviceEnrollmentLimit\", m.GetDeviceEnrollmentLimit())\n if err != nil {\n return err\n }\n }\n if m.GetDeviceManagementTroubleshootingEvents() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetDeviceManagementTroubleshootingEvents())\n err = writer.WriteCollectionOfObjectValues(\"deviceManagementTroubleshootingEvents\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetDirectReports() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetDirectReports())\n err = writer.WriteCollectionOfObjectValues(\"directReports\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"displayName\", m.GetDisplayName())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"drive\", m.GetDrive())\n if err != nil {\n return err\n }\n }\n if m.GetDrives() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetDrives())\n err = writer.WriteCollectionOfObjectValues(\"drives\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteTimeValue(\"employeeHireDate\", m.GetEmployeeHireDate())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"employeeId\", m.GetEmployeeId())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"employeeOrgData\", m.GetEmployeeOrgData())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"employeeType\", m.GetEmployeeType())\n if err != nil {\n return err\n }\n }\n if m.GetEvents() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetEvents())\n err = writer.WriteCollectionOfObjectValues(\"events\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetExtensions() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetExtensions())\n err = writer.WriteCollectionOfObjectValues(\"extensions\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"externalUserState\", m.GetExternalUserState())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteTimeValue(\"externalUserStateChangeDateTime\", m.GetExternalUserStateChangeDateTime())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"faxNumber\", m.GetFaxNumber())\n if err != nil {\n return err\n }\n }\n if m.GetFollowedSites() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetFollowedSites())\n err = writer.WriteCollectionOfObjectValues(\"followedSites\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"givenName\", m.GetGivenName())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteTimeValue(\"hireDate\", m.GetHireDate())\n if err != nil {\n return err\n }\n }\n if m.GetIdentities() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetIdentities())\n err = writer.WriteCollectionOfObjectValues(\"identities\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetImAddresses() != nil {\n err = writer.WriteCollectionOfStringValues(\"imAddresses\", m.GetImAddresses())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"inferenceClassification\", m.GetInferenceClassification())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"insights\", m.GetInsights())\n if err != nil {\n return err\n }\n }\n if m.GetInterests() != nil {\n err = writer.WriteCollectionOfStringValues(\"interests\", m.GetInterests())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteBoolValue(\"isResourceAccount\", m.GetIsResourceAccount())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"jobTitle\", m.GetJobTitle())\n if err != nil {\n return err\n }\n }\n if m.GetJoinedTeams() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetJoinedTeams())\n err = writer.WriteCollectionOfObjectValues(\"joinedTeams\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteTimeValue(\"lastPasswordChangeDateTime\", m.GetLastPasswordChangeDateTime())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"legalAgeGroupClassification\", m.GetLegalAgeGroupClassification())\n if err != nil {\n return err\n }\n }\n if m.GetLicenseAssignmentStates() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetLicenseAssignmentStates())\n err = writer.WriteCollectionOfObjectValues(\"licenseAssignmentStates\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetLicenseDetails() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetLicenseDetails())\n err = writer.WriteCollectionOfObjectValues(\"licenseDetails\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"mail\", m.GetMail())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"mailboxSettings\", m.GetMailboxSettings())\n if err != nil {\n return err\n }\n }\n if m.GetMailFolders() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetMailFolders())\n err = writer.WriteCollectionOfObjectValues(\"mailFolders\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"mailNickname\", m.GetMailNickname())\n if err != nil {\n return err\n }\n }\n if m.GetManagedAppRegistrations() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetManagedAppRegistrations())\n err = writer.WriteCollectionOfObjectValues(\"managedAppRegistrations\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetManagedDevices() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetManagedDevices())\n err = writer.WriteCollectionOfObjectValues(\"managedDevices\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"manager\", m.GetManager())\n if err != nil {\n return err\n }\n }\n if m.GetMemberOf() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetMemberOf())\n err = writer.WriteCollectionOfObjectValues(\"memberOf\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetMessages() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetMessages())\n err = writer.WriteCollectionOfObjectValues(\"messages\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"mobilePhone\", m.GetMobilePhone())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"mySite\", m.GetMySite())\n if err != nil {\n return err\n }\n }\n if m.GetOauth2PermissionGrants() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetOauth2PermissionGrants())\n err = writer.WriteCollectionOfObjectValues(\"oauth2PermissionGrants\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"officeLocation\", m.GetOfficeLocation())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"onenote\", m.GetOnenote())\n if err != nil {\n return err\n }\n }\n if m.GetOnlineMeetings() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetOnlineMeetings())\n err = writer.WriteCollectionOfObjectValues(\"onlineMeetings\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"onPremisesDistinguishedName\", m.GetOnPremisesDistinguishedName())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"onPremisesDomainName\", m.GetOnPremisesDomainName())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"onPremisesExtensionAttributes\", m.GetOnPremisesExtensionAttributes())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"onPremisesImmutableId\", m.GetOnPremisesImmutableId())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteTimeValue(\"onPremisesLastSyncDateTime\", m.GetOnPremisesLastSyncDateTime())\n if err != nil {\n return err\n }\n }\n if m.GetOnPremisesProvisioningErrors() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetOnPremisesProvisioningErrors())\n err = writer.WriteCollectionOfObjectValues(\"onPremisesProvisioningErrors\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"onPremisesSamAccountName\", m.GetOnPremisesSamAccountName())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"onPremisesSecurityIdentifier\", m.GetOnPremisesSecurityIdentifier())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteBoolValue(\"onPremisesSyncEnabled\", m.GetOnPremisesSyncEnabled())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"onPremisesUserPrincipalName\", m.GetOnPremisesUserPrincipalName())\n if err != nil {\n return err\n }\n }\n if m.GetOtherMails() != nil {\n err = writer.WriteCollectionOfStringValues(\"otherMails\", m.GetOtherMails())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"outlook\", m.GetOutlook())\n if err != nil {\n return err\n }\n }\n if m.GetOwnedDevices() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetOwnedDevices())\n err = writer.WriteCollectionOfObjectValues(\"ownedDevices\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetOwnedObjects() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetOwnedObjects())\n err = writer.WriteCollectionOfObjectValues(\"ownedObjects\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"passwordPolicies\", m.GetPasswordPolicies())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"passwordProfile\", m.GetPasswordProfile())\n if err != nil {\n return err\n }\n }\n if m.GetPastProjects() != nil {\n err = writer.WriteCollectionOfStringValues(\"pastProjects\", m.GetPastProjects())\n if err != nil {\n return err\n }\n }\n if m.GetPeople() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetPeople())\n err = writer.WriteCollectionOfObjectValues(\"people\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"photo\", m.GetPhoto())\n if err != nil {\n return err\n }\n }\n if m.GetPhotos() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetPhotos())\n err = writer.WriteCollectionOfObjectValues(\"photos\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"planner\", m.GetPlanner())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"postalCode\", m.GetPostalCode())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"preferredDataLocation\", m.GetPreferredDataLocation())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"preferredLanguage\", m.GetPreferredLanguage())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"preferredName\", m.GetPreferredName())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"presence\", m.GetPresence())\n if err != nil {\n return err\n }\n }\n if m.GetProvisionedPlans() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetProvisionedPlans())\n err = writer.WriteCollectionOfObjectValues(\"provisionedPlans\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetProxyAddresses() != nil {\n err = writer.WriteCollectionOfStringValues(\"proxyAddresses\", m.GetProxyAddresses())\n if err != nil {\n return err\n }\n }\n if m.GetRegisteredDevices() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetRegisteredDevices())\n err = writer.WriteCollectionOfObjectValues(\"registeredDevices\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetResponsibilities() != nil {\n err = writer.WriteCollectionOfStringValues(\"responsibilities\", m.GetResponsibilities())\n if err != nil {\n return err\n }\n }\n if m.GetSchools() != nil {\n err = writer.WriteCollectionOfStringValues(\"schools\", m.GetSchools())\n if err != nil {\n return err\n }\n }\n if m.GetScopedRoleMemberOf() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetScopedRoleMemberOf())\n err = writer.WriteCollectionOfObjectValues(\"scopedRoleMemberOf\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"securityIdentifier\", m.GetSecurityIdentifier())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"settings\", m.GetSettings())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteBoolValue(\"showInAddressList\", m.GetShowInAddressList())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteTimeValue(\"signInSessionsValidFromDateTime\", m.GetSignInSessionsValidFromDateTime())\n if err != nil {\n return err\n }\n }\n if m.GetSkills() != nil {\n err = writer.WriteCollectionOfStringValues(\"skills\", m.GetSkills())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"state\", m.GetState())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"streetAddress\", m.GetStreetAddress())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"surname\", m.GetSurname())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"teamwork\", m.GetTeamwork())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"todo\", m.GetTodo())\n if err != nil {\n return err\n }\n }\n if m.GetTransitiveMemberOf() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetTransitiveMemberOf())\n err = writer.WriteCollectionOfObjectValues(\"transitiveMemberOf\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"usageLocation\", m.GetUsageLocation())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"userPrincipalName\", m.GetUserPrincipalName())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"userType\", m.GetUserType())\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (mr *MockPKGMockRecorder) Encode() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Encode\", reflect.TypeOf((*MockPKG)(nil).Encode))\n}", "func Serialize(input interface{}) (msg []byte, err error) {\n\tbuffer, err := json.Marshal(input)\n\treturn buffer, err\n\n\t// TODO: Do we really need wire here?\n\t/*\n\t\tvar count int\n\n\t\tbuffer := new(bytes.Buffer)\n\n\t\twire.WriteBinary(input, buffer, &count, &err)\n\n\t\treturn buffer.Bytes(), err\n\t*/\n}", "func (*nopSerializer) Marshal(Message) ([]byte, error) { return nil, nil }", "func (m *OnlineMeetingInfo) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n {\n err := writer.WriteStringValue(\"conferenceId\", m.GetConferenceId())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"joinUrl\", m.GetJoinUrl())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"@odata.type\", m.GetOdataType())\n if err != nil {\n return err\n }\n }\n if m.GetPhones() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetPhones()))\n for i, v := range m.GetPhones() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err := writer.WriteCollectionOfObjectValues(\"phones\", cast)\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"quickDial\", m.GetQuickDial())\n if err != nil {\n return err\n }\n }\n if m.GetTollFreeNumbers() != nil {\n err := writer.WriteCollectionOfStringValues(\"tollFreeNumbers\", m.GetTollFreeNumbers())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"tollNumber\", m.GetTollNumber())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteAdditionalData(m.GetAdditionalData())\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (m *MockSerializer) CallOnly(data interface{}) error {\n\targs := m.MethodCalled(\"CallOnly\", data)\n\n\treturn args.Error(0)\n}", "func (mr *MockAPIMockRecorder) Marshal(arg0 interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Marshal\", reflect.TypeOf((*MockAPI)(nil).Marshal), arg0)\n}", "func (e *EntityNotFoundError) Serialize() []byte {\n\tg, _ := json.Marshal(map[string]interface{}{\n\t\t\"code\": \"ERR-001\",\n\t\t\"error\": \"EntityNotFoundError\",\n\t\t\"description\": e.Error(),\n\t\t\"success\": false,\n\t})\n\n\treturn g\n}", "func TestMsgSerialize(t *testing.T) {\n handler := new(CmdMsgHandler)\n cmd := new(CmdMsg)\n cmd.Cmd = CMD_ENV\n cmd.Data = \"\"\n\n b, err := handler.SerializeMsg(cmd)\n if err != nil {\n t.Fatal(err)\n }\n\n obj, err := handler.DeserializeMsg(b, 255)\n if err != nil {\n t.Fatal(err)\n }\n\n newCmd, ok := obj.(*CmdMsg)\n if !ok {\n t.Fatal(\"Invalid type received %T\", obj)\n }\n\n if cmd.Cmd != newCmd.Cmd {\n t.Fatalf(\n \"Cmd mismatch: %s vs %s\", \n cmd.Cmd, \n newCmd.Cmd,\n )\n }\n\n if cmd.Data != newCmd.Data {\n t.Fatalf(\n \"Data mismatch: %s vs %s\", \n cmd.Data, \n newCmd.Data,\n ) }\n\n log.Printf(\"TestMsgSerialize: passed\")\n}", "func (g *Generic) Serialize() ([]byte, error) {\n\tlog.Println(\"DEPRECATED: MarshalBinary instead\")\n\treturn g.MarshalBinary()\n}", "func (e *InvalidPageError) Serialize() []byte {\n\tg, _ := json.Marshal(map[string]interface{}{\n\t\t\"code\": \"ERR-007\",\n\t\t\"error\": \"InvalidPageError\",\n\t\t\"description\": e.Error(),\n\t\t\"success\": false,\n\t})\n\n\treturn g\n}", "func (m *DiscoveredSensitiveType) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n if m.GetClassificationAttributes() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetClassificationAttributes()))\n for i, v := range m.GetClassificationAttributes() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err := writer.WriteCollectionOfObjectValues(\"classificationAttributes\", cast)\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteInt32Value(\"confidence\", m.GetConfidence())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteInt32Value(\"count\", m.GetCount())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteUUIDValue(\"id\", m.GetId())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"@odata.type\", m.GetOdataType())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteAdditionalData(m.GetAdditionalData())\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (o Array_ID_A) Serialize(\n\tbyteOrder binary.ByteOrder,\n\tstream io.Writer,\n) error {\n\treturn fmt.Errorf(\"not yet implemented\")\n}", "func MustSerializeParams(o ...interface{}) []byte {\n\treturn MustSerialize(o)\n}", "func (m *CloudCommunications) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.Entity.Serialize(writer)\n if err != nil {\n return err\n }\n if m.GetCalls() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetCalls()))\n for i, v := range m.GetCalls() {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n err = writer.WriteCollectionOfObjectValues(\"calls\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetOnlineMeetings() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetOnlineMeetings()))\n for i, v := range m.GetOnlineMeetings() {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n err = writer.WriteCollectionOfObjectValues(\"onlineMeetings\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetPresences() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetPresences()))\n for i, v := range m.GetPresences() {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n err = writer.WriteCollectionOfObjectValues(\"presences\", cast)\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (b Bytes) Serialize() ([]byte, error) {\n\treturn b, nil\n}", "func TestTxSerializeSize(t *testing.T) {\n\t// Empty tx message.\n\tnoTx := NewNativeMsgTx(1, nil, nil)\n\n\ttests := []struct {\n\t\tin *MsgTx // Tx to encode\n\t\tsize int // Expected serialized size\n\t}{\n\t\t// No inputs or outpus.\n\t\t{noTx, 34},\n\n\t\t// Transcaction with an input and an output.\n\t\t{multiTx, 238},\n\t}\n\n\tt.Logf(\"Running %d tests\", len(tests))\n\tfor i, test := range tests {\n\t\tserializedSize := test.in.SerializeSize()\n\t\tif serializedSize != test.size {\n\t\t\tt.Errorf(\"MsgTx.SerializeSize: #%d got: %d, want: %d\", i,\n\t\t\t\tserializedSize, test.size)\n\t\t\tcontinue\n\t\t}\n\t}\n}", "func (m *ThreatAssessmentRequest) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.Entity.Serialize(writer)\n if err != nil {\n return err\n }\n if m.GetCategory() != nil {\n cast := (*m.GetCategory()).String()\n err = writer.WriteStringValue(\"category\", &cast)\n if err != nil {\n return err\n }\n }\n if m.GetContentType() != nil {\n cast := (*m.GetContentType()).String()\n err = writer.WriteStringValue(\"contentType\", &cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"createdBy\", m.GetCreatedBy())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteTimeValue(\"createdDateTime\", m.GetCreatedDateTime())\n if err != nil {\n return err\n }\n }\n if m.GetExpectedAssessment() != nil {\n cast := (*m.GetExpectedAssessment()).String()\n err = writer.WriteStringValue(\"expectedAssessment\", &cast)\n if err != nil {\n return err\n }\n }\n if m.GetRequestSource() != nil {\n cast := (*m.GetRequestSource()).String()\n err = writer.WriteStringValue(\"requestSource\", &cast)\n if err != nil {\n return err\n }\n }\n if m.GetResults() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetResults())\n err = writer.WriteCollectionOfObjectValues(\"results\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetStatus() != nil {\n cast := (*m.GetStatus()).String()\n err = writer.WriteStringValue(\"status\", &cast)\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (m *UserSimulationEventInfo) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n {\n err := writer.WriteStringValue(\"browser\", m.GetBrowser())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteTimeValue(\"eventDateTime\", m.GetEventDateTime())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"eventName\", m.GetEventName())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"ipAddress\", m.GetIpAddress())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"@odata.type\", m.GetOdataType())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"osPlatformDeviceDetails\", m.GetOsPlatformDeviceDetails())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteAdditionalData(m.GetAdditionalData())\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (m *SolutionsRoot) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n if m.GetBusinessScenarios() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetBusinessScenarios()))\n for i, v := range m.GetBusinessScenarios() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err := writer.WriteCollectionOfObjectValues(\"businessScenarios\", cast)\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"@odata.type\", m.GetOdataType())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteObjectValue(\"virtualEvents\", m.GetVirtualEvents())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteAdditionalData(m.GetAdditionalData())\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (mr *MockVirtualServiceClientMockRecorder) Write(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Write\", reflect.TypeOf((*MockVirtualServiceClient)(nil).Write), arg0, arg1)\n}", "func (m *Workbook) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.Entity.Serialize(writer)\n if err != nil {\n return err\n }\n {\n err = writer.WriteObjectValue(\"application\", m.GetApplication())\n if err != nil {\n return err\n }\n }\n if m.GetComments() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetComments())\n err = writer.WriteCollectionOfObjectValues(\"comments\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"functions\", m.GetFunctions())\n if err != nil {\n return err\n }\n }\n if m.GetNames() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetNames())\n err = writer.WriteCollectionOfObjectValues(\"names\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetOperations() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetOperations())\n err = writer.WriteCollectionOfObjectValues(\"operations\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetTables() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetTables())\n err = writer.WriteCollectionOfObjectValues(\"tables\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetWorksheets() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetWorksheets())\n err = writer.WriteCollectionOfObjectValues(\"worksheets\", cast)\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (msg *MsgTx) Serialize(w io.Writer) error {\n\t// At the current time, there is no difference between the protos encoding\n\t// at protocol version 0 and the stable long-term storage format. As\n\t// a result, make use of VVSEncode.\n\t//\n\t// Passing a encoding type of WitnessEncoding to VVSEncode for MsgTx\n\t// indicates that the transaction's witnesses (if any) should be\n\t// serialized according to the new serialization structure defined in\n\t// BIP0144.\n\treturn msg.VVSEncode(w, 0, BaseEncoding)\n}", "func (mr *MockBatchMockRecorder) Write() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Write\", reflect.TypeOf((*MockBatch)(nil).Write))\n}", "func (m *Media) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n {\n err := writer.WriteObjectValue(\"calleeDevice\", m.GetCalleeDevice())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteObjectValue(\"calleeNetwork\", m.GetCalleeNetwork())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteObjectValue(\"callerDevice\", m.GetCallerDevice())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteObjectValue(\"callerNetwork\", m.GetCallerNetwork())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"label\", m.GetLabel())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"@odata.type\", m.GetOdataType())\n if err != nil {\n return err\n }\n }\n if m.GetStreams() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetStreams())\n err := writer.WriteCollectionOfObjectValues(\"streams\", cast)\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteAdditionalData(m.GetAdditionalData())\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (m *Synchronization) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.Entity.Serialize(writer)\n if err != nil {\n return err\n }\n if m.GetJobs() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetJobs()))\n for i, v := range m.GetJobs() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"jobs\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetSecrets() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetSecrets()))\n for i, v := range m.GetSecrets() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"secrets\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetTemplates() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetTemplates()))\n for i, v := range m.GetTemplates() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"templates\", cast)\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (m *LabelActionBase) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n {\n err := writer.WriteStringValue(\"name\", m.GetName())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"@odata.type\", m.GetOdataType())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteAdditionalData(m.GetAdditionalData())\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (mr *MockHash32MockRecorder) Write(arg0 interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Write\", reflect.TypeOf((*MockHash32)(nil).Write), arg0)\n}", "func (m *Printer) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.PrinterBase.Serialize(writer)\n if err != nil {\n return err\n }\n if m.GetConnectors() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetConnectors()))\n for i, v := range m.GetConnectors() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"connectors\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteBoolValue(\"hasPhysicalDevice\", m.GetHasPhysicalDevice())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteBoolValue(\"isShared\", m.GetIsShared())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteTimeValue(\"lastSeenDateTime\", m.GetLastSeenDateTime())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteTimeValue(\"registeredDateTime\", m.GetRegisteredDateTime())\n if err != nil {\n return err\n }\n }\n if m.GetShares() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetShares()))\n for i, v := range m.GetShares() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"shares\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetTaskTriggers() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetTaskTriggers()))\n for i, v := range m.GetTaskTriggers() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"taskTriggers\", cast)\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (m *ExternalConnection) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.Entity.Serialize(writer)\n if err != nil {\n return err\n }\n {\n err = writer.WriteObjectValue(\"configuration\", m.GetConfiguration())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"description\", m.GetDescription())\n if err != nil {\n return err\n }\n }\n if m.GetGroups() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetGroups())\n err = writer.WriteCollectionOfObjectValues(\"groups\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetItems() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetItems())\n err = writer.WriteCollectionOfObjectValues(\"items\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"name\", m.GetName())\n if err != nil {\n return err\n }\n }\n if m.GetOperations() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetOperations())\n err = writer.WriteCollectionOfObjectValues(\"operations\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"schema\", m.GetSchema())\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (m *ThreatAssessmentRequest) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.Entity.Serialize(writer)\n if err != nil {\n return err\n }\n if m.GetCategory() != nil {\n cast := (*m.GetCategory()).String()\n err = writer.WriteStringValue(\"category\", &cast)\n if err != nil {\n return err\n }\n }\n if m.GetContentType() != nil {\n cast := (*m.GetContentType()).String()\n err = writer.WriteStringValue(\"contentType\", &cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"createdBy\", m.GetCreatedBy())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteTimeValue(\"createdDateTime\", m.GetCreatedDateTime())\n if err != nil {\n return err\n }\n }\n if m.GetExpectedAssessment() != nil {\n cast := (*m.GetExpectedAssessment()).String()\n err = writer.WriteStringValue(\"expectedAssessment\", &cast)\n if err != nil {\n return err\n }\n }\n if m.GetRequestSource() != nil {\n cast := (*m.GetRequestSource()).String()\n err = writer.WriteStringValue(\"requestSource\", &cast)\n if err != nil {\n return err\n }\n }\n if m.GetResults() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetResults()))\n for i, v := range m.GetResults() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"results\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetStatus() != nil {\n cast := (*m.GetStatus()).String()\n err = writer.WriteStringValue(\"status\", &cast)\n if err != nil {\n return err\n }\n }\n return nil\n}", "func AssertSerializeErr(t *testing.T, dialect jet.Dialect, clause jet.Serializer, errString string) {\n\tdefer func() {\n\t\tr := recover()\n\t\trequire.Equal(t, r, errString)\n\t}()\n\n\tout := jet.SQLBuilder{Dialect: dialect}\n\tjet.Serialize(clause, jet.SelectStatementType, &out)\n}", "func (mr *MockServerMockRecorder) Dump(arg0, arg1 interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Dump\", reflect.TypeOf((*MockServer)(nil).Dump), arg0, arg1)\n}", "func (m *EventMessageDetail) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n {\n err := writer.WriteStringValue(\"@odata.type\", m.GetOdataType())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteAdditionalData(m.GetAdditionalData())\n if err != nil {\n return err\n }\n }\n return nil\n}", "func RunJSONSerializationTestForPartnerInfo(subject PartnerInfo) string {\n\t// Serialize to JSON\n\tbin, err := json.Marshal(subject)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Deserialize back into memory\n\tvar actual PartnerInfo\n\terr = json.Unmarshal(bin, &actual)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Check for outcome\n\tmatch := cmp.Equal(subject, actual, cmpopts.EquateEmpty())\n\tif !match {\n\t\tactualFmt := pretty.Sprint(actual)\n\t\tsubjectFmt := pretty.Sprint(subject)\n\t\tresult := diff.Diff(subjectFmt, actualFmt)\n\t\treturn result\n\t}\n\n\treturn \"\"\n}", "func (mr *MockHash32MockRecorder) Write(p interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Write\", reflect.TypeOf((*MockHash32)(nil).Write), p)\n}", "func (mr *MockHashMockRecorder) Write(p interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Write\", reflect.TypeOf((*MockHash)(nil).Write), p)\n}", "func (m *Vulnerability) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.Entity.Serialize(writer)\n if err != nil {\n return err\n }\n {\n err = writer.WriteBoolValue(\"activeExploitsObserved\", m.GetActiveExploitsObserved())\n if err != nil {\n return err\n }\n }\n if m.GetArticles() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetArticles()))\n for i, v := range m.GetArticles() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"articles\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetCommonWeaknessEnumerationIds() != nil {\n err = writer.WriteCollectionOfStringValues(\"commonWeaknessEnumerationIds\", m.GetCommonWeaknessEnumerationIds())\n if err != nil {\n return err\n }\n }\n if m.GetComponents() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetComponents()))\n for i, v := range m.GetComponents() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"components\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteTimeValue(\"createdDateTime\", m.GetCreatedDateTime())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"cvss2Summary\", m.GetCvss2Summary())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"cvss3Summary\", m.GetCvss3Summary())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"description\", m.GetDescription())\n if err != nil {\n return err\n }\n }\n if m.GetExploits() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetExploits()))\n for i, v := range m.GetExploits() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"exploits\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteBoolValue(\"exploitsAvailable\", m.GetExploitsAvailable())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteBoolValue(\"hasChatter\", m.GetHasChatter())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteTimeValue(\"lastModifiedDateTime\", m.GetLastModifiedDateTime())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteInt32Value(\"priorityScore\", m.GetPriorityScore())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteTimeValue(\"publishedDateTime\", m.GetPublishedDateTime())\n if err != nil {\n return err\n }\n }\n if m.GetReferences() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetReferences()))\n for i, v := range m.GetReferences() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"references\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"remediation\", m.GetRemediation())\n if err != nil {\n return err\n }\n }\n if m.GetSeverity() != nil {\n cast := (*m.GetSeverity()).String()\n err = writer.WriteStringValue(\"severity\", &cast)\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (writer *Writer) Serialize(v interface{}) {\n\tif v == nil {\n\t\twriter.WriteNil()\n\t} else {\n\t\tv := reflect.ValueOf(v)\n\t\tvalueEncoders[v.Kind()](writer, v)\n\t}\n}", "func (o *A_2) Serialize(\r\n\tbyteOrder binary.ByteOrder,\r\n\tstream io.Writer,\r\n) error {\r\n\t//TODO: implement\r\n\t/*\r\n\t\tif err := o.cursor.Serialize(byteOrder, stream); err != nil {\r\n\t\t\treturn err\r\n\t\t}\r\n\t\t\tif err := o.limit.Serialize(byteOrder, stream); err != nil {\r\n\t\t\t\treturn err\r\n\t\t\t}\r\n\t*/\r\n\treturn fmt.Errorf(\"not yet implemented\")\r\n}", "func (m *Malware) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n {\n err := writer.WriteStringValue(\"description\", m.GetDescription())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"@odata.type\", m.GetOdataType())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteAdditionalData(m.GetAdditionalData())\n if err != nil {\n return err\n }\n }\n return nil\n}", "func TestTxSerialize(t *testing.T) {\n\tnoTx := NewNativeMsgTx(1, nil, nil)\n\tnoTxEncoded := []byte{\n\t\t0x01, 0x00, 0x00, 0x00, // Version\n\t\t0x00, // Varint for number of input transactions\n\t\t0x00, // Varint for number of output transactions\n\t\t0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Lock time\n\t\t0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n\t\t0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n\t\t0x00, 0x00, 0x00, 0x00, // Sub Network ID\n\t}\n\n\tregistryTx := NewRegistryMsgTx(1, nil, nil, 16)\n\tregistryTxEncoded := []byte{\n\t\t0x01, 0x00, 0x00, 0x00, // Version\n\t\t0x00, // Varint for number of input transactions\n\t\t0x00, // Varint for number of output transactions\n\t\t0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Lock time\n\t\t0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n\t\t0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n\t\t0x00, 0x00, 0x00, 0x00, // Sub Network ID\n\t\t0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Gas\n\t\t0x77, 0x56, 0x36, 0xb4, 0x89, 0x32, 0xe9, 0xa8,\n\t\t0xbb, 0x67, 0xe6, 0x54, 0x84, 0x36, 0x93, 0x8d,\n\t\t0x9f, 0xc5, 0x62, 0x49, 0x79, 0x5c, 0x0d, 0x0a,\n\t\t0x86, 0xaf, 0x7c, 0x5d, 0x54, 0x45, 0x4c, 0x4b, // Payload hash\n\t\t0x08, // Payload length varint\n\t\t0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Payload / Gas limit\n\t}\n\n\tsubnetworkTx := NewSubnetworkMsgTx(1, nil, nil, &subnetworkid.SubnetworkID{0xff}, 5, []byte{0, 1, 2})\n\n\tsubnetworkTxEncoded := []byte{\n\t\t0x01, 0x00, 0x00, 0x00, // Version\n\t\t0x00, // Varint for number of input transactions\n\t\t0x00, // Varint for number of output transactions\n\t\t0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Lock time\n\t\t0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n\t\t0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n\t\t0x00, 0x00, 0x00, 0x00, // Sub Network ID\n\t\t0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Gas\n\t\t0x35, 0xf9, 0xf2, 0x93, 0x0e, 0xa3, 0x44, 0x61,\n\t\t0x88, 0x22, 0x79, 0x5e, 0xee, 0xc5, 0x68, 0xae,\n\t\t0x67, 0xab, 0x29, 0x87, 0xd8, 0xb1, 0x9e, 0x45,\n\t\t0x91, 0xe1, 0x05, 0x27, 0xba, 0xa1, 0xdf, 0x3d, // Payload hash\n\t\t0x03, // Payload length varint\n\t\t0x00, 0x01, 0x02, // Payload\n\t}\n\n\ttests := []struct {\n\t\tname string\n\t\tin *MsgTx // Message to encode\n\t\tout *MsgTx // Expected decoded message\n\t\tbuf []byte // Serialized data\n\t\tscriptPubKeyLocs []int // Expected output script locations\n\t}{\n\t\t// No transactions.\n\t\t{\n\t\t\t\"noTx\",\n\t\t\tnoTx,\n\t\t\tnoTx,\n\t\t\tnoTxEncoded,\n\t\t\tnil,\n\t\t},\n\n\t\t// Registry Transaction.\n\t\t{\n\t\t\t\"registryTx\",\n\t\t\tregistryTx,\n\t\t\tregistryTx,\n\t\t\tregistryTxEncoded,\n\t\t\tnil,\n\t\t},\n\n\t\t// Sub Network Transaction.\n\t\t{\n\t\t\t\"subnetworkTx\",\n\t\t\tsubnetworkTx,\n\t\t\tsubnetworkTx,\n\t\t\tsubnetworkTxEncoded,\n\t\t\tnil,\n\t\t},\n\n\t\t// Multiple transactions.\n\t\t{\n\t\t\t\"multiTx\",\n\t\t\tmultiTx,\n\t\t\tmultiTx,\n\t\t\tmultiTxEncoded,\n\t\t\tmultiTxScriptPubKeyLocs,\n\t\t},\n\t}\n\n\tt.Logf(\"Running %d tests\", len(tests))\n\tfor i, test := range tests {\n\t\t// Serialize the transaction.\n\t\tvar buf bytes.Buffer\n\t\terr := test.in.Serialize(&buf)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Serialize %s: error %v\", test.name, err)\n\t\t\tcontinue\n\t\t}\n\t\tif !bytes.Equal(buf.Bytes(), test.buf) {\n\t\t\tt.Errorf(\"Serialize %s:\\n got: %s want: %s\", test.name,\n\t\t\t\tspew.Sdump(buf.Bytes()), spew.Sdump(test.buf))\n\t\t\tcontinue\n\t\t}\n\n\t\t// Deserialize the transaction.\n\t\tvar tx MsgTx\n\t\trbuf := bytes.NewReader(test.buf)\n\t\terr = tx.Deserialize(rbuf)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Deserialize #%d error %v\", i, err)\n\t\t\tcontinue\n\t\t}\n\t\tif !reflect.DeepEqual(&tx, test.out) {\n\t\t\tt.Errorf(\"Deserialize #%d\\n got: %s want: %s\", i,\n\t\t\t\tspew.Sdump(&tx), spew.Sdump(test.out))\n\t\t\tcontinue\n\t\t}\n\n\t\t// Ensure the public key script locations are accurate.\n\t\tscriptPubKeyLocs := test.in.ScriptPubKeyLocs()\n\t\tif !reflect.DeepEqual(scriptPubKeyLocs, test.scriptPubKeyLocs) {\n\t\t\tt.Errorf(\"ScriptPubKeyLocs #%d\\n got: %s want: %s\", i,\n\t\t\t\tspew.Sdump(scriptPubKeyLocs),\n\t\t\t\tspew.Sdump(test.scriptPubKeyLocs))\n\t\t\tcontinue\n\t\t}\n\t\tfor j, loc := range scriptPubKeyLocs {\n\t\t\twantScriptPubKey := test.in.TxOut[j].ScriptPubKey\n\t\t\tgotScriptPubKey := test.buf[loc : loc+len(wantScriptPubKey)]\n\t\t\tif !bytes.Equal(gotScriptPubKey, wantScriptPubKey) {\n\t\t\t\tt.Errorf(\"ScriptPubKeyLocs #%d:%d\\n unexpected \"+\n\t\t\t\t\t\"script got: %s want: %s\", i, j,\n\t\t\t\t\tspew.Sdump(gotScriptPubKey),\n\t\t\t\t\tspew.Sdump(wantScriptPubKey))\n\t\t\t}\n\t\t}\n\t}\n}", "func (a *AddMixer) Serialize() ([]byte, error) {\n\treturn serializer.SerializeAny(a.In1, a.In2, a.Out)\n}", "func (m *DeviceAndAppManagementAssignmentFilter) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.Entity.Serialize(writer)\n if err != nil {\n return err\n }\n if m.GetAssignmentFilterManagementType() != nil {\n cast := (*m.GetAssignmentFilterManagementType()).String()\n err = writer.WriteStringValue(\"assignmentFilterManagementType\", &cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteTimeValue(\"createdDateTime\", m.GetCreatedDateTime())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"description\", m.GetDescription())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"displayName\", m.GetDisplayName())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteTimeValue(\"lastModifiedDateTime\", m.GetLastModifiedDateTime())\n if err != nil {\n return err\n }\n }\n if m.GetPayloads() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetPayloads()))\n for i, v := range m.GetPayloads() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"payloads\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetPlatform() != nil {\n cast := (*m.GetPlatform()).String()\n err = writer.WriteStringValue(\"platform\", &cast)\n if err != nil {\n return err\n }\n }\n if m.GetRoleScopeTags() != nil {\n err = writer.WriteCollectionOfStringValues(\"roleScopeTags\", m.GetRoleScopeTags())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"rule\", m.GetRule())\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (mr *MockManagerMockRecorder) SerializeContentSHA(arg0 interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"SerializeContentSHA\", reflect.TypeOf((*MockManager)(nil).SerializeContentSHA), arg0)\n}", "func Serialize(data interface{}) string {\n\tval, _ := json.Marshal(data)\n\treturn string(val);\n}", "func (t *TxIn) SerializeSize() int {\n\treturn 37\n}", "func (a *Aggregate) Serialize(ctx context.Context) {\n\tselect {\n\tcase a.serialize <- struct{}{}:\n\tcase <-time.After(time.Minute):\n\t\tdlog.Server.Warn(\"Starting to serialize mapredice data takes over a minute\")\n\tcase <-ctx.Done():\n\t}\n}", "func (mr *MockConnMockRecorder) WriteJSON(v interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"WriteJSON\", reflect.TypeOf((*MockConn)(nil).WriteJSON), v)\n}", "func TestEmitInterfaceFailure(t *testing.T) {\n\tbatch := NewBatch()\n\t// See https://stackoverflow.com/a/48901259\n\tx := map[string]interface{}{\n\t\t\"foo\": make(chan int),\n\t}\n\terr := batch.emitInterface(x)\n\tswitch err.(type) {\n\tcase *json.UnsupportedTypeError:\n\t\t// nothing\n\tdefault:\n\t\tt.Fatal(\"Expected a json.UnsupportedTypeError here\")\n\t}\n}", "func (m *SimulationEventCollectionResponse) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.BaseCollectionPaginationCountResponse.Serialize(writer)\n if err != nil {\n return err\n }\n if m.GetValue() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetValue()))\n for i, v := range m.GetValue() {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n err = writer.WriteCollectionOfObjectValues(\"value\", cast)\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (m *ActivateDeviceEsimActionResult) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.DeviceActionResult.Serialize(writer)\n if err != nil {\n return err\n }\n {\n err = writer.WriteStringValue(\"carrierUrl\", m.GetCarrierUrl())\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (m *AccessPackage) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.Entity.Serialize(writer)\n if err != nil {\n return err\n }\n if m.GetAccessPackagesIncompatibleWith() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetAccessPackagesIncompatibleWith())\n err = writer.WriteCollectionOfObjectValues(\"accessPackagesIncompatibleWith\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetAssignmentPolicies() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetAssignmentPolicies())\n err = writer.WriteCollectionOfObjectValues(\"assignmentPolicies\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"catalog\", m.GetCatalog())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteTimeValue(\"createdDateTime\", m.GetCreatedDateTime())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"description\", m.GetDescription())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"displayName\", m.GetDisplayName())\n if err != nil {\n return err\n }\n }\n if m.GetIncompatibleAccessPackages() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetIncompatibleAccessPackages())\n err = writer.WriteCollectionOfObjectValues(\"incompatibleAccessPackages\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetIncompatibleGroups() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetIncompatibleGroups())\n err = writer.WriteCollectionOfObjectValues(\"incompatibleGroups\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteBoolValue(\"isHidden\", m.GetIsHidden())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteTimeValue(\"modifiedDateTime\", m.GetModifiedDateTime())\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (m *List) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.BaseItem.Serialize(writer)\n if err != nil {\n return err\n }\n if m.GetColumns() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetColumns())\n err = writer.WriteCollectionOfObjectValues(\"columns\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetContentTypes() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetContentTypes())\n err = writer.WriteCollectionOfObjectValues(\"contentTypes\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"displayName\", m.GetDisplayName())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"drive\", m.GetDrive())\n if err != nil {\n return err\n }\n }\n if m.GetItems() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetItems())\n err = writer.WriteCollectionOfObjectValues(\"items\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"list\", m.GetList())\n if err != nil {\n return err\n }\n }\n if m.GetOperations() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetOperations())\n err = writer.WriteCollectionOfObjectValues(\"operations\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"sharepointIds\", m.GetSharepointIds())\n if err != nil {\n return err\n }\n }\n if m.GetSubscriptions() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetSubscriptions())\n err = writer.WriteCollectionOfObjectValues(\"subscriptions\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"system\", m.GetSystem())\n if err != nil {\n return err\n }\n }\n return nil\n}", "func AuthMsgsSerializationTest(t *testing.T, serializerTest func(t *testing.T, msg wire.Msg)) {\n\tt.Helper()\n\n\trng := pkgtest.Prng(t)\n\tserializerTest(t, wire.NewAuthResponseMsg(NewRandomAccount(rng)))\n}", "func (mr *MockManagerMockRecorder) SaveKustomize(arg0 interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"SaveKustomize\", reflect.TypeOf((*MockManager)(nil).SaveKustomize), arg0)\n}", "func serializeResponse(w http.ResponseWriter, payload interface{}) ([]byte, bool) {\n\tglog.V(6).Infof(APIlogString(fmt.Sprintf(\"response payload before serialization (%T): %v\", payload, payload)))\n\n\tserial, err := json.Marshal(payload)\n\tif err != nil {\n\t\tglog.Error(APIlogString(err))\n\t\thttp.Error(w, \"Internal server error\", http.StatusInternalServerError)\n\t\treturn nil, true\n\t}\n\n\treturn serial, false\n}", "func TestPacket_Serialize(t *testing.T) {\n\ttearDown := setUp(t)\n\tdefer tearDown(t)\n\n\tdata := packet.Serialize()\n\tassert.Equal(t, []byte{0x21, 0x31}, data[0:2])\n\tassert.Equal(t, uint16(len(payload)+32), binary.BigEndian.Uint16(data[2:4]))\n\tassert.Equal(t, uint32(0), binary.BigEndian.Uint32(data[4:8]))\n\tassert.Equal(t, uint32(0xAAAABBBB), binary.BigEndian.Uint32(data[8:12]))\n\tassert.Equal(t, uint32(0xCCCCDDDD), binary.BigEndian.Uint32(data[12:16]))\n\tassert.Equal(t, deviceToken, data[16:32])\n}", "func (mr *MockSnapshotMockRecorder) MarshalJSON() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"MarshalJSON\", reflect.TypeOf((*MockSnapshot)(nil).MarshalJSON))\n}", "func (mr *MockResponseWriterMockRecorder) Write(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Write\", reflect.TypeOf((*MockResponseWriter)(nil).Write), arg0)\n}", "func (m *Application) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.DirectoryObject.Serialize(writer)\n if err != nil {\n return err\n }\n if m.GetAddIns() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetAddIns())\n err = writer.WriteCollectionOfObjectValues(\"addIns\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"api\", m.GetApi())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"appId\", m.GetAppId())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"applicationTemplateId\", m.GetApplicationTemplateId())\n if err != nil {\n return err\n }\n }\n if m.GetAppRoles() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetAppRoles())\n err = writer.WriteCollectionOfObjectValues(\"appRoles\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"certification\", m.GetCertification())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteTimeValue(\"createdDateTime\", m.GetCreatedDateTime())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"createdOnBehalfOf\", m.GetCreatedOnBehalfOf())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"defaultRedirectUri\", m.GetDefaultRedirectUri())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"description\", m.GetDescription())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"disabledByMicrosoftStatus\", m.GetDisabledByMicrosoftStatus())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"displayName\", m.GetDisplayName())\n if err != nil {\n return err\n }\n }\n if m.GetExtensionProperties() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetExtensionProperties())\n err = writer.WriteCollectionOfObjectValues(\"extensionProperties\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetFederatedIdentityCredentials() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetFederatedIdentityCredentials())\n err = writer.WriteCollectionOfObjectValues(\"federatedIdentityCredentials\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"groupMembershipClaims\", m.GetGroupMembershipClaims())\n if err != nil {\n return err\n }\n }\n if m.GetHomeRealmDiscoveryPolicies() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetHomeRealmDiscoveryPolicies())\n err = writer.WriteCollectionOfObjectValues(\"homeRealmDiscoveryPolicies\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetIdentifierUris() != nil {\n err = writer.WriteCollectionOfStringValues(\"identifierUris\", m.GetIdentifierUris())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"info\", m.GetInfo())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteBoolValue(\"isDeviceOnlyAuthSupported\", m.GetIsDeviceOnlyAuthSupported())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteBoolValue(\"isFallbackPublicClient\", m.GetIsFallbackPublicClient())\n if err != nil {\n return err\n }\n }\n if m.GetKeyCredentials() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetKeyCredentials())\n err = writer.WriteCollectionOfObjectValues(\"keyCredentials\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteByteArrayValue(\"logo\", m.GetLogo())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"notes\", m.GetNotes())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteBoolValue(\"oauth2RequirePostResponse\", m.GetOauth2RequirePostResponse())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"optionalClaims\", m.GetOptionalClaims())\n if err != nil {\n return err\n }\n }\n if m.GetOwners() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetOwners())\n err = writer.WriteCollectionOfObjectValues(\"owners\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"parentalControlSettings\", m.GetParentalControlSettings())\n if err != nil {\n return err\n }\n }\n if m.GetPasswordCredentials() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetPasswordCredentials())\n err = writer.WriteCollectionOfObjectValues(\"passwordCredentials\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"publicClient\", m.GetPublicClient())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"publisherDomain\", m.GetPublisherDomain())\n if err != nil {\n return err\n }\n }\n if m.GetRequiredResourceAccess() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetRequiredResourceAccess())\n err = writer.WriteCollectionOfObjectValues(\"requiredResourceAccess\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"samlMetadataUrl\", m.GetSamlMetadataUrl())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"serviceManagementReference\", m.GetServiceManagementReference())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"signInAudience\", m.GetSignInAudience())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"spa\", m.GetSpa())\n if err != nil {\n return err\n }\n }\n if m.GetTags() != nil {\n err = writer.WriteCollectionOfStringValues(\"tags\", m.GetTags())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"tokenEncryptionKeyId\", m.GetTokenEncryptionKeyId())\n if err != nil {\n return err\n }\n }\n if m.GetTokenIssuancePolicies() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetTokenIssuancePolicies())\n err = writer.WriteCollectionOfObjectValues(\"tokenIssuancePolicies\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetTokenLifetimePolicies() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetTokenLifetimePolicies())\n err = writer.WriteCollectionOfObjectValues(\"tokenLifetimePolicies\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"verifiedPublisher\", m.GetVerifiedPublisher())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"web\", m.GetWeb())\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (m *ItemItemsItemWorkbookFunctionsRandBetweenPostRequestBody) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n {\n err := writer.WriteObjectValue(\"bottom\", m.GetBottom())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteObjectValue(\"top\", m.GetTop())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteAdditionalData(m.GetAdditionalData())\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (m *Set) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.Entity.Serialize(writer)\n if err != nil {\n return err\n }\n if m.GetChildren() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetChildren()))\n for i, v := range m.GetChildren() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"children\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteTimeValue(\"createdDateTime\", m.GetCreatedDateTime())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"description\", m.GetDescription())\n if err != nil {\n return err\n }\n }\n if m.GetLocalizedNames() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetLocalizedNames()))\n for i, v := range m.GetLocalizedNames() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"localizedNames\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"parentGroup\", m.GetParentGroup())\n if err != nil {\n return err\n }\n }\n if m.GetProperties() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetProperties()))\n for i, v := range m.GetProperties() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"properties\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetRelations() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetRelations()))\n for i, v := range m.GetRelations() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"relations\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetTerms() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetTerms()))\n for i, v := range m.GetTerms() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"terms\", cast)\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (m *AttackSimulationRoot) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.Entity.Serialize(writer)\n if err != nil {\n return err\n }\n if m.GetSimulationAutomations() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetSimulationAutomations())\n err = writer.WriteCollectionOfObjectValues(\"simulationAutomations\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetSimulations() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetSimulations())\n err = writer.WriteCollectionOfObjectValues(\"simulations\", cast)\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (m *Reminder) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n {\n err := writer.WriteStringValue(\"changeKey\", m.GetChangeKey())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteObjectValue(\"eventEndTime\", m.GetEventEndTime())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"eventId\", m.GetEventId())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteObjectValue(\"eventLocation\", m.GetEventLocation())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteObjectValue(\"eventStartTime\", m.GetEventStartTime())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"eventSubject\", m.GetEventSubject())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"eventWebLink\", m.GetEventWebLink())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"@odata.type\", m.GetOdataType())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteObjectValue(\"reminderFireTime\", m.GetReminderFireTime())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteAdditionalData(m.GetAdditionalData())\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (m *RequestSchedule) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n {\n err := writer.WriteObjectValue(\"expiration\", m.GetExpiration())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"@odata.type\", m.GetOdataType())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteObjectValue(\"recurrence\", m.GetRecurrence())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteTimeValue(\"startDateTime\", m.GetStartDateTime())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteAdditionalData(m.GetAdditionalData())\n if err != nil {\n return err\n }\n }\n return nil\n}", "func TestMarshal(t *testing.T) {\n\tfor _, c := range []struct {\n\t\tname string\n\t\tfieldPairs []interface{}\n\t\t// errNeedle is \"\" if we expect no error. Otherwise, it is a string that\n\t\t// we expect to see in the resulting err.Error().\n\t\terrNeedle string\n\t}{\n\t\t{\n\t\t\t\"no fields\",\n\t\t\t[]interface{}{},\n\t\t\t\"\",\n\t\t},\n\t\t{\n\t\t\t\"simple\",\n\t\t\t[]interface{}{\"k0\", \"v0\"},\n\t\t\t\"\",\n\t\t},\n\t\t{\n\t\t\t\"mixed value types\",\n\t\t\t// Numeric types turn into float64s in JSON.\n\t\t\t[]interface{}{\"k0\", \"v0\", \"k1\", float64(1), \"k2\", true},\n\t\t\t\"\",\n\t\t},\n\t\t{\n\t\t\t\"odd field pairs\",\n\t\t\t[]interface{}{\"k0\", \"v0\", \"k1\"},\n\t\t\t\"even\",\n\t\t},\n\t\t{\n\t\t\t\"non-string key\",\n\t\t\t[]interface{}{0, \"v0\"},\n\t\t\t\"string\",\n\t\t},\n\t\t{\n\t\t\t\"duplicate keys\",\n\t\t\t[]interface{}{\"k0\", \"v0\", \"k0\", \"v1\"},\n\t\t\t\"duplicate\",\n\t\t},\n\t} {\n\t\tt.Run(c.name, func(t *testing.T) {\n\t\t\tmarshalOK := c.errNeedle == \"\"\n\t\t\ts, err := Marshal(c.name, c.fieldPairs)\n\t\t\tif got, want := err == nil, marshalOK; got != want {\n\t\t\t\tt.Fatalf(\"got %v, want %v\", got, want)\n\t\t\t}\n\t\t\tif !marshalOK {\n\t\t\t\tif !strings.Contains(err.Error(), c.errNeedle) {\n\t\t\t\t\tt.Errorf(\"error %q does not contain expected substring %q\", err.Error(), c.errNeedle)\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\t\t\tvar m map[string]interface{}\n\t\t\terr = json.Unmarshal([]byte(s), &m)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatalf(\"unmarshaling failed: %v\", err)\n\t\t\t}\n\t\t\t// The +1 is for the eventType.\n\t\t\tif got, want := len(m), (len(c.fieldPairs)/2)+1; got != want {\n\t\t\t\tt.Errorf(\"got %v, want %v\", got, want)\n\t\t\t}\n\t\t\ttyp, ok := m[eventTypeFieldKey]\n\t\t\tif ok {\n\t\t\t\tif got, want := typ, c.name; got != want {\n\t\t\t\t\tt.Errorf(\"got %v, want %v\", got, want)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tt.Errorf(\"eventType field not marshaled\")\n\t\t\t}\n\t\t\tfor i := 0; i < len(c.fieldPairs); i++ {\n\t\t\t\tkey := c.fieldPairs[i].(string)\n\t\t\t\ti++\n\t\t\t\tvalue := c.fieldPairs[i]\n\t\t\t\tmvalue, ok := m[key]\n\t\t\t\tif !ok {\n\t\t\t\t\tt.Errorf(\"field with key %q not marshaled\", key)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif got, want := mvalue, value; got != want {\n\t\t\t\t\tt.Errorf(\"got %v(%T), want %v(%T)\", got, got, want, want)\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n}", "func (m *BusinessFlowCollectionResponse) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.BaseCollectionPaginationCountResponse.Serialize(writer)\n if err != nil {\n return err\n }\n if m.GetValue() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetValue()))\n for i, v := range m.GetValue() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"value\", cast)\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (msg *Block) SerializeNoWitness(w io.Writer) (e error) {\n\treturn msg.BtcEncode(w, 0, BaseEncoding)\n}" ]
[ "0.6066313", "0.5894949", "0.5891789", "0.58146894", "0.58111197", "0.5800852", "0.5732166", "0.57182896", "0.55868983", "0.55799645", "0.55763125", "0.5544834", "0.5529394", "0.5507338", "0.5499269", "0.5482491", "0.5481901", "0.5469212", "0.546522", "0.5440465", "0.54272604", "0.54016376", "0.53917485", "0.53813607", "0.5371474", "0.5365194", "0.5359742", "0.5357882", "0.53572536", "0.5350572", "0.53293043", "0.53220695", "0.5318806", "0.5313016", "0.5306094", "0.5302456", "0.53023076", "0.5300225", "0.529986", "0.52955246", "0.52951837", "0.5289414", "0.52698976", "0.52405155", "0.5234871", "0.52215576", "0.52101296", "0.5191993", "0.518095", "0.5177197", "0.5176464", "0.51597553", "0.515671", "0.5154559", "0.5150638", "0.5144947", "0.5142756", "0.5142592", "0.5142583", "0.5141763", "0.5135505", "0.5134551", "0.5134092", "0.5132791", "0.5130238", "0.5126162", "0.5109759", "0.51078534", "0.5107435", "0.50944555", "0.5088248", "0.5087528", "0.5084496", "0.5071822", "0.5067964", "0.506701", "0.50636137", "0.5052545", "0.5049188", "0.504771", "0.5045206", "0.50443727", "0.50403184", "0.50355065", "0.50275964", "0.50247204", "0.502428", "0.50184923", "0.50171775", "0.50053996", "0.50027895", "0.5001944", "0.5001132", "0.4996849", "0.499552", "0.49908665", "0.4990672", "0.49887103", "0.49875376", "0.49847063" ]
0.70770717
0
Sign mocks base method
func (m *MockClient) Sign(arg0 []byte) ([]byte, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Sign", arg0) ret0, _ := ret[0].([]byte) ret1, _ := ret[1].(error) return ret0, ret1 }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (m *CryptographyServiceMock) Sign(p []byte) (r *insolar.Signature, r1 error) {\n\tcounter := atomic.AddUint64(&m.SignPreCounter, 1)\n\tdefer atomic.AddUint64(&m.SignCounter, 1)\n\n\tif len(m.SignMock.expectationSeries) > 0 {\n\t\tif counter > uint64(len(m.SignMock.expectationSeries)) {\n\t\t\tm.t.Fatalf(\"Unexpected call to CryptographyServiceMock.Sign. %v\", p)\n\t\t\treturn\n\t\t}\n\n\t\tinput := m.SignMock.expectationSeries[counter-1].input\n\t\ttestify_assert.Equal(m.t, *input, CryptographyServiceMockSignInput{p}, \"CryptographyService.Sign got unexpected parameters\")\n\n\t\tresult := m.SignMock.expectationSeries[counter-1].result\n\t\tif result == nil {\n\t\t\tm.t.Fatal(\"No results are set for the CryptographyServiceMock.Sign\")\n\t\t\treturn\n\t\t}\n\n\t\tr = result.r\n\t\tr1 = result.r1\n\n\t\treturn\n\t}\n\n\tif m.SignMock.mainExpectation != nil {\n\n\t\tinput := m.SignMock.mainExpectation.input\n\t\tif input != nil {\n\t\t\ttestify_assert.Equal(m.t, *input, CryptographyServiceMockSignInput{p}, \"CryptographyService.Sign got unexpected parameters\")\n\t\t}\n\n\t\tresult := m.SignMock.mainExpectation.result\n\t\tif result == nil {\n\t\t\tm.t.Fatal(\"No results are set for the CryptographyServiceMock.Sign\")\n\t\t}\n\n\t\tr = result.r\n\t\tr1 = result.r1\n\n\t\treturn\n\t}\n\n\tif m.SignFunc == nil {\n\t\tm.t.Fatalf(\"Unexpected call to CryptographyServiceMock.Sign. %v\", p)\n\t\treturn\n\t}\n\n\treturn m.SignFunc(p)\n}", "func (m *MockSigner) Sign(arg0 *ecdsa.PrivateKey, arg1 proto0.Message) (*proto.Signature, error) {\n\tret := m.ctrl.Call(m, \"Sign\", arg0, arg1)\n\tret0, _ := ret[0].(*proto.Signature)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (b *Base) Sign(req *SignReq) (*SignResp, error) {\n\treturn nil, ErrFunctionNotSupported\n}", "func TestSign(w http.ResponseWriter, r *http.Request) {\n\tconf := ConfLoad()\n\n\t// Returns a Public / Private Key Pair\n\t// Read JSON config from app.yaml\n\tif v := os.Getenv(\"PRIV_KEY\"); v != \"\" {\n\t\terr := json.Unmarshal([]byte(v), &conf)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"%#v\", conf)\n\t\t\tpanic(err)\n\t\t}\n\t}\n\n\t// Get the public key\n\tvar pubkey ecdsa.PublicKey\n\tpubkey = conf.PublicKey\n\n\t// Try signing a message\n\tmessage := []byte(\"99999999\")\n\tsig1, sig2, err := ecdsa.Sign(rand.Reader, &conf.PrivateKey, message)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// Try verifying the signature\n\tresult := ecdsa.Verify(&pubkey, message, sig1, sig2)\n\tif result != true {\n\t\tpanic(\"Unable to verify signature\")\n\t}\n\n\tfmt.Fprintf(w, \"message: %#v\\n\\nsig1: %#v\\nsig2: %#v\", string(message[:]), sig1, sig2)\n\n}", "func (_Ethdkg *EthdkgCaller) Sign(opts *bind.CallOpts, message []byte, privK *big.Int) ([2]*big.Int, error) {\n\tvar (\n\t\tret0 = new([2]*big.Int)\n\t)\n\tout := ret0\n\terr := _Ethdkg.contract.Call(opts, out, \"Sign\", message, privK)\n\treturn *ret0, err\n}", "func (m *MockTransactionApi) SignWithPrivkey(tx *types.Transaction, outpoint *types.OutPoint, privkey *types.Privkey, sighashType types.SigHashType, utxoList *[]types.UtxoData) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"SignWithPrivkey\", tx, outpoint, privkey, sighashType, utxoList)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockFullNode) WalletSign(arg0 context.Context, arg1 address.Address, arg2 []byte, arg3 types0.MsgMeta) (*crypto.Signature, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"WalletSign\", arg0, arg1, arg2, arg3)\n\tret0, _ := ret[0].(*crypto.Signature)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (_BondedECDSAKeep *BondedECDSAKeepTransactor) Sign(opts *bind.TransactOpts, _digest [32]byte) (*types.Transaction, error) {\n\treturn _BondedECDSAKeep.contract.Transact(opts, \"sign\", _digest)\n}", "func (pv *ParamsVerification) Sign(p []byte) string {\n\t// Generate hash code\n\tmac := hmac.New(sha256.New, []byte(pv.ClientSecret))\n\t_, _ = mac.Write(p)\n\texpectedMAC := mac.Sum(nil)\n\n\t// Generate base64\n\tbase64Sign := base64.StdEncoding.EncodeToString(expectedMAC)\n\tbase64Sign = strings.ReplaceAll(base64Sign, \"+\", \"-\")\n\tbase64Sign = strings.ReplaceAll(base64Sign, \"/\", \"_\")\n\tbase64Sign = strings.TrimRight(base64Sign, \"=\")\n\n\treturn base64Sign\n}", "func (validator *validatorImpl) Sign(msg []byte) ([]byte, error) {\n\treturn validator.signWithEnrollmentKey(msg)\n}", "func TestBasicSign(t *testing.T) {\n\tcs := NewEd25519()\n\tkey, err := cs.Create(data.CanonicalRootRole, \"\", data.ED25519Key)\n\trequire.NoError(t, err)\n\ttestData := data.Signed{\n\t\tSigned: &json.RawMessage{},\n\t}\n\n\terr = Sign(cs, &testData, key)\n\trequire.NoError(t, err)\n\n\tif len(testData.Signatures) != 1 {\n\t\tt.Fatalf(\"Incorrect number of signatures: %d\", len(testData.Signatures))\n\t}\n\n\tif testData.Signatures[0].KeyID != key.ID() {\n\t\tt.Fatalf(\"Wrong signature ID returned: %s\", testData.Signatures[0].KeyID)\n\t}\n}", "func (m *mCryptographyServiceMockSign) Return(r *insolar.Signature, r1 error) *CryptographyServiceMock {\n\tm.mock.SignFunc = nil\n\tm.expectationSeries = nil\n\n\tif m.mainExpectation == nil {\n\t\tm.mainExpectation = &CryptographyServiceMockSignExpectation{}\n\t}\n\tm.mainExpectation.result = &CryptographyServiceMockSignResult{r, r1}\n\treturn m.mock\n}", "func TmSign(publicKey PublicKey, privateKey PrivateKey, digest Digest) Seal { panic(\"\") }", "func TestSignContractSuccess(t *testing.T) {\n\tsignatureHelper(t, false)\n}", "func (_m *Keychain) Sign(_a0 []byte) ([]byte, error) {\n\tret := _m.Called(_a0)\n\n\tvar r0 []byte\n\tif rf, ok := ret.Get(0).(func([]byte) []byte); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).([]byte)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func([]byte) error); ok {\n\t\tr1 = rf(_a0)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func Sign(ctx context.Context, txf Factory, name string, txBuilder client.TxBuilder, overwriteSig bool) error {\n\tif txf.keybase == nil {\n\t\treturn errors.New(\"keybase must be set prior to signing a transaction\")\n\t}\n\n\tvar err error\n\tsignMode := txf.signMode\n\tif signMode == signing.SignMode_SIGN_MODE_UNSPECIFIED {\n\t\t// use the SignModeHandler's default mode if unspecified\n\t\tsignMode, err = authsigning.APISignModeToInternal(txf.txConfig.SignModeHandler().DefaultMode())\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tk, err := txf.keybase.Key(name)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tpubKey, err := k.GetPubKey()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsignerData := authsigning.SignerData{\n\t\tChainID: txf.chainID,\n\t\tAccountNumber: txf.accountNumber,\n\t\tSequence: txf.sequence,\n\t\tPubKey: pubKey,\n\t\tAddress: sdk.AccAddress(pubKey.Address()).String(),\n\t}\n\n\t// For SIGN_MODE_DIRECT, calling SetSignatures calls setSignerInfos on\n\t// TxBuilder under the hood, and SignerInfos is needed to generated the\n\t// sign bytes. This is the reason for setting SetSignatures here, with a\n\t// nil signature.\n\t//\n\t// Note: this line is not needed for SIGN_MODE_LEGACY_AMINO, but putting it\n\t// also doesn't affect its generated sign bytes, so for code's simplicity\n\t// sake, we put it here.\n\tsigData := signing.SingleSignatureData{\n\t\tSignMode: signMode,\n\t\tSignature: nil,\n\t}\n\tsig := signing.SignatureV2{\n\t\tPubKey: pubKey,\n\t\tData: &sigData,\n\t\tSequence: txf.Sequence(),\n\t}\n\n\tvar prevSignatures []signing.SignatureV2\n\tif !overwriteSig {\n\t\tprevSignatures, err = txBuilder.GetTx().GetSignaturesV2()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\t// Overwrite or append signer infos.\n\tvar sigs []signing.SignatureV2\n\tif overwriteSig {\n\t\tsigs = []signing.SignatureV2{sig}\n\t} else {\n\t\tsigs = append(sigs, prevSignatures...)\n\t\tsigs = append(sigs, sig)\n\t}\n\tif err := txBuilder.SetSignatures(sigs...); err != nil {\n\t\treturn err\n\t}\n\n\tif err := checkMultipleSigners(txBuilder.GetTx()); err != nil {\n\t\treturn err\n\t}\n\n\tbytesToSign, err := authsigning.GetSignBytesAdapter(\n\t\tctx, txf.txConfig.SignModeHandler(),\n\t\tsignMode, signerData, txBuilder.GetTx())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Sign those bytes\n\tsigBytes, _, err := txf.keybase.Sign(name, bytesToSign, signMode)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Construct the SignatureV2 struct\n\tsigData = signing.SingleSignatureData{\n\t\tSignMode: signMode,\n\t\tSignature: sigBytes,\n\t}\n\tsig = signing.SignatureV2{\n\t\tPubKey: pubKey,\n\t\tData: &sigData,\n\t\tSequence: txf.Sequence(),\n\t}\n\n\tif overwriteSig {\n\t\terr = txBuilder.SetSignatures(sig)\n\t} else {\n\t\tprevSignatures = append(prevSignatures, sig)\n\t\terr = txBuilder.SetSignatures(prevSignatures...)\n\t}\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to set signatures on payload: %w\", err)\n\t}\n\n\t// Run optional preprocessing if specified. By default, this is unset\n\t// and will return nil.\n\treturn txf.PreprocessTx(name, txBuilder)\n}", "func (m *mCryptographyServiceMockSign) Set(f func(p []byte) (r *insolar.Signature, r1 error)) *CryptographyServiceMock {\n\tm.mainExpectation = nil\n\tm.expectationSeries = nil\n\n\tm.mock.SignFunc = f\n\treturn m.mock\n}", "func (c CryptoServiceTester) TestSignWithKey(t *testing.T) {\n\tcryptoService := c.cryptoServiceFactory()\n\tcontent := []byte(\"this is a secret\")\n\n\ttufKey, err := cryptoService.Create(c.role, c.gun, c.keyAlgo)\n\trequire.NoError(t, err, c.errorMsg(\"error creating key\"))\n\n\t// Test Sign\n\tprivKey, role, err := cryptoService.GetPrivateKey(tufKey.ID())\n\trequire.NoError(t, err, c.errorMsg(\"failed to get private key\"))\n\trequire.Equal(t, c.role, role)\n\n\tsignature, err := privKey.Sign(rand.Reader, content, nil)\n\trequire.NoError(t, err, c.errorMsg(\"signing failed\"))\n\n\tverifier, ok := signed.Verifiers[algoToSigType[c.keyAlgo]]\n\trequire.True(t, ok, c.errorMsg(\"Unknown verifier for algorithm\"))\n\n\terr = verifier.Verify(tufKey, signature, content)\n\trequire.NoError(t, err,\n\t\tc.errorMsg(\"verification failed for %s key type\", c.keyAlgo))\n}", "func Sign(rand io.Reader, priv *PrivateKey, hash []byte) (r, s *big.Int, err error)", "func (mmSignWith *mDigestHolderMockSignWith) When(signer DigestSigner) *DigestHolderMockSignWithExpectation {\n\tif mmSignWith.mock.funcSignWith != nil {\n\t\tmmSignWith.mock.t.Fatalf(\"DigestHolderMock.SignWith mock is already set by Set\")\n\t}\n\n\texpectation := &DigestHolderMockSignWithExpectation{\n\t\tmock: mmSignWith.mock,\n\t\tparams: &DigestHolderMockSignWithParams{signer},\n\t}\n\tmmSignWith.expectations = append(mmSignWith.expectations, expectation)\n\treturn expectation\n}", "func (m *MockSignerDecrypter) Sign(arg0 io.Reader, arg1 []byte, arg2 crypto.SignerOpts) ([]byte, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Sign\", arg0, arg1, arg2)\n\tret0, _ := ret[0].([]byte)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (_Ethdkg *EthdkgCallerSession) Sign(message []byte, privK *big.Int) ([2]*big.Int, error) {\n\treturn _Ethdkg.Contract.Sign(&_Ethdkg.CallOpts, message, privK)\n}", "func TestSignContractFailure(t *testing.T) {\n\tsignatureHelper(t, true)\n}", "func (m *mCryptographyServiceMockSign) Expect(p []byte) *mCryptographyServiceMockSign {\n\tm.mock.SignFunc = nil\n\tm.expectationSeries = nil\n\n\tif m.mainExpectation == nil {\n\t\tm.mainExpectation = &CryptographyServiceMockSignExpectation{}\n\t}\n\tm.mainExpectation.input = &CryptographyServiceMockSignInput{p}\n\treturn m\n}", "func (m *DigestHolderMock) MinimockSignWithInspect() {\n\tfor _, e := range m.SignWithMock.expectations {\n\t\tif mm_atomic.LoadUint64(&e.Counter) < 1 {\n\t\t\tm.t.Errorf(\"Expected call to DigestHolderMock.SignWith with params: %#v\", *e.params)\n\t\t}\n\t}\n\n\t// if default expectation was set then invocations count should be greater than zero\n\tif m.SignWithMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterSignWithCounter) < 1 {\n\t\tif m.SignWithMock.defaultExpectation.params == nil {\n\t\t\tm.t.Error(\"Expected call to DigestHolderMock.SignWith\")\n\t\t} else {\n\t\t\tm.t.Errorf(\"Expected call to DigestHolderMock.SignWith with params: %#v\", *m.SignWithMock.defaultExpectation.params)\n\t\t}\n\t}\n\t// if func was set then invocations count should be greater than zero\n\tif m.funcSignWith != nil && mm_atomic.LoadUint64(&m.afterSignWithCounter) < 1 {\n\t\tm.t.Error(\"Expected call to DigestHolderMock.SignWith\")\n\t}\n}", "func TestSenderRequest_Sign(t *testing.T) {\r\n\r\n\t// Create key\r\n\tkey, err := bitcoin.CreatePrivateKeyString()\r\n\tassert.NoError(t, err)\r\n\tassert.NotNil(t, key)\r\n\r\n\t// Create the request / message\r\n\tsenderRequest := &SenderRequest{\r\n\t\tDt: time.Now().UTC().Format(time.RFC3339),\r\n\t\tSenderHandle: testAlias + \"@\" + testDomain,\r\n\t\tSenderName: testName,\r\n\t\tPurpose: testMessage,\r\n\t}\r\n\r\n\tvar signature string\r\n\r\n\tt.Run(\"invalid key - empty\", func(t *testing.T) {\r\n\t\tsignature, err = senderRequest.Sign(\"\")\r\n\t\tassert.Error(t, err)\r\n\t\tassert.Equal(t, len(signature), 0)\r\n\t})\r\n\r\n\tt.Run(\"invalid key - 0\", func(t *testing.T) {\r\n\t\tsignature, err = senderRequest.Sign(\"0\")\r\n\t\tassert.Error(t, err)\r\n\t\tassert.Equal(t, len(signature), 0)\r\n\t})\r\n\r\n\tt.Run(\"invalid dt\", func(t *testing.T) {\r\n\t\tsenderRequest.Dt = \"\"\r\n\t\tsignature, err = senderRequest.Sign(key)\r\n\t\tassert.Error(t, err)\r\n\t\tassert.Equal(t, len(signature), 0)\r\n\t})\r\n\r\n\tt.Run(\"invalid sender handle\", func(t *testing.T) {\r\n\t\tsenderRequest.Dt = time.Now().UTC().Format(time.RFC3339)\r\n\t\tsenderRequest.SenderHandle = \"\"\r\n\t\tsignature, err = senderRequest.Sign(key)\r\n\t\tassert.Error(t, err)\r\n\t\tassert.Equal(t, len(signature), 0)\r\n\t})\r\n\r\n\tt.Run(\"valid signature\", func(t *testing.T) {\r\n\t\tsenderRequest.SenderHandle = testAlias + \"@\" + testDomain\r\n\t\tsignature, err = senderRequest.Sign(key)\r\n\t\tassert.NoError(t, err)\r\n\t\tassert.NotEqual(t, len(signature), 0)\r\n\r\n\t\t// Get address for verification\r\n\t\tvar address string\r\n\t\taddress, err = bitcoin.GetAddressFromPrivateKeyString(key, false)\r\n\t\tassert.NoError(t, err)\r\n\r\n\t\t// Verify the signature\r\n\t\terr = senderRequest.Verify(address, signature)\r\n\t\tassert.NoError(t, err)\r\n\t})\r\n}", "func (k otherKey) Sign(rand io.Reader, digest []byte, opts crypto.SignerOpts) (signature []byte, err error) {\n\t_, _, _ = rand, digest, opts\n\treturn nil, nil\n}", "func (m EncMessage) Sign(k []byte) error {\n\treturn errors.New(\"Sign method must be overridden\")\n}", "func TestSign(t *testing.T) {\n\tt.Parallel()\n\n\tprivKey, err := crypto.GenerateSecp256k1Key()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tsigner := crypto.NewDefaultSigner(privKey)\n\n\tpayload := []byte(\"foo\")\n\tch, err := cac.New(payload)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tid := make([]byte, swarm.HashSize)\n\t// creates the soc\n\ts := soc.New(id, ch)\n\n\t// signs the chunk\n\tsch, err := s.Sign(signer)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tchunkData := sch.Data()\n\t// get signature in the chunk\n\tcursor := swarm.HashSize\n\tsignature := chunkData[cursor : cursor+swarm.SocSignatureSize]\n\n\t// get the public key of the signer\n\tpublicKey, err := signer.PublicKey()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\towner, err := crypto.NewEthereumAddress(*publicKey)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\ttoSignBytes, err := soc.Hash(id, ch.Address().Bytes())\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// verifies if the owner matches\n\trecoveredOwner, err := soc.RecoverAddress(signature, toSignBytes)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif !bytes.Equal(recoveredOwner, owner) {\n\t\tt.Fatalf(\"owner address mismatch. got %x want %x\", recoveredOwner, owner)\n\t}\n}", "func (ra *RestrictedAgent) Sign(key ssh.PublicKey, data []byte) (*ssh.Signature, error) {\n\treturn nil, ErrForbidden\n}", "func TestReSign(t *testing.T) {\n\tcs := NewEd25519()\n\tkey, err := cs.Create(data.CanonicalRootRole, \"\", data.ED25519Key)\n\trequire.NoError(t, err)\n\ttestData := data.Signed{\n\t\tSigned: &json.RawMessage{},\n\t}\n\n\tSign(cs, &testData, key)\n\tSign(cs, &testData, key)\n\n\tif len(testData.Signatures) != 1 {\n\t\tt.Fatalf(\"Incorrect number of signatures: %d\", len(testData.Signatures))\n\t}\n\n\tif testData.Signatures[0].KeyID != key.ID() {\n\t\tt.Fatalf(\"Wrong signature ID returned: %s\", testData.Signatures[0].KeyID)\n\t}\n\n}", "func Sign(suite suites.Suite, x kyber.Scalar, msg []byte) ([]byte, error) {\n\tHM := hashToPoint(suite, msg)\n\txHM := HM.Mul(x, HM)\n\ts, err := xHM.MarshalBinary()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn s, nil\n}", "func (priv *PrivateKey) Sign(rand io.Reader, msg []byte, opts crypto.SignerOpts) ([]byte, error)", "func (priv *PrivateKey) Sign(rand io.Reader, msg []byte, opts crypto.SignerOpts) ([]byte, error)", "func (_Ethdkg *EthdkgSession) Sign(message []byte, privK *big.Int) ([2]*big.Int, error) {\n\treturn _Ethdkg.Contract.Sign(&_Ethdkg.CallOpts, message, privK)\n}", "func (m *MetricsProvider) SignerSign(value time.Duration) {\n}", "func TestTokenSignature(t *testing.T) {\n\tdb.InitDB()\n\tvar router *gin.Engine = routes.SetupRouter()\n\n\tvar user models.UserCreate = utils.CreateUser(\"Tom\", \"qwerty1234\", t, router)\n\tuser.Token = utils.ConnectUser(\"Tom\", \"qwerty1234\", t, router)\n\n\tsplittedToken := strings.Split(user.Token, \".\")\n\tif len(splittedToken) != 3 {\n\t\tlog.Fatal(\"Bad token.\")\n\t\tt.Fail()\n\t}\n\n\theader := splittedToken[0]\n\tpayload := splittedToken[1]\n\tsignature := splittedToken[2]\n\tsignature = signature + \"modif\"\n\tmodifiedToken := header + \".\" + payload + \".\" + signature\n\n\tvar url string = \"/v1/user/\" + strconv.Itoa(user.ID)\n\tvar bearer = \"Bearer \" + modifiedToken\n\trecord := httptest.NewRecorder()\n\trequest, _ := http.NewRequest(\"GET\", url, nil)\n\trequest.Header.Add(\"Content-Type\", \"application/json\")\n\trequest.Header.Add(\"Authorization\", bearer)\n\n\trouter.ServeHTTP(record, request)\n\n\tvar message Message\n\terr := json.Unmarshal([]byte(record.Body.String()), &message)\n\tif err != nil {\n\t\tlog.Fatal(\"Bad output: \", err.Error())\n\t\tt.Fail()\n\t}\n\n\tassert.Equal(t, record.Code, 403)\n\tassert.Equal(t, message.Message, \"Bad signature\")\n\n\tuser.Token = utils.ConnectUser(\"Tom\", \"qwerty1234\", t, router)\n\tutils.CleanUser(user.ID, user.Token, t, router)\n\tdb.CloseDB()\n}", "func Test_CanSign_Correct(t *testing.T) {\n\n\t// prepare input\n\tvar transactionInput *TransactionInput = &TransactionInput{\n\t\tOutputID: \"outID\",\n\t\tOutputIndex: 10,\n\t}\n\tvar unspentTransactions = []*UnspentTransactionOutput{\n\t\t{\n\t\t\tOutputID: \"outID-1\",\n\t\t\tOutputIndex: 1000,\n\t\t\tAddress: \"addressX\",\n\t\t},\n\t\t{\n\t\t\tOutputID: \"outID\",\n\t\t\tOutputIndex: 10,\n\t\t\tAddress: \"public_key\",\n\t\t},\n\t}\n\tvar publicKey = \"public_key\"\n\n\t// call can sign\n\tresult := CanSign(unspentTransactions, transactionInput, publicKey)\n\n\t// result should false\n\tif !result {\n\t\tt.Errorf(\"The result must be true when there is unspent transaction and adddress is the same the public key\")\n\t}\n}", "func TestSignContract(t *testing.T) {\n\t// Setup\n\tstop, clients, contractPath, contractFilePath := setupSignature(t)\n\tdefer stop()\n\n\t// Sign!\n\tcloseChannel := make(chan []byte, 3)\n\tfor i := 0; i < 3; i++ {\n\t\tsetLastArg(clients[i], \"sign\", true)\n\t\tsetLastArg(clients[i], contractPath, false)\n\t\tgo func(c *exec.Cmd, i int) {\n\t\t\ttime.Sleep(time.Duration(i*2) * time.Second)\n\t\t\tc.Stdin = strings.NewReader(contractFilePath + \"\\npassword\\nyes\\n\")\n\t\t\tc.Stderr = os.Stderr\n\t\t\toutput, err := c.Output()\n\t\t\tif err != nil {\n\t\t\t\toutput = nil\n\t\t\t}\n\t\t\tcloseChannel <- output\n\t\t}(clients[i], i)\n\t}\n\n\tregexes := []*regexp.Regexp{\n\t\tregexp.MustCompile(`Everybody is ready, starting the signature [a-f0-9]+`),\n\t\tregexp.MustCompile(`Do you REALLY want to sign contract\\.txt\\? Type 'yes' to confirm:`),\n\t}\n\tfor i := 0; i < 3; i++ {\n\t\toutput := <-closeChannel\n\t\tassert.NotEqual(t, nil, output, \"The return error should be null\")\n\t\tfor _, r := range regexes {\n\t\t\tassert.True(t, r.Match(output), \"Regex is not satisfied: \", r.String())\n\t\t}\n\t}\n\n\tcheckProofFile(t, 3)\n\ttime.Sleep(time.Second)\n}", "func (q *Qsign) Sign(v interface{}) ([]byte, error) {\n\tdigest, err := q.Digest(v)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\th := q.hasher()\n\th.Write(digest)\n\n\te := q.encoder()\n\tdst := make([]byte, e.EncodedLen(h.Size()))\n\te.Encode(dst, h.Sum(nil))\n\n\treturn dst, nil\n}", "func Sign(name string, message string, password string)([]byte, []byte, error){\n\n\tvar manager cryptostore.Manager\n\trootDir := os.Getenv(\"BASECLIHOME\")\n\tfmt.Println(\"rootdir\"+rootDir)\n\tkeyDir := filepath.Join(rootDir, KeySubdir)\n\n\tsignEssue.Message = []byte(message)\n\t// TODO: smarter loading??? with language and fallback?\n\tcodec := keys.MustLoadCodec(\"english\")\n\tmanager = cryptostore.New(\n\t\tcryptostore.SecretBox,\n\t\tfilestorage.New(keyDir),\n\t\tcodec,\n\t)\n\tvar sign keys.Signable\n\tfmt.Println(&sign)\n\tsign = &signEssue\n\tfmt.Println(sign)\n\terr := manager.Sign(name, password, sign)\n\tif err != nil{\n\t\treturn \tnil, nil, err\n\t}else {\n\t\treturn signEssue.Publikey.Bytes()[1:], signEssue.Sig.Bytes()[1:], nil\n\t}\n}", "func (c CryptoServiceTester) TestSignNoMatchingKeys(t *testing.T) {\n\tcryptoService := c.cryptoServiceFactory()\n\n\tprivKey, err := utils.GenerateECDSAKey(rand.Reader)\n\trequire.NoError(t, err, c.errorMsg(\"error creating key\"))\n\n\t// Test Sign\n\t_, _, err = cryptoService.GetPrivateKey(privKey.ID())\n\trequire.Error(t, err, c.errorMsg(\"Should not have found private key\"))\n}", "func (_BondedECDSAKeep *BondedECDSAKeepTransactorSession) Sign(_digest [32]byte) (*types.Transaction, error) {\n\treturn _BondedECDSAKeep.Contract.Sign(&_BondedECDSAKeep.TransactOpts, _digest)\n}", "func TestVerifySignedMessage(t *testing.T) {\n\tfor _, tc := range []struct {\n\t\tdesc string\n\t\tsettings *crypt.PkiSettings\n\t\tsetup func(mdb *mocks.MockDepsBundle, setupDone *bool) error\n\t\tmessageToSign string\n\t\tbase64Signature string\n\t\tPEMPublicKey string\n\t\texpectedError *testtools.ErrorSpec\n\t\texpectedValidity bool\n\t}{\n\t\t{\n\t\t\tdesc: \"invalid base64 signature\",\n\t\t\tsettings: &crypt.PkiSettings{\n\t\t\t\tAlgorithm: x509.ECDSA,\n\t\t\t\tPrivateKeyPath: \".prog/ecdsa_priv.key\",\n\t\t\t\tPublicKeyPath: \".prog/ecdsa.pub\",\n\t\t\t},\n\t\t\tsetup: func(mdb *mocks.MockDepsBundle, setupDone *bool) error {\n\t\t\t\treturn nil\n\t\t\t},\n\t\t\tmessageToSign: \"some other message\",\n\t\t\tbase64Signature: \"@#$^&*()_\",\n\t\t\tPEMPublicKey: \"\",\n\t\t\texpectedError: &testtools.ErrorSpec{\n\t\t\t\tType: \"base64.CorruptInputError\",\n\t\t\t\tMessage: \"illegal base64 data at input byte 0\",\n\t\t\t},\n\t\t\texpectedValidity: false,\n\t\t},\n\t\t{\n\t\t\tdesc: \"empty PEM key\",\n\t\t\tsettings: &crypt.PkiSettings{\n\t\t\t\tAlgorithm: x509.ECDSA,\n\t\t\t\tPrivateKeyPath: \".prog/ecdsa_priv.key\",\n\t\t\t\tPublicKeyPath: \".prog/ecdsa.pub\",\n\t\t\t},\n\t\t\tsetup: func(mdb *mocks.MockDepsBundle, setupDone *bool) error {\n\t\t\t\treturn nil\n\t\t\t},\n\t\t\tmessageToSign: \"some other message\",\n\t\t\tbase64Signature: \"abcdefgh\",\n\t\t\tPEMPublicKey: \"\",\n\t\t\texpectedError: &testtools.ErrorSpec{\n\t\t\t\tType: \"*errors.errorString\",\n\t\t\t\tMessage: \"No PEM data was found\",\n\t\t\t},\n\t\t\texpectedValidity: false,\n\t\t},\n\t\t{\n\t\t\tdesc: \"bad key data\",\n\t\t\tsettings: &crypt.PkiSettings{\n\t\t\t\tAlgorithm: x509.ECDSA,\n\t\t\t\tPrivateKeyPath: \".prog/ecdsa_priv.key\",\n\t\t\t\tPublicKeyPath: \".prog/ecdsa.pub\",\n\t\t\t},\n\t\t\tsetup: func(mdb *mocks.MockDepsBundle, setupDone *bool) error {\n\t\t\t\treturn nil\n\t\t\t},\n\t\t\tmessageToSign: \"some other message\",\n\t\t\tbase64Signature: \"abcdefgh\",\n\t\t\tPEMPublicKey: \"-----BEGIN INVALID DATA-----\\n\" +\n\t\t\t\t\"MTIzNDU2Nzg5MGFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6\\n\" +\n\t\t\t\t\"-----END INVALID DATA-----\\n\",\n\t\t\texpectedError: &testtools.ErrorSpec{\n\t\t\t\tType: \"asn1.StructuralError\",\n\t\t\t\tMessage: \"asn1: structure \" +\n\t\t\t\t\t\"error: tags don't match (16 vs {class:0 \" +\n\t\t\t\t\t\"tag:17 \" +\n\t\t\t\t\t\"length:50 \" +\n\t\t\t\t\t\"isCompound:true}) {optional:false \" +\n\t\t\t\t\t\"explicit:false \" +\n\t\t\t\t\t\"application:false \" +\n\t\t\t\t\t\"defaultValue:<nil> \" +\n\t\t\t\t\t\"tag:<nil> \" +\n\t\t\t\t\t\"stringType:0 \" +\n\t\t\t\t\t\"timeType:0 \" +\n\t\t\t\t\t\"set:false \" +\n\t\t\t\t\t\"omitEmpty:false} publicKeyInfo @2\",\n\t\t\t},\n\t\t\texpectedValidity: false,\n\t\t},\n\t\t{\n\t\t\tdesc: \"invalid signature\",\n\t\t\tsettings: &crypt.PkiSettings{\n\t\t\t\tAlgorithm: x509.ECDSA,\n\t\t\t\tPrivateKeyPath: \".prog/ecdsa_priv.key\",\n\t\t\t\tPublicKeyPath: \".prog/ecdsa.pub\",\n\t\t\t},\n\t\t\tsetup: func(mdb *mocks.MockDepsBundle, setupDone *bool) error {\n\t\t\t\treturn nil\n\t\t\t},\n\t\t\tmessageToSign: \"some other message\",\n\t\t\tbase64Signature: \"abcdefgh\",\n\t\t\tPEMPublicKey: \"-----BEGIN ECDSA PUBLIC KEY-----\\n\" +\n\t\t\t\t\"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE7WzVjtn9Gk+WHr5xbv8XMvooqU25\\n\" +\n\t\t\t\t\"BhgNjZ/vHZLBdVtCOjk4KxjS1UBfQm0c3TRxWBl3hj2AmnJbCrnGofMHBQ==\\n\" +\n\t\t\t\t\"-----END ECDSA PUBLIC KEY-----\\n\",\n\t\t\texpectedError: &testtools.ErrorSpec{\n\t\t\t\tType: \"asn1.SyntaxError\",\n\t\t\t\tMessage: \"asn1: syntax error: truncated tag or length\",\n\t\t\t},\n\t\t\texpectedValidity: false,\n\t\t},\n\t\t{\n\t\t\tdesc: \"ecdsa key for rsa mode\",\n\t\t\tsettings: &crypt.PkiSettings{\n\t\t\t\tAlgorithm: x509.RSA,\n\t\t\t\tPrivateKeyPath: \".prog/ecdsa_priv.key\",\n\t\t\t\tPublicKeyPath: \".prog/ecdsa.pub\",\n\t\t\t},\n\t\t\tsetup: func(mdb *mocks.MockDepsBundle, setupDone *bool) error {\n\t\t\t\treturn nil\n\t\t\t},\n\t\t\tmessageToSign: \"some other message\",\n\t\t\tbase64Signature: \"N3SuIdWI7XlXDteTmcOZUd2OBacyUWY+/+A8SC4QUBz9rXnldBqXha6YyGwnTuizxuy6quQ2QDFdtW16dj7EQk3lozfngskyhc2r86q3AUbdFDvrQVphMQhzsgBhHVoMjCL/YRfvtzCTWhBxegjVMLraLDCBb8IZTIqcMYafYyeJTvAnjBuntlZ+14TDuTt14Uqz85T04CXxBEqlIXMMKpTc01ST4Jsxz5HLO+At1htXp5eHOUFtQSilm3G7iO8ynhgPcXHDWfMAWu6VySUoHWCG70pJaCq6ehF7223t0UFOCqAyDyyQyP9yeUHj8F75SPSxfJm8iKXGx2LND/qLYw==\",\n\t\t\tPEMPublicKey: \"-----BEGIN RSA PUBLIC KEY-----\\n\" +\n\t\t\t\t\"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE7WzVjtn9Gk+WHr5xbv8XMvooqU25\\n\" +\n\t\t\t\t\"BhgNjZ/vHZLBdVtCOjk4KxjS1UBfQm0c3TRxWBl3hj2AmnJbCrnGofMHBQ==\\n\" +\n\t\t\t\t\"-----END RSA PUBLIC KEY-----\\n\",\n\t\t\texpectedError: &testtools.ErrorSpec{\n\t\t\t\tType: \"*errors.errorString\",\n\t\t\t\tMessage: \"Expecting a *rsa.PublicKey, but encountered a *ecdsa.PublicKey instead\",\n\t\t\t},\n\t\t\texpectedValidity: false,\n\t\t},\n\t\t{\n\t\t\tdesc: \"rsa key for ecdsa mode\",\n\t\t\tsettings: &crypt.PkiSettings{\n\t\t\t\tAlgorithm: x509.ECDSA,\n\t\t\t\tPrivateKeyPath: \".prog/ecdsa_priv.key\",\n\t\t\t\tPublicKeyPath: \".prog/ecdsa.pub\",\n\t\t\t},\n\t\t\tsetup: func(mdb *mocks.MockDepsBundle, setupDone *bool) error {\n\t\t\t\treturn nil\n\t\t\t},\n\t\t\tmessageToSign: \"some other message\",\n\t\t\tbase64Signature: \"MEYCIQDPM0fc/PFauoZzpltH3RpWtlaqRnL0gFk5WFiLMrFqrwIhAIDvlBozU6Ky2UC9xOSq3YZ5iFuO356t9RnHOElaaXFJ\",\n\t\t\tPEMPublicKey: \"-----BEGIN RSA PUBLIC KEY-----\\n\" +\n\t\t\t\t\"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAzCTTFKQBHfTN8jW6q8PT\\n\" +\n\t\t\t\t\"HNZKWnRPxSt9kpgWmyqFaZnEUipgoKGAxSIsVrl2PJSm5OlgkVzx+MY+LWM64VKM\\n\" +\n\t\t\t\t\"bRpUUGJR3zdMNhwZQX0hjOpLpVJvUwD78utVs8vijrU7sH48usFiaZQYjy4m4hQh\\n\" +\n\t\t\t\t\"63/x4h3KVz7YqUnlRMzYJFT43+AwYzYuEpzWRxtW7IObJPtjtmYVoqva98fF6aj5\\n\" +\n\t\t\t\t\"uHAsvaAgZGBalHXmCiPzKiGU/halzXSPvyJ2Cqz2aUqMHgwi/2Ip4z/mrfX+mUTa\\n\" +\n\t\t\t\t\"S+LyBy7GgqJ5vbkGArMagJIc0eARF60r6Uf483xh17oniABdLJy4qlLf6PcEU+ut\\n\" +\n\t\t\t\t\"EwIDAQAB\\n\" +\n\t\t\t\t\"-----END RSA PUBLIC KEY-----\\n\",\n\t\t\texpectedError: &testtools.ErrorSpec{\n\t\t\t\tType: \"*errors.errorString\",\n\t\t\t\tMessage: \"Expecting a *ecdsa.PublicKey, but encountered a *rsa.PublicKey instead\",\n\t\t\t},\n\t\t\texpectedValidity: false,\n\t\t},\n\t} {\n\t\tt.Run(fmt.Sprintf(\"Subtest: %s\", tc.desc), func(tt *testing.T) {\n\t\t\tmockDepsBundle := mocks.NewDefaultMockDeps(\"\", []string{\"progname\"}, \"/home/user\", nil)\n\t\t\treturnedNormally := false\n\t\t\tvar tooling *crypt.CryptoTooling\n\t\t\tvar actualErr error\n\t\t\tvar actualValidity bool\n\t\t\terr := mockDepsBundle.InvokeCallInMockedEnv(func() error {\n\t\t\t\tsetupComplete := false\n\t\t\t\tinnerErr := tc.setup(mockDepsBundle, &setupComplete)\n\t\t\t\tif innerErr != nil {\n\t\t\t\t\treturn innerErr\n\t\t\t\t}\n\t\t\t\tvar toolingErr error\n\t\t\t\ttooling, toolingErr = crypt.GetCryptoTooling(mockDepsBundle.Deps, tc.settings)\n\t\t\t\tif toolingErr != nil {\n\t\t\t\t\treturn toolingErr\n\t\t\t\t}\n\t\t\t\tsetupComplete = true\n\t\t\t\tactualValidity, actualErr = tooling.VerifySignedMessage(tc.messageToSign, tc.base64Signature, tc.PEMPublicKey)\n\t\t\t\treturnedNormally = true\n\t\t\t\treturn nil\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\ttt.Errorf(\"Unexpected error calling mockDepsBundle.InvokeCallInMockedEnv(): %s\", err.Error())\n\t\t\t}\n\t\t\tif exitStatus := mockDepsBundle.GetExitStatus(); (exitStatus != 0) || !returnedNormally {\n\t\t\t\ttt.Error(\"EncodeAndSaveKey() should not have paniced or called os.Exit.\")\n\t\t\t}\n\t\t\tif (mockDepsBundle.OutBuf.String() != \"\") || (mockDepsBundle.ErrBuf.String() != \"\") {\n\t\t\t\ttt.Errorf(\"EncodeAndSaveKey() should not have output any data. Saw stdout:\\n%s\\nstderr:\\n%s\", mockDepsBundle.OutBuf.String(), mockDepsBundle.ErrBuf.String())\n\t\t\t}\n\t\t\tif err := tc.expectedError.EnsureMatches(actualErr); err != nil {\n\t\t\t\ttt.Error(err.Error())\n\t\t\t}\n\t\t\tif tc.expectedError == nil {\n\t\t\t\tif actualValidity != tc.expectedValidity {\n\t\t\t\t\ttt.Errorf(\"Signature is %#v when %#v expected\", actualValidity, tc.expectedValidity)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif tc.expectedValidity {\n\t\t\t\t\ttt.Error(\"TEST CASE INVALID. Should not expect \\\"valid\\\".\")\n\t\t\t\t}\n\t\t\t\tif actualValidity {\n\t\t\t\t\ttt.Error(\"Error was expected. Should not report \\\"valid\\\".\")\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n}", "func (p *PrivateKey) Sign(mesg string) string {\n\tvar enc, m big.Int\n\tsetBytesReverse(&m, []byte(mesg))\n\tenc.Exp(&m, p.keyD, p.keyN)\n\treturn intToBase64(&enc)\n}", "func signatureHelper(t *testing.T, failure bool) {\n\t// Setup\n\tstop, clients, contractPath, contractFilePath := setupSignature(t)\n\tdefer stop()\n\n\tstopBefore, expectedProofFile1, expectedProofFile2 := \"1\", 0, 0\n\tif !failure {\n\t\tstopBefore, expectedProofFile1, expectedProofFile2 = \"2\", 2, 1\n\t}\n\n\t// Configure client3 to be faulty\n\tsetLastArg(clients[2], \"--stopbefore\", true)\n\tsetLastArg(clients[2], stopBefore, false)\n\tsetLastArg(clients[2], \"sign\", false)\n\n\t// Sign!\n\tcloseChannel := make(chan []byte, 3)\n\tfor i := 0; i < 3; i++ {\n\t\tsetLastArg(clients[i], \"sign\", true)\n\t\tsetLastArg(clients[i], contractPath, false)\n\t\tgo func(c *exec.Cmd, i int) {\n\t\t\tc.Stdin = strings.NewReader(contractFilePath + \"\\npassword\\nyes\\n\")\n\t\t\tc.Stderr = bufio.NewWriter(os.Stdout)\n\t\t\toutput, _ := c.Output()\n\t\t\tcloseChannel <- output\n\t\t}(clients[i], i)\n\t}\n\n\tfor i := 0; i < 3; i++ {\n\t\t// TODO check stderr?\n\t\t<-closeChannel\n\t}\n\n\tcheckProofFile(t, expectedProofFile1)\n\tfilename := checkRecoverFile(t, \"client3@example.com\")\n\tcallRecover(newClient(clients[2]), filename)\n\t_ = os.Remove(filename)\n\tcheckProofFile(t, expectedProofFile2)\n\n\ttime.Sleep(time.Second)\n\treturn\n}", "func Sign(payload string, secretKey string) string {\n\tmac := hmac.New(sha256.New, []byte(secretKey))\n\tmac.Write([]byte(payload))\n\treturn hex.EncodeToString(mac.Sum(nil))\n}", "func (m *mSignatureKeyHolderMockGetSignMethod) Return(r SignMethod) *SignatureKeyHolderMock {\n\tm.mock.GetSignMethodFunc = nil\n\tm.expectationSeries = nil\n\n\tif m.mainExpectation == nil {\n\t\tm.mainExpectation = &SignatureKeyHolderMockGetSignMethodExpectation{}\n\t}\n\tm.mainExpectation.result = &SignatureKeyHolderMockGetSignMethodResult{r}\n\treturn m.mock\n}", "func (mmSignWith *mDigestHolderMockSignWith) Return(s1 SignedDigestHolder) *DigestHolderMock {\n\tif mmSignWith.mock.funcSignWith != nil {\n\t\tmmSignWith.mock.t.Fatalf(\"DigestHolderMock.SignWith mock is already set by Set\")\n\t}\n\n\tif mmSignWith.defaultExpectation == nil {\n\t\tmmSignWith.defaultExpectation = &DigestHolderMockSignWithExpectation{mock: mmSignWith.mock}\n\t}\n\tmmSignWith.defaultExpectation.results = &DigestHolderMockSignWithResults{s1}\n\treturn mmSignWith.mock\n}", "func (m *MockTransactionApi) VerifySign(tx *types.Transaction, outpoint *types.OutPoint, amount int64, txinUtxoList *[]types.UtxoData) (bool, string, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"VerifySign\", tx, outpoint, amount, txinUtxoList)\n\tret0, _ := ret[0].(bool)\n\tret1, _ := ret[1].(string)\n\tret2, _ := ret[2].(error)\n\treturn ret0, ret1, ret2\n}", "func (pk *PrivateKey) Sign(message []byte) *Signature {\n var signature Signature\n copy(signature[:], ed25519.Sign(pk[:], message)[:])\n return &signature\n}", "func (sk PrivateKey) Sign(message []byte, hasher Hasher) ([]byte, error) {\n\treturn sk.privateKey.Sign(message, hasher)\n}", "func Sign(m string, kp *Keypair) *Signature {\n\treturn genSignature(m, kp.private)\n}", "func (mmSignWith *mDigestHolderMockSignWith) Set(f func(signer DigestSigner) (s1 SignedDigestHolder)) *DigestHolderMock {\n\tif mmSignWith.defaultExpectation != nil {\n\t\tmmSignWith.mock.t.Fatalf(\"Default expectation is already set for the DigestHolder.SignWith method\")\n\t}\n\n\tif len(mmSignWith.expectations) > 0 {\n\t\tmmSignWith.mock.t.Fatalf(\"Some expectations are already set for the DigestHolder.SignWith method\")\n\t}\n\n\tmmSignWith.mock.funcSignWith = f\n\treturn mmSignWith.mock\n}", "func (b *Block) sign() error {\n\tvar sigErr error\n\tsignBytes := b.signablePayload()\n\tsig, sigErr := cs.SignBlock(signBytes)\n\tif sigErr != nil {\n\t\treturn sigErr\n\t}\n\n\tb.Sig = fmt.Sprintf(\"%x\", sig)\n\n\treturn nil\n}", "func (pk PrivateKey) Sign(message []byte) Signature {\n\tvar signature Signature\n\tcopy(signature[:], ed25519.Sign(pk[:], message)[:])\n\treturn signature\n}", "func NewMockSigner(kis []KeyInfo) MockSigner {\n\tvar ms MockSigner\n\tms.AddrKeyInfo = make(map[address.Address]KeyInfo)\n\tfor _, k := range kis {\n\t\t// extract public key\n\t\tpub := k.PublicKey()\n\t\tnewAddr, err := address.NewSecp256k1Address(pub)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tms.Addresses = append(ms.Addresses, newAddr)\n\t\tms.AddrKeyInfo[newAddr] = k\n\t\tms.PubKeys = append(ms.PubKeys, pub)\n\t}\n\treturn ms\n}", "func Sign(meth Method, f *File) ([]byte, error) {\n\tc := cosigner(strings.Join(f.Payload(meth), \"\\n\"))\n\tb, err := co.Sign(c, sha1.New, AwsSecretKey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn b.Base64()\n}", "func (m *MockTransactionApi) AddPubkeySign(tx *types.Transaction, outpoint *types.OutPoint, hashType types.HashType, pubkey *types.Pubkey, signature string) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"AddPubkeySign\", tx, outpoint, hashType, pubkey, signature)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (mr *MockClientMockRecorder) Sign(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Sign\", reflect.TypeOf((*MockClient)(nil).Sign), arg0)\n}", "func TestSignHash(t *testing.T) {\n\tprivateKey, err := crypto.DecodePrivateKey(\"L4rK1yDtCWekvXuE6oXD9jCYfFNV2cWRpVuPLBcCU2z8TrisoyY1\")\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tpreTestTx := testTxs[0]\n\ttestTx := testTxs[1]\n\ttxHash, err := SignatureHash(&testTx.tx, preTestTx.tx.Outs[0].Script, crypto.SigHashAll, 0)\n\tsignature, err := privateKey.Sign(txHash.GetCloneBytes())\n\tret, err := CheckSig(txHash, signature.Serialize(), privateKey.PubKey().ToBytes())\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tif !ret {\n\t\tt.Error(\"chec signature failed\")\n\t}\n\n}", "func sign(privateKey *rsa.PrivateKey, data []byte) ([]byte, error) {\n\th := sha256.New()\n\th.Write(data)\n\td := h.Sum(nil)\n\treturn rsa.SignPKCS1v15(rand.Reader, privateKey, crypto.SHA256, d)\n}", "func TestRootFromSignedCopiesSignatures(t *testing.T) {\n\tsigned, err := validRootTemplate().ToSigned()\n\trequire.NoError(t, err)\n\n\tsignedRoot, err := RootFromSigned(signed)\n\trequire.NoError(t, err)\n\n\tsigned.Signatures[0] = Signature{KeyID: \"key3\", Method: \"method3\", Signature: []byte(\"world\")}\n\n\trequire.Equal(t, \"key3\", signed.Signatures[0].KeyID)\n\trequire.Equal(t, \"key1\", signedRoot.Signatures[0].KeyID)\n}", "func (s *SigningMethodGCPJWTImpl) Sign(signingString string, key interface{}) (string, error) {\n\tvar ctx context.Context\n\n\t// check to make sure the key is a context.Context\n\tswitch k := key.(type) {\n\tcase context.Context:\n\t\tctx = k\n\tdefault:\n\t\treturn \"\", jwt.ErrInvalidKey\n\t}\n\n\t// Get the IAMSignBlobConfig from the context\n\tconfig, ok := FromContextJWT(ctx)\n\tif !ok {\n\t\treturn \"\", fmt.Errorf(\"IAMSignJWTConfig missing from provided context!\")\n\t}\n\n\t// Default config.OAuth2HTTPClient is a google.DefaultClient\n\tif config.OAuth2HTTPClient == nil {\n\t\tc, err := getDefaultOauthClient(ctx)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tconfig.OAuth2HTTPClient = c\n\t}\n\n\t// Default the ProjectID to a wildcard\n\tif config.ProjectID == \"\" {\n\t\tconfig.ProjectID = \"-\"\n\t}\n\n\t// Prepare the call\n\t// First decode the JSON string and discard the header\n\tparts := strings.Split(signingString, \".\")\n\tif len(parts) != 2 {\n\t\treturn \"\", fmt.Errorf(\"expected a 2 part string to sign, but got %d instead\", len(parts))\n\t}\n\tjwtClaimSet, err := jwt.DecodeSegment(parts[1])\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tsignReq := &iam.SignJwtRequest{Payload: string(jwtClaimSet)}\n\tname := fmt.Sprintf(\"projects/%s/serviceAccounts/%s\", config.ProjectID, config.ServiceAccount)\n\n\t// Do the call\n\tiamService, err := iam.New(config.OAuth2HTTPClient)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tsignResp, err := iamService.Projects.ServiceAccounts.SignJwt(name, signReq).Do()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// Check the response\n\tif signResp.HTTPStatusCode != http.StatusOK {\n\t\treturn \"\", fmt.Errorf(\"unexpected response code from signing request, expected %d but got %d instead\", http.StatusOK, signResp.HTTPStatusCode)\n\t}\n\n\treturn signResp.SignedJwt, nil\n}", "func Sign(operation []byte, privKey ecdsa.PrivateKey) (signedR, signedS *big.Int, err error) {\n\tr, s, err := ecdsa.Sign(rand.Reader, &privKey, operation)\n\tif err != nil {\n\t\treturn big.NewInt(0), big.NewInt(0), err\n\t}\n\n\tsignedR = r\n\tsignedS = s\n\treturn\n}", "func (kh *KeyHandler) Sign(buf []byte) ([]byte, cop.Error) {\n\treturn make([]byte, 0), nil\n}", "func (m *mSignatureKeyHolderMockGetSignMethod) Expect() *mSignatureKeyHolderMockGetSignMethod {\n\tm.mock.GetSignMethodFunc = nil\n\tm.expectationSeries = nil\n\n\tif m.mainExpectation == nil {\n\t\tm.mainExpectation = &SignatureKeyHolderMockGetSignMethodExpectation{}\n\t}\n\n\treturn m\n}", "func Sign(claims jwt.Claims) (string, error) {\n\tkey, err := getPrivateKey()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\t// create a new token\n\ttoken := jwt.NewWithClaims(signAlg, claims)\n\treturn token.SignedString(key)\n}", "func (*noSignHash) SignHash() {\n}", "func Sign(s *big.Int, params *Params, key *PrivateKey, attrs AttributeList, message *big.Int) (*Signature, error) {\n\treturn SignPrecomputed(s, params, key, attrs, PrepareAttributeSet(params, attrs), message)\n}", "func Test_VerifySigFromTass(t *testing.T) {\n\trequire := require.New(t)\n\n\t//c := &sm2.Driver{}\n\n\txBytes := common.FromHex(\"0000000000000000000000000000000000000000000000000000000000000000FD4241057FEC6CBEEC501F7E1763751B8F6DFCFB910FB634FBB76A16639EF172\")\n\tyBytes := common.FromHex(\"00000000000000000000000000000000000000000000000000000000000000001C6DA89F9C1A5EE9B6108E5A2A5FE336962630A34DBA1AF428451E1CE63BB3CF\")\n\tx := new(big.Int).SetBytes(xBytes)\n\ty := new(big.Int).SetBytes(yBytes)\n\n\tpublicKey := &gmsm_sm2.PublicKey{\n\t\tX: x,\n\t\tY: y,\n\t}\n\tvar pubSM2 sm2.PubKeySM2\n\tcopy(pubSM2[:], gmsm_sm2.Compress(publicKey))\n\n\trBytes := common.FromHex(\"00000000000000000000000000000000000000000000000000000000000000003AA29337E7149047FB8AE83F30AA00125E23173C88F284ADDED2E5B59ACAA5B9\")\n\tsBytes := common.FromHex(\"0000000000000000000000000000000000000000000000000000000000000000E2E9338109D74269578216039FD4D1C764E7F6F142CBB2E3035E7E49D375D330\")\n\tr := new(big.Int).SetBytes(rBytes)\n\ts := new(big.Int).SetBytes(sBytes)\n\n\tsignature := sm2.SignatureSM2(sm2.Serialize(r, s))\n\n\tmsg := []byte(\"112233445566112233445566112233445566112233445566\")\n\tok := pubSM2.VerifyBytes(msg, signature)\n\trequire.Equal(true, ok)\n}", "func (_BondedECDSAKeep *BondedECDSAKeepSession) Sign(_digest [32]byte) (*types.Transaction, error) {\n\treturn _BondedECDSAKeep.Contract.Sign(&_BondedECDSAKeep.TransactOpts, _digest)\n}", "func Sign(message, secretKey []byte) ([]byte, error) {\n\treturn defaultPH.cryptoSign(message, secretKey)\n}", "func (l LocalIdentity) Sign(message []byte) ed25519.Signature {\n\treturn l.privateKey.Sign(message)\n}", "func (s *SigningMethodIAM) Sign(signingString string, key interface{}) (string, error) {\n\tvar ctx context.Context\n\n\t// check to make sure the key is a context.Context\n\tswitch k := key.(type) {\n\tcase context.Context:\n\t\tctx = k\n\tdefault:\n\t\treturn \"\", jwt.ErrInvalidKey\n\t}\n\n\t// Get the IAMConfig from the context\n\tconfig, ok := IAMFromContext(ctx)\n\tif !ok {\n\t\treturn \"\", ErrMissingConfig\n\t}\n\n\t// Use the user provided IAMService or generate our own\n\tiamService := config.IAMService\n\tif iamService == nil {\n\t\tvar err error\n\t\tiamService, err = iamcredentials.NewService(ctx)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t}\n\n\t// Do the call\n\treturn s.sign(ctx, iamService, config, signingString)\n}", "func (transaction *ScheduleSignTransaction) Sign(\n\tprivateKey PrivateKey,\n) *ScheduleSignTransaction {\n\treturn transaction.SignWith(privateKey.PublicKey(), privateKey.Sign)\n}", "func Sign(params Params, key string) string {\n\tsort.Sort(params)\n\tpreSignWithKey := params.ToQueryString() + \"&key=\" + key\n\treturn fmt.Sprintf(\"%X\", md5.Sum([]byte(preSignWithKey)))\n}", "func Sign(params Params, key string) string {\n\tsort.Sort(params)\n\tpreSignWithKey := params.ToQueryString() + \"&key=\" + key\n\treturn fmt.Sprintf(\"%X\", md5.Sum([]byte(preSignWithKey)))\n}", "func Sign(message string) (string, error) {\n\n\t// TODO check length on string\n\t// Sign\n\tvar h hash.Hash\n\th = sha256.New()\n\n\tio.WriteString(h, message)\n\tsignhash := h.Sum(nil)\n\n\trsaKey, err := loadPrivateKeyFromFile()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\trsaSignature, err := rsa.SignPKCS1v15(rand.Reader, rsaKey, crypto.SHA256, signhash)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t\treturn \"\", err\n\t}\n\n\tsEnc := base64.StdEncoding.EncodeToString(rsaSignature)\n\treturn sEnc, nil\n}", "func (m *CryptographyServiceMock) Verify(p crypto.PublicKey, p1 insolar.Signature, p2 []byte) (r bool) {\n\tcounter := atomic.AddUint64(&m.VerifyPreCounter, 1)\n\tdefer atomic.AddUint64(&m.VerifyCounter, 1)\n\n\tif len(m.VerifyMock.expectationSeries) > 0 {\n\t\tif counter > uint64(len(m.VerifyMock.expectationSeries)) {\n\t\t\tm.t.Fatalf(\"Unexpected call to CryptographyServiceMock.Verify. %v %v %v\", p, p1, p2)\n\t\t\treturn\n\t\t}\n\n\t\tinput := m.VerifyMock.expectationSeries[counter-1].input\n\t\ttestify_assert.Equal(m.t, *input, CryptographyServiceMockVerifyInput{p, p1, p2}, \"CryptographyService.Verify got unexpected parameters\")\n\n\t\tresult := m.VerifyMock.expectationSeries[counter-1].result\n\t\tif result == nil {\n\t\t\tm.t.Fatal(\"No results are set for the CryptographyServiceMock.Verify\")\n\t\t\treturn\n\t\t}\n\n\t\tr = result.r\n\n\t\treturn\n\t}\n\n\tif m.VerifyMock.mainExpectation != nil {\n\n\t\tinput := m.VerifyMock.mainExpectation.input\n\t\tif input != nil {\n\t\t\ttestify_assert.Equal(m.t, *input, CryptographyServiceMockVerifyInput{p, p1, p2}, \"CryptographyService.Verify got unexpected parameters\")\n\t\t}\n\n\t\tresult := m.VerifyMock.mainExpectation.result\n\t\tif result == nil {\n\t\t\tm.t.Fatal(\"No results are set for the CryptographyServiceMock.Verify\")\n\t\t}\n\n\t\tr = result.r\n\n\t\treturn\n\t}\n\n\tif m.VerifyFunc == nil {\n\t\tm.t.Fatalf(\"Unexpected call to CryptographyServiceMock.Verify. %v %v %v\", p, p1, p2)\n\t\treturn\n\t}\n\n\treturn m.VerifyFunc(p, p1, p2)\n}", "func (id *Identity) Sign(data []byte) []byte {\n\treturn ed25519.Sign(id.PrivateKey, data)\n}", "func (ca *FakeCA) Sign([]byte, []string, time.Duration, bool) ([]byte, error) {\n\tif ca.SignErr != nil {\n\t\treturn nil, ca.SignErr\n\t}\n\treturn ca.SignedCert, nil\n}", "func sign(key *rsa.PrivateKey, blob []byte) ([]byte, error) {\n\th := sha1.New()\n\th.Write(blob)\n\tdigest := h.Sum(nil)\n\treturn rsa.SignPKCS1v15(nil, key, crypto.SHA1, digest)\n}", "func Sign(rand io.Reader, obj Signable, signer Signer, hash Hash) (Signature, error) {\n\tbytes, err := obj.SigningBytes()\n\tif err != nil {\n\t\treturn Signature{}, errors.WithStack(err)\n\t}\n\n\tsig, err := signer.Sign(rand, hash, bytes)\n\tif err != nil {\n\t\treturn Signature{}, errors.WithStack(err)\n\t}\n\treturn sig, nil\n}", "func (mmSignWith *mDigestHolderMockSignWith) Expect(signer DigestSigner) *mDigestHolderMockSignWith {\n\tif mmSignWith.mock.funcSignWith != nil {\n\t\tmmSignWith.mock.t.Fatalf(\"DigestHolderMock.SignWith mock is already set by Set\")\n\t}\n\n\tif mmSignWith.defaultExpectation == nil {\n\t\tmmSignWith.defaultExpectation = &DigestHolderMockSignWithExpectation{}\n\t}\n\n\tmmSignWith.defaultExpectation.params = &DigestHolderMockSignWithParams{signer}\n\tfor _, e := range mmSignWith.expectations {\n\t\tif minimock.Equal(e.params, mmSignWith.defaultExpectation.params) {\n\t\t\tmmSignWith.mock.t.Fatalf(\"Expectation set by When has same params: %#v\", *mmSignWith.defaultExpectation.params)\n\t\t}\n\t}\n\n\treturn mmSignWith\n}", "func (cosigner *LocalCosigner) Sign(req CosignerSignRequest) (CosignerSignResponse, error) {\n\tcosigner.lastSignStateMutex.Lock()\n\tdefer cosigner.lastSignStateMutex.Unlock()\n\n\tres := CosignerSignResponse{}\n\tlss := cosigner.lastSignState\n\n\theight, round, step, err := UnpackHRS(req.SignBytes)\n\tif err != nil {\n\t\treturn res, err\n\t}\n\n\tsameHRS, err := lss.CheckHRS(height, round, step)\n\tif err != nil {\n\t\treturn res, err\n\t}\n\n\t// If the HRS is the same the sign bytes may still differ by timestamp\n\t// It is ok to re-sign a different timestamp if that is the only difference in the sign bytes\n\tif sameHRS {\n\t\tif bytes.Equal(req.SignBytes, lss.SignBytes) {\n\t\t\tres.EphemeralPublic = lss.EphemeralPublic\n\t\t\tres.Signature = lss.Signature\n\t\t\treturn res, nil\n\t\t} else if _, ok := lss.OnlyDifferByTimestamp(req.SignBytes); !ok {\n\t\t\treturn res, errors.New(\"Mismatched data\")\n\t\t}\n\n\t\t// saame HRS, and only differ by timestamp - ok to sign again\n\t}\n\n\thrsKey := HRSKey{\n\t\tHeight: height,\n\t\tRound: round,\n\t\tStep: step,\n\t}\n\tmeta, ok := cosigner.hrsMeta[hrsKey]\n\tif !ok {\n\t\treturn res, errors.New(\"No metadata at HRS\")\n\t}\n\n\tshareParts := make([]tsed25519.Scalar, 0)\n\tpublicKeys := make([]tsed25519.Element, 0)\n\n\t// calculate secret and public keys\n\tfor _, peer := range meta.Peers {\n\t\tif len(peer.Share) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tshareParts = append(shareParts, peer.Share)\n\t\tpublicKeys = append(publicKeys, peer.EphemeralSecretPublicKey)\n\t}\n\n\tephemeralShare := tsed25519.AddScalars(shareParts)\n\tephemeralPublic := tsed25519.AddElements(publicKeys)\n\n\t// check bounds for ephemeral share to avoid passing out of bounds valids to SignWithShare\n\t{\n\t\tif len(ephemeralShare) != 32 {\n\t\t\treturn res, errors.New(\"Ephemeral share is out of bounds.\")\n\t\t}\n\n\t\tvar scalarBytes [32]byte\n\t\tcopy(scalarBytes[:], ephemeralShare)\n\t\tif !edwards25519.ScMinimal(&scalarBytes) {\n\t\t\treturn res, errors.New(\"Ephemeral share is out of bounds.\")\n\t\t}\n\t}\n\n\tshare := cosigner.key.ShareKey[:]\n\tsig := tsed25519.SignWithShare(req.SignBytes, share, ephemeralShare, cosigner.pubKeyBytes, ephemeralPublic)\n\n\tcosigner.lastSignState.Height = height\n\tcosigner.lastSignState.Round = round\n\tcosigner.lastSignState.Step = step\n\tcosigner.lastSignState.EphemeralPublic = ephemeralPublic\n\tcosigner.lastSignState.Signature = sig\n\tcosigner.lastSignState.SignBytes = req.SignBytes\n\tcosigner.lastSignState.Save()\n\n\tfor existingKey := range cosigner.hrsMeta {\n\t\t// delete any HRS lower than our signed level\n\t\t// we will not be providing parts for any lower HRS\n\t\tif existingKey.Less(hrsKey) {\n\t\t\tdelete(cosigner.hrsMeta, existingKey)\n\t\t}\n\t}\n\n\tres.EphemeralPublic = ephemeralPublic\n\tres.Signature = sig\n\treturn res, nil\n}", "func (d *identityManager) Sign(message []byte) ([]byte, error) {\n\treturn Sign(d.key.PrivateKey, message)\n}", "func (s *SMJWT) Sign(claims jwt.Claims) (string, error) {\n\tif s.privateKey == nil {\n\t\treturn \"\", ErrNoPrivateKeySpecified\n\t}\n\n\ttoken := jwt.NewWithClaims(jwt.SigningMethodRS256, claims)\n\treturn token.SignedString(s.privateKey)\n}", "func (c *CoordinatorHelper) Sign(\n\tctx context.Context,\n\tpayloads []*types.SigningPayload,\n) ([]*types.Signature, error) {\n\treturn c.keyStorage.Sign(ctx, payloads)\n}", "func (s *HmacSigner) Sign(payload []byte) string {\n\tmac := hmac.New(s.h, s.key)\n\tmac.Write(payload)\n\treturn s.e(mac.Sum(nil))\n}", "func (ms MockSigner) SignBytes(data []byte, addr address.Address) (Signature, error) {\n\tki, ok := ms.AddrKeyInfo[addr]\n\tif !ok {\n\t\tpanic(\"unknown address\")\n\t}\n\n\thash := blake2b.Sum256(data)\n\treturn crypto.Sign(ki.Key(), hash[:])\n}", "func (m *SigningMethodRSA) Sign(signingString string, key interface{}) (string, error) {\n\tvar rsaKey *rsa.PrivateKey\n\tvar ok bool\n\n\t// Validate type of key\n\tif rsaKey, ok = key.(*rsa.PrivateKey); !ok {\n\t\treturn \"\", ErrInvalidKey\n\t}\n\n\t// Create the hasher\n\tif !m.Hash.Available() {\n\t\treturn \"\", ErrHashUnavailable\n\t}\n\n\thasher := m.Hash.New()\n\thasher.Write([]byte(signingString))\n\n\t// Sign the string and return the encoded bytes\n\tif sigBytes, err := rsa.SignPKCS1v15(rand.Reader, rsaKey, m.Hash, hasher.Sum(nil)); err == nil {\n\t\treturn EncodeSegment(sigBytes), nil\n\t} else {\n\t\treturn \"\", err\n\t}\n}", "func (transaction *TokenMintTransaction) Sign(\n\tprivateKey PrivateKey,\n) *TokenMintTransaction {\n\treturn transaction.SignWith(privateKey.PublicKey(), privateKey.Sign)\n}", "func (v4 Signer) Sign(ctx context.Context, r *http.Request, body io.ReadSeeker, service, region string, signTime time.Time) (http.Header, error) {\n\treturn v4.signWithBody(ctx, r, body, service, region, 0, signTime)\n}", "func (p *Payload) Sign(key []byte) (signature [32]byte) {\n\tsignature = sha256.Sum256(append(p.message[:], key[:]...))\n\tp.signature = signature\n\treturn\n}", "func (m *MockMachine) SignerKey() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"SignerKey\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func (addr *Address) Sign(privKey *id.PrivKey) error {\n\tbuf := make([]byte, surge.SizeHintU8+surge.SizeHintString(addr.Value)+surge.SizeHintU64)\n\treturn addr.SignWithBuffer(privKey, buf)\n}", "func (tf *TracingFingerprint) Sign() string {\n\tsign := tf.Fingerprint.Sign()\n\ttf.tracer.Sign(sign)\n\treturn sign\n}", "func (obj *RawCardSigner) Sign(rawCard *RawCard, signerId string, privateKey foundation.PrivateKey) error {\n\tsignerIdChar := C.CString(signerId)\n\tdefer C.free(unsafe.Pointer(signerIdChar))\n\tsignerIdStr := C.vsc_str_from_str(signerIdChar)\n\n\tproxyResult := /*pr4*/ C.vssc_raw_card_signer_sign(obj.cCtx, (*C.vssc_raw_card_t)(unsafe.Pointer(rawCard.Ctx())), signerIdStr, (*C.vscf_impl_t)(unsafe.Pointer(privateKey.Ctx())))\n\n\terr := CoreSdkErrorHandleStatus(proxyResult)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\truntime.KeepAlive(obj)\n\n\truntime.KeepAlive(rawCard)\n\n\truntime.KeepAlive(signerId)\n\n\truntime.KeepAlive(privateKey)\n\n\treturn nil\n}", "func sign(credentials Credentials, req Request, option *SignOption) string {\n\tsigningKey := getSigningKey(credentials, option)\n\treq.prepareHeaders(option)\n\tcanonicalRequest := req.canonical(option)\n\tsignature := util.HmacSha256Hex(signingKey, canonicalRequest)\n\n\treturn signature\n}" ]
[ "0.73569053", "0.68571746", "0.6440196", "0.6397187", "0.6395241", "0.6389407", "0.6373618", "0.63479185", "0.6286529", "0.6282975", "0.6222466", "0.6218619", "0.62139755", "0.6212541", "0.6208312", "0.62067086", "0.618209", "0.6171891", "0.6165349", "0.61397684", "0.6135525", "0.61122584", "0.6095109", "0.6092974", "0.6064169", "0.6061388", "0.60526574", "0.6042685", "0.60024244", "0.6001824", "0.59737915", "0.5965108", "0.596105", "0.596105", "0.5957223", "0.5940368", "0.5879613", "0.5871676", "0.5870547", "0.5852694", "0.584486", "0.58380634", "0.5823511", "0.5811626", "0.5809505", "0.5803043", "0.57860994", "0.578525", "0.57713586", "0.57624555", "0.57613987", "0.5760774", "0.575974", "0.57524955", "0.5751753", "0.57494056", "0.574039", "0.5740242", "0.57368344", "0.5734752", "0.5722676", "0.5721517", "0.5719681", "0.5711202", "0.56893086", "0.56884205", "0.56799716", "0.56771123", "0.56767553", "0.5676752", "0.56732184", "0.56676716", "0.5659351", "0.5655011", "0.5654485", "0.5648707", "0.56344277", "0.56344277", "0.56320244", "0.56298244", "0.56204695", "0.5618979", "0.5616103", "0.5613317", "0.56090486", "0.5600367", "0.5592873", "0.5589591", "0.5580142", "0.55728865", "0.5570658", "0.5569945", "0.55594647", "0.554978", "0.5540948", "0.5534345", "0.55338144", "0.55313015", "0.55307406", "0.5527662" ]
0.742772
0
Sign indicates an expected call of Sign
func (mr *MockClientMockRecorder) Sign(arg0 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Sign", reflect.TypeOf((*MockClient)(nil).Sign), arg0) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (m EncMessage) Sign(k []byte) error {\n\treturn errors.New(\"Sign method must be overridden\")\n}", "func (x *Big) Sign() int {\n\tif debug {\n\t\tx.validate()\n\t}\n\n\tif (x.IsFinite() && x.isZero()) || x.IsNaN(0) {\n\t\treturn 0\n\t}\n\tif x.form&signbit != 0 {\n\t\treturn -1\n\t}\n\treturn 1\n}", "func Sign(x int) int {\n\tif x < 0 {\n\t\treturn -1\n\t}\n\treturn 1\n}", "func Sign(a int) int {\n\treturn neogointernal.Opcode1(\"SIGN\", a).(int)\n}", "func (validator *validatorImpl) Sign(msg []byte) ([]byte, error) {\n\treturn validator.signWithEnrollmentKey(msg)\n}", "func (_Ethdkg *EthdkgCaller) Sign(opts *bind.CallOpts, message []byte, privK *big.Int) ([2]*big.Int, error) {\n\tvar (\n\t\tret0 = new([2]*big.Int)\n\t)\n\tout := ret0\n\terr := _Ethdkg.contract.Call(opts, out, \"Sign\", message, privK)\n\treturn *ret0, err\n}", "func (m *Money) Sign() int {\n\tif m.M < 0 {\n\t\treturn -1\n\t}\n\treturn 1\n}", "func (_BondedECDSAKeep *BondedECDSAKeepTransactor) Sign(opts *bind.TransactOpts, _digest [32]byte) (*types.Transaction, error) {\n\treturn _BondedECDSAKeep.contract.Transact(opts, \"sign\", _digest)\n}", "func (b *Base) Sign(req *SignReq) (*SignResp, error) {\n\treturn nil, ErrFunctionNotSupported\n}", "func Sign(x float64) float64 {\n\tif x < 0 {\n\t\treturn -1\n\t}\n\tif x > 0 {\n\t\treturn 1\n\t}\n\treturn 0\n}", "func (adr *Address) Sign(tr *tx.Transaction) error {\n\treturn tr.Sign(adr.Address)\n}", "func Sign(x *big.Int) int {\n\treturn x.Sign()\n}", "func (b *Block) sign() error {\n\tvar sigErr error\n\tsignBytes := b.signablePayload()\n\tsig, sigErr := cs.SignBlock(signBytes)\n\tif sigErr != nil {\n\t\treturn sigErr\n\t}\n\n\tb.Sig = fmt.Sprintf(\"%x\", sig)\n\n\treturn nil\n}", "func (c Currency) Sign() int {\n\tif c.m < 0 {\n\t\treturn -1\n\t}\n\treturn 1\n}", "func (m *MetricsProvider) SignerSign(value time.Duration) {\n}", "func (tf *TracingFingerprint) Sign() string {\n\tsign := tf.Fingerprint.Sign()\n\ttf.tracer.Sign(sign)\n\treturn sign\n}", "func Sign(x Value) int {\n\tif v, ok := x.(*ratVal); ok {\n\t\tx = v.Value\n\t}\n\treturn constant.Sign(x)\n}", "func (_Ethdkg *EthdkgCallerSession) Sign(message []byte, privK *big.Int) ([2]*big.Int, error) {\n\treturn _Ethdkg.Contract.Sign(&_Ethdkg.CallOpts, message, privK)\n}", "func (x *Rat) Sign() int {}", "func (mr *MockSignerMockRecorder) Sign(arg0, arg1 interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Sign\", reflect.TypeOf((*MockSigner)(nil).Sign), arg0, arg1)\n}", "func (q *Quantity) Sign() int {\n\tif q.d.Dec != nil {\n\t\treturn q.d.Dec.Sign()\n\t}\n\treturn q.i.Sign()\n}", "func (x *Int) Sign() int {}", "func (i Int) Sign() int {\n\treturn i.i.Sign()\n}", "func (state *MSCBaseStateSigned) VerifySign(id identity.OffChainID, role Role) (isValid bool, err error) {\n\n\tvar signToValidate []byte\n\n\tswitch role {\n\tcase Sender:\n\t\tsignToValidate = state.SignSender\n\tcase Receiver:\n\t\tsignToValidate = state.SignReceiver\n\tdefault:\n\t\treturn false, fmt.Errorf(\"Invalid role\")\n\t}\n\n\thash := state.MSContractBaseState.SoliditySHA3()\n\tisValid, err = identity.VerifySignatureEth(hash, signToValidate, id.OnChainID.Bytes())\n\tif err != nil {\n\t\treturn false, err\n\t}\n\treturn isValid, nil\n}", "func (mr *MockSignerDecrypterMockRecorder) Sign(arg0, arg1, arg2 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Sign\", reflect.TypeOf((*MockSignerDecrypter)(nil).Sign), arg0, arg1, arg2)\n}", "func (kp *FromAddress) Sign(input []byte) ([]byte, error) {\n\treturn nil, ErrCannotSign\n}", "func TestBasicSign(t *testing.T) {\n\tcs := NewEd25519()\n\tkey, err := cs.Create(data.CanonicalRootRole, \"\", data.ED25519Key)\n\trequire.NoError(t, err)\n\ttestData := data.Signed{\n\t\tSigned: &json.RawMessage{},\n\t}\n\n\terr = Sign(cs, &testData, key)\n\trequire.NoError(t, err)\n\n\tif len(testData.Signatures) != 1 {\n\t\tt.Fatalf(\"Incorrect number of signatures: %d\", len(testData.Signatures))\n\t}\n\n\tif testData.Signatures[0].KeyID != key.ID() {\n\t\tt.Fatalf(\"Wrong signature ID returned: %s\", testData.Signatures[0].KeyID)\n\t}\n}", "func (_Ethdkg *EthdkgSession) Sign(message []byte, privK *big.Int) ([2]*big.Int, error) {\n\treturn _Ethdkg.Contract.Sign(&_Ethdkg.CallOpts, message, privK)\n}", "func Sign(suite suites.Suite, x kyber.Scalar, msg []byte) ([]byte, error) {\n\tHM := hashToPoint(suite, msg)\n\txHM := HM.Mul(x, HM)\n\ts, err := xHM.MarshalBinary()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn s, nil\n}", "func Core_Sign(SIG []byte, M []byte, S []byte) int {\n\tD := bls_hash_to_point(M)\n\ts := FromBytes(S)\n\tD = G1mul(D, s)\n\tD.ToBytes(SIG, true)\n\treturn BLS_OK\n}", "func (kh *KeyHandler) Sign(buf []byte) ([]byte, cop.Error) {\n\treturn make([]byte, 0), nil\n}", "func (mr *MockTransactionApiMockRecorder) VerifySign(tx, outpoint, amount, txinUtxoList interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"VerifySign\", reflect.TypeOf((*MockTransactionApi)(nil).VerifySign), tx, outpoint, amount, txinUtxoList)\n}", "func (p *PrivateKey) Sign(mesg string) string {\n\tvar enc, m big.Int\n\tsetBytesReverse(&m, []byte(mesg))\n\tenc.Exp(&m, p.keyD, p.keyN)\n\treturn intToBase64(&enc)\n}", "func (d Decimal) Sign() int {\n\tif d.value == nil {\n\t\treturn 0\n\t}\n\treturn d.value.Sign()\n}", "func (d Decimal) Sign() int {\n\tif d.value == nil {\n\t\treturn 0\n\t}\n\treturn d.value.Sign()\n}", "func Sign(v float32) float32 {\n\tif v >= 0.0 {\n\t\treturn 1.0\n\t}\n\treturn -1.0\n}", "func TestSignContractSuccess(t *testing.T) {\n\tsignatureHelper(t, false)\n}", "func (addr *Address) Sign(privKey *id.PrivKey) error {\n\tbuf := make([]byte, surge.SizeHintU8+surge.SizeHintString(addr.Value)+surge.SizeHintU64)\n\treturn addr.SignWithBuffer(privKey, buf)\n}", "func (c *Conn) Sign(buf []byte) []byte {\n\tc.WriteToHash(buf)\n\tc.WriteToHash(c.chalUs)\n\tbuf = c.h.Sum(buf)\n\tc.h.Reset()\n\treturn buf\n}", "func TestSignContractFailure(t *testing.T) {\n\tsignatureHelper(t, true)\n}", "func Sign(operation []byte, privKey ecdsa.PrivateKey) (signedR, signedS *big.Int, err error) {\n\tr, s, err := ecdsa.Sign(rand.Reader, &privKey, operation)\n\tif err != nil {\n\t\treturn big.NewInt(0), big.NewInt(0), err\n\t}\n\n\tsignedR = r\n\tsignedS = s\n\treturn\n}", "func (f Fixed) Sign() int {\n\tif f.IsNaN() {\n\t\treturn 0\n\t}\n\treturn f.Cmp(ZERO)\n}", "func (f Fixed) Sign() int {\n\tif f.IsNaN() {\n\t\treturn 0\n\t}\n\treturn f.Cmp(ZERO)\n}", "func (q *Qsign) Sign(v interface{}) ([]byte, error) {\n\tdigest, err := q.Digest(v)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\th := q.hasher()\n\th.Write(digest)\n\n\te := q.encoder()\n\tdst := make([]byte, e.EncodedLen(h.Size()))\n\te.Encode(dst, h.Sum(nil))\n\n\treturn dst, nil\n}", "func (m *CryptographyServiceMock) Sign(p []byte) (r *insolar.Signature, r1 error) {\n\tcounter := atomic.AddUint64(&m.SignPreCounter, 1)\n\tdefer atomic.AddUint64(&m.SignCounter, 1)\n\n\tif len(m.SignMock.expectationSeries) > 0 {\n\t\tif counter > uint64(len(m.SignMock.expectationSeries)) {\n\t\t\tm.t.Fatalf(\"Unexpected call to CryptographyServiceMock.Sign. %v\", p)\n\t\t\treturn\n\t\t}\n\n\t\tinput := m.SignMock.expectationSeries[counter-1].input\n\t\ttestify_assert.Equal(m.t, *input, CryptographyServiceMockSignInput{p}, \"CryptographyService.Sign got unexpected parameters\")\n\n\t\tresult := m.SignMock.expectationSeries[counter-1].result\n\t\tif result == nil {\n\t\t\tm.t.Fatal(\"No results are set for the CryptographyServiceMock.Sign\")\n\t\t\treturn\n\t\t}\n\n\t\tr = result.r\n\t\tr1 = result.r1\n\n\t\treturn\n\t}\n\n\tif m.SignMock.mainExpectation != nil {\n\n\t\tinput := m.SignMock.mainExpectation.input\n\t\tif input != nil {\n\t\t\ttestify_assert.Equal(m.t, *input, CryptographyServiceMockSignInput{p}, \"CryptographyService.Sign got unexpected parameters\")\n\t\t}\n\n\t\tresult := m.SignMock.mainExpectation.result\n\t\tif result == nil {\n\t\t\tm.t.Fatal(\"No results are set for the CryptographyServiceMock.Sign\")\n\t\t}\n\n\t\tr = result.r\n\t\tr1 = result.r1\n\n\t\treturn\n\t}\n\n\tif m.SignFunc == nil {\n\t\tm.t.Fatalf(\"Unexpected call to CryptographyServiceMock.Sign. %v\", p)\n\t\treturn\n\t}\n\n\treturn m.SignFunc(p)\n}", "func (s *BaseLittleDuckListener) EnterFactor_sign(ctx *Factor_signContext) {}", "func (ra *RestrictedAgent) Sign(key ssh.PublicKey, data []byte) (*ssh.Signature, error) {\n\treturn nil, ErrForbidden\n}", "func Sign(scope *Scope, x tf.Output) (y tf.Output) {\n\tif scope.Err() != nil {\n\t\treturn\n\t}\n\topspec := tf.OpSpec{\n\t\tType: \"Sign\",\n\t\tInput: []tf.Input{\n\t\t\tx,\n\t\t},\n\t}\n\top := scope.AddOperation(opspec)\n\treturn op.Output(0)\n}", "func (_BondedECDSAKeep *BondedECDSAKeepTransactorSession) Sign(_digest [32]byte) (*types.Transaction, error) {\n\treturn _BondedECDSAKeep.Contract.Sign(&_BondedECDSAKeep.TransactOpts, _digest)\n}", "func (transaction *ScheduleSignTransaction) Sign(\n\tprivateKey PrivateKey,\n) *ScheduleSignTransaction {\n\treturn transaction.SignWith(privateKey.PublicKey(), privateKey.Sign)\n}", "func (z *Int) Sign() int {\n\tif z.IsZero() {\n\t\treturn 0\n\t}\n\tif z.Lt(SignedMin) {\n\t\treturn 1\n\t}\n\treturn -1\n}", "func Sign(m string, kp *Keypair) *Signature {\n\treturn genSignature(m, kp.private)\n}", "func (state *VPCStateSigned) VerifySign(id identity.OffChainID, role Role) (isValid bool, err error) {\n\n\tvar signToValidate []byte\n\n\tswitch role {\n\tcase Sender:\n\t\tsignToValidate = state.SignSender\n\tcase Receiver:\n\t\tsignToValidate = state.SignReceiver\n\tdefault:\n\t\treturn false, fmt.Errorf(\"Invalid role\")\n\t}\n\n\thash := state.VPCState.SoliditySHA3()\n\tisValid, err = identity.VerifySignatureEth(hash, signToValidate, id.OnChainID.Bytes())\n\tif err != nil {\n\t\treturn false, err\n\t}\n\treturn isValid, nil\n}", "func Test_CanSign_NilInput(t *testing.T) {\n\n\t// prepare input\n\tvar transactionInput *TransactionInput\n\tvar unspentTransactions []*UnspentTransactionOutput\n\tvar publicKey = \"\"\n\n\t// call can sign\n\tresult := CanSign(unspentTransactions, transactionInput, publicKey)\n\n\t// result should false\n\tif result {\n\t\tt.Errorf(\"result of nil transaction should be false.\")\n\t}\n}", "func Test_CanSign_NoUnspentTransactionMatches(t *testing.T) {\n\n\t// prepare input\n\tvar transactionInput *TransactionInput = &TransactionInput{\n\t\tOutputID: \"outID\",\n\t\tOutputIndex: 10,\n\t}\n\tvar unspentTransactions = []*UnspentTransactionOutput{\n\t\t{\n\t\t\tOutputID: \"outID1\",\n\t\t\tOutputIndex: 100,\n\t\t\tAddress: \"addressX\",\n\t\t},\n\t}\n\tvar publicKey = \"public_key\"\n\n\t// call can sign\n\tresult := CanSign(unspentTransactions, transactionInput, publicKey)\n\n\t// result should false\n\tif result {\n\t\tt.Errorf(\"when no unspent transaction matches the result should be false\")\n\t}\n}", "func Test_CanSign_Correct(t *testing.T) {\n\n\t// prepare input\n\tvar transactionInput *TransactionInput = &TransactionInput{\n\t\tOutputID: \"outID\",\n\t\tOutputIndex: 10,\n\t}\n\tvar unspentTransactions = []*UnspentTransactionOutput{\n\t\t{\n\t\t\tOutputID: \"outID-1\",\n\t\t\tOutputIndex: 1000,\n\t\t\tAddress: \"addressX\",\n\t\t},\n\t\t{\n\t\t\tOutputID: \"outID\",\n\t\t\tOutputIndex: 10,\n\t\t\tAddress: \"public_key\",\n\t\t},\n\t}\n\tvar publicKey = \"public_key\"\n\n\t// call can sign\n\tresult := CanSign(unspentTransactions, transactionInput, publicKey)\n\n\t// result should false\n\tif !result {\n\t\tt.Errorf(\"The result must be true when there is unspent transaction and adddress is the same the public key\")\n\t}\n}", "func (m *MockClient) Sign(arg0 []byte) ([]byte, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Sign\", arg0)\n\tret0, _ := ret[0].([]byte)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (v *CA) Sign(csrPEM []byte, ttl time.Duration) ([]byte, error) {\n\treturn nil, fmt.Errorf(\"not implemented\")\n}", "func TestSign(w http.ResponseWriter, r *http.Request) {\n\tconf := ConfLoad()\n\n\t// Returns a Public / Private Key Pair\n\t// Read JSON config from app.yaml\n\tif v := os.Getenv(\"PRIV_KEY\"); v != \"\" {\n\t\terr := json.Unmarshal([]byte(v), &conf)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"%#v\", conf)\n\t\t\tpanic(err)\n\t\t}\n\t}\n\n\t// Get the public key\n\tvar pubkey ecdsa.PublicKey\n\tpubkey = conf.PublicKey\n\n\t// Try signing a message\n\tmessage := []byte(\"99999999\")\n\tsig1, sig2, err := ecdsa.Sign(rand.Reader, &conf.PrivateKey, message)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// Try verifying the signature\n\tresult := ecdsa.Verify(&pubkey, message, sig1, sig2)\n\tif result != true {\n\t\tpanic(\"Unable to verify signature\")\n\t}\n\n\tfmt.Fprintf(w, \"message: %#v\\n\\nsig1: %#v\\nsig2: %#v\", string(message[:]), sig1, sig2)\n\n}", "func (v4 Signer) Sign(ctx context.Context, r *http.Request, body io.ReadSeeker, service, region string, signTime time.Time) (http.Header, error) {\n\treturn v4.signWithBody(ctx, r, body, service, region, 0, signTime)\n}", "func (p *ProtocolTECDSA) Sign(message *big.Int) Signature {\n\ttps := p.presig[0]\n\tp.presig = p.presig[1:]\n\n\tkKey, _ := tps.k.Exp()\n\tR, _ := kKey.RevealExp()\n\tr := hash(R)\n\n\ttau, _ := tps.tau.Reveal()\n\n\ta, b := message.Div(message, tau), r.Div(r, tau)\n\tsTDSecret := p.lin(a, tps.rho, b, tps.eta)\n\n\ts, _ := sTDSecret.Reveal()\n\n\treturn Signature{r, s}\n}", "func RatSign(x *big.Rat,) int", "func (m *MockSigner) Sign(arg0 *ecdsa.PrivateKey, arg1 proto0.Message) (*proto.Signature, error) {\n\tret := m.ctrl.Call(m, \"Sign\", arg0, arg1)\n\tret0, _ := ret[0].(*proto.Signature)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func Sign(s *big.Int, params *Params, key *PrivateKey, attrs AttributeList, message *big.Int) (*Signature, error) {\n\treturn SignPrecomputed(s, params, key, attrs, PrepareAttributeSet(params, attrs), message)\n}", "func (m *DigestHolderMock) MinimockSignWithInspect() {\n\tfor _, e := range m.SignWithMock.expectations {\n\t\tif mm_atomic.LoadUint64(&e.Counter) < 1 {\n\t\t\tm.t.Errorf(\"Expected call to DigestHolderMock.SignWith with params: %#v\", *e.params)\n\t\t}\n\t}\n\n\t// if default expectation was set then invocations count should be greater than zero\n\tif m.SignWithMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterSignWithCounter) < 1 {\n\t\tif m.SignWithMock.defaultExpectation.params == nil {\n\t\t\tm.t.Error(\"Expected call to DigestHolderMock.SignWith\")\n\t\t} else {\n\t\t\tm.t.Errorf(\"Expected call to DigestHolderMock.SignWith with params: %#v\", *m.SignWithMock.defaultExpectation.params)\n\t\t}\n\t}\n\t// if func was set then invocations count should be greater than zero\n\tif m.funcSignWith != nil && mm_atomic.LoadUint64(&m.afterSignWithCounter) < 1 {\n\t\tm.t.Error(\"Expected call to DigestHolderMock.SignWith\")\n\t}\n}", "func Sign(msg []byte, seckey []byte) ([]byte, error) {\n\treturn secp256k1.Sign(msg, seckey)\n}", "func (p Point) Sign() (int64) {\n\tnum, _ :=strconv.Atoi(string(p.Val[len(p.Val)-1]))\n\ttempnum:= (int64(num)/128)\n\treturn tempnum\n}", "func (x *Big) Signbit() bool {\n\tif debug {\n\t\tx.validate()\n\t}\n\treturn x.form&signbit != 0\n}", "func (*noSignHash) SignHash() {\n}", "func (c *Client) Sign(addr Address, message Data) (*DataResponse, error) {\n\trequest := c.newRequest(EthSign)\n\n\trequest.Params = []string{\n\t\tstring(addr),\n\t\tstring(message),\n\t}\n\tresponse := &DataResponse{}\n\n\treturn response, c.send(request, response)\n}", "func (_BondedECDSAKeep *BondedECDSAKeepSession) Sign(_digest [32]byte) (*types.Transaction, error) {\n\treturn _BondedECDSAKeep.Contract.Sign(&_BondedECDSAKeep.TransactOpts, _digest)\n}", "func (c *curve) coordSign(i *mod.Int) uint {\n\treturn i.V.Bit(0)\n}", "func (ca *FakeCA) Sign([]byte, []string, time.Duration, bool) ([]byte, error) {\n\tif ca.SignErr != nil {\n\t\treturn nil, ca.SignErr\n\t}\n\treturn ca.SignedCert, nil\n}", "func (x *Float) Signbit() bool {}", "func Sign(v string, s string) string {\n\thasher := sha256.New()\n\thasher.Write([]byte(v + s))\n\treturn v + \".\" + Encode(string(hasher.Sum(nil)))\n}", "func (fn *formulaFuncs) SIGN(argsList *list.List) formulaArg {\n\tif argsList.Len() != 1 {\n\t\treturn newErrorFormulaArg(formulaErrorVALUE, \"SIGN requires 1 numeric argument\")\n\t}\n\tval := argsList.Front().Value.(formulaArg).ToNumber()\n\tif val.Type == ArgError {\n\t\treturn val\n\t}\n\tif val.Number < 0 {\n\t\treturn newNumberFormulaArg(-1)\n\t}\n\tif val.Number > 0 {\n\t\treturn newNumberFormulaArg(1)\n\t}\n\treturn newNumberFormulaArg(0)\n}", "func (s *SendTx) Sign(pubkey crypto.PubKey, sig crypto.Signature) error {\n\taddr := pubkey.Address()\n\tset := s.Tx.SetSignature(addr, sig)\n\tif !set {\n\t\treturn errors.Errorf(\"Cannot add signature for address %X\", addr)\n\t}\n\ts.signers = append(s.signers, pubkey)\n\treturn nil\n}", "func Sign(text string, priv *ecdsa.PrivateKey) ([]byte, *big.Int, *big.Int, []byte) {\n\tvar h hash.Hash\n\th = md5.New()\n\tr := big.NewInt(0)\n\ts := big.NewInt(0)\n\n\tio.WriteString(h, text)\n\tsignhash := h.Sum(nil)\n\n\tr, s, err := ecdsa.Sign(rand.Reader, priv, signhash)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n\n\tsignature := r.Bytes()\n\tsignature = append(signature, s.Bytes()...)\n\treturn signature, r, s, signhash\n}", "func (m *MockTransactionApi) VerifySign(tx *types.Transaction, outpoint *types.OutPoint, amount int64, txinUtxoList *[]types.UtxoData) (bool, string, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"VerifySign\", tx, outpoint, amount, txinUtxoList)\n\tret0, _ := ret[0].(bool)\n\tret1, _ := ret[1].(string)\n\tret2, _ := ret[2].(error)\n\treturn ret0, ret1, ret2\n}", "func (k *KeyRing) Sign(cleartext []byte) (signature []byte, err error) {\n\tif k.Locked() {\n\t\terr = ErrKeyRingLocked\n\t\treturn\n\t}\n\n\tsignature = k.cryptoEngine.Sign(k.secret.Buffer(), cleartext)\n\treturn\n}", "func Sign(params Params, key string) string {\n\tsort.Sort(params)\n\tpreSignWithKey := params.ToQueryString() + \"&key=\" + key\n\treturn fmt.Sprintf(\"%X\", md5.Sum([]byte(preSignWithKey)))\n}", "func Sign(params Params, key string) string {\n\tsort.Sort(params)\n\tpreSignWithKey := params.ToQueryString() + \"&key=\" + key\n\treturn fmt.Sprintf(\"%X\", md5.Sum([]byte(preSignWithKey)))\n}", "func (m *DigestHolderMock) MinimockSignWithDone() bool {\n\tfor _, e := range m.SignWithMock.expectations {\n\t\tif mm_atomic.LoadUint64(&e.Counter) < 1 {\n\t\t\treturn false\n\t\t}\n\t}\n\n\t// if default expectation was set then invocations count should be greater than zero\n\tif m.SignWithMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterSignWithCounter) < 1 {\n\t\treturn false\n\t}\n\t// if func was set then invocations count should be greater than zero\n\tif m.funcSignWith != nil && mm_atomic.LoadUint64(&m.afterSignWithCounter) < 1 {\n\t\treturn false\n\t}\n\treturn true\n}", "func (k otherKey) Sign(rand io.Reader, digest []byte, opts crypto.SignerOpts) (signature []byte, err error) {\n\t_, _, _ = rand, digest, opts\n\treturn nil, nil\n}", "func TestSignContract(t *testing.T) {\n\t// Setup\n\tstop, clients, contractPath, contractFilePath := setupSignature(t)\n\tdefer stop()\n\n\t// Sign!\n\tcloseChannel := make(chan []byte, 3)\n\tfor i := 0; i < 3; i++ {\n\t\tsetLastArg(clients[i], \"sign\", true)\n\t\tsetLastArg(clients[i], contractPath, false)\n\t\tgo func(c *exec.Cmd, i int) {\n\t\t\ttime.Sleep(time.Duration(i*2) * time.Second)\n\t\t\tc.Stdin = strings.NewReader(contractFilePath + \"\\npassword\\nyes\\n\")\n\t\t\tc.Stderr = os.Stderr\n\t\t\toutput, err := c.Output()\n\t\t\tif err != nil {\n\t\t\t\toutput = nil\n\t\t\t}\n\t\t\tcloseChannel <- output\n\t\t}(clients[i], i)\n\t}\n\n\tregexes := []*regexp.Regexp{\n\t\tregexp.MustCompile(`Everybody is ready, starting the signature [a-f0-9]+`),\n\t\tregexp.MustCompile(`Do you REALLY want to sign contract\\.txt\\? Type 'yes' to confirm:`),\n\t}\n\tfor i := 0; i < 3; i++ {\n\t\toutput := <-closeChannel\n\t\tassert.NotEqual(t, nil, output, \"The return error should be null\")\n\t\tfor _, r := range regexes {\n\t\t\tassert.True(t, r.Match(output), \"Regex is not satisfied: \", r.String())\n\t\t}\n\t}\n\n\tcheckProofFile(t, 3)\n\ttime.Sleep(time.Second)\n}", "func VerifySign(key string, qs string) bool {\n\tunsignedQueryString := signRegex.ReplaceAllString(qs, \"\")\n\n\tsign := Sign(key, unsignedQueryString)\n\tvalues, _ := url.ParseQuery(qs)\n\n\treturn values.Get(\"sig\") == sign\n}", "func TmSign(publicKey PublicKey, privateKey PrivateKey, digest Digest) Seal { panic(\"\") }", "func (h *Handler) Sign(ctx context.Context, req *pb.SignRequest) (*pb.SignResponse, error) {\n\tlog.Trace().Msg(\"Handling request\")\n\n\tres := &pb.SignResponse{}\n\tif req == nil {\n\t\tlog.Warn().Str(\"result\", \"denied\").Msg(\"Request not specified\")\n\t\tres.State = pb.ResponseState_DENIED\n\t\treturn res, nil\n\t}\n\tif req.GetAccount() == \"\" && req.GetPublicKey() == nil {\n\t\tlog.Warn().Str(\"result\", \"denied\").Msg(\"Neither accout nor public key specified\")\n\t\tres.State = pb.ResponseState_DENIED\n\t\treturn res, nil\n\t}\n\tif !strings.Contains(req.GetAccount(), \"/\") {\n\t\tlog.Warn().Str(\"result\", \"denied\").Msg(\"Invalid account specified\")\n\t\tres.State = pb.ResponseState_DENIED\n\t\treturn res, nil\n\t}\n\n\tdata := &rules.SignData{\n\t\tDomain: req.Domain,\n\t\tData: req.Data,\n\t}\n\tresult, signature := h.signer.SignGeneric(ctx, handlers.GenerateCredentials(ctx), req.GetAccount(), req.GetPublicKey(), data)\n\tswitch result {\n\tcase core.ResultSucceeded:\n\t\tres.State = pb.ResponseState_SUCCEEDED\n\t\tres.Signature = signature\n\tcase core.ResultDenied:\n\t\tres.State = pb.ResponseState_DENIED\n\tcase core.ResultFailed:\n\t\tres.State = pb.ResponseState_FAILED\n\tdefault:\n\t\tres.State = pb.ResponseState_UNKNOWN\n\t}\n\n\tlog.Trace().Str(\"result\", \"succeeded\").Msg(\"Success\")\n\treturn res, nil\n}", "func Test_CanSign_NoUnspentTransactions(t *testing.T) {\n\n\t// prepare input\n\tvar transactionInput *TransactionInput = &TransactionInput{\n\t\tOutputID: \"outID\",\n\t\tOutputIndex: 10,\n\t}\n\tvar unspentTransactions []*UnspentTransactionOutput\n\tvar publicKey = \"\"\n\n\t// call can sign\n\tresult := CanSign(unspentTransactions, transactionInput, publicKey)\n\n\t// result should false\n\tif result {\n\t\tt.Errorf(\"result when there are no unspent transactions should be false.\")\n\t}\n}", "func (b *Base) SignInit(req *SignInitReq) error {\n\treturn ErrFunctionNotSupported\n}", "func (pv *ParamsVerification) Sign(p []byte) string {\n\t// Generate hash code\n\tmac := hmac.New(sha256.New, []byte(pv.ClientSecret))\n\t_, _ = mac.Write(p)\n\texpectedMAC := mac.Sum(nil)\n\n\t// Generate base64\n\tbase64Sign := base64.StdEncoding.EncodeToString(expectedMAC)\n\tbase64Sign = strings.ReplaceAll(base64Sign, \"+\", \"-\")\n\tbase64Sign = strings.ReplaceAll(base64Sign, \"/\", \"_\")\n\tbase64Sign = strings.TrimRight(base64Sign, \"=\")\n\n\treturn base64Sign\n}", "func (transaction *ContractUpdateTransaction) Sign(\n\tprivateKey PrivateKey,\n) *ContractUpdateTransaction {\n\treturn transaction.SignWith(privateKey.PublicKey(), privateKey.Sign)\n}", "func (k *onChainPrivateKey) Sign(msg []byte) (signature []byte, err error) {\n\tsig, err := crypto.Sign(onChainHash(msg), (*ecdsa.PrivateKey)(k))\n\treturn sig, err\n}", "func (v *BlockVote) Sign(w module.Wallet) error {\n\thash := v.Hash()\n\tsigBs, err := w.Sign(hash)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn v.json.Signature.UnmarshalBinary(sigBs)\n}", "func (transaction *TokenMintTransaction) Sign(\n\tprivateKey PrivateKey,\n) *TokenMintTransaction {\n\treturn transaction.SignWith(privateKey.PublicKey(), privateKey.Sign)\n}", "func (k *EnterpriseCertSigner) Sign(args SignArgs, resp *[]byte) (err error) {\n\treturn nil\n}", "func Sign(rand io.Reader, priv *PrivateKey, hash []byte) (r, s *big.Int, err error)", "func (k *Ed25519PrivateKey) Sign(msg []byte) ([]byte, error) {\n\treturn ed25519.Sign(k.k, msg), nil\n}", "func Sign(priv *ecdsa.PrivateKey, hash []byte) (r, s *big.Int, err error) {\n\treturn ecdsa.Sign(rand.Reader, priv, hash)\n}", "func sign() int {\n\ts := -1 + rand.Intn(2)\n\tif s == 0 {\n\t\ts++\n\t}\n\treturn s\n}" ]
[ "0.7038499", "0.6973596", "0.6949446", "0.6931641", "0.6850552", "0.68438876", "0.6784213", "0.6778353", "0.677179", "0.67147094", "0.66983044", "0.66941196", "0.6673838", "0.6659925", "0.66452146", "0.66187435", "0.6618732", "0.6616466", "0.6575433", "0.65533817", "0.6511533", "0.6488697", "0.6466173", "0.6461364", "0.6451597", "0.6426668", "0.6388947", "0.6378557", "0.637788", "0.63736784", "0.6363097", "0.63589233", "0.63576776", "0.6327539", "0.6327539", "0.632331", "0.6319927", "0.63068855", "0.62938714", "0.6271628", "0.62485325", "0.6235009", "0.6235009", "0.6218889", "0.61970633", "0.61762416", "0.6159452", "0.6138648", "0.6111252", "0.6105366", "0.61008286", "0.6095427", "0.6093671", "0.60807645", "0.60779095", "0.6074044", "0.6032227", "0.60140616", "0.60015357", "0.5994586", "0.59934056", "0.59908295", "0.5978785", "0.5976234", "0.5975075", "0.59489954", "0.59381497", "0.5936058", "0.59046155", "0.5899449", "0.58943933", "0.58727497", "0.58711386", "0.5862999", "0.5844845", "0.5815775", "0.58091605", "0.5804379", "0.5794127", "0.5793012", "0.5786591", "0.5786591", "0.5773307", "0.57502437", "0.57395184", "0.57330173", "0.57328784", "0.57300866", "0.57193494", "0.57191235", "0.57086736", "0.570492", "0.56989753", "0.5690336", "0.56893224", "0.5687948", "0.5681669", "0.56696314", "0.5653164", "0.5639274" ]
0.7184497
0
SigningManager mocks base method
func (m *MockClient) SigningManager() core.SigningManager { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "SigningManager") ret0, _ := ret[0].(core.SigningManager) return ret0 }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (m *MockProviders) SigningManager() core.SigningManager {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"SigningManager\")\n\tret0, _ := ret[0].(core.SigningManager)\n\treturn ret0\n}", "func (pc *MockProviderContext) SigningManager() fab.SigningManager {\n\treturn pc.signingManager\n}", "func NewMockSigner(kis []KeyInfo) MockSigner {\n\tvar ms MockSigner\n\tms.AddrKeyInfo = make(map[address.Address]KeyInfo)\n\tfor _, k := range kis {\n\t\t// extract public key\n\t\tpub := k.PublicKey()\n\t\tnewAddr, err := address.NewSecp256k1Address(pub)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tms.Addresses = append(ms.Addresses, newAddr)\n\t\tms.AddrKeyInfo[newAddr] = k\n\t\tms.PubKeys = append(ms.PubKeys, pub)\n\t}\n\treturn ms\n}", "func (m *CryptographyServiceMock) Sign(p []byte) (r *insolar.Signature, r1 error) {\n\tcounter := atomic.AddUint64(&m.SignPreCounter, 1)\n\tdefer atomic.AddUint64(&m.SignCounter, 1)\n\n\tif len(m.SignMock.expectationSeries) > 0 {\n\t\tif counter > uint64(len(m.SignMock.expectationSeries)) {\n\t\t\tm.t.Fatalf(\"Unexpected call to CryptographyServiceMock.Sign. %v\", p)\n\t\t\treturn\n\t\t}\n\n\t\tinput := m.SignMock.expectationSeries[counter-1].input\n\t\ttestify_assert.Equal(m.t, *input, CryptographyServiceMockSignInput{p}, \"CryptographyService.Sign got unexpected parameters\")\n\n\t\tresult := m.SignMock.expectationSeries[counter-1].result\n\t\tif result == nil {\n\t\t\tm.t.Fatal(\"No results are set for the CryptographyServiceMock.Sign\")\n\t\t\treturn\n\t\t}\n\n\t\tr = result.r\n\t\tr1 = result.r1\n\n\t\treturn\n\t}\n\n\tif m.SignMock.mainExpectation != nil {\n\n\t\tinput := m.SignMock.mainExpectation.input\n\t\tif input != nil {\n\t\t\ttestify_assert.Equal(m.t, *input, CryptographyServiceMockSignInput{p}, \"CryptographyService.Sign got unexpected parameters\")\n\t\t}\n\n\t\tresult := m.SignMock.mainExpectation.result\n\t\tif result == nil {\n\t\t\tm.t.Fatal(\"No results are set for the CryptographyServiceMock.Sign\")\n\t\t}\n\n\t\tr = result.r\n\t\tr1 = result.r1\n\n\t\treturn\n\t}\n\n\tif m.SignFunc == nil {\n\t\tm.t.Fatalf(\"Unexpected call to CryptographyServiceMock.Sign. %v\", p)\n\t\treturn\n\t}\n\n\treturn m.SignFunc(p)\n}", "func (m *DeviceHealthAttestationState) SetTestSigning(value *string)() {\n err := m.GetBackingStore().Set(\"testSigning\", value)\n if err != nil {\n panic(err)\n }\n}", "func TestVerifySignedMessage(t *testing.T) {\n\tfor _, tc := range []struct {\n\t\tdesc string\n\t\tsettings *crypt.PkiSettings\n\t\tsetup func(mdb *mocks.MockDepsBundle, setupDone *bool) error\n\t\tmessageToSign string\n\t\tbase64Signature string\n\t\tPEMPublicKey string\n\t\texpectedError *testtools.ErrorSpec\n\t\texpectedValidity bool\n\t}{\n\t\t{\n\t\t\tdesc: \"invalid base64 signature\",\n\t\t\tsettings: &crypt.PkiSettings{\n\t\t\t\tAlgorithm: x509.ECDSA,\n\t\t\t\tPrivateKeyPath: \".prog/ecdsa_priv.key\",\n\t\t\t\tPublicKeyPath: \".prog/ecdsa.pub\",\n\t\t\t},\n\t\t\tsetup: func(mdb *mocks.MockDepsBundle, setupDone *bool) error {\n\t\t\t\treturn nil\n\t\t\t},\n\t\t\tmessageToSign: \"some other message\",\n\t\t\tbase64Signature: \"@#$^&*()_\",\n\t\t\tPEMPublicKey: \"\",\n\t\t\texpectedError: &testtools.ErrorSpec{\n\t\t\t\tType: \"base64.CorruptInputError\",\n\t\t\t\tMessage: \"illegal base64 data at input byte 0\",\n\t\t\t},\n\t\t\texpectedValidity: false,\n\t\t},\n\t\t{\n\t\t\tdesc: \"empty PEM key\",\n\t\t\tsettings: &crypt.PkiSettings{\n\t\t\t\tAlgorithm: x509.ECDSA,\n\t\t\t\tPrivateKeyPath: \".prog/ecdsa_priv.key\",\n\t\t\t\tPublicKeyPath: \".prog/ecdsa.pub\",\n\t\t\t},\n\t\t\tsetup: func(mdb *mocks.MockDepsBundle, setupDone *bool) error {\n\t\t\t\treturn nil\n\t\t\t},\n\t\t\tmessageToSign: \"some other message\",\n\t\t\tbase64Signature: \"abcdefgh\",\n\t\t\tPEMPublicKey: \"\",\n\t\t\texpectedError: &testtools.ErrorSpec{\n\t\t\t\tType: \"*errors.errorString\",\n\t\t\t\tMessage: \"No PEM data was found\",\n\t\t\t},\n\t\t\texpectedValidity: false,\n\t\t},\n\t\t{\n\t\t\tdesc: \"bad key data\",\n\t\t\tsettings: &crypt.PkiSettings{\n\t\t\t\tAlgorithm: x509.ECDSA,\n\t\t\t\tPrivateKeyPath: \".prog/ecdsa_priv.key\",\n\t\t\t\tPublicKeyPath: \".prog/ecdsa.pub\",\n\t\t\t},\n\t\t\tsetup: func(mdb *mocks.MockDepsBundle, setupDone *bool) error {\n\t\t\t\treturn nil\n\t\t\t},\n\t\t\tmessageToSign: \"some other message\",\n\t\t\tbase64Signature: \"abcdefgh\",\n\t\t\tPEMPublicKey: \"-----BEGIN INVALID DATA-----\\n\" +\n\t\t\t\t\"MTIzNDU2Nzg5MGFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6\\n\" +\n\t\t\t\t\"-----END INVALID DATA-----\\n\",\n\t\t\texpectedError: &testtools.ErrorSpec{\n\t\t\t\tType: \"asn1.StructuralError\",\n\t\t\t\tMessage: \"asn1: structure \" +\n\t\t\t\t\t\"error: tags don't match (16 vs {class:0 \" +\n\t\t\t\t\t\"tag:17 \" +\n\t\t\t\t\t\"length:50 \" +\n\t\t\t\t\t\"isCompound:true}) {optional:false \" +\n\t\t\t\t\t\"explicit:false \" +\n\t\t\t\t\t\"application:false \" +\n\t\t\t\t\t\"defaultValue:<nil> \" +\n\t\t\t\t\t\"tag:<nil> \" +\n\t\t\t\t\t\"stringType:0 \" +\n\t\t\t\t\t\"timeType:0 \" +\n\t\t\t\t\t\"set:false \" +\n\t\t\t\t\t\"omitEmpty:false} publicKeyInfo @2\",\n\t\t\t},\n\t\t\texpectedValidity: false,\n\t\t},\n\t\t{\n\t\t\tdesc: \"invalid signature\",\n\t\t\tsettings: &crypt.PkiSettings{\n\t\t\t\tAlgorithm: x509.ECDSA,\n\t\t\t\tPrivateKeyPath: \".prog/ecdsa_priv.key\",\n\t\t\t\tPublicKeyPath: \".prog/ecdsa.pub\",\n\t\t\t},\n\t\t\tsetup: func(mdb *mocks.MockDepsBundle, setupDone *bool) error {\n\t\t\t\treturn nil\n\t\t\t},\n\t\t\tmessageToSign: \"some other message\",\n\t\t\tbase64Signature: \"abcdefgh\",\n\t\t\tPEMPublicKey: \"-----BEGIN ECDSA PUBLIC KEY-----\\n\" +\n\t\t\t\t\"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE7WzVjtn9Gk+WHr5xbv8XMvooqU25\\n\" +\n\t\t\t\t\"BhgNjZ/vHZLBdVtCOjk4KxjS1UBfQm0c3TRxWBl3hj2AmnJbCrnGofMHBQ==\\n\" +\n\t\t\t\t\"-----END ECDSA PUBLIC KEY-----\\n\",\n\t\t\texpectedError: &testtools.ErrorSpec{\n\t\t\t\tType: \"asn1.SyntaxError\",\n\t\t\t\tMessage: \"asn1: syntax error: truncated tag or length\",\n\t\t\t},\n\t\t\texpectedValidity: false,\n\t\t},\n\t\t{\n\t\t\tdesc: \"ecdsa key for rsa mode\",\n\t\t\tsettings: &crypt.PkiSettings{\n\t\t\t\tAlgorithm: x509.RSA,\n\t\t\t\tPrivateKeyPath: \".prog/ecdsa_priv.key\",\n\t\t\t\tPublicKeyPath: \".prog/ecdsa.pub\",\n\t\t\t},\n\t\t\tsetup: func(mdb *mocks.MockDepsBundle, setupDone *bool) error {\n\t\t\t\treturn nil\n\t\t\t},\n\t\t\tmessageToSign: \"some other message\",\n\t\t\tbase64Signature: \"N3SuIdWI7XlXDteTmcOZUd2OBacyUWY+/+A8SC4QUBz9rXnldBqXha6YyGwnTuizxuy6quQ2QDFdtW16dj7EQk3lozfngskyhc2r86q3AUbdFDvrQVphMQhzsgBhHVoMjCL/YRfvtzCTWhBxegjVMLraLDCBb8IZTIqcMYafYyeJTvAnjBuntlZ+14TDuTt14Uqz85T04CXxBEqlIXMMKpTc01ST4Jsxz5HLO+At1htXp5eHOUFtQSilm3G7iO8ynhgPcXHDWfMAWu6VySUoHWCG70pJaCq6ehF7223t0UFOCqAyDyyQyP9yeUHj8F75SPSxfJm8iKXGx2LND/qLYw==\",\n\t\t\tPEMPublicKey: \"-----BEGIN RSA PUBLIC KEY-----\\n\" +\n\t\t\t\t\"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE7WzVjtn9Gk+WHr5xbv8XMvooqU25\\n\" +\n\t\t\t\t\"BhgNjZ/vHZLBdVtCOjk4KxjS1UBfQm0c3TRxWBl3hj2AmnJbCrnGofMHBQ==\\n\" +\n\t\t\t\t\"-----END RSA PUBLIC KEY-----\\n\",\n\t\t\texpectedError: &testtools.ErrorSpec{\n\t\t\t\tType: \"*errors.errorString\",\n\t\t\t\tMessage: \"Expecting a *rsa.PublicKey, but encountered a *ecdsa.PublicKey instead\",\n\t\t\t},\n\t\t\texpectedValidity: false,\n\t\t},\n\t\t{\n\t\t\tdesc: \"rsa key for ecdsa mode\",\n\t\t\tsettings: &crypt.PkiSettings{\n\t\t\t\tAlgorithm: x509.ECDSA,\n\t\t\t\tPrivateKeyPath: \".prog/ecdsa_priv.key\",\n\t\t\t\tPublicKeyPath: \".prog/ecdsa.pub\",\n\t\t\t},\n\t\t\tsetup: func(mdb *mocks.MockDepsBundle, setupDone *bool) error {\n\t\t\t\treturn nil\n\t\t\t},\n\t\t\tmessageToSign: \"some other message\",\n\t\t\tbase64Signature: \"MEYCIQDPM0fc/PFauoZzpltH3RpWtlaqRnL0gFk5WFiLMrFqrwIhAIDvlBozU6Ky2UC9xOSq3YZ5iFuO356t9RnHOElaaXFJ\",\n\t\t\tPEMPublicKey: \"-----BEGIN RSA PUBLIC KEY-----\\n\" +\n\t\t\t\t\"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAzCTTFKQBHfTN8jW6q8PT\\n\" +\n\t\t\t\t\"HNZKWnRPxSt9kpgWmyqFaZnEUipgoKGAxSIsVrl2PJSm5OlgkVzx+MY+LWM64VKM\\n\" +\n\t\t\t\t\"bRpUUGJR3zdMNhwZQX0hjOpLpVJvUwD78utVs8vijrU7sH48usFiaZQYjy4m4hQh\\n\" +\n\t\t\t\t\"63/x4h3KVz7YqUnlRMzYJFT43+AwYzYuEpzWRxtW7IObJPtjtmYVoqva98fF6aj5\\n\" +\n\t\t\t\t\"uHAsvaAgZGBalHXmCiPzKiGU/halzXSPvyJ2Cqz2aUqMHgwi/2Ip4z/mrfX+mUTa\\n\" +\n\t\t\t\t\"S+LyBy7GgqJ5vbkGArMagJIc0eARF60r6Uf483xh17oniABdLJy4qlLf6PcEU+ut\\n\" +\n\t\t\t\t\"EwIDAQAB\\n\" +\n\t\t\t\t\"-----END RSA PUBLIC KEY-----\\n\",\n\t\t\texpectedError: &testtools.ErrorSpec{\n\t\t\t\tType: \"*errors.errorString\",\n\t\t\t\tMessage: \"Expecting a *ecdsa.PublicKey, but encountered a *rsa.PublicKey instead\",\n\t\t\t},\n\t\t\texpectedValidity: false,\n\t\t},\n\t} {\n\t\tt.Run(fmt.Sprintf(\"Subtest: %s\", tc.desc), func(tt *testing.T) {\n\t\t\tmockDepsBundle := mocks.NewDefaultMockDeps(\"\", []string{\"progname\"}, \"/home/user\", nil)\n\t\t\treturnedNormally := false\n\t\t\tvar tooling *crypt.CryptoTooling\n\t\t\tvar actualErr error\n\t\t\tvar actualValidity bool\n\t\t\terr := mockDepsBundle.InvokeCallInMockedEnv(func() error {\n\t\t\t\tsetupComplete := false\n\t\t\t\tinnerErr := tc.setup(mockDepsBundle, &setupComplete)\n\t\t\t\tif innerErr != nil {\n\t\t\t\t\treturn innerErr\n\t\t\t\t}\n\t\t\t\tvar toolingErr error\n\t\t\t\ttooling, toolingErr = crypt.GetCryptoTooling(mockDepsBundle.Deps, tc.settings)\n\t\t\t\tif toolingErr != nil {\n\t\t\t\t\treturn toolingErr\n\t\t\t\t}\n\t\t\t\tsetupComplete = true\n\t\t\t\tactualValidity, actualErr = tooling.VerifySignedMessage(tc.messageToSign, tc.base64Signature, tc.PEMPublicKey)\n\t\t\t\treturnedNormally = true\n\t\t\t\treturn nil\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\ttt.Errorf(\"Unexpected error calling mockDepsBundle.InvokeCallInMockedEnv(): %s\", err.Error())\n\t\t\t}\n\t\t\tif exitStatus := mockDepsBundle.GetExitStatus(); (exitStatus != 0) || !returnedNormally {\n\t\t\t\ttt.Error(\"EncodeAndSaveKey() should not have paniced or called os.Exit.\")\n\t\t\t}\n\t\t\tif (mockDepsBundle.OutBuf.String() != \"\") || (mockDepsBundle.ErrBuf.String() != \"\") {\n\t\t\t\ttt.Errorf(\"EncodeAndSaveKey() should not have output any data. Saw stdout:\\n%s\\nstderr:\\n%s\", mockDepsBundle.OutBuf.String(), mockDepsBundle.ErrBuf.String())\n\t\t\t}\n\t\t\tif err := tc.expectedError.EnsureMatches(actualErr); err != nil {\n\t\t\t\ttt.Error(err.Error())\n\t\t\t}\n\t\t\tif tc.expectedError == nil {\n\t\t\t\tif actualValidity != tc.expectedValidity {\n\t\t\t\t\ttt.Errorf(\"Signature is %#v when %#v expected\", actualValidity, tc.expectedValidity)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif tc.expectedValidity {\n\t\t\t\t\ttt.Error(\"TEST CASE INVALID. Should not expect \\\"valid\\\".\")\n\t\t\t\t}\n\t\t\t\tif actualValidity {\n\t\t\t\t\ttt.Error(\"Error was expected. Should not report \\\"valid\\\".\")\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n}", "func mockedGranter(kubeutil *kube.Kube, app *v1.RadixRegistration, namespace string, serviceAccount *corev1.ServiceAccount) error {\n\treturn nil\n}", "func TestCryptoSignerInterfaceBehavior(t *testing.T) {\n\tcs := NewCryptoService(trustmanager.NewKeyMemoryStore(passphraseRetriever))\n\tinterfaces.EmptyCryptoServiceInterfaceBehaviorTests(t, cs)\n\tinterfaces.CreateGetKeyCryptoServiceInterfaceBehaviorTests(t, cs, data.ECDSAKey)\n\n\tcs = NewCryptoService(trustmanager.NewKeyMemoryStore(passphraseRetriever))\n\tinterfaces.CreateListKeyCryptoServiceInterfaceBehaviorTests(t, cs, data.ECDSAKey)\n\n\tcs = NewCryptoService(trustmanager.NewKeyMemoryStore(passphraseRetriever))\n\tinterfaces.AddGetKeyCryptoServiceInterfaceBehaviorTests(t, cs, data.ECDSAKey)\n\n\tcs = NewCryptoService(trustmanager.NewKeyMemoryStore(passphraseRetriever))\n\tinterfaces.AddListKeyCryptoServiceInterfaceBehaviorTests(t, cs, data.ECDSAKey)\n}", "func (c *Provider) SigningManager() core.SigningManager {\n\treturn c.signingManager\n}", "func (mmSignWith *mDigestHolderMockSignWith) Set(f func(signer DigestSigner) (s1 SignedDigestHolder)) *DigestHolderMock {\n\tif mmSignWith.defaultExpectation != nil {\n\t\tmmSignWith.mock.t.Fatalf(\"Default expectation is already set for the DigestHolder.SignWith method\")\n\t}\n\n\tif len(mmSignWith.expectations) > 0 {\n\t\tmmSignWith.mock.t.Fatalf(\"Some expectations are already set for the DigestHolder.SignWith method\")\n\t}\n\n\tmmSignWith.mock.funcSignWith = f\n\treturn mmSignWith.mock\n}", "func (m *MockMachine) SignerKey() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"SignerKey\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func (mmSignWith *mDigestHolderMockSignWith) When(signer DigestSigner) *DigestHolderMockSignWithExpectation {\n\tif mmSignWith.mock.funcSignWith != nil {\n\t\tmmSignWith.mock.t.Fatalf(\"DigestHolderMock.SignWith mock is already set by Set\")\n\t}\n\n\texpectation := &DigestHolderMockSignWithExpectation{\n\t\tmock: mmSignWith.mock,\n\t\tparams: &DigestHolderMockSignWithParams{signer},\n\t}\n\tmmSignWith.expectations = append(mmSignWith.expectations, expectation)\n\treturn expectation\n}", "func (m *MockClient) Sign(arg0 []byte) ([]byte, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Sign\", arg0)\n\tret0, _ := ret[0].([]byte)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *mCryptographyServiceMockSign) Set(f func(p []byte) (r *insolar.Signature, r1 error)) *CryptographyServiceMock {\n\tm.mainExpectation = nil\n\tm.expectationSeries = nil\n\n\tm.mock.SignFunc = f\n\treturn m.mock\n}", "func TestSenderRequest_Sign(t *testing.T) {\r\n\r\n\t// Create key\r\n\tkey, err := bitcoin.CreatePrivateKeyString()\r\n\tassert.NoError(t, err)\r\n\tassert.NotNil(t, key)\r\n\r\n\t// Create the request / message\r\n\tsenderRequest := &SenderRequest{\r\n\t\tDt: time.Now().UTC().Format(time.RFC3339),\r\n\t\tSenderHandle: testAlias + \"@\" + testDomain,\r\n\t\tSenderName: testName,\r\n\t\tPurpose: testMessage,\r\n\t}\r\n\r\n\tvar signature string\r\n\r\n\tt.Run(\"invalid key - empty\", func(t *testing.T) {\r\n\t\tsignature, err = senderRequest.Sign(\"\")\r\n\t\tassert.Error(t, err)\r\n\t\tassert.Equal(t, len(signature), 0)\r\n\t})\r\n\r\n\tt.Run(\"invalid key - 0\", func(t *testing.T) {\r\n\t\tsignature, err = senderRequest.Sign(\"0\")\r\n\t\tassert.Error(t, err)\r\n\t\tassert.Equal(t, len(signature), 0)\r\n\t})\r\n\r\n\tt.Run(\"invalid dt\", func(t *testing.T) {\r\n\t\tsenderRequest.Dt = \"\"\r\n\t\tsignature, err = senderRequest.Sign(key)\r\n\t\tassert.Error(t, err)\r\n\t\tassert.Equal(t, len(signature), 0)\r\n\t})\r\n\r\n\tt.Run(\"invalid sender handle\", func(t *testing.T) {\r\n\t\tsenderRequest.Dt = time.Now().UTC().Format(time.RFC3339)\r\n\t\tsenderRequest.SenderHandle = \"\"\r\n\t\tsignature, err = senderRequest.Sign(key)\r\n\t\tassert.Error(t, err)\r\n\t\tassert.Equal(t, len(signature), 0)\r\n\t})\r\n\r\n\tt.Run(\"valid signature\", func(t *testing.T) {\r\n\t\tsenderRequest.SenderHandle = testAlias + \"@\" + testDomain\r\n\t\tsignature, err = senderRequest.Sign(key)\r\n\t\tassert.NoError(t, err)\r\n\t\tassert.NotEqual(t, len(signature), 0)\r\n\r\n\t\t// Get address for verification\r\n\t\tvar address string\r\n\t\taddress, err = bitcoin.GetAddressFromPrivateKeyString(key, false)\r\n\t\tassert.NoError(t, err)\r\n\r\n\t\t// Verify the signature\r\n\t\terr = senderRequest.Verify(address, signature)\r\n\t\tassert.NoError(t, err)\r\n\t})\r\n}", "func (mm *MessageMaker) Signer() *MockSigner {\n\treturn mm.signer\n}", "func (mm *MessageMaker) Signer() *MockSigner {\n\treturn mm.signer\n}", "func (a *ActiveDevice) setSigningKey(g *GlobalContext, uv keybase1.UserVersion, deviceID keybase1.DeviceID,\n\tsigKey GenericKey, deviceName string) error {\n\ta.Lock()\n\tdefer a.Unlock()\n\n\tif err := a.internalUpdateUserVersionDeviceID(uv, deviceID); err != nil {\n\t\treturn err\n\t}\n\n\ta.signingKey = sigKey\n\tif len(deviceName) > 0 {\n\t\ta.deviceName = deviceName\n\t}\n\ta.nistFactory = NewNISTFactory(g, uv.Uid, deviceID, sigKey)\n\treturn nil\n}", "func (m *mSignatureKeyHolderMockGetSignMethod) Set(f func() (r SignMethod)) *SignatureKeyHolderMock {\n\tm.mainExpectation = nil\n\tm.expectationSeries = nil\n\n\tm.mock.GetSignMethodFunc = f\n\treturn m.mock\n}", "func (m *CryptographyServiceMock) Verify(p crypto.PublicKey, p1 insolar.Signature, p2 []byte) (r bool) {\n\tcounter := atomic.AddUint64(&m.VerifyPreCounter, 1)\n\tdefer atomic.AddUint64(&m.VerifyCounter, 1)\n\n\tif len(m.VerifyMock.expectationSeries) > 0 {\n\t\tif counter > uint64(len(m.VerifyMock.expectationSeries)) {\n\t\t\tm.t.Fatalf(\"Unexpected call to CryptographyServiceMock.Verify. %v %v %v\", p, p1, p2)\n\t\t\treturn\n\t\t}\n\n\t\tinput := m.VerifyMock.expectationSeries[counter-1].input\n\t\ttestify_assert.Equal(m.t, *input, CryptographyServiceMockVerifyInput{p, p1, p2}, \"CryptographyService.Verify got unexpected parameters\")\n\n\t\tresult := m.VerifyMock.expectationSeries[counter-1].result\n\t\tif result == nil {\n\t\t\tm.t.Fatal(\"No results are set for the CryptographyServiceMock.Verify\")\n\t\t\treturn\n\t\t}\n\n\t\tr = result.r\n\n\t\treturn\n\t}\n\n\tif m.VerifyMock.mainExpectation != nil {\n\n\t\tinput := m.VerifyMock.mainExpectation.input\n\t\tif input != nil {\n\t\t\ttestify_assert.Equal(m.t, *input, CryptographyServiceMockVerifyInput{p, p1, p2}, \"CryptographyService.Verify got unexpected parameters\")\n\t\t}\n\n\t\tresult := m.VerifyMock.mainExpectation.result\n\t\tif result == nil {\n\t\t\tm.t.Fatal(\"No results are set for the CryptographyServiceMock.Verify\")\n\t\t}\n\n\t\tr = result.r\n\n\t\treturn\n\t}\n\n\tif m.VerifyFunc == nil {\n\t\tm.t.Fatalf(\"Unexpected call to CryptographyServiceMock.Verify. %v %v %v\", p, p1, p2)\n\t\treturn\n\t}\n\n\treturn m.VerifyFunc(p, p1, p2)\n}", "func setupSignature(t *testing.T) (stop func(), clients []*exec.Cmd, contractPath, contractFilePath string) {\n\t// Cleanup\n\teraseDatabase()\n\n\t// Start the platform\n\tworkingDir, err := ioutil.TempDir(\"\", \"dfss_\")\n\tassert.Equal(t, nil, err)\n\t_, _, _, stop, ca, err := startPlatform(workingDir)\n\tassert.Equal(t, nil, err)\n\n\ttime.Sleep(2 * time.Second)\n\n\t// Register clients\n\tclient1, err := createClient(workingDir, ca, 9091)\n\tassert.Equal(t, nil, err)\n\terr = registerAndAuth(client1, \"client1@example.com\", \"password\", \"\", true, true)\n\tassert.Equal(t, nil, err)\n\tclient2, err := createClient(workingDir, ca, 9092)\n\tassert.Equal(t, nil, err)\n\terr = registerAndAuth(client2, \"client2@example.com\", \"password\", \"\", true, true)\n\tassert.Equal(t, nil, err)\n\tclient3, err := createClient(workingDir, ca, 9093)\n\tassert.Equal(t, nil, err)\n\terr = registerAndAuth(client3, \"client3@example.com\", \"password\", \"\", true, true)\n\tassert.Equal(t, nil, err)\n\n\t// Create contract\n\tclient1 = newClient(client1)\n\tsetLastArg(client1, \"new\", true)\n\tcontractFilePath = filepath.Join(\"testdata\", \"contract.txt\")\n\tclient1.Stdin = strings.NewReader(\n\t\t\"password\\n\" +\n\t\t\tcontractFilePath + \"\\n\" +\n\t\t\t\"\\n\" +\n\t\t\t\"client1@example.com\\n\" +\n\t\t\t\"client2@example.com\\n\" +\n\t\t\t\"client3@example.com\\n\" +\n\t\t\t\"\\n\",\n\t)\n\terr = checkStderr(t, client1, \"\")\n\tassert.Equal(t, nil, err)\n\n\t// Get contract file\n\tcontractEntity := getContract(\"contract.txt\", 0)\n\tcontractData, err := contract.GetJSON(contractEntity)\n\tassert.Equal(t, nil, err)\n\tcontractPath = filepath.Join(workingDir, \"c.dfss\")\n\terr = ioutil.WriteFile(contractPath, contractData, os.ModePerm)\n\tassert.Equal(t, nil, err)\n\n\t// Test with wrong file, should abort\n\twrongFileClient := newClient(client1)\n\tsetLastArg(wrongFileClient, \"sign\", true)\n\tsetLastArg(wrongFileClient, contractPath, false)\n\twrongFileClient.Stdin = strings.NewReader(\"wrongfile.txt\\npassword\\nyes\\n\")\n\t_, err = wrongFileClient.Output()\n\tassert.NotNil(t, err)\n\n\tclients = make([]*exec.Cmd, 3)\n\tclients[0] = newClient(client1)\n\tclients[1] = newClient(client2)\n\tclients[2] = newClient(client3)\n\treturn\n}", "func TestKeyExchangeSigning(t *testing.T) {\n\tA := \"peerA\"\n\tB := \"peerB\"\n\n\t// generate A's key\n\tkeyA, err := rsa.GenerateKey(rand.Reader, 512)\n\tif err != nil {\n\t\tt.Errorf(\"Could not create private key: %v\", err)\n\t}\n\n\t// generate B's key\n\tkeyB, err := rsa.GenerateKey(rand.Reader, 512)\n\tif err != nil {\n\t\tt.Errorf(\"Could not create private key: %v\", err)\n\t}\n\n\trecordForB := KeyRecord{\n\t\tOwner: B,\n\t\tKeyPub: keyB.PublicKey,\n\t}\n\n\t// A signs B's key\n\tkeyBBytes, err := SerializeKey(recordForB.KeyPub)\n\n\tif err != nil {\n\t\tt.Errorf(\"Could not serialize the key: %v\", err)\n\t}\n\n\tmsg := create(keyBBytes, recordForB.Owner, *keyA, A)\n\n\t// check that the signature is correct\n\terr = Verify(msg, keyA.PublicKey)\n\n\tif err != nil {\n\t\tt.Errorf(\"Signature of message is wrong: %v\", err)\n\t}\n\n\ttrustedRecordForB := TrustedKeyRecord{\n\t\tKeyRecord: recordForB,\n\t\tConfidence: 1.0,\n\t}\n\n\tmsg = trustedRecordForB.ConstructMessage(*keyA, A)\n\n\terr = Verify(msg, keyA.PublicKey)\n\n\tif err != nil {\n\t\tt.Errorf(\"Signature of message is wrong: %v\", err)\n\t}\n}", "func NewSignedMessageForTestGetter(ms MockSigner) func() *SignedMessage {\n\ti := 0\n\treturn func() *SignedMessage {\n\t\ts := fmt.Sprintf(\"smsg%d\", i)\n\t\ti++\n\t\tnewAddr, err := address.NewActorAddress([]byte(s + \"-to\"))\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tmsg := NewMessage(\n\t\t\tms.Addresses[0], // from needs to be an address from the signer\n\t\t\tnewAddr,\n\t\t\t0,\n\t\t\tZeroAttoFIL,\n\t\t\ts,\n\t\t\t[]byte(\"params\"))\n\t\tsmsg, err := NewSignedMessage(*msg, &ms, NewGasPrice(0), NewGasUnits(0))\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\treturn smsg\n\t}\n}", "func (m *mSignatureKeyHolderMockGetSignatureKeyMethod) Set(f func() (r SignatureMethod)) *SignatureKeyHolderMock {\n\tm.mainExpectation = nil\n\tm.expectationSeries = nil\n\n\tm.mock.GetSignatureKeyMethodFunc = f\n\treturn m.mock\n}", "func (c CryptoServiceTester) TestSignWithKey(t *testing.T) {\n\tcryptoService := c.cryptoServiceFactory()\n\tcontent := []byte(\"this is a secret\")\n\n\ttufKey, err := cryptoService.Create(c.role, c.gun, c.keyAlgo)\n\trequire.NoError(t, err, c.errorMsg(\"error creating key\"))\n\n\t// Test Sign\n\tprivKey, role, err := cryptoService.GetPrivateKey(tufKey.ID())\n\trequire.NoError(t, err, c.errorMsg(\"failed to get private key\"))\n\trequire.Equal(t, c.role, role)\n\n\tsignature, err := privKey.Sign(rand.Reader, content, nil)\n\trequire.NoError(t, err, c.errorMsg(\"signing failed\"))\n\n\tverifier, ok := signed.Verifiers[algoToSigType[c.keyAlgo]]\n\trequire.True(t, ok, c.errorMsg(\"Unknown verifier for algorithm\"))\n\n\terr = verifier.Verify(tufKey, signature, content)\n\trequire.NoError(t, err,\n\t\tc.errorMsg(\"verification failed for %s key type\", c.keyAlgo))\n}", "func (mmSignWith *mDigestHolderMockSignWith) Return(s1 SignedDigestHolder) *DigestHolderMock {\n\tif mmSignWith.mock.funcSignWith != nil {\n\t\tmmSignWith.mock.t.Fatalf(\"DigestHolderMock.SignWith mock is already set by Set\")\n\t}\n\n\tif mmSignWith.defaultExpectation == nil {\n\t\tmmSignWith.defaultExpectation = &DigestHolderMockSignWithExpectation{mock: mmSignWith.mock}\n\t}\n\tmmSignWith.defaultExpectation.results = &DigestHolderMockSignWithResults{s1}\n\treturn mmSignWith.mock\n}", "func (m *MockTransactionApi) SignWithPrivkey(tx *types.Transaction, outpoint *types.OutPoint, privkey *types.Privkey, sighashType types.SigHashType, utxoList *[]types.UtxoData) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"SignWithPrivkey\", tx, outpoint, privkey, sighashType, utxoList)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func mockChildPackages() {\n\n\t// Fake an AWS credentials file so that the mfile package will nehave as if it is happy\n\tsetFakeCredentials()\n\n\t// Fake out the creds package into using an apparently credentials response from AWS\n\tcreds.SetGetSessionTokenFunc(func(awsService *sts.STS, input *sts.GetSessionTokenInput) (*sts.GetSessionTokenOutput, error) {\n\t\treturn getSessionTokenOutput, nil\n\t})\n\n}", "func (c CryptoServiceTester) TestCreateAndGetWhenMultipleKeystores(t *testing.T) {\n\tcryptoService := c.cryptoServiceFactory()\n\tcryptoService.keyStores = append(cryptoService.keyStores,\n\t\ttrustmanager.NewKeyMemoryStore(passphraseRetriever))\n\n\t// Test Create\n\ttufKey, err := cryptoService.Create(c.role, c.gun, c.keyAlgo)\n\trequire.NoError(t, err, c.errorMsg(\"error creating key\"))\n\n\t// Only the first keystore should have the key\n\tkeyPath := tufKey.ID()\n\t_, _, err = cryptoService.keyStores[0].GetKey(keyPath)\n\trequire.NoError(t, err, c.errorMsg(\n\t\t\"First keystore does not have the key %s\", keyPath))\n\t_, _, err = cryptoService.keyStores[1].GetKey(keyPath)\n\trequire.Error(t, err, c.errorMsg(\n\t\t\"Second keystore has the key %s\", keyPath))\n\n\t// GetKey works across multiple keystores\n\tretrievedKey := cryptoService.GetKey(tufKey.ID())\n\trequire.NotNil(t, retrievedKey,\n\t\tc.errorMsg(\"Could not find key ID %s\", tufKey.ID()))\n}", "func (m *DeviceHealthAttestationState) GetTestSigning()(*string) {\n val, err := m.GetBackingStore().Get(\"testSigning\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func TestSend(t *testing.T) {\n\thelper := sleet_t.NewTestHelper(t)\n\turl := \"https://cert.api.firstdata.com/gateway/v2/payments\"\n\n\tvar gotHeader http.Header\n\tvar authRequestRaw, authResponseRaw, authErrorRaw []byte\n\n\tauthRequestRaw = helper.ReadFile(\"test_data/authRequest.json\")\n\tauthResponseRaw = helper.ReadFile(\"test_data/authResponse.json\")\n\tauthErrorRaw = helper.ReadFile(\"test_data/400Response.json\")\n\n\tvar request *Request = new(Request)\n\thelper.Unmarshal(authRequestRaw, request)\n\n\tt.Run(\"With Successful Response\", func(t *testing.T) {\n\t\thttpmock.Activate()\n\t\tdefer httpmock.DeactivateAndReset()\n\n\t\thttpmock.RegisterResponder(\"POST\", url, func(req *http.Request) (*http.Response, error) {\n\t\t\tgotHeader = req.Header\n\t\t\tresp := httpmock.NewBytesResponse(http.StatusOK, authResponseRaw)\n\t\t\treturn resp, nil\n\t\t})\n\n\t\tfirstDataClient := NewClient(common.Sandbox, Credentials{defaultApiKey, defaultApiSecret})\n\n\t\tvar want *Response = new(Response)\n\t\thelper.Unmarshal(authResponseRaw, want)\n\n\t\tgot, _, err := firstDataClient.sendRequest(context.TODO(), defaultReqId, url, *request)\n\n\t\tt.Run(\"Response Struct\", func(t *testing.T) {\n\t\t\tif err != nil {\n\t\t\t\tt.Fatalf(\"Error thrown after sending request %q\", err)\n\t\t\t}\n\n\t\t\tif !cmp.Equal(*got, *want, sleet_t.CompareUnexported) {\n\t\t\t\tt.Error(\"Response body does not match expected\")\n\t\t\t\tt.Error(cmp.Diff(*want, *got, sleet_t.CompareUnexported))\n\t\t\t}\n\t\t})\n\n\t\tt.Run(\"Request Headers\", func(t *testing.T) {\n\t\t\ttimestamp := strconv.FormatInt(time.Now().Unix(), 10)\n\n\t\t\tsignature := makeSignature(\n\t\t\t\ttimestamp,\n\t\t\t\tfirstDataClient.credentials.ApiKey,\n\t\t\t\tfirstDataClient.credentials.ApiSecret,\n\t\t\t\tdefaultReqId,\n\t\t\t\tstrings.TrimSpace(string(authRequestRaw)),\n\t\t\t)\n\n\t\t\theader_cases := []struct {\n\t\t\t\tlabel string\n\t\t\t\twant string\n\t\t\t\tgot string\n\t\t\t}{\n\t\t\t\t{\"defaultApiKey\", defaultApiKey, gotHeader.Get(\"Api-Key\")},\n\t\t\t\t{\"RequestID\", defaultReqId, gotHeader.Get(\"Client-Request-Id\")},\n\t\t\t\t{\"Signature\", signature, gotHeader.Get(\"Message-Signature\")},\n\t\t\t\t{\"Timestamp\", timestamp, gotHeader.Get(\"Timestamp\")},\n\t\t\t}\n\n\t\t\tfor _, c := range header_cases {\n\t\t\t\tt.Run(c.label, func(t *testing.T) {\n\t\t\t\t\tif c.got != c.want {\n\t\t\t\t\t\tt.Errorf(\"Got %q, want %q\", c.got, c.want)\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t}\n\t\t})\n\t})\n\n\tt.Run(\"With Error Response\", func(t *testing.T) {\n\t\thttpmock.Activate()\n\t\tdefer httpmock.DeactivateAndReset()\n\n\t\thttpmock.RegisterResponder(\"POST\", url, func(req *http.Request) (*http.Response, error) {\n\t\t\tgotHeader = req.Header\n\t\t\tresp := httpmock.NewBytesResponse(http.StatusForbidden, authErrorRaw)\n\t\t\treturn resp, nil\n\t\t})\n\n\t\tfirstDataClient := NewClient(common.Sandbox, Credentials{defaultApiKey, defaultApiSecret})\n\n\t\tvar want *Response = new(Response)\n\t\thelper.Unmarshal(authErrorRaw, want)\n\n\t\tgot, _, err := firstDataClient.sendRequest(context.TODO(), defaultReqId, url, *request)\n\n\t\tt.Run(\"Response Struct\", func(t *testing.T) {\n\t\t\tif err != nil {\n\t\t\t\tt.Fatalf(\"Error thrown after sending request %q\", err)\n\t\t\t}\n\n\t\t\tif !cmp.Equal(*got, *want, sleet_t.CompareUnexported) {\n\t\t\t\tt.Error(\"Response body does not match expected\")\n\t\t\t\tt.Error(cmp.Diff(*want, *got, sleet_t.CompareUnexported))\n\t\t\t}\n\t\t})\n\t})\n}", "func Sign(ctx context.Context, txf Factory, name string, txBuilder client.TxBuilder, overwriteSig bool) error {\n\tif txf.keybase == nil {\n\t\treturn errors.New(\"keybase must be set prior to signing a transaction\")\n\t}\n\n\tvar err error\n\tsignMode := txf.signMode\n\tif signMode == signing.SignMode_SIGN_MODE_UNSPECIFIED {\n\t\t// use the SignModeHandler's default mode if unspecified\n\t\tsignMode, err = authsigning.APISignModeToInternal(txf.txConfig.SignModeHandler().DefaultMode())\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tk, err := txf.keybase.Key(name)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tpubKey, err := k.GetPubKey()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsignerData := authsigning.SignerData{\n\t\tChainID: txf.chainID,\n\t\tAccountNumber: txf.accountNumber,\n\t\tSequence: txf.sequence,\n\t\tPubKey: pubKey,\n\t\tAddress: sdk.AccAddress(pubKey.Address()).String(),\n\t}\n\n\t// For SIGN_MODE_DIRECT, calling SetSignatures calls setSignerInfos on\n\t// TxBuilder under the hood, and SignerInfos is needed to generated the\n\t// sign bytes. This is the reason for setting SetSignatures here, with a\n\t// nil signature.\n\t//\n\t// Note: this line is not needed for SIGN_MODE_LEGACY_AMINO, but putting it\n\t// also doesn't affect its generated sign bytes, so for code's simplicity\n\t// sake, we put it here.\n\tsigData := signing.SingleSignatureData{\n\t\tSignMode: signMode,\n\t\tSignature: nil,\n\t}\n\tsig := signing.SignatureV2{\n\t\tPubKey: pubKey,\n\t\tData: &sigData,\n\t\tSequence: txf.Sequence(),\n\t}\n\n\tvar prevSignatures []signing.SignatureV2\n\tif !overwriteSig {\n\t\tprevSignatures, err = txBuilder.GetTx().GetSignaturesV2()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\t// Overwrite or append signer infos.\n\tvar sigs []signing.SignatureV2\n\tif overwriteSig {\n\t\tsigs = []signing.SignatureV2{sig}\n\t} else {\n\t\tsigs = append(sigs, prevSignatures...)\n\t\tsigs = append(sigs, sig)\n\t}\n\tif err := txBuilder.SetSignatures(sigs...); err != nil {\n\t\treturn err\n\t}\n\n\tif err := checkMultipleSigners(txBuilder.GetTx()); err != nil {\n\t\treturn err\n\t}\n\n\tbytesToSign, err := authsigning.GetSignBytesAdapter(\n\t\tctx, txf.txConfig.SignModeHandler(),\n\t\tsignMode, signerData, txBuilder.GetTx())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Sign those bytes\n\tsigBytes, _, err := txf.keybase.Sign(name, bytesToSign, signMode)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Construct the SignatureV2 struct\n\tsigData = signing.SingleSignatureData{\n\t\tSignMode: signMode,\n\t\tSignature: sigBytes,\n\t}\n\tsig = signing.SignatureV2{\n\t\tPubKey: pubKey,\n\t\tData: &sigData,\n\t\tSequence: txf.Sequence(),\n\t}\n\n\tif overwriteSig {\n\t\terr = txBuilder.SetSignatures(sig)\n\t} else {\n\t\tprevSignatures = append(prevSignatures, sig)\n\t\terr = txBuilder.SetSignatures(prevSignatures...)\n\t}\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to set signatures on payload: %w\", err)\n\t}\n\n\t// Run optional preprocessing if specified. By default, this is unset\n\t// and will return nil.\n\treturn txf.PreprocessTx(name, txBuilder)\n}", "func (m *SignatureKeyHolderMock) CheckMocksCalled() {\n\tm.Finish()\n}", "func (c CryptoServiceTester) TestSignNoMatchingKeys(t *testing.T) {\n\tcryptoService := c.cryptoServiceFactory()\n\n\tprivKey, err := utils.GenerateECDSAKey(rand.Reader)\n\trequire.NoError(t, err, c.errorMsg(\"error creating key\"))\n\n\t// Test Sign\n\t_, _, err = cryptoService.GetPrivateKey(privKey.ID())\n\trequire.Error(t, err, c.errorMsg(\"Should not have found private key\"))\n}", "func NewKeyManager(t mockConstructorTestingTNewKeyManager) *KeyManager {\n\tmock := &KeyManager{}\n\tmock.Mock.Test(t)\n\n\tt.Cleanup(func() { mock.AssertExpectations(t) })\n\n\treturn mock\n}", "func (m *mCryptographyServiceMockSign) Return(r *insolar.Signature, r1 error) *CryptographyServiceMock {\n\tm.mock.SignFunc = nil\n\tm.expectationSeries = nil\n\n\tif m.mainExpectation == nil {\n\t\tm.mainExpectation = &CryptographyServiceMockSignExpectation{}\n\t}\n\tm.mainExpectation.result = &CryptographyServiceMockSignResult{r, r1}\n\treturn m.mock\n}", "func (m *mSignatureKeyHolderMockGetSignatureKeyType) Set(f func() (r SignatureKeyType)) *SignatureKeyHolderMock {\n\tm.mainExpectation = nil\n\tm.expectationSeries = nil\n\n\tm.mock.GetSignatureKeyTypeFunc = f\n\treturn m.mock\n}", "func Test_VerifySigFromTass(t *testing.T) {\n\trequire := require.New(t)\n\n\t//c := &sm2.Driver{}\n\n\txBytes := common.FromHex(\"0000000000000000000000000000000000000000000000000000000000000000FD4241057FEC6CBEEC501F7E1763751B8F6DFCFB910FB634FBB76A16639EF172\")\n\tyBytes := common.FromHex(\"00000000000000000000000000000000000000000000000000000000000000001C6DA89F9C1A5EE9B6108E5A2A5FE336962630A34DBA1AF428451E1CE63BB3CF\")\n\tx := new(big.Int).SetBytes(xBytes)\n\ty := new(big.Int).SetBytes(yBytes)\n\n\tpublicKey := &gmsm_sm2.PublicKey{\n\t\tX: x,\n\t\tY: y,\n\t}\n\tvar pubSM2 sm2.PubKeySM2\n\tcopy(pubSM2[:], gmsm_sm2.Compress(publicKey))\n\n\trBytes := common.FromHex(\"00000000000000000000000000000000000000000000000000000000000000003AA29337E7149047FB8AE83F30AA00125E23173C88F284ADDED2E5B59ACAA5B9\")\n\tsBytes := common.FromHex(\"0000000000000000000000000000000000000000000000000000000000000000E2E9338109D74269578216039FD4D1C764E7F6F142CBB2E3035E7E49D375D330\")\n\tr := new(big.Int).SetBytes(rBytes)\n\ts := new(big.Int).SetBytes(sBytes)\n\n\tsignature := sm2.SignatureSM2(sm2.Serialize(r, s))\n\n\tmsg := []byte(\"112233445566112233445566112233445566112233445566\")\n\tok := pubSM2.VerifyBytes(msg, signature)\n\trequire.Equal(true, ok)\n}", "func (m *mSignatureKeyHolderMockGetSignatureKeyType) Return(r SignatureKeyType) *SignatureKeyHolderMock {\n\tm.mock.GetSignatureKeyTypeFunc = nil\n\tm.expectationSeries = nil\n\n\tif m.mainExpectation == nil {\n\t\tm.mainExpectation = &SignatureKeyHolderMockGetSignatureKeyTypeExpectation{}\n\t}\n\tm.mainExpectation.result = &SignatureKeyHolderMockGetSignatureKeyTypeResult{r}\n\treturn m.mock\n}", "func TestPrettyPrintRootAndSigningKeys(t *testing.T) {\n\tret := passphrase.ConstantRetriever(\"pass\")\n\tkeyStores := []trustmanager.KeyStore{\n\t\ttrustmanager.NewKeyMemoryStore(ret),\n\t\t&otherMemoryStore{GenericKeyStore: *trustmanager.NewKeyMemoryStore(ret)},\n\t}\n\n\tlongNameShortened := \"...\" + strings.Repeat(\"z\", 37)\n\n\tkeys := make([]data.PrivateKey, 4)\n\tfor i := 0; i < 4; i++ {\n\t\tkey, err := utils.GenerateED25519Key(rand.Reader)\n\t\trequire.NoError(t, err)\n\t\tkeys[i] = key\n\t}\n\n\troot := data.CanonicalRootRole\n\n\t// add keys to the key stores\n\trequire.NoError(t, keyStores[0].AddKey(trustmanager.KeyInfo{Role: root, Gun: \"\"}, keys[0]))\n\trequire.NoError(t, keyStores[1].AddKey(trustmanager.KeyInfo{Role: root, Gun: \"\"}, keys[0]))\n\trequire.NoError(t, keyStores[0].AddKey(trustmanager.KeyInfo{Role: data.CanonicalTargetsRole, Gun: data.GUN(strings.Repeat(\"/a\", 30))}, keys[1]))\n\trequire.NoError(t, keyStores[1].AddKey(trustmanager.KeyInfo{Role: data.CanonicalSnapshotRole, Gun: \"short/gun\"}, keys[1]))\n\trequire.NoError(t, keyStores[0].AddKey(trustmanager.KeyInfo{Role: \"targets/a\", Gun: \"\"}, keys[3]))\n\trequire.NoError(t, keyStores[0].AddKey(trustmanager.KeyInfo{Role: \"invalidRole\", Gun: \"\"}, keys[2]))\n\n\texpected := [][]string{\n\t\t// root always comes first\n\t\t{root.String(), keys[0].ID(), keyStores[0].Name()},\n\t\t{root.String(), keys[0].ID(), longNameShortened},\n\t\t// these have no gun, so they come first\n\t\t{\"invalidRole\", keys[2].ID(), keyStores[0].Name()},\n\t\t{\"targets/a\", keys[3].ID(), keyStores[0].Name()},\n\t\t// these have guns, and are sorted then by guns\n\t\t{data.CanonicalTargetsRole.String(), \"...\" + strings.Repeat(\"/a\", 11), keys[1].ID(), keyStores[0].Name()},\n\t\t{data.CanonicalSnapshotRole.String(), \"short/gun\", keys[1].ID(), longNameShortened},\n\t}\n\n\tvar b bytes.Buffer\n\tprettyPrintKeys(keyStores, &b)\n\ttext, err := ioutil.ReadAll(&b)\n\trequire.NoError(t, err)\n\n\tlines := strings.Split(strings.TrimSpace(string(text)), \"\\n\")\n\trequire.Len(t, lines, len(expected)+2)\n\n\t// starts with headers\n\trequire.True(t, reflect.DeepEqual(strings.Fields(lines[0]),\n\t\t[]string{\"ROLE\", \"GUN\", \"KEY\", \"ID\", \"LOCATION\"}))\n\trequire.Equal(t, \"----\", lines[1][:4])\n\n\tfor i, line := range lines[2:] {\n\t\t// we are purposely not putting spaces in test data so easier to split\n\t\tsplitted := strings.Fields(line)\n\t\tfor j, v := range splitted {\n\t\t\trequire.Equal(t, expected[i][j], strings.TrimSpace(v))\n\t\t}\n\t}\n}", "func signatureHelper(t *testing.T, failure bool) {\n\t// Setup\n\tstop, clients, contractPath, contractFilePath := setupSignature(t)\n\tdefer stop()\n\n\tstopBefore, expectedProofFile1, expectedProofFile2 := \"1\", 0, 0\n\tif !failure {\n\t\tstopBefore, expectedProofFile1, expectedProofFile2 = \"2\", 2, 1\n\t}\n\n\t// Configure client3 to be faulty\n\tsetLastArg(clients[2], \"--stopbefore\", true)\n\tsetLastArg(clients[2], stopBefore, false)\n\tsetLastArg(clients[2], \"sign\", false)\n\n\t// Sign!\n\tcloseChannel := make(chan []byte, 3)\n\tfor i := 0; i < 3; i++ {\n\t\tsetLastArg(clients[i], \"sign\", true)\n\t\tsetLastArg(clients[i], contractPath, false)\n\t\tgo func(c *exec.Cmd, i int) {\n\t\t\tc.Stdin = strings.NewReader(contractFilePath + \"\\npassword\\nyes\\n\")\n\t\t\tc.Stderr = bufio.NewWriter(os.Stdout)\n\t\t\toutput, _ := c.Output()\n\t\t\tcloseChannel <- output\n\t\t}(clients[i], i)\n\t}\n\n\tfor i := 0; i < 3; i++ {\n\t\t// TODO check stderr?\n\t\t<-closeChannel\n\t}\n\n\tcheckProofFile(t, expectedProofFile1)\n\tfilename := checkRecoverFile(t, \"client3@example.com\")\n\tcallRecover(newClient(clients[2]), filename)\n\t_ = os.Remove(filename)\n\tcheckProofFile(t, expectedProofFile2)\n\n\ttime.Sleep(time.Second)\n\treturn\n}", "func (m *mSignatureKeyHolderMockGetSignatureKeyMethod) Return(r SignatureMethod) *SignatureKeyHolderMock {\n\tm.mock.GetSignatureKeyMethodFunc = nil\n\tm.expectationSeries = nil\n\n\tif m.mainExpectation == nil {\n\t\tm.mainExpectation = &SignatureKeyHolderMockGetSignatureKeyMethodExpectation{}\n\t}\n\tm.mainExpectation.result = &SignatureKeyHolderMockGetSignatureKeyMethodResult{r}\n\treturn m.mock\n}", "func (f *Factory) Sign(name string, txBuilder sdk.TxBuilder) error {\n\tsignMode := f.signMode\n\tif signMode == signing.SignMode_SIGN_MODE_UNSPECIFIED {\n\t\t// use the SignModeHandler's default mode if unspecified\n\t\tsignMode = f.txConfig.SignModeHandler().DefaultMode()\n\t}\n\tsignerData := sdk.SignerData{\n\t\tChainID: f.chainID,\n\t\tAccountNumber: f.accountNumber,\n\t\tSequence: f.sequence,\n\t}\n\n\tpubkey, _, err := f.keyManager.Find(name, f.password)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// For SIGN_MODE_DIRECT, calling SetSignatures calls setSignerInfos on\n\t// Factory under the hood, and SignerInfos is needed to generated the\n\t// sign bytes. This is the reason for setting SetSignatures here, with a\n\t// nil signature.\n\t//\n\t// Note: this line is not needed for SIGN_MODE_LEGACY_AMINO, but putting it\n\t// also doesn't affect its generated sign bytes, so for code's simplicity\n\t// sake, we put it here.\n\tsigData := signing.SingleSignatureData{\n\t\tSignMode: signMode,\n\t\tSignature: nil,\n\t}\n\tsig := signing.SignatureV2{\n\t\tPubKey: pubkey,\n\t\tData: &sigData,\n\t\tSequence: f.Sequence(),\n\t}\n\tif err := txBuilder.SetSignatures(sig); err != nil {\n\t\treturn err\n\t}\n\n\t// Generate the bytes to be signed.\n\tsignBytes, err := f.signModeHandler.GetSignBytes(signMode, signerData, txBuilder.GetTx())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Sign those bytes\n\tsigBytes, _, err := f.keyManager.Sign(name, f.password, signBytes)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Construct the SignatureV2 struct\n\tsigData = signing.SingleSignatureData{\n\t\tSignMode: signMode,\n\t\tSignature: sigBytes,\n\t}\n\tsig = signing.SignatureV2{\n\t\tPubKey: pubkey,\n\t\tData: &sigData,\n\t\tSequence: f.Sequence(),\n\t}\n\n\t// And here the tx is populated with the signature\n\treturn txBuilder.SetSignatures(sig)\n}", "func TestService_Handle_Inviter(t *testing.T) {\n\tmockStore := &mockstorage.MockStore{Store: make(map[string]mockstorage.DBEntry)}\n\tstoreProv := mockstorage.NewCustomMockStoreProvider(mockStore)\n\tk := newKMS(t, storeProv)\n\tprov := &protocol.MockProvider{\n\t\tStoreProvider: storeProv,\n\t\tServiceMap: map[string]interface{}{\n\t\t\tmediator.Coordination: &mockroute.MockMediatorSvc{},\n\t\t},\n\t\tCustomKMS: k,\n\t\tKeyTypeValue: kms.ED25519Type,\n\t\tKeyAgreementTypeValue: kms.X25519ECDHKWType,\n\t}\n\n\tctx := &context{\n\t\toutboundDispatcher: prov.OutboundDispatcher(),\n\t\tcrypto: &tinkcrypto.Crypto{},\n\t\tkms: k,\n\t\tkeyType: kms.ED25519Type,\n\t\tkeyAgreementType: kms.X25519ECDHKWType,\n\t}\n\n\tverPubKey, encPubKey := newSigningAndEncryptionDIDKeys(t, ctx)\n\n\tctx.vdRegistry = &mockvdr.MockVDRegistry{CreateValue: createDIDDocWithKey(verPubKey, encPubKey)}\n\n\tconnRec, err := connection.NewRecorder(prov)\n\trequire.NoError(t, err)\n\trequire.NotNil(t, connRec)\n\n\tctx.connectionRecorder = connRec\n\n\tdoc, err := ctx.vdRegistry.Create(testMethod, nil)\n\trequire.NoError(t, err)\n\n\ts, err := New(prov)\n\trequire.NoError(t, err)\n\n\tactionCh := make(chan service.DIDCommAction, 10)\n\terr = s.RegisterActionEvent(actionCh)\n\trequire.NoError(t, err)\n\n\tstatusCh := make(chan service.StateMsg, 10)\n\terr = s.RegisterMsgEvent(statusCh)\n\trequire.NoError(t, err)\n\n\tcompletedFlag := make(chan struct{})\n\trespondedFlag := make(chan struct{})\n\n\tgo msgEventListener(t, statusCh, respondedFlag, completedFlag)\n\n\tgo func() { service.AutoExecuteActionEvent(actionCh) }()\n\n\tinvitation := &Invitation{\n\t\tType: InvitationMsgType,\n\t\tID: randomString(),\n\t\tLabel: \"Bob\",\n\t\tRecipientKeys: []string{verPubKey},\n\t\tServiceEndpoint: \"http://alice.agent.example.com:8081\",\n\t}\n\n\terr = ctx.connectionRecorder.SaveInvitation(invitation.ID, invitation)\n\trequire.NoError(t, err)\n\n\tthid := randomString()\n\n\t// Invitation was previously sent by Alice to Bob.\n\t// Bob now sends a did-exchange Invitation\n\tpayloadBytes, err := json.Marshal(\n\t\t&Request{\n\t\t\tType: RequestMsgType,\n\t\t\tID: thid,\n\t\t\tLabel: \"Bob\",\n\t\t\tThread: &decorator.Thread{\n\t\t\t\tPID: invitation.ID,\n\t\t\t},\n\t\t\tDID: doc.DIDDocument.ID,\n\t\t\tDocAttach: unsignedDocAttach(t, doc.DIDDocument),\n\t\t})\n\trequire.NoError(t, err)\n\tmsg, err := service.ParseDIDCommMsgMap(payloadBytes)\n\trequire.NoError(t, err)\n\t_, err = s.HandleInbound(msg, service.NewDIDCommContext(doc.DIDDocument.ID, \"\", nil))\n\trequire.NoError(t, err)\n\n\tselect {\n\tcase <-respondedFlag:\n\tcase <-time.After(2 * time.Second):\n\t\trequire.Fail(t, \"didn't receive post event responded\")\n\t}\n\t// Alice automatically sends exchange Response to Bob\n\t// Bob replies with an ACK\n\tpayloadBytes, err = json.Marshal(\n\t\t&model.Ack{\n\t\t\tType: AckMsgType,\n\t\t\tID: randomString(),\n\t\t\tStatus: \"OK\",\n\t\t\tThread: &decorator.Thread{ID: thid},\n\t\t})\n\trequire.NoError(t, err)\n\n\tdidMsg, err := service.ParseDIDCommMsgMap(payloadBytes)\n\trequire.NoError(t, err)\n\n\t_, err = s.HandleInbound(didMsg, service.NewDIDCommContext(doc.DIDDocument.ID, \"\", nil))\n\trequire.NoError(t, err)\n\n\tselect {\n\tcase <-completedFlag:\n\tcase <-time.After(2 * time.Second):\n\t\trequire.Fail(t, \"didn't receive post event complete\")\n\t}\n\n\tvalidateState(t, s, thid, findNamespace(AckMsgType), (&completed{}).Name())\n}", "func TestNewIdentityManager(t *testing.T) {\n\tt.Run(\"success\", func(t *testing.T) {\n\t\tepCfg := &mocks.EndpointConfig{}\n\t\tepCfg.NetworkConfigReturns(&fab.NetworkConfig{\n\t\t\tOrganizations: map[string]fab.OrganizationConfig{\"org1msp\": {}},\n\t\t})\n\n\t\tm, err := newIdentityManager(\"org1MSP\", &mocks.CryptoSuite{}, epCfg, \"./msp\")\n\t\trequire.NoError(t, err)\n\t\trequire.NotNil(t, m)\n\t})\n\n\tt.Run(\"No endpoint config -> error\", func(t *testing.T) {\n\t\tm, err := newIdentityManager(\"org1MSP\", &mocks.CryptoSuite{}, nil, \"./msp\")\n\t\trequire.EqualError(t, err, \"endpoint config is required\")\n\t\trequire.Nil(t, m)\n\t})\n\n\tt.Run(\"No org name -> error\", func(t *testing.T) {\n\t\tm, err := newIdentityManager(\"\", nil, &mocks.EndpointConfig{}, \"./msp\")\n\t\trequire.EqualError(t, err, \"orgName is required\")\n\t\trequire.Nil(t, m)\n\t})\n\n\tt.Run(\"No crypto suite -> error\", func(t *testing.T) {\n\t\tm, err := newIdentityManager(\"org1MSP\", nil, &mocks.EndpointConfig{}, \"./msp\")\n\t\trequire.EqualError(t, err, \"cryptoProvider is required\")\n\t\trequire.Nil(t, m)\n\t})\n\n\tt.Run(\"Org not found -> error\", func(t *testing.T) {\n\t\tepCfg := &mocks.EndpointConfig{}\n\t\tepCfg.NetworkConfigReturns(&fab.NetworkConfig{})\n\n\t\tm, err := newIdentityManager(\"org1MSP\", &mocks.CryptoSuite{}, epCfg, \"./msp\")\n\t\trequire.EqualError(t, err, \"org config retrieval failed\")\n\t\trequire.Nil(t, m)\n\t})\n\n\tt.Run(\"MSP config path not provided -> error\", func(t *testing.T) {\n\t\tepCfg := &mocks.EndpointConfig{}\n\t\tepCfg.NetworkConfigReturns(&fab.NetworkConfig{\n\t\t\tOrganizations: map[string]fab.OrganizationConfig{\"org1msp\": {}},\n\t\t})\n\n\t\tm, err := newIdentityManager(\"org1MSP\", &mocks.CryptoSuite{}, epCfg, \"\")\n\t\trequire.EqualError(t, err, \"either mspConfigPath or an embedded list of users is required\")\n\t\trequire.Nil(t, m)\n\t})\n}", "func NewSignatureKeyHolderMock(t minimock.Tester) *SignatureKeyHolderMock {\n\tm := &SignatureKeyHolderMock{t: t}\n\n\tif controller, ok := t.(minimock.MockController); ok {\n\t\tcontroller.RegisterMocker(m)\n\t}\n\n\tm.AsByteStringMock = mSignatureKeyHolderMockAsByteString{mock: m}\n\tm.AsBytesMock = mSignatureKeyHolderMockAsBytes{mock: m}\n\tm.EqualsMock = mSignatureKeyHolderMockEquals{mock: m}\n\tm.FixedByteSizeMock = mSignatureKeyHolderMockFixedByteSize{mock: m}\n\tm.FoldToUint64Mock = mSignatureKeyHolderMockFoldToUint64{mock: m}\n\tm.GetSignMethodMock = mSignatureKeyHolderMockGetSignMethod{mock: m}\n\tm.GetSignatureKeyMethodMock = mSignatureKeyHolderMockGetSignatureKeyMethod{mock: m}\n\tm.GetSignatureKeyTypeMock = mSignatureKeyHolderMockGetSignatureKeyType{mock: m}\n\tm.ReadMock = mSignatureKeyHolderMockRead{mock: m}\n\tm.WriteToMock = mSignatureKeyHolderMockWriteTo{mock: m}\n\n\treturn m\n}", "func (m *MockSigner) Sign(arg0 *ecdsa.PrivateKey, arg1 proto0.Message) (*proto.Signature, error) {\n\tret := m.ctrl.Call(m, \"Sign\", arg0, arg1)\n\tret0, _ := ret[0].(*proto.Signature)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (mmSignWith *mDigestHolderMockSignWith) Expect(signer DigestSigner) *mDigestHolderMockSignWith {\n\tif mmSignWith.mock.funcSignWith != nil {\n\t\tmmSignWith.mock.t.Fatalf(\"DigestHolderMock.SignWith mock is already set by Set\")\n\t}\n\n\tif mmSignWith.defaultExpectation == nil {\n\t\tmmSignWith.defaultExpectation = &DigestHolderMockSignWithExpectation{}\n\t}\n\n\tmmSignWith.defaultExpectation.params = &DigestHolderMockSignWithParams{signer}\n\tfor _, e := range mmSignWith.expectations {\n\t\tif minimock.Equal(e.params, mmSignWith.defaultExpectation.params) {\n\t\t\tmmSignWith.mock.t.Fatalf(\"Expectation set by When has same params: %#v\", *mmSignWith.defaultExpectation.params)\n\t\t}\n\t}\n\n\treturn mmSignWith\n}", "func TestDelegatorProxyValidatorShares7Steps(t *testing.T) {\n\n}", "func (m *mSignatureKeyHolderMockGetSignMethod) Return(r SignMethod) *SignatureKeyHolderMock {\n\tm.mock.GetSignMethodFunc = nil\n\tm.expectationSeries = nil\n\n\tif m.mainExpectation == nil {\n\t\tm.mainExpectation = &SignatureKeyHolderMockGetSignMethodExpectation{}\n\t}\n\tm.mainExpectation.result = &SignatureKeyHolderMockGetSignMethodResult{r}\n\treturn m.mock\n}", "func NewCryptographyServiceMock(t minimock.Tester) *CryptographyServiceMock {\n\tm := &CryptographyServiceMock{t: t}\n\n\tif controller, ok := t.(minimock.MockController); ok {\n\t\tcontroller.RegisterMocker(m)\n\t}\n\n\tm.GetPublicKeyMock = mCryptographyServiceMockGetPublicKey{mock: m}\n\tm.SignMock = mCryptographyServiceMockSign{mock: m}\n\tm.VerifyMock = mCryptographyServiceMockVerify{mock: m}\n\n\treturn m\n}", "func (m *mActiveNodeMockGetSignatureVerifier) Set(f func() (r cryptkit.SignatureVerifier)) *ActiveNodeMock {\n\tm.mainExpectation = nil\n\tm.expectationSeries = nil\n\n\tm.mock.GetSignatureVerifierFunc = f\n\treturn m.mock\n}", "func (mmGetPacketSignature *mPacketParserMockGetPacketSignature) Set(f func() (s1 cryptkit.SignedDigest)) *PacketParserMock {\n\tif mmGetPacketSignature.defaultExpectation != nil {\n\t\tmmGetPacketSignature.mock.t.Fatalf(\"Default expectation is already set for the PacketParser.GetPacketSignature method\")\n\t}\n\n\tif len(mmGetPacketSignature.expectations) > 0 {\n\t\tmmGetPacketSignature.mock.t.Fatalf(\"Some expectations are already set for the PacketParser.GetPacketSignature method\")\n\t}\n\n\tmmGetPacketSignature.mock.funcGetPacketSignature = f\n\treturn mmGetPacketSignature.mock\n}", "func NewMockSigner(ctrl *gomock.Controller) *MockSigner {\n\tmock := &MockSigner{ctrl: ctrl}\n\tmock.recorder = &MockSignerMockRecorder{mock}\n\treturn mock\n}", "func (m *MockSignerDecrypter) Sign(arg0 io.Reader, arg1 []byte, arg2 crypto.SignerOpts) ([]byte, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Sign\", arg0, arg1, arg2)\n\tret0, _ := ret[0].([]byte)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func newKeyServerWithMocking(user upspin.UserName, ref string, data []byte) (*server, *storagetest.ExpectDownloadCapturePut) {\n\tmockGCP := &storagetest.ExpectDownloadCapturePut{\n\t\tRef: []string{ref},\n\t\tData: [][]byte{data},\n\t\tPutContents: make([][]byte, 0, 1),\n\t\tPutRef: make([]string, 0, 1),\n\t}\n\ts := &server{\n\t\tstorage: mockGCP,\n\t\tuser: user,\n\t\tlookupTXT: mockLookupTXT,\n\t\tlogger: &noopLogger{},\n\t\tcache: cache.NewLRU(10),\n\t\tnegCache: cache.NewLRU(10),\n\t}\n\treturn s, mockGCP\n}", "func NewSignedMessageForTestGetter(ms MockSigner) func(uint64) *types.SignedMessage {\n\ti := 0\n\treturn func(nonce uint64) *types.SignedMessage {\n\t\ts := fmt.Sprintf(\"smsg%d\", i)\n\t\ti++\n\t\tnewAddr, err := address.NewSecp256k1Address([]byte(s + \"-to\"))\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tmsg := NewMeteredMessage(\n\t\t\tms.Addresses[0], // from needs to be an address from the signer\n\t\t\tnewAddr,\n\t\t\tnonce,\n\t\t\ttypes.ZeroFIL,\n\t\t\t0,\n\t\t\t[]byte(\"params\"),\n\t\t\ttypes.ZeroFIL,\n\t\t\ttypes.ZeroFIL,\n\t\t\t0,\n\t\t)\n\t\tsmsg, err := NewSignedMessage(context.TODO(), *msg, &ms)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\treturn smsg\n\t}\n}", "func NewMockSignersAndKeyInfo(numSigners int) (MockSigner, []KeyInfo) {\n\tki := MustGenerateKeyInfo(numSigners, 42)\n\tsigner := NewMockSigner(ki)\n\treturn signer, ki\n}", "func (mmGetPacketSignature *mPacketParserMockGetPacketSignature) Return(s1 cryptkit.SignedDigest) *PacketParserMock {\n\tif mmGetPacketSignature.mock.funcGetPacketSignature != nil {\n\t\tmmGetPacketSignature.mock.t.Fatalf(\"PacketParserMock.GetPacketSignature mock is already set by Set\")\n\t}\n\n\tif mmGetPacketSignature.defaultExpectation == nil {\n\t\tmmGetPacketSignature.defaultExpectation = &PacketParserMockGetPacketSignatureExpectation{mock: mmGetPacketSignature.mock}\n\t}\n\tmmGetPacketSignature.defaultExpectation.results = &PacketParserMockGetPacketSignatureResults{s1}\n\treturn mmGetPacketSignature.mock\n}", "func (m *SignatureKeyHolderMock) Equals(p SignatureKeyHolder) (r bool) {\n\tcounter := atomic.AddUint64(&m.EqualsPreCounter, 1)\n\tdefer atomic.AddUint64(&m.EqualsCounter, 1)\n\n\tif len(m.EqualsMock.expectationSeries) > 0 {\n\t\tif counter > uint64(len(m.EqualsMock.expectationSeries)) {\n\t\t\tm.t.Fatalf(\"Unexpected call to SignatureKeyHolderMock.Equals. %v\", p)\n\t\t\treturn\n\t\t}\n\n\t\tinput := m.EqualsMock.expectationSeries[counter-1].input\n\t\ttestify_assert.Equal(m.t, *input, SignatureKeyHolderMockEqualsInput{p}, \"SignatureKeyHolder.Equals got unexpected parameters\")\n\n\t\tresult := m.EqualsMock.expectationSeries[counter-1].result\n\t\tif result == nil {\n\t\t\tm.t.Fatal(\"No results are set for the SignatureKeyHolderMock.Equals\")\n\t\t\treturn\n\t\t}\n\n\t\tr = result.r\n\n\t\treturn\n\t}\n\n\tif m.EqualsMock.mainExpectation != nil {\n\n\t\tinput := m.EqualsMock.mainExpectation.input\n\t\tif input != nil {\n\t\t\ttestify_assert.Equal(m.t, *input, SignatureKeyHolderMockEqualsInput{p}, \"SignatureKeyHolder.Equals got unexpected parameters\")\n\t\t}\n\n\t\tresult := m.EqualsMock.mainExpectation.result\n\t\tif result == nil {\n\t\t\tm.t.Fatal(\"No results are set for the SignatureKeyHolderMock.Equals\")\n\t\t}\n\n\t\tr = result.r\n\n\t\treturn\n\t}\n\n\tif m.EqualsFunc == nil {\n\t\tm.t.Fatalf(\"Unexpected call to SignatureKeyHolderMock.Equals. %v\", p)\n\t\treturn\n\t}\n\n\treturn m.EqualsFunc(p)\n}", "func NewSysProbeUtil(t interface {\n\tmock.TestingT\n\tCleanup(func())\n}) *SysProbeUtil {\n\tmock := &SysProbeUtil{}\n\tmock.Mock.Test(t)\n\n\tt.Cleanup(func() { mock.AssertExpectations(t) })\n\n\treturn mock\n}", "func (m *mCryptographyServiceMockVerify) Set(f func(p crypto.PublicKey, p1 insolar.Signature, p2 []byte) (r bool)) *CryptographyServiceMock {\n\tm.mainExpectation = nil\n\tm.expectationSeries = nil\n\n\tm.mock.VerifyFunc = f\n\treturn m.mock\n}", "func (m *mSignatureKeyHolderMockEquals) Set(f func(p SignatureKeyHolder) (r bool)) *SignatureKeyHolderMock {\n\tm.mainExpectation = nil\n\tm.expectationSeries = nil\n\n\tm.mock.EqualsFunc = f\n\treturn m.mock\n}", "func TestTokenSignature(t *testing.T) {\n\tdb.InitDB()\n\tvar router *gin.Engine = routes.SetupRouter()\n\n\tvar user models.UserCreate = utils.CreateUser(\"Tom\", \"qwerty1234\", t, router)\n\tuser.Token = utils.ConnectUser(\"Tom\", \"qwerty1234\", t, router)\n\n\tsplittedToken := strings.Split(user.Token, \".\")\n\tif len(splittedToken) != 3 {\n\t\tlog.Fatal(\"Bad token.\")\n\t\tt.Fail()\n\t}\n\n\theader := splittedToken[0]\n\tpayload := splittedToken[1]\n\tsignature := splittedToken[2]\n\tsignature = signature + \"modif\"\n\tmodifiedToken := header + \".\" + payload + \".\" + signature\n\n\tvar url string = \"/v1/user/\" + strconv.Itoa(user.ID)\n\tvar bearer = \"Bearer \" + modifiedToken\n\trecord := httptest.NewRecorder()\n\trequest, _ := http.NewRequest(\"GET\", url, nil)\n\trequest.Header.Add(\"Content-Type\", \"application/json\")\n\trequest.Header.Add(\"Authorization\", bearer)\n\n\trouter.ServeHTTP(record, request)\n\n\tvar message Message\n\terr := json.Unmarshal([]byte(record.Body.String()), &message)\n\tif err != nil {\n\t\tlog.Fatal(\"Bad output: \", err.Error())\n\t\tt.Fail()\n\t}\n\n\tassert.Equal(t, record.Code, 403)\n\tassert.Equal(t, message.Message, \"Bad signature\")\n\n\tuser.Token = utils.ConnectUser(\"Tom\", \"qwerty1234\", t, router)\n\tutils.CleanUser(user.ID, user.Token, t, router)\n\tdb.CloseDB()\n}", "func newMockKvCapabilityVerifier(t mockConstructorTestingTnewMockKvCapabilityVerifier) *mockKvCapabilityVerifier {\n\tmock := &mockKvCapabilityVerifier{}\n\tmock.Mock.Test(t)\n\n\tt.Cleanup(func() { mock.AssertExpectations(t) })\n\n\treturn mock\n}", "func NewTranslationKeyStore(t mockConstructorTestingTNewTranslationKeyStore) *TranslationKeyStore {\n\tmock := &TranslationKeyStore{}\n\tmock.Mock.Test(t)\n\n\tt.Cleanup(func() { mock.AssertExpectations(t) })\n\n\treturn mock\n}", "func (_m *Keychain) Sign(_a0 []byte) ([]byte, error) {\n\tret := _m.Called(_a0)\n\n\tvar r0 []byte\n\tif rf, ok := ret.Get(0).(func([]byte) []byte); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).([]byte)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func([]byte) error); ok {\n\t\tr1 = rf(_a0)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (m *mSignatureKeyHolderMockGetSignMethod) Expect() *mSignatureKeyHolderMockGetSignMethod {\n\tm.mock.GetSignMethodFunc = nil\n\tm.expectationSeries = nil\n\n\tif m.mainExpectation == nil {\n\t\tm.mainExpectation = &SignatureKeyHolderMockGetSignMethodExpectation{}\n\t}\n\n\treturn m\n}", "func NewMockKeystore(auth *communications.Headers, logger log.Logger) definitions.Keystore {\n\ts := new(inmemKeystore)\n\ts.headers = auth\n\treturn s\n}", "func (m *mActiveNodeMockGetSignatureVerifier) Return(r cryptkit.SignatureVerifier) *ActiveNodeMock {\n\tm.mock.GetSignatureVerifierFunc = nil\n\tm.expectationSeries = nil\n\n\tif m.mainExpectation == nil {\n\t\tm.mainExpectation = &ActiveNodeMockGetSignatureVerifierExpectation{}\n\t}\n\tm.mainExpectation.result = &ActiveNodeMockGetSignatureVerifierResult{r}\n\treturn m.mock\n}", "func (_m *mockSigningKeyGetter) flushCachedSigningKeys(issuer string) error {\n\tret := _m.Called(issuer)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(string) error); ok {\n\t\tr0 = rf(issuer)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (mr *MockClientMockRecorder) SigningManager() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"SigningManager\", reflect.TypeOf((*MockClient)(nil).SigningManager))\n}", "func (m *MockFullNode) WalletSign(arg0 context.Context, arg1 address.Address, arg2 []byte, arg3 types0.MsgMeta) (*crypto.Signature, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"WalletSign\", arg0, arg1, arg2, arg3)\n\tret0, _ := ret[0].(*crypto.Signature)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (s *ServiceSuite) TestMacaroonPaperFig6FailsWithBindingOnTamperedSignature(c *gc.C) {\n\tlocator := bakery.NewThirdPartyStore()\n\tas := newBakery(\"as-loc\", locator)\n\tts := newBakery(\"ts-loc\", locator)\n\tfs := newBakery(\"fs-loc\", locator)\n\n\t// ts creates a macaroon.\n\ttsMacaroon, err := ts.Oven.NewMacaroon(testContext, bakery.LatestVersion, ages, nil, bakery.LoginOp)\n\tc.Assert(err, gc.IsNil)\n\n\t// ts somehow sends the macaroon to fs which adds a third party caveat to be discharged by as.\n\terr = fs.Oven.AddCaveat(testContext, tsMacaroon, checkers.Caveat{Location: \"as-loc\", Condition: \"user==bob\"})\n\tc.Assert(err, gc.IsNil)\n\n\t// client asks for a discharge macaroon for each third party caveat\n\td, err := bakery.DischargeAll(testContext, tsMacaroon, func(ctx context.Context, cav macaroon.Caveat, payload []byte) (*bakery.Macaroon, error) {\n\t\tc.Assert(cav.Location, gc.Equals, \"as-loc\")\n\t\treturn discharge(ctx, as.Oven, thirdPartyStrcmpChecker(\"user==bob\"), cav, payload)\n\t})\n\tc.Assert(err, gc.IsNil)\n\n\t// client has all the discharge macaroons. For each discharge macaroon bind it to our tsMacaroon\n\t// and add it to our request.\n\tfor _, dm := range d[1:] {\n\t\tdm.Bind([]byte(\"tampered-signature\")) // Bind against an incorrect signature.\n\t}\n\n\t// client makes request to ts.\n\t_, err = ts.Checker.Auth(d).Allow(testContext, bakery.LoginOp)\n\t// TODO fix this error message.\n\tc.Assert(err, gc.ErrorMatches, \"verification failed: signature mismatch after caveat verification\")\n}", "func (m *SignatureKeyHolderMock) MinimockFinish() {\n\n\tif !m.AsByteStringFinished() {\n\t\tm.t.Fatal(\"Expected call to SignatureKeyHolderMock.AsByteString\")\n\t}\n\n\tif !m.AsBytesFinished() {\n\t\tm.t.Fatal(\"Expected call to SignatureKeyHolderMock.AsBytes\")\n\t}\n\n\tif !m.EqualsFinished() {\n\t\tm.t.Fatal(\"Expected call to SignatureKeyHolderMock.Equals\")\n\t}\n\n\tif !m.FixedByteSizeFinished() {\n\t\tm.t.Fatal(\"Expected call to SignatureKeyHolderMock.FixedByteSize\")\n\t}\n\n\tif !m.FoldToUint64Finished() {\n\t\tm.t.Fatal(\"Expected call to SignatureKeyHolderMock.FoldToUint64\")\n\t}\n\n\tif !m.GetSignMethodFinished() {\n\t\tm.t.Fatal(\"Expected call to SignatureKeyHolderMock.GetSignMethod\")\n\t}\n\n\tif !m.GetSignatureKeyMethodFinished() {\n\t\tm.t.Fatal(\"Expected call to SignatureKeyHolderMock.GetSignatureKeyMethod\")\n\t}\n\n\tif !m.GetSignatureKeyTypeFinished() {\n\t\tm.t.Fatal(\"Expected call to SignatureKeyHolderMock.GetSignatureKeyType\")\n\t}\n\n\tif !m.ReadFinished() {\n\t\tm.t.Fatal(\"Expected call to SignatureKeyHolderMock.Read\")\n\t}\n\n\tif !m.WriteToFinished() {\n\t\tm.t.Fatal(\"Expected call to SignatureKeyHolderMock.WriteTo\")\n\t}\n\n}", "func TestAuthenticatedRequest(t *testing.T) {\n\tvar e error\n\tprivateKey, e = readPrivateKey()\n\tif e != nil {\n\t\tpanic(e)\n\t}\n\tConvey(\"Simple authenticated requests\", t, func() {\n\t\tConvey(\"Authenticated GET to / path should return a 200 response\", func() {\n\t\t\tw := makeAuthenticatedRequest(\"GET\", \"/\", jwt.MapClaims{\"foo\": \"bar\"}, nil)\n\t\t\tSo(w.Code, ShouldEqual, http.StatusOK)\n\t\t})\n\t\tConvey(\"Authenticated GET to /protected path should return a 200 response if expected algorithm is not specified\", func() {\n\t\t\tvar expectedAlgorithm jwt.SigningMethod = nil\n\t\t\tw := makeAuthenticatedRequest(\"GET\", \"/protected\", jwt.MapClaims{\"foo\": \"bar\"}, expectedAlgorithm)\n\t\t\tSo(w.Code, ShouldEqual, http.StatusOK)\n\t\t\tresponseBytes, err := ioutil.ReadAll(w.Body)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\tresponseString := string(responseBytes)\n\t\t\t// check that the encoded data in the jwt was properly returned as json\n\t\t\tSo(responseString, ShouldEqual, `{\"text\":\"bar\"}`)\n\t\t})\n\t\tConvey(\"Authenticated GET to /protected path should return a 200 response if expected algorithm is correct\", func() {\n\t\t\texpectedAlgorithm := jwt.SigningMethodHS256\n\t\t\tw := makeAuthenticatedRequest(\"GET\", \"/protected\", jwt.MapClaims{\"foo\": \"bar\"}, expectedAlgorithm)\n\t\t\tSo(w.Code, ShouldEqual, http.StatusOK)\n\t\t\tresponseBytes, err := ioutil.ReadAll(w.Body)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\tresponseString := string(responseBytes)\n\t\t\t// check that the encoded data in the jwt was properly returned as json\n\t\t\tSo(responseString, ShouldEqual, `{\"text\":\"bar\"}`)\n\t\t})\n\t\tConvey(\"Authenticated GET to /protected path should return a 401 response if algorithm is not expected one\", func() {\n\t\t\texpectedAlgorithm := jwt.SigningMethodRS256\n\t\t\tw := makeAuthenticatedRequest(\"GET\", \"/protected\", jwt.MapClaims{\"foo\": \"bar\"}, expectedAlgorithm)\n\t\t\tSo(w.Code, ShouldEqual, http.StatusUnauthorized)\n\t\t\tresponseBytes, err := ioutil.ReadAll(w.Body)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\tresponseString := string(responseBytes)\n\t\t\t// check that the encoded data in the jwt was properly returned as json\n\t\t\tSo(strings.TrimSpace(responseString), ShouldEqual, \"Expected RS256 signing method but token specified HS256\")\n\t\t})\n\t})\n}", "func (e *DigestHolderMockSignWithExpectation) Then(s1 SignedDigestHolder) *DigestHolderMock {\n\te.results = &DigestHolderMockSignWithResults{s1}\n\treturn e.mock\n}", "func (_m *mockSigningKeyGetter) getSigningKey(r *http.Request, issuer string, kid string) ([]byte, error) {\n\tret := _m.Called(r, issuer, kid)\n\n\tvar r0 []byte\n\tif rf, ok := ret.Get(0).(func(*http.Request, string, string) []byte); ok {\n\t\tr0 = rf(r, issuer, kid)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).([]byte)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(*http.Request, string, string) error); ok {\n\t\tr1 = rf(r, issuer, kid)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func TestWorkloadAgentGenerateSecretFromFile(t *testing.T) {\n\tfakeCACli, err := mock.NewMockCAClient(0, time.Hour)\n\tif err != nil {\n\t\tt.Fatalf(\"Error creating Mock CA client: %v\", err)\n\t}\n\topt := Options{\n\t\tRotationInterval: 200 * time.Millisecond,\n\t\tEvictionDuration: 0,\n\t}\n\n\tfetcher := &secretfetcher.SecretFetcher{\n\t\tUseCaClient: true,\n\t\tCaClient: fakeCACli,\n\t}\n\n\tvar wgAddedWatch sync.WaitGroup\n\tvar notifyEvent sync.WaitGroup\n\n\taddedWatchProbe := func(_ string, _ bool) { wgAddedWatch.Done() }\n\n\tvar closed bool\n\tnotifyCallback := func(_ ConnKey, _ *model.SecretItem) error {\n\t\tif !closed {\n\t\t\tnotifyEvent.Done()\n\t\t}\n\t\treturn nil\n\t}\n\n\t// Supply a fake watcher so that we can watch file events.\n\tvar fakeWatcher *filewatcher.FakeWatcher\n\tnewFileWatcher, fakeWatcher = filewatcher.NewFakeWatcher(addedWatchProbe)\n\n\tsc := NewSecretCache(fetcher, notifyCallback, opt)\n\tdefer func() {\n\t\tclosed = true\n\t\tsc.Close()\n\t\tnewFileWatcher = filewatcher.NewWatcher\n\t}()\n\n\trootCertPath := \"./testdata/root-cert.pem\"\n\tkeyPath := \"./testdata/key.pem\"\n\tcertChainPath := \"./testdata/cert-chain.pem\"\n\tsc.existingRootCertFile = rootCertPath\n\tsc.existingKeyFile = keyPath\n\tsc.existingCertChainFile = certChainPath\n\tcertchain, err := ioutil.ReadFile(certChainPath)\n\tif err != nil {\n\t\tt.Fatalf(\"Error reading the cert chain file: %v\", err)\n\t}\n\tprivateKey, err := ioutil.ReadFile(keyPath)\n\tif err != nil {\n\t\tt.Fatalf(\"Error reading the private key file: %v\", err)\n\t}\n\trootCert, err := ioutil.ReadFile(rootCertPath)\n\tif err != nil {\n\t\tt.Fatalf(\"Error reading the root cert file: %v\", err)\n\t}\n\n\tconID := \"proxy1-id\"\n\tctx := context.Background()\n\n\twgAddedWatch.Add(1) // Watch should be added for cert file.\n\tnotifyEvent.Add(1) // Nofify should be called once.\n\n\tgotSecret, err := sc.GenerateSecret(ctx, conID, WorkloadKeyCertResourceName, \"jwtToken1\")\n\n\twgAddedWatch.Wait()\n\tnotifyEvent.Wait()\n\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to get secrets: %v\", err)\n\t}\n\tcheckBool(t, \"SecretExist\", sc.SecretExist(conID, WorkloadKeyCertResourceName, \"jwtToken1\", gotSecret.Version), true)\n\texpectedSecret := &model.SecretItem{\n\t\tResourceName: WorkloadKeyCertResourceName,\n\t\tCertificateChain: certchain,\n\t\tPrivateKey: privateKey,\n\t}\n\tif err := verifySecret(gotSecret, expectedSecret); err != nil {\n\t\tt.Errorf(\"Secret verification failed: %v\", err)\n\t}\n\n\twgAddedWatch.Add(1) // Watch should be added for root file.\n\tnotifyEvent.Add(1) // Notify should be called once.\n\n\tgotSecretRoot, err := sc.GenerateSecret(ctx, conID, RootCertReqResourceName, \"jwtToken1\")\n\n\twgAddedWatch.Wait()\n\tnotifyEvent.Wait()\n\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to get secrets: %v\", err)\n\t}\n\tcheckBool(t, \"SecretExist\", sc.SecretExist(conID, RootCertReqResourceName, \"jwtToken1\", gotSecretRoot.Version), true)\n\tif got, want := atomic.LoadUint64(&sc.rootCertChangedCount), uint64(0); got != want {\n\t\tt.Errorf(\"rootCertChangedCount: got: %v, want: %v\", got, want)\n\t}\n\n\trootExpiration, err := nodeagentutil.ParseCertAndGetExpiryTimestamp(rootCert)\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to get the expiration time from the existing root file\")\n\t}\n\texpectedSecret = &model.SecretItem{\n\t\tResourceName: RootCertReqResourceName,\n\t\tRootCert: rootCert,\n\t\tExpireTime: rootExpiration,\n\t}\n\tif err := verifyRootCASecret(gotSecretRoot, expectedSecret); err != nil {\n\t\tt.Errorf(\"Secret verification failed: %v\", err)\n\t}\n\n\tkey := ConnKey{\n\t\tConnectionID: conID,\n\t\tResourceName: WorkloadKeyCertResourceName,\n\t}\n\tcachedSecret, found := sc.secrets.Load(key)\n\tif !found {\n\t\tt.Errorf(\"Failed to find secret for proxy %q from secret store: %v\", conID, err)\n\t}\n\tif !reflect.DeepEqual(*gotSecret, cachedSecret) {\n\t\tt.Errorf(\"Secret key: got %+v, want %+v\", *gotSecret, cachedSecret)\n\t}\n\n\t// Inject a file write event and validate that Notify is called.\n\tnotifyEvent.Add(1)\n\tfakeWatcher.InjectEvent(certChainPath, fsnotify.Event{\n\t\tName: certChainPath,\n\t\tOp: fsnotify.Write,\n\t})\n\tnotifyEvent.Wait()\n}", "func (m *MockManager) SerializeContentSHA(arg0 string) error {\n\tret := m.ctrl.Call(m, \"SerializeContentSHA\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func TestSenderRequest_Verify(t *testing.T) {\r\n\r\n\t// Create key\r\n\tkey, err := bitcoin.CreatePrivateKeyString()\r\n\tassert.NoError(t, err)\r\n\tassert.NotNil(t, key)\r\n\r\n\t// Create the request / message\r\n\tsenderRequest := &SenderRequest{\r\n\t\tDt: time.Now().UTC().Format(time.RFC3339),\r\n\t\tSenderHandle: testAlias + \"@\" + testDomain,\r\n\t\tSenderName: testName,\r\n\t\tPurpose: testMessage,\r\n\t}\r\n\r\n\t// Sign\r\n\tvar signature string\r\n\tsignature, err = senderRequest.Sign(key)\r\n\tassert.NoError(t, err)\r\n\tassert.NotEqual(t, 0, len(signature))\r\n\r\n\t// Get address from private key\r\n\tvar address string\r\n\taddress, err = bitcoin.GetAddressFromPrivateKeyString(key, false)\r\n\tassert.NoError(t, err)\r\n\tassert.NotNil(t, address)\r\n\r\n\tt.Run(\"valid verification\", func(t *testing.T) {\r\n\t\terr = senderRequest.Verify(address, signature)\r\n\t\tassert.NoError(t, err)\r\n\t})\r\n\r\n\tt.Run(\"invalid - empty address\", func(t *testing.T) {\r\n\t\terr = senderRequest.Verify(\"\", signature)\r\n\t\tassert.Error(t, err)\r\n\t})\r\n\r\n\tt.Run(\"invalid - empty signature\", func(t *testing.T) {\r\n\t\terr = senderRequest.Verify(address, \"\")\r\n\t\tassert.Error(t, err)\r\n\t})\r\n\r\n\tt.Run(\"invalid - wrong signature - hex short\", func(t *testing.T) {\r\n\t\terr = senderRequest.Verify(address, \"0\")\r\n\t\tassert.Error(t, err)\r\n\t})\r\n\r\n\tt.Run(\"invalid - wrong signature\", func(t *testing.T) {\r\n\t\terr = senderRequest.Verify(address, \"73646661736466736466617364667364666173646673646661736466\")\r\n\t\tassert.Error(t, err)\r\n\t})\r\n}", "func (s) TestDistributor(t *testing.T) {\n\tdist := NewDistributor()\n\n\t// Read cert/key files from testdata.\n\tkm, err := loadKeyMaterials()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\t// wantKM1 has both local and root certs.\n\twantKM1 := *km\n\t// wantKM2 has only local certs. Roots are nil-ed out.\n\twantKM2 := *km\n\twantKM2.Roots = nil\n\n\t// Create a goroutines which work in lockstep with the rest of the test.\n\t// This goroutine reads the key material from the distributor while the rest\n\t// of the test sets it.\n\tvar wg sync.WaitGroup\n\twg.Add(1)\n\terrCh := make(chan error)\n\tproceedCh := make(chan struct{})\n\tgo func() {\n\t\tdefer wg.Done()\n\n\t\t// The first call to KeyMaterial() should timeout because no key\n\t\t// material has been set on the distributor as yet.\n\t\tctx, cancel := context.WithTimeout(context.Background(), defaultTestTimeout/2)\n\t\tdefer cancel()\n\t\tif _, err := dist.KeyMaterial(ctx); err != context.DeadlineExceeded {\n\t\t\terrCh <- err\n\t\t\treturn\n\t\t}\n\t\tproceedCh <- struct{}{}\n\n\t\t// This call to KeyMaterial() should return the key material with both\n\t\t// the local certs and the root certs.\n\t\tctx, cancel = context.WithTimeout(context.Background(), defaultTestTimeout)\n\t\tdefer cancel()\n\t\tgotKM, err := dist.KeyMaterial(ctx)\n\t\tif err != nil {\n\t\t\terrCh <- err\n\t\t\treturn\n\t\t}\n\t\tif !reflect.DeepEqual(gotKM, &wantKM1) {\n\t\t\terrCh <- fmt.Errorf(\"provider.KeyMaterial() = %+v, want %+v\", gotKM, wantKM1)\n\t\t}\n\t\tproceedCh <- struct{}{}\n\n\t\t// This call to KeyMaterial() should eventually return key material with\n\t\t// only the local certs.\n\t\tctx, cancel = context.WithTimeout(context.Background(), defaultTestTimeout)\n\t\tdefer cancel()\n\t\tfor {\n\t\t\tgotKM, err := dist.KeyMaterial(ctx)\n\t\t\tif err != nil {\n\t\t\t\terrCh <- err\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif reflect.DeepEqual(gotKM, &wantKM2) {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tproceedCh <- struct{}{}\n\n\t\t// This call to KeyMaterial() should return nil key material and a\n\t\t// non-nil error.\n\t\tctx, cancel = context.WithTimeout(context.Background(), defaultTestTimeout)\n\t\tdefer cancel()\n\t\tfor {\n\t\t\tgotKM, err := dist.KeyMaterial(ctx)\n\t\t\tif gotKM == nil && err == errProviderTestInternal {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\t// If we have gotten any error other than\n\t\t\t\t// errProviderTestInternal, we should bail out.\n\t\t\t\terrCh <- err\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tproceedCh <- struct{}{}\n\n\t\t// This call to KeyMaterial() should eventually return errProviderClosed\n\t\t// error.\n\t\tctx, cancel = context.WithTimeout(context.Background(), defaultTestTimeout)\n\t\tdefer cancel()\n\t\tfor {\n\t\t\tif _, err := dist.KeyMaterial(ctx); err == errProviderClosed {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\ttime.Sleep(100 * time.Millisecond)\n\t\t}\n\t}()\n\n\twaitAndDo(t, proceedCh, errCh, func() {\n\t\tdist.Set(&wantKM1, nil)\n\t})\n\n\twaitAndDo(t, proceedCh, errCh, func() {\n\t\tdist.Set(&wantKM2, nil)\n\t})\n\n\twaitAndDo(t, proceedCh, errCh, func() {\n\t\tdist.Set(&wantKM2, errProviderTestInternal)\n\t})\n\n\twaitAndDo(t, proceedCh, errCh, func() {\n\t\tdist.Stop()\n\t})\n\n}", "func (m *SignatureKeyHolderMock) MinimockWait(timeout time.Duration) {\n\ttimeoutCh := time.After(timeout)\n\tfor {\n\t\tok := true\n\t\tok = ok && m.AsByteStringFinished()\n\t\tok = ok && m.AsBytesFinished()\n\t\tok = ok && m.EqualsFinished()\n\t\tok = ok && m.FixedByteSizeFinished()\n\t\tok = ok && m.FoldToUint64Finished()\n\t\tok = ok && m.GetSignMethodFinished()\n\t\tok = ok && m.GetSignatureKeyMethodFinished()\n\t\tok = ok && m.GetSignatureKeyTypeFinished()\n\t\tok = ok && m.ReadFinished()\n\t\tok = ok && m.WriteToFinished()\n\n\t\tif ok {\n\t\t\treturn\n\t\t}\n\n\t\tselect {\n\t\tcase <-timeoutCh:\n\n\t\t\tif !m.AsByteStringFinished() {\n\t\t\t\tm.t.Error(\"Expected call to SignatureKeyHolderMock.AsByteString\")\n\t\t\t}\n\n\t\t\tif !m.AsBytesFinished() {\n\t\t\t\tm.t.Error(\"Expected call to SignatureKeyHolderMock.AsBytes\")\n\t\t\t}\n\n\t\t\tif !m.EqualsFinished() {\n\t\t\t\tm.t.Error(\"Expected call to SignatureKeyHolderMock.Equals\")\n\t\t\t}\n\n\t\t\tif !m.FixedByteSizeFinished() {\n\t\t\t\tm.t.Error(\"Expected call to SignatureKeyHolderMock.FixedByteSize\")\n\t\t\t}\n\n\t\t\tif !m.FoldToUint64Finished() {\n\t\t\t\tm.t.Error(\"Expected call to SignatureKeyHolderMock.FoldToUint64\")\n\t\t\t}\n\n\t\t\tif !m.GetSignMethodFinished() {\n\t\t\t\tm.t.Error(\"Expected call to SignatureKeyHolderMock.GetSignMethod\")\n\t\t\t}\n\n\t\t\tif !m.GetSignatureKeyMethodFinished() {\n\t\t\t\tm.t.Error(\"Expected call to SignatureKeyHolderMock.GetSignatureKeyMethod\")\n\t\t\t}\n\n\t\t\tif !m.GetSignatureKeyTypeFinished() {\n\t\t\t\tm.t.Error(\"Expected call to SignatureKeyHolderMock.GetSignatureKeyType\")\n\t\t\t}\n\n\t\t\tif !m.ReadFinished() {\n\t\t\t\tm.t.Error(\"Expected call to SignatureKeyHolderMock.Read\")\n\t\t\t}\n\n\t\t\tif !m.WriteToFinished() {\n\t\t\t\tm.t.Error(\"Expected call to SignatureKeyHolderMock.WriteTo\")\n\t\t\t}\n\n\t\t\tm.t.Fatalf(\"Some mocks were not called on time: %s\", timeout)\n\t\t\treturn\n\t\tdefault:\n\t\t\ttime.Sleep(time.Millisecond)\n\t\t}\n\t}\n}", "func setupGovKeeper(t *testing.T, expectations ...func(sdk.Context, mocks)) (\n\t*keeper.Keeper,\n\tmocks,\n\tmoduletestutil.TestEncodingConfig,\n\tsdk.Context,\n) {\n\tt.Helper()\n\tkey := storetypes.NewKVStoreKey(types.StoreKey)\n\tstoreService := runtime.NewKVStoreService(key)\n\ttestCtx := testutil.DefaultContextWithDB(t, key, storetypes.NewTransientStoreKey(\"transient_test\"))\n\tctx := testCtx.Ctx.WithBlockHeader(cmtproto.Header{Time: cmttime.Now()})\n\tencCfg := moduletestutil.MakeTestEncodingConfig()\n\tv1.RegisterInterfaces(encCfg.InterfaceRegistry)\n\tv1beta1.RegisterInterfaces(encCfg.InterfaceRegistry)\n\tbanktypes.RegisterInterfaces(encCfg.InterfaceRegistry)\n\n\t// Create MsgServiceRouter, but don't populate it before creating the gov\n\t// keeper.\n\tmsr := baseapp.NewMsgServiceRouter()\n\n\t// gomock initializations\n\tctrl := gomock.NewController(t)\n\tm := mocks{\n\t\tacctKeeper: govtestutil.NewMockAccountKeeper(ctrl),\n\t\tbankKeeper: govtestutil.NewMockBankKeeper(ctrl),\n\t\tstakingKeeper: govtestutil.NewMockStakingKeeper(ctrl),\n\t\tdistributionKeeper: govtestutil.NewMockDistributionKeeper(ctrl),\n\t}\n\tif len(expectations) == 0 {\n\t\tmockDefaultExpectations(ctx, m)\n\t} else {\n\t\tfor _, exp := range expectations {\n\t\t\texp(ctx, m)\n\t\t}\n\t}\n\n\t// Gov keeper initializations\n\n\tgovKeeper := keeper.NewKeeper(encCfg.Codec, storeService, m.acctKeeper, m.bankKeeper, m.stakingKeeper, m.distributionKeeper, msr, types.DefaultConfig(), govAcct.String())\n\trequire.NoError(t, govKeeper.ProposalID.Set(ctx, 1))\n\tgovRouter := v1beta1.NewRouter() // Also register legacy gov handlers to test them too.\n\tgovRouter.AddRoute(types.RouterKey, v1beta1.ProposalHandler)\n\tgovKeeper.SetLegacyRouter(govRouter)\n\terr := govKeeper.Params.Set(ctx, v1.DefaultParams())\n\trequire.NoError(t, err)\n\terr = govKeeper.Constitution.Set(ctx, \"constitution\")\n\trequire.NoError(t, err)\n\n\t// Register all handlers for the MegServiceRouter.\n\tmsr.SetInterfaceRegistry(encCfg.InterfaceRegistry)\n\tv1.RegisterMsgServer(msr, keeper.NewMsgServerImpl(govKeeper))\n\tbanktypes.RegisterMsgServer(msr, nil) // Nil is fine here as long as we never execute the proposal's Msgs.\n\n\treturn govKeeper, m, encCfg, ctx\n}", "func (m *mCryptographyServiceMockVerify) Expect(p crypto.PublicKey, p1 insolar.Signature, p2 []byte) *mCryptographyServiceMockVerify {\n\tm.mock.VerifyFunc = nil\n\tm.expectationSeries = nil\n\n\tif m.mainExpectation == nil {\n\t\tm.mainExpectation = &CryptographyServiceMockVerifyExpectation{}\n\t}\n\tm.mainExpectation.input = &CryptographyServiceMockVerifyInput{p, p1, p2}\n\treturn m\n}", "func TestMissingSigningKey(t *testing.T) {\n\tf, _ := createNewSwizzler(t)\n\n\t// delete the snapshot, timestamp, and root keys\n\tnoKeys := []data.RoleName{\n\t\tdata.CanonicalSnapshotRole, data.CanonicalTimestampRole, data.CanonicalRootRole}\n\tfor _, role := range noKeys {\n\t\tk := f.CryptoService.ListKeys(role)\n\t\trequire.Len(t, k, 1)\n\t\trequire.NoError(t, f.CryptoService.RemoveKey(k[0]))\n\t}\n\n\t// these are all the functions that require re-signing\n\trequire.IsType(t, ErrNoKeyForRole{}, f.OffsetMetadataVersion(data.CanonicalSnapshotRole, 1))\n\trequire.IsType(t, ErrNoKeyForRole{}, f.ExpireMetadata(data.CanonicalSnapshotRole))\n\trequire.IsType(t, ErrNoKeyForRole{}, f.SetThreshold(data.CanonicalSnapshotRole, 2))\n\trequire.IsType(t, ErrNoKeyForRole{}, f.UpdateSnapshotHashes())\n\trequire.IsType(t, ErrNoKeyForRole{}, f.UpdateTimestampHash())\n}", "func (mr *MockProvidersMockRecorder) SigningManager() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"SigningManager\", reflect.TypeOf((*MockProviders)(nil).SigningManager))\n}", "func TestRootFromSignedCopiesSignatures(t *testing.T) {\n\tsigned, err := validRootTemplate().ToSigned()\n\trequire.NoError(t, err)\n\n\tsignedRoot, err := RootFromSigned(signed)\n\trequire.NoError(t, err)\n\n\tsigned.Signatures[0] = Signature{KeyID: \"key3\", Method: \"method3\", Signature: []byte(\"world\")}\n\n\trequire.Equal(t, \"key3\", signed.Signatures[0].KeyID)\n\trequire.Equal(t, \"key1\", signedRoot.Signatures[0].KeyID)\n}", "func (mt *mockTokenBuilder) SetKeyService(keyService string) {\n\t//TODO some mocking\n}", "func GenTestsForVerify(f *os.File) {\n\titems := []*verifyItem{\n\t\t{Keys: 1, Message: \"\"},\n\t\t{Keys: 1, Message: \"idena go\"},\n\t\t{Keys: 1, Message: \"long message: 9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999\"},\n\t\t{Keys: 2, Message: \"2 keys 1\"},\n\t\t{Keys: 2, Message: \"2 keys 2\"},\n\t\t{Keys: 3, Message: \"3 keys\"},\n\t\t{Keys: 4, Message: \"4 keys\"},\n\t\t{Keys: 10, Message: \"10 keys\"},\n\t\t{Keys: 100, Message: \"100 keys\"},\n\t\t{Keys: 356, Message: \"356 keys\"},\n\t\t{Keys: 800, Message: \"800 keys\"},\n\t\t{Keys: 1024, Message: \"1024 keys\"},\n\t\t{Keys: 2048, Message: \"2048 keys\"},\n\t\t{Keys: 4000, Message: \"4000 keys\"},\n\t\t{Keys: 6000, Message: \"4000 keys\"},\n\t\t{Keys: 9000, Message: \"9000 keys\"},\n\t\t{Keys: 10000, Message: \"10000 keys\"},\n\t}\n\tpriKeys := make([]*bls.PriKey, 0)\n\tpubKeys1 := make([]*bls.PubKey1, 0)\n\tpubKeys2 := make([]*bls.PubKey2, 0)\n\tfor i, item := range items {\n\t\tfmt.Printf(\"generating %v: keys=%v, message=%v\\n\", i+1, item.Keys, item.Message)\n\t\t// prepare keys\n\t\tfor i := len(priKeys); i < item.Keys; i++ {\n\t\t\tk, _ := bls.NewPriKey(nil)\n\t\t\tpriKeys = append(priKeys, k)\n\t\t\tpubKeys1, pubKeys2 = append(pubKeys1, k.GetPub1()), append(pubKeys2, k.GetPub2())\n\t\t}\n\t\tsigs := make([]*bls.Signature, item.Keys)\n\t\tfor i := 0; i < item.Keys; i++ {\n\t\t\tsigs[i] = priKeys[i].Sign([]byte(item.Message))\n\t\t}\n\t\tasig := bls.AggregateSignatures(sigs)\n\t\titem.Signature = asig.ToHex()\n\t\tapk1 := bls.AggregatePubKeys1(pubKeys1[:item.Keys])\n\t\titem.Apk1 = apk1.ToHex()\n\t\tapk2 := bls.AggregatePubKeys2(pubKeys2[:item.Keys])\n\t\titem.Apk2 = apk2.ToHex()\n\t}\n\ts, _ := json.MarshalIndent(items, \"\", \" \")\n\t_, _ = f.Write(s)\n\tfmt.Printf(\"\\n> Data has written to %v\\n\", f.Name())\n}", "func (m *MockisCryptoAsymApiReqSetupPrivateKeyEx_Key) isCryptoAsymApiReqSetupPrivateKeyEx_Key() {\n\tm.ctrl.Call(m, \"isCryptoAsymApiReqSetupPrivateKeyEx_Key\")\n}", "func (m *mSignatureKeyHolderMockGetSignatureKeyMethod) Expect() *mSignatureKeyHolderMockGetSignatureKeyMethod {\n\tm.mock.GetSignatureKeyMethodFunc = nil\n\tm.expectationSeries = nil\n\n\tif m.mainExpectation == nil {\n\t\tm.mainExpectation = &SignatureKeyHolderMockGetSignatureKeyMethodExpectation{}\n\t}\n\n\treturn m\n}", "func TestSlashValidatorAtCurrentHeightWithSlashingProtection(t *testing.T) {\n\t// use disr types module name to withdraw the reward without errors and\n\tmoduleDelegatorName := distrtypes.ModuleName\n\n\tapp, ctx, _, _ := bootstrapSlashTest(t, 10)\n\tapp.StakingKeeper.SetSlashingProtestedModules(func() map[string]struct{} {\n\t\treturn map[string]struct{}{\n\t\t\tmoduleDelegatorName: {},\n\t\t}\n\t})\n\tapp.StakingKeeper.SetHooks(types.NewMultiStakingHooks(app.DistrKeeper.Hooks()))\n\n\tvalBondTokens := app.StakingKeeper.TokensFromConsensusPower(ctx, 10)\n\tvalReward := app.StakingKeeper.TokensFromConsensusPower(ctx, 1).ToDec()\n\tdelBondTokens := app.StakingKeeper.TokensFromConsensusPower(ctx, 2)\n\tdelProtectedBondTokens := app.StakingKeeper.TokensFromConsensusPower(ctx, 4)\n\tdelProtectedExpectedReward := app.StakingKeeper.TokensFromConsensusPower(ctx, 875).QuoRaw(1000) // 0.875\n\ttotalDelegation := valBondTokens.Add(delBondTokens).Add(delProtectedBondTokens)\n\n\tfraction := sdk.NewDecWithPrec(5, 1)\n\n\t// generate delegator account\n\tdelAddr := simapp.AddTestAddrs(app, ctx, 1, delBondTokens)[0]\n\t// generate protected delegator account\n\terr := app.BankKeeper.SendCoinsFromAccountToModule(ctx, simapp.AddTestAddrs(app, ctx, 1, delProtectedBondTokens)[0],\n\t\tmoduleDelegatorName, sdk.NewCoins(sdk.NewCoin(app.StakingKeeper.BondDenom(ctx), delProtectedBondTokens)))\n\trequire.NoError(t, err)\n\tdelProtectedAddr := app.AccountKeeper.GetModuleAddress(moduleDelegatorName)\n\n\t// get already created validator\n\tvaConsAddr := sdk.ConsAddress(PKs[0].Address())\n\t// delegate from normal account\n\tval, found := app.StakingKeeper.GetValidatorByConsAddr(ctx, vaConsAddr)\n\trequire.True(t, found)\n\t// call this function here to init the validator in the distribution module\n\tapp.StakingKeeper.AfterValidatorCreated(ctx, val.GetOperator())\n\n\t// delegate from normal account\n\tdelShares := delegate(t, app, ctx, vaConsAddr, delAddr, delBondTokens)\n\t// delegate from protected account\n\tdelegate(t, app, ctx, vaConsAddr, delProtectedAddr, delProtectedBondTokens)\n\n\t// capture the current bond state\n\tbondedPool := app.StakingKeeper.GetBondedPool(ctx)\n\toldBondedPoolBalances := app.BankKeeper.GetAllBalances(ctx, bondedPool.GetAddress())\n\t// end block\n\tapplyValidatorSetUpdates(t, ctx, app.StakingKeeper, 1)\n\n\t// mint coins for the distr module\n\trequire.NoError(t, app.BankKeeper.MintCoins(ctx, minttypes.ModuleName, sdk.NewCoins(sdk.NewCoin(app.StakingKeeper.BondDenom(ctx), valReward.TruncateInt()))))\n\trequire.NoError(t, app.BankKeeper.SendCoinsFromModuleToModule(ctx, minttypes.ModuleName, distrtypes.ModuleName, sdk.NewCoins(sdk.NewCoin(app.StakingKeeper.BondDenom(ctx), valReward.TruncateInt()))))\n\t// add reward to the validator to withdraw by the protected module\n\tapp.DistrKeeper.AllocateTokensToValidator(ctx, val, sdk.NewDecCoins(sdk.NewDecCoinFromDec(app.StakingKeeper.BondDenom(ctx), valReward)))\n\n\t// get current power\n\tpower := app.StakingKeeper.GetLastValidatorPower(ctx, val.GetOperator())\n\trequire.Equal(t, app.StakingKeeper.TokensToConsensusPower(ctx, totalDelegation), power)\n\n\t// increase the block number to be able to get the reward\n\tctx = app.BaseApp.NewContext(false, tmproto.Header{Height: app.LastBlockHeight() + 1})\n\t// now slash based on the current power\n\tapp.StakingKeeper.Slash(ctx, vaConsAddr, ctx.BlockHeight(), power, fraction)\n\t// end block\n\tapplyValidatorSetUpdates(t, ctx, app.StakingKeeper, 1)\n\n\t// read updated test\n\tval, found = app.StakingKeeper.GetValidator(ctx, val.GetOperator())\n\tassert.True(t, found)\n\t// power decreased, the protected delegation was remove from the calculation\n\t// since the module is protected from the slashing\n\texpectedPower := app.StakingKeeper.TokensToConsensusPower(ctx,\n\t\ttotalDelegation.Sub(delProtectedBondTokens).\n\t\t\tToDec().Mul(fraction).TruncateInt())\n\tpower = val.GetConsensusPower(app.StakingKeeper.PowerReduction(ctx))\n\trequire.Equal(t, expectedPower, power)\n\n\t// pool bonded shares decreased\n\tnewBondedPoolBalances := app.BankKeeper.GetAllBalances(ctx, bondedPool.GetAddress())\n\tdiffTokens := oldBondedPoolBalances.Sub(newBondedPoolBalances).AmountOf(app.StakingKeeper.BondDenom(ctx))\n\trequire.Equal(t, totalDelegation.Sub(delProtectedBondTokens).ToDec().Mul(fraction).TruncateInt().\n\t\t// add undelegated tokens\n\t\tAdd(delProtectedBondTokens).String(), diffTokens.String())\n\n\t// check the delegation slashing\n\tunbondDelegationAmount, err := app.StakingKeeper.Unbond(ctx, delAddr, val.GetOperator(), delShares)\n\tassert.NoError(t, err)\n\t// the amount 50% less because of the slashing\n\tassert.Equal(t, delBondTokens.ToDec().Mul(fraction).TruncateInt(), unbondDelegationAmount)\n\n\t// check that protected module has no delegation now\n\t_, found = app.StakingKeeper.GetDelegation(ctx, delProtectedAddr, val.GetOperator())\n\tassert.False(t, found)\n\n\tdelProtectedBalance := app.BankKeeper.GetAllBalances(ctx, delProtectedAddr)\n\tassert.Equal(t, sdk.NewCoins(sdk.NewCoin(app.StakingKeeper.BondDenom(ctx), delProtectedBondTokens.Add(delProtectedExpectedReward))), delProtectedBalance)\n}", "func TestHandleNewValidator(t *testing.T) {\n\tapp := simapp.Setup(false)\n\tctx := app.BaseApp.NewContext(false, tmproto.Header{})\n\n\taddrDels := simapp.AddTestAddrsIncremental(app, ctx, 1, sdk.TokensFromConsensusPower(200, sdk.DefaultPowerReduction))\n\tvalAddrs := simapp.ConvertAddrsToValAddrs(addrDels)\n\tpks := simapp.CreateTestPubKeys(1)\n\taddr, val := valAddrs[0], pks[0]\n\ttstaking := teststaking.NewHelper(t, ctx, app.CustomStakingKeeper, app.CustomGovKeeper)\n\tctx = ctx.WithBlockHeight(1)\n\n\t// Validator created\n\ttstaking.CreateValidator(addr, val, true)\n\n\tstaking.EndBlocker(ctx, app.CustomStakingKeeper)\n\n\t// Now a validator, for two blocks\n\tapp.CustomSlashingKeeper.HandleValidatorSignature(ctx, val.Address(), 100, true)\n\tctx = ctx.WithBlockHeight(2)\n\tapp.CustomSlashingKeeper.HandleValidatorSignature(ctx, val.Address(), 100, false)\n\n\tinfo, found := app.CustomSlashingKeeper.GetValidatorSigningInfo(ctx, sdk.ConsAddress(val.Address()))\n\trequire.True(t, found)\n\trequire.Equal(t, int64(1), info.StartHeight)\n\trequire.Equal(t, int64(1), info.MischanceConfidence)\n\trequire.Equal(t, int64(0), info.Mischance)\n\trequire.Equal(t, int64(1), info.MissedBlocksCounter)\n\trequire.Equal(t, int64(1), info.ProducedBlocksCounter)\n\trequire.Equal(t, time.Unix(0, 0).UTC(), info.InactiveUntil)\n\n\t// validator should be active still, should not have been inactivated\n\tvalidator, _ := app.CustomStakingKeeper.GetValidatorByConsAddr(ctx, sdk.GetConsAddress(val))\n\trequire.Equal(t, stakingtypes.Active, validator.GetStatus())\n}", "func (m *DigestHolderMock) MinimockSignWithInspect() {\n\tfor _, e := range m.SignWithMock.expectations {\n\t\tif mm_atomic.LoadUint64(&e.Counter) < 1 {\n\t\t\tm.t.Errorf(\"Expected call to DigestHolderMock.SignWith with params: %#v\", *e.params)\n\t\t}\n\t}\n\n\t// if default expectation was set then invocations count should be greater than zero\n\tif m.SignWithMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterSignWithCounter) < 1 {\n\t\tif m.SignWithMock.defaultExpectation.params == nil {\n\t\t\tm.t.Error(\"Expected call to DigestHolderMock.SignWith\")\n\t\t} else {\n\t\t\tm.t.Errorf(\"Expected call to DigestHolderMock.SignWith with params: %#v\", *m.SignWithMock.defaultExpectation.params)\n\t\t}\n\t}\n\t// if func was set then invocations count should be greater than zero\n\tif m.funcSignWith != nil && mm_atomic.LoadUint64(&m.afterSignWithCounter) < 1 {\n\t\tm.t.Error(\"Expected call to DigestHolderMock.SignWith\")\n\t}\n}", "func MockSealProof(proofType abi.RegisteredSealProof, minerAddr address.Address) ([]byte, error) {\n\tplen, err := proofType.ProofSize()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tproof := make([]byte, plen)\n\ti := copy(proof, mockSealProofPrefix)\n\tbinary.BigEndian.PutUint64(proof[i:], uint64(proofType))\n\ti += 8\n\ti += copy(proof[i:], minerAddr.Bytes())\n\treturn proof, nil\n}", "func (m *MockKeystore) EXPECT() *MockKeystoreMockRecorder {\n\treturn m.recorder\n}", "func (m *MockKeystore) EXPECT() *MockKeystoreMockRecorder {\n\treturn m.recorder\n}", "func TestSyncCredentials(t *testing.T) {\n\tkey, err := goRSA.GenerateKey(rand.Reader, 2048)\n\tassert.NoError(t, err)\n\n\texpSigner, err := ssh.NewSignerFromKey(key)\n\tassert.NoError(t, err)\n\n\texpHost := \"8.8.8.8\"\n\tmockFs := afero.NewMemMapFs()\n\n\tgetSftpFs = func(host string, signer ssh.Signer) (sftpFs, error) {\n\t\tassert.Equal(t, expSigner, signer)\n\t\tassert.Equal(t, expHost, host)\n\t\treturn mockSFTPFs{mockFs}, nil\n\t}\n\n\tca, err := rsa.NewCertificateAuthority()\n\tassert.NoError(t, err)\n\n\tcredentialedMachines := map[string]struct{}{}\n\tsyncCredentialsOnce(expSigner, ca,\n\t\t[]db.Machine{{PublicIP: expHost, PrivateIP: \"9.9.9.9\"}},\n\t\tcredentialedMachines)\n\tassert.Len(t, credentialedMachines, 1)\n\n\taferoFs := afero.Afero{Fs: mockFs}\n\tcertBytes, err := aferoFs.ReadFile(filepath.Join(tlsIO.MinionTLSDir, \"quilt.crt\"))\n\tassert.NoError(t, err)\n\tassert.NotEmpty(t, certBytes)\n\n\tkeyBytes, err := aferoFs.ReadFile(filepath.Join(tlsIO.MinionTLSDir, \"quilt.key\"))\n\tassert.NoError(t, err)\n\tassert.NotEmpty(t, keyBytes)\n\n\tcaBytes, err := aferoFs.ReadFile(filepath.Join(tlsIO.MinionTLSDir,\n\t\t\"certificate_authority.crt\"))\n\tassert.NoError(t, err)\n\tassert.NotEmpty(t, caBytes)\n}", "func (m *CryptographyServiceMock) CheckMocksCalled() {\n\tm.Finish()\n}" ]
[ "0.6785916", "0.6281368", "0.61853397", "0.61265033", "0.6016525", "0.592078", "0.5888198", "0.5882686", "0.5746892", "0.5725966", "0.56851", "0.56679803", "0.5576283", "0.55425304", "0.54525506", "0.5445765", "0.5445765", "0.5444539", "0.5439745", "0.54370964", "0.5416044", "0.5414758", "0.54021543", "0.53748715", "0.5361519", "0.5332156", "0.53113747", "0.5296614", "0.5296607", "0.52906865", "0.528123", "0.52753794", "0.5260811", "0.52595", "0.52483714", "0.52471966", "0.5243438", "0.5238439", "0.5238411", "0.5235445", "0.5224488", "0.52185446", "0.5201778", "0.5193008", "0.51921415", "0.5190983", "0.51889974", "0.51864594", "0.51774186", "0.5175045", "0.5138169", "0.51270604", "0.51108676", "0.5109353", "0.5101822", "0.5072238", "0.5055519", "0.50538194", "0.5028797", "0.50222147", "0.5013571", "0.5010214", "0.50079125", "0.50047827", "0.5001866", "0.50007087", "0.49935657", "0.498166", "0.49810144", "0.49773052", "0.49662858", "0.49645585", "0.49630088", "0.49540702", "0.49445885", "0.4942568", "0.4937983", "0.49365988", "0.4935299", "0.49265346", "0.49224478", "0.49170843", "0.4905023", "0.49048933", "0.4900649", "0.4899051", "0.48983788", "0.48980942", "0.4886465", "0.48814878", "0.488088", "0.48799878", "0.4876407", "0.48762742", "0.48745525", "0.48732942", "0.48638487", "0.48638487", "0.48583442", "0.48579228" ]
0.6744976
1
SigningManager indicates an expected call of SigningManager
func (mr *MockClientMockRecorder) SigningManager() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SigningManager", reflect.TypeOf((*MockClient)(nil).SigningManager)) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (mr *MockProvidersMockRecorder) SigningManager() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"SigningManager\", reflect.TypeOf((*MockProviders)(nil).SigningManager))\n}", "func (pc *MockProviderContext) SigningManager() fab.SigningManager {\n\treturn pc.signingManager\n}", "func (m *MetricsProvider) SignerSign(value time.Duration) {\n}", "func (c *Provider) SigningManager() core.SigningManager {\n\treturn c.signingManager\n}", "func TestSignContractFailure(t *testing.T) {\n\tsignatureHelper(t, true)\n}", "func (m *DigestHolderMock) MinimockSignWithDone() bool {\n\tfor _, e := range m.SignWithMock.expectations {\n\t\tif mm_atomic.LoadUint64(&e.Counter) < 1 {\n\t\t\treturn false\n\t\t}\n\t}\n\n\t// if default expectation was set then invocations count should be greater than zero\n\tif m.SignWithMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterSignWithCounter) < 1 {\n\t\treturn false\n\t}\n\t// if func was set then invocations count should be greater than zero\n\tif m.funcSignWith != nil && mm_atomic.LoadUint64(&m.afterSignWithCounter) < 1 {\n\t\treturn false\n\t}\n\treturn true\n}", "func TestSignContractSuccess(t *testing.T) {\n\tsignatureHelper(t, false)\n}", "func TestVerifySignedMessage(t *testing.T) {\n\tfor _, tc := range []struct {\n\t\tdesc string\n\t\tsettings *crypt.PkiSettings\n\t\tsetup func(mdb *mocks.MockDepsBundle, setupDone *bool) error\n\t\tmessageToSign string\n\t\tbase64Signature string\n\t\tPEMPublicKey string\n\t\texpectedError *testtools.ErrorSpec\n\t\texpectedValidity bool\n\t}{\n\t\t{\n\t\t\tdesc: \"invalid base64 signature\",\n\t\t\tsettings: &crypt.PkiSettings{\n\t\t\t\tAlgorithm: x509.ECDSA,\n\t\t\t\tPrivateKeyPath: \".prog/ecdsa_priv.key\",\n\t\t\t\tPublicKeyPath: \".prog/ecdsa.pub\",\n\t\t\t},\n\t\t\tsetup: func(mdb *mocks.MockDepsBundle, setupDone *bool) error {\n\t\t\t\treturn nil\n\t\t\t},\n\t\t\tmessageToSign: \"some other message\",\n\t\t\tbase64Signature: \"@#$^&*()_\",\n\t\t\tPEMPublicKey: \"\",\n\t\t\texpectedError: &testtools.ErrorSpec{\n\t\t\t\tType: \"base64.CorruptInputError\",\n\t\t\t\tMessage: \"illegal base64 data at input byte 0\",\n\t\t\t},\n\t\t\texpectedValidity: false,\n\t\t},\n\t\t{\n\t\t\tdesc: \"empty PEM key\",\n\t\t\tsettings: &crypt.PkiSettings{\n\t\t\t\tAlgorithm: x509.ECDSA,\n\t\t\t\tPrivateKeyPath: \".prog/ecdsa_priv.key\",\n\t\t\t\tPublicKeyPath: \".prog/ecdsa.pub\",\n\t\t\t},\n\t\t\tsetup: func(mdb *mocks.MockDepsBundle, setupDone *bool) error {\n\t\t\t\treturn nil\n\t\t\t},\n\t\t\tmessageToSign: \"some other message\",\n\t\t\tbase64Signature: \"abcdefgh\",\n\t\t\tPEMPublicKey: \"\",\n\t\t\texpectedError: &testtools.ErrorSpec{\n\t\t\t\tType: \"*errors.errorString\",\n\t\t\t\tMessage: \"No PEM data was found\",\n\t\t\t},\n\t\t\texpectedValidity: false,\n\t\t},\n\t\t{\n\t\t\tdesc: \"bad key data\",\n\t\t\tsettings: &crypt.PkiSettings{\n\t\t\t\tAlgorithm: x509.ECDSA,\n\t\t\t\tPrivateKeyPath: \".prog/ecdsa_priv.key\",\n\t\t\t\tPublicKeyPath: \".prog/ecdsa.pub\",\n\t\t\t},\n\t\t\tsetup: func(mdb *mocks.MockDepsBundle, setupDone *bool) error {\n\t\t\t\treturn nil\n\t\t\t},\n\t\t\tmessageToSign: \"some other message\",\n\t\t\tbase64Signature: \"abcdefgh\",\n\t\t\tPEMPublicKey: \"-----BEGIN INVALID DATA-----\\n\" +\n\t\t\t\t\"MTIzNDU2Nzg5MGFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6\\n\" +\n\t\t\t\t\"-----END INVALID DATA-----\\n\",\n\t\t\texpectedError: &testtools.ErrorSpec{\n\t\t\t\tType: \"asn1.StructuralError\",\n\t\t\t\tMessage: \"asn1: structure \" +\n\t\t\t\t\t\"error: tags don't match (16 vs {class:0 \" +\n\t\t\t\t\t\"tag:17 \" +\n\t\t\t\t\t\"length:50 \" +\n\t\t\t\t\t\"isCompound:true}) {optional:false \" +\n\t\t\t\t\t\"explicit:false \" +\n\t\t\t\t\t\"application:false \" +\n\t\t\t\t\t\"defaultValue:<nil> \" +\n\t\t\t\t\t\"tag:<nil> \" +\n\t\t\t\t\t\"stringType:0 \" +\n\t\t\t\t\t\"timeType:0 \" +\n\t\t\t\t\t\"set:false \" +\n\t\t\t\t\t\"omitEmpty:false} publicKeyInfo @2\",\n\t\t\t},\n\t\t\texpectedValidity: false,\n\t\t},\n\t\t{\n\t\t\tdesc: \"invalid signature\",\n\t\t\tsettings: &crypt.PkiSettings{\n\t\t\t\tAlgorithm: x509.ECDSA,\n\t\t\t\tPrivateKeyPath: \".prog/ecdsa_priv.key\",\n\t\t\t\tPublicKeyPath: \".prog/ecdsa.pub\",\n\t\t\t},\n\t\t\tsetup: func(mdb *mocks.MockDepsBundle, setupDone *bool) error {\n\t\t\t\treturn nil\n\t\t\t},\n\t\t\tmessageToSign: \"some other message\",\n\t\t\tbase64Signature: \"abcdefgh\",\n\t\t\tPEMPublicKey: \"-----BEGIN ECDSA PUBLIC KEY-----\\n\" +\n\t\t\t\t\"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE7WzVjtn9Gk+WHr5xbv8XMvooqU25\\n\" +\n\t\t\t\t\"BhgNjZ/vHZLBdVtCOjk4KxjS1UBfQm0c3TRxWBl3hj2AmnJbCrnGofMHBQ==\\n\" +\n\t\t\t\t\"-----END ECDSA PUBLIC KEY-----\\n\",\n\t\t\texpectedError: &testtools.ErrorSpec{\n\t\t\t\tType: \"asn1.SyntaxError\",\n\t\t\t\tMessage: \"asn1: syntax error: truncated tag or length\",\n\t\t\t},\n\t\t\texpectedValidity: false,\n\t\t},\n\t\t{\n\t\t\tdesc: \"ecdsa key for rsa mode\",\n\t\t\tsettings: &crypt.PkiSettings{\n\t\t\t\tAlgorithm: x509.RSA,\n\t\t\t\tPrivateKeyPath: \".prog/ecdsa_priv.key\",\n\t\t\t\tPublicKeyPath: \".prog/ecdsa.pub\",\n\t\t\t},\n\t\t\tsetup: func(mdb *mocks.MockDepsBundle, setupDone *bool) error {\n\t\t\t\treturn nil\n\t\t\t},\n\t\t\tmessageToSign: \"some other message\",\n\t\t\tbase64Signature: \"N3SuIdWI7XlXDteTmcOZUd2OBacyUWY+/+A8SC4QUBz9rXnldBqXha6YyGwnTuizxuy6quQ2QDFdtW16dj7EQk3lozfngskyhc2r86q3AUbdFDvrQVphMQhzsgBhHVoMjCL/YRfvtzCTWhBxegjVMLraLDCBb8IZTIqcMYafYyeJTvAnjBuntlZ+14TDuTt14Uqz85T04CXxBEqlIXMMKpTc01ST4Jsxz5HLO+At1htXp5eHOUFtQSilm3G7iO8ynhgPcXHDWfMAWu6VySUoHWCG70pJaCq6ehF7223t0UFOCqAyDyyQyP9yeUHj8F75SPSxfJm8iKXGx2LND/qLYw==\",\n\t\t\tPEMPublicKey: \"-----BEGIN RSA PUBLIC KEY-----\\n\" +\n\t\t\t\t\"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE7WzVjtn9Gk+WHr5xbv8XMvooqU25\\n\" +\n\t\t\t\t\"BhgNjZ/vHZLBdVtCOjk4KxjS1UBfQm0c3TRxWBl3hj2AmnJbCrnGofMHBQ==\\n\" +\n\t\t\t\t\"-----END RSA PUBLIC KEY-----\\n\",\n\t\t\texpectedError: &testtools.ErrorSpec{\n\t\t\t\tType: \"*errors.errorString\",\n\t\t\t\tMessage: \"Expecting a *rsa.PublicKey, but encountered a *ecdsa.PublicKey instead\",\n\t\t\t},\n\t\t\texpectedValidity: false,\n\t\t},\n\t\t{\n\t\t\tdesc: \"rsa key for ecdsa mode\",\n\t\t\tsettings: &crypt.PkiSettings{\n\t\t\t\tAlgorithm: x509.ECDSA,\n\t\t\t\tPrivateKeyPath: \".prog/ecdsa_priv.key\",\n\t\t\t\tPublicKeyPath: \".prog/ecdsa.pub\",\n\t\t\t},\n\t\t\tsetup: func(mdb *mocks.MockDepsBundle, setupDone *bool) error {\n\t\t\t\treturn nil\n\t\t\t},\n\t\t\tmessageToSign: \"some other message\",\n\t\t\tbase64Signature: \"MEYCIQDPM0fc/PFauoZzpltH3RpWtlaqRnL0gFk5WFiLMrFqrwIhAIDvlBozU6Ky2UC9xOSq3YZ5iFuO356t9RnHOElaaXFJ\",\n\t\t\tPEMPublicKey: \"-----BEGIN RSA PUBLIC KEY-----\\n\" +\n\t\t\t\t\"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAzCTTFKQBHfTN8jW6q8PT\\n\" +\n\t\t\t\t\"HNZKWnRPxSt9kpgWmyqFaZnEUipgoKGAxSIsVrl2PJSm5OlgkVzx+MY+LWM64VKM\\n\" +\n\t\t\t\t\"bRpUUGJR3zdMNhwZQX0hjOpLpVJvUwD78utVs8vijrU7sH48usFiaZQYjy4m4hQh\\n\" +\n\t\t\t\t\"63/x4h3KVz7YqUnlRMzYJFT43+AwYzYuEpzWRxtW7IObJPtjtmYVoqva98fF6aj5\\n\" +\n\t\t\t\t\"uHAsvaAgZGBalHXmCiPzKiGU/halzXSPvyJ2Cqz2aUqMHgwi/2Ip4z/mrfX+mUTa\\n\" +\n\t\t\t\t\"S+LyBy7GgqJ5vbkGArMagJIc0eARF60r6Uf483xh17oniABdLJy4qlLf6PcEU+ut\\n\" +\n\t\t\t\t\"EwIDAQAB\\n\" +\n\t\t\t\t\"-----END RSA PUBLIC KEY-----\\n\",\n\t\t\texpectedError: &testtools.ErrorSpec{\n\t\t\t\tType: \"*errors.errorString\",\n\t\t\t\tMessage: \"Expecting a *ecdsa.PublicKey, but encountered a *rsa.PublicKey instead\",\n\t\t\t},\n\t\t\texpectedValidity: false,\n\t\t},\n\t} {\n\t\tt.Run(fmt.Sprintf(\"Subtest: %s\", tc.desc), func(tt *testing.T) {\n\t\t\tmockDepsBundle := mocks.NewDefaultMockDeps(\"\", []string{\"progname\"}, \"/home/user\", nil)\n\t\t\treturnedNormally := false\n\t\t\tvar tooling *crypt.CryptoTooling\n\t\t\tvar actualErr error\n\t\t\tvar actualValidity bool\n\t\t\terr := mockDepsBundle.InvokeCallInMockedEnv(func() error {\n\t\t\t\tsetupComplete := false\n\t\t\t\tinnerErr := tc.setup(mockDepsBundle, &setupComplete)\n\t\t\t\tif innerErr != nil {\n\t\t\t\t\treturn innerErr\n\t\t\t\t}\n\t\t\t\tvar toolingErr error\n\t\t\t\ttooling, toolingErr = crypt.GetCryptoTooling(mockDepsBundle.Deps, tc.settings)\n\t\t\t\tif toolingErr != nil {\n\t\t\t\t\treturn toolingErr\n\t\t\t\t}\n\t\t\t\tsetupComplete = true\n\t\t\t\tactualValidity, actualErr = tooling.VerifySignedMessage(tc.messageToSign, tc.base64Signature, tc.PEMPublicKey)\n\t\t\t\treturnedNormally = true\n\t\t\t\treturn nil\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\ttt.Errorf(\"Unexpected error calling mockDepsBundle.InvokeCallInMockedEnv(): %s\", err.Error())\n\t\t\t}\n\t\t\tif exitStatus := mockDepsBundle.GetExitStatus(); (exitStatus != 0) || !returnedNormally {\n\t\t\t\ttt.Error(\"EncodeAndSaveKey() should not have paniced or called os.Exit.\")\n\t\t\t}\n\t\t\tif (mockDepsBundle.OutBuf.String() != \"\") || (mockDepsBundle.ErrBuf.String() != \"\") {\n\t\t\t\ttt.Errorf(\"EncodeAndSaveKey() should not have output any data. Saw stdout:\\n%s\\nstderr:\\n%s\", mockDepsBundle.OutBuf.String(), mockDepsBundle.ErrBuf.String())\n\t\t\t}\n\t\t\tif err := tc.expectedError.EnsureMatches(actualErr); err != nil {\n\t\t\t\ttt.Error(err.Error())\n\t\t\t}\n\t\t\tif tc.expectedError == nil {\n\t\t\t\tif actualValidity != tc.expectedValidity {\n\t\t\t\t\ttt.Errorf(\"Signature is %#v when %#v expected\", actualValidity, tc.expectedValidity)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif tc.expectedValidity {\n\t\t\t\t\ttt.Error(\"TEST CASE INVALID. Should not expect \\\"valid\\\".\")\n\t\t\t\t}\n\t\t\t\tif actualValidity {\n\t\t\t\t\ttt.Error(\"Error was expected. Should not report \\\"valid\\\".\")\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n}", "func (validator *validatorImpl) Sign(msg []byte) ([]byte, error) {\n\treturn validator.signWithEnrollmentKey(msg)\n}", "func (mr *MockMachineMockRecorder) SignerKey() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"SignerKey\", reflect.TypeOf((*MockMachine)(nil).SignerKey))\n}", "func TestSenderRequest_Sign(t *testing.T) {\r\n\r\n\t// Create key\r\n\tkey, err := bitcoin.CreatePrivateKeyString()\r\n\tassert.NoError(t, err)\r\n\tassert.NotNil(t, key)\r\n\r\n\t// Create the request / message\r\n\tsenderRequest := &SenderRequest{\r\n\t\tDt: time.Now().UTC().Format(time.RFC3339),\r\n\t\tSenderHandle: testAlias + \"@\" + testDomain,\r\n\t\tSenderName: testName,\r\n\t\tPurpose: testMessage,\r\n\t}\r\n\r\n\tvar signature string\r\n\r\n\tt.Run(\"invalid key - empty\", func(t *testing.T) {\r\n\t\tsignature, err = senderRequest.Sign(\"\")\r\n\t\tassert.Error(t, err)\r\n\t\tassert.Equal(t, len(signature), 0)\r\n\t})\r\n\r\n\tt.Run(\"invalid key - 0\", func(t *testing.T) {\r\n\t\tsignature, err = senderRequest.Sign(\"0\")\r\n\t\tassert.Error(t, err)\r\n\t\tassert.Equal(t, len(signature), 0)\r\n\t})\r\n\r\n\tt.Run(\"invalid dt\", func(t *testing.T) {\r\n\t\tsenderRequest.Dt = \"\"\r\n\t\tsignature, err = senderRequest.Sign(key)\r\n\t\tassert.Error(t, err)\r\n\t\tassert.Equal(t, len(signature), 0)\r\n\t})\r\n\r\n\tt.Run(\"invalid sender handle\", func(t *testing.T) {\r\n\t\tsenderRequest.Dt = time.Now().UTC().Format(time.RFC3339)\r\n\t\tsenderRequest.SenderHandle = \"\"\r\n\t\tsignature, err = senderRequest.Sign(key)\r\n\t\tassert.Error(t, err)\r\n\t\tassert.Equal(t, len(signature), 0)\r\n\t})\r\n\r\n\tt.Run(\"valid signature\", func(t *testing.T) {\r\n\t\tsenderRequest.SenderHandle = testAlias + \"@\" + testDomain\r\n\t\tsignature, err = senderRequest.Sign(key)\r\n\t\tassert.NoError(t, err)\r\n\t\tassert.NotEqual(t, len(signature), 0)\r\n\r\n\t\t// Get address for verification\r\n\t\tvar address string\r\n\t\taddress, err = bitcoin.GetAddressFromPrivateKeyString(key, false)\r\n\t\tassert.NoError(t, err)\r\n\r\n\t\t// Verify the signature\r\n\t\terr = senderRequest.Verify(address, signature)\r\n\t\tassert.NoError(t, err)\r\n\t})\r\n}", "func (m *MockProviders) SigningManager() core.SigningManager {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"SigningManager\")\n\tret0, _ := ret[0].(core.SigningManager)\n\treturn ret0\n}", "func (m *MockClient) SigningManager() core.SigningManager {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"SigningManager\")\n\tret0, _ := ret[0].(core.SigningManager)\n\treturn ret0\n}", "func (uv *UtxoVM) verifySignatures(tx *pb.Transaction, digestHash []byte) (bool, map[string]bool, error) {\n\t// XuperSign is not empty, use XuperSign verify\n\tif tx.GetXuperSign() != nil {\n\t\treturn uv.verifyXuperSign(tx, digestHash)\n\t}\n\n\t// Not XuperSign(multisig/rignsign etc.), use old signature process\n\tverifiedAddr := make(map[string]bool)\n\tif len(tx.InitiatorSigns) < 1 || len(tx.AuthRequire) != len(tx.AuthRequireSigns) {\n\t\treturn false, nil, errors.New(\"invalid signature param\")\n\t}\n\n\t// verify initiator\n\takType := acl.IsAccount(tx.Initiator)\n\tif akType == 0 {\n\t\t// check initiator address signature\n\t\tok, err := pm.IdentifyAK(tx.Initiator, tx.InitiatorSigns[0], digestHash)\n\t\tif err != nil || !ok {\n\t\t\tuv.xlog.Warn(\"verifySignatures failed\", \"address\", tx.Initiator, \"error\", err)\n\t\t\treturn false, nil, err\n\t\t}\n\t\tverifiedAddr[tx.Initiator] = true\n\t} else if akType == 1 {\n\t\tinitiatorAddr := make([]string, 0)\n\t\t// check initiator account signatures\n\t\tfor _, sign := range tx.InitiatorSigns {\n\t\t\tak, err := uv.cryptoClient.GetEcdsaPublicKeyFromJSON([]byte(sign.PublicKey))\n\t\t\tif err != nil {\n\t\t\t\tuv.xlog.Warn(\"verifySignatures failed\", \"address\", tx.Initiator, \"error\", err)\n\t\t\t\treturn false, nil, err\n\t\t\t}\n\t\t\taddr, err := uv.cryptoClient.GetAddressFromPublicKey(ak)\n\t\t\tif err != nil {\n\t\t\t\tuv.xlog.Warn(\"verifySignatures failed\", \"address\", tx.Initiator, \"error\", err)\n\t\t\t\treturn false, nil, err\n\t\t\t}\n\t\t\tok, err := pm.IdentifyAK(addr, sign, digestHash)\n\t\t\tif !ok {\n\t\t\t\tuv.xlog.Warn(\"verifySignatures failed\", \"address\", tx.Initiator, \"error\", err)\n\t\t\t\treturn ok, nil, err\n\t\t\t}\n\t\t\tverifiedAddr[addr] = true\n\t\t\tinitiatorAddr = append(initiatorAddr, tx.Initiator+\"/\"+addr)\n\t\t}\n\t\tok, err := pm.IdentifyAccount(tx.Initiator, initiatorAddr, uv.aclMgr)\n\t\tif !ok {\n\t\t\tuv.xlog.Warn(\"verifySignatures initiator permission check failed\",\n\t\t\t\t\"account\", tx.Initiator, \"error\", err)\n\t\t\treturn false, nil, err\n\t\t}\n\t} else {\n\t\tuv.xlog.Warn(\"verifySignatures failed, invalid address\", \"address\", tx.Initiator)\n\t\treturn false, nil, ErrInvalidSignature\n\t}\n\n\t// verify authRequire\n\tfor idx, authReq := range tx.AuthRequire {\n\t\tsplitRes := strings.Split(authReq, \"/\")\n\t\taddr := splitRes[len(splitRes)-1]\n\t\tsignInfo := tx.AuthRequireSigns[idx]\n\t\tif _, has := verifiedAddr[addr]; has {\n\t\t\tcontinue\n\t\t}\n\t\tok, err := pm.IdentifyAK(addr, signInfo, digestHash)\n\t\tif err != nil || !ok {\n\t\t\tuv.xlog.Warn(\"verifySignatures failed\", \"address\", addr, \"error\", err)\n\t\t\treturn false, nil, err\n\t\t}\n\t\tverifiedAddr[addr] = true\n\t}\n\treturn true, verifiedAddr, nil\n}", "func TestMissingSigningKey(t *testing.T) {\n\tf, _ := createNewSwizzler(t)\n\n\t// delete the snapshot, timestamp, and root keys\n\tnoKeys := []data.RoleName{\n\t\tdata.CanonicalSnapshotRole, data.CanonicalTimestampRole, data.CanonicalRootRole}\n\tfor _, role := range noKeys {\n\t\tk := f.CryptoService.ListKeys(role)\n\t\trequire.Len(t, k, 1)\n\t\trequire.NoError(t, f.CryptoService.RemoveKey(k[0]))\n\t}\n\n\t// these are all the functions that require re-signing\n\trequire.IsType(t, ErrNoKeyForRole{}, f.OffsetMetadataVersion(data.CanonicalSnapshotRole, 1))\n\trequire.IsType(t, ErrNoKeyForRole{}, f.ExpireMetadata(data.CanonicalSnapshotRole))\n\trequire.IsType(t, ErrNoKeyForRole{}, f.SetThreshold(data.CanonicalSnapshotRole, 2))\n\trequire.IsType(t, ErrNoKeyForRole{}, f.UpdateSnapshotHashes())\n\trequire.IsType(t, ErrNoKeyForRole{}, f.UpdateTimestampHash())\n}", "func (mr *MockClientMockRecorder) Sign(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Sign\", reflect.TypeOf((*MockClient)(nil).Sign), arg0)\n}", "func (m *imageProcessor) checkSignature(e *kevent.Kevent) {\n\tchecksum := e.Kparams.MustGetUint32(kparams.ImageCheckSum)\n\tsign, ok := m.signatures[checksum]\n\tif !ok {\n\t\tfilename := e.GetParamAsString(kparams.FileName)\n\t\tsign = signature.Check(filename)\n\t\tif sign == nil {\n\t\t\treturn\n\t\t}\n\t\tif sign.IsSigned() {\n\t\t\tsign.Verify()\n\t\t}\n\t\tm.signatures[checksum] = sign\n\t}\n\tif sign != nil {\n\t\t_ = e.Kparams.SetValue(kparams.ImageSignatureType, sign.Type)\n\t\t_ = e.Kparams.SetValue(kparams.ImageSignatureLevel, sign.Level)\n\t}\n}", "func (m *DeviceHealthAttestationState) SetTestSigning(value *string)() {\n err := m.GetBackingStore().Set(\"testSigning\", value)\n if err != nil {\n panic(err)\n }\n}", "func Sign(ctx context.Context, txf Factory, name string, txBuilder client.TxBuilder, overwriteSig bool) error {\n\tif txf.keybase == nil {\n\t\treturn errors.New(\"keybase must be set prior to signing a transaction\")\n\t}\n\n\tvar err error\n\tsignMode := txf.signMode\n\tif signMode == signing.SignMode_SIGN_MODE_UNSPECIFIED {\n\t\t// use the SignModeHandler's default mode if unspecified\n\t\tsignMode, err = authsigning.APISignModeToInternal(txf.txConfig.SignModeHandler().DefaultMode())\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tk, err := txf.keybase.Key(name)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tpubKey, err := k.GetPubKey()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsignerData := authsigning.SignerData{\n\t\tChainID: txf.chainID,\n\t\tAccountNumber: txf.accountNumber,\n\t\tSequence: txf.sequence,\n\t\tPubKey: pubKey,\n\t\tAddress: sdk.AccAddress(pubKey.Address()).String(),\n\t}\n\n\t// For SIGN_MODE_DIRECT, calling SetSignatures calls setSignerInfos on\n\t// TxBuilder under the hood, and SignerInfos is needed to generated the\n\t// sign bytes. This is the reason for setting SetSignatures here, with a\n\t// nil signature.\n\t//\n\t// Note: this line is not needed for SIGN_MODE_LEGACY_AMINO, but putting it\n\t// also doesn't affect its generated sign bytes, so for code's simplicity\n\t// sake, we put it here.\n\tsigData := signing.SingleSignatureData{\n\t\tSignMode: signMode,\n\t\tSignature: nil,\n\t}\n\tsig := signing.SignatureV2{\n\t\tPubKey: pubKey,\n\t\tData: &sigData,\n\t\tSequence: txf.Sequence(),\n\t}\n\n\tvar prevSignatures []signing.SignatureV2\n\tif !overwriteSig {\n\t\tprevSignatures, err = txBuilder.GetTx().GetSignaturesV2()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\t// Overwrite or append signer infos.\n\tvar sigs []signing.SignatureV2\n\tif overwriteSig {\n\t\tsigs = []signing.SignatureV2{sig}\n\t} else {\n\t\tsigs = append(sigs, prevSignatures...)\n\t\tsigs = append(sigs, sig)\n\t}\n\tif err := txBuilder.SetSignatures(sigs...); err != nil {\n\t\treturn err\n\t}\n\n\tif err := checkMultipleSigners(txBuilder.GetTx()); err != nil {\n\t\treturn err\n\t}\n\n\tbytesToSign, err := authsigning.GetSignBytesAdapter(\n\t\tctx, txf.txConfig.SignModeHandler(),\n\t\tsignMode, signerData, txBuilder.GetTx())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Sign those bytes\n\tsigBytes, _, err := txf.keybase.Sign(name, bytesToSign, signMode)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Construct the SignatureV2 struct\n\tsigData = signing.SingleSignatureData{\n\t\tSignMode: signMode,\n\t\tSignature: sigBytes,\n\t}\n\tsig = signing.SignatureV2{\n\t\tPubKey: pubKey,\n\t\tData: &sigData,\n\t\tSequence: txf.Sequence(),\n\t}\n\n\tif overwriteSig {\n\t\terr = txBuilder.SetSignatures(sig)\n\t} else {\n\t\tprevSignatures = append(prevSignatures, sig)\n\t\terr = txBuilder.SetSignatures(prevSignatures...)\n\t}\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to set signatures on payload: %w\", err)\n\t}\n\n\t// Run optional preprocessing if specified. By default, this is unset\n\t// and will return nil.\n\treturn txf.PreprocessTx(name, txBuilder)\n}", "func (m *CryptographyServiceMock) Sign(p []byte) (r *insolar.Signature, r1 error) {\n\tcounter := atomic.AddUint64(&m.SignPreCounter, 1)\n\tdefer atomic.AddUint64(&m.SignCounter, 1)\n\n\tif len(m.SignMock.expectationSeries) > 0 {\n\t\tif counter > uint64(len(m.SignMock.expectationSeries)) {\n\t\t\tm.t.Fatalf(\"Unexpected call to CryptographyServiceMock.Sign. %v\", p)\n\t\t\treturn\n\t\t}\n\n\t\tinput := m.SignMock.expectationSeries[counter-1].input\n\t\ttestify_assert.Equal(m.t, *input, CryptographyServiceMockSignInput{p}, \"CryptographyService.Sign got unexpected parameters\")\n\n\t\tresult := m.SignMock.expectationSeries[counter-1].result\n\t\tif result == nil {\n\t\t\tm.t.Fatal(\"No results are set for the CryptographyServiceMock.Sign\")\n\t\t\treturn\n\t\t}\n\n\t\tr = result.r\n\t\tr1 = result.r1\n\n\t\treturn\n\t}\n\n\tif m.SignMock.mainExpectation != nil {\n\n\t\tinput := m.SignMock.mainExpectation.input\n\t\tif input != nil {\n\t\t\ttestify_assert.Equal(m.t, *input, CryptographyServiceMockSignInput{p}, \"CryptographyService.Sign got unexpected parameters\")\n\t\t}\n\n\t\tresult := m.SignMock.mainExpectation.result\n\t\tif result == nil {\n\t\t\tm.t.Fatal(\"No results are set for the CryptographyServiceMock.Sign\")\n\t\t}\n\n\t\tr = result.r\n\t\tr1 = result.r1\n\n\t\treturn\n\t}\n\n\tif m.SignFunc == nil {\n\t\tm.t.Fatalf(\"Unexpected call to CryptographyServiceMock.Sign. %v\", p)\n\t\treturn\n\t}\n\n\treturn m.SignFunc(p)\n}", "func (mr *MockTransactionApiMockRecorder) VerifySign(tx, outpoint, amount, txinUtxoList interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"VerifySign\", reflect.TypeOf((*MockTransactionApi)(nil).VerifySign), tx, outpoint, amount, txinUtxoList)\n}", "func (s *ServiceSuite) TestMacaroonPaperFig6FailsWithBindingOnTamperedSignature(c *gc.C) {\n\tlocator := bakery.NewThirdPartyStore()\n\tas := newBakery(\"as-loc\", locator)\n\tts := newBakery(\"ts-loc\", locator)\n\tfs := newBakery(\"fs-loc\", locator)\n\n\t// ts creates a macaroon.\n\ttsMacaroon, err := ts.Oven.NewMacaroon(testContext, bakery.LatestVersion, ages, nil, bakery.LoginOp)\n\tc.Assert(err, gc.IsNil)\n\n\t// ts somehow sends the macaroon to fs which adds a third party caveat to be discharged by as.\n\terr = fs.Oven.AddCaveat(testContext, tsMacaroon, checkers.Caveat{Location: \"as-loc\", Condition: \"user==bob\"})\n\tc.Assert(err, gc.IsNil)\n\n\t// client asks for a discharge macaroon for each third party caveat\n\td, err := bakery.DischargeAll(testContext, tsMacaroon, func(ctx context.Context, cav macaroon.Caveat, payload []byte) (*bakery.Macaroon, error) {\n\t\tc.Assert(cav.Location, gc.Equals, \"as-loc\")\n\t\treturn discharge(ctx, as.Oven, thirdPartyStrcmpChecker(\"user==bob\"), cav, payload)\n\t})\n\tc.Assert(err, gc.IsNil)\n\n\t// client has all the discharge macaroons. For each discharge macaroon bind it to our tsMacaroon\n\t// and add it to our request.\n\tfor _, dm := range d[1:] {\n\t\tdm.Bind([]byte(\"tampered-signature\")) // Bind against an incorrect signature.\n\t}\n\n\t// client makes request to ts.\n\t_, err = ts.Checker.Auth(d).Allow(testContext, bakery.LoginOp)\n\t// TODO fix this error message.\n\tc.Assert(err, gc.ErrorMatches, \"verification failed: signature mismatch after caveat verification\")\n}", "func (t *SuiteSuite) VerifyMethodsWrongSignatureSkipped1(x int) {\n\tt.Fatalf(\"This should never run.\")\n}", "func (mr *MockSignerMockRecorder) Sign(arg0, arg1 interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Sign\", reflect.TypeOf((*MockSigner)(nil).Sign), arg0, arg1)\n}", "func (m *DigestHolderMock) MinimockSignWithInspect() {\n\tfor _, e := range m.SignWithMock.expectations {\n\t\tif mm_atomic.LoadUint64(&e.Counter) < 1 {\n\t\t\tm.t.Errorf(\"Expected call to DigestHolderMock.SignWith with params: %#v\", *e.params)\n\t\t}\n\t}\n\n\t// if default expectation was set then invocations count should be greater than zero\n\tif m.SignWithMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterSignWithCounter) < 1 {\n\t\tif m.SignWithMock.defaultExpectation.params == nil {\n\t\t\tm.t.Error(\"Expected call to DigestHolderMock.SignWith\")\n\t\t} else {\n\t\t\tm.t.Errorf(\"Expected call to DigestHolderMock.SignWith with params: %#v\", *m.SignWithMock.defaultExpectation.params)\n\t\t}\n\t}\n\t// if func was set then invocations count should be greater than zero\n\tif m.funcSignWith != nil && mm_atomic.LoadUint64(&m.afterSignWithCounter) < 1 {\n\t\tm.t.Error(\"Expected call to DigestHolderMock.SignWith\")\n\t}\n}", "func TestSign(w http.ResponseWriter, r *http.Request) {\n\tconf := ConfLoad()\n\n\t// Returns a Public / Private Key Pair\n\t// Read JSON config from app.yaml\n\tif v := os.Getenv(\"PRIV_KEY\"); v != \"\" {\n\t\terr := json.Unmarshal([]byte(v), &conf)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"%#v\", conf)\n\t\t\tpanic(err)\n\t\t}\n\t}\n\n\t// Get the public key\n\tvar pubkey ecdsa.PublicKey\n\tpubkey = conf.PublicKey\n\n\t// Try signing a message\n\tmessage := []byte(\"99999999\")\n\tsig1, sig2, err := ecdsa.Sign(rand.Reader, &conf.PrivateKey, message)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// Try verifying the signature\n\tresult := ecdsa.Verify(&pubkey, message, sig1, sig2)\n\tif result != true {\n\t\tpanic(\"Unable to verify signature\")\n\t}\n\n\tfmt.Fprintf(w, \"message: %#v\\n\\nsig1: %#v\\nsig2: %#v\", string(message[:]), sig1, sig2)\n\n}", "func (m *CryptographyServiceMock) SignFinished() bool {\n\t// if expectation series were set then invocations count should be equal to expectations count\n\tif len(m.SignMock.expectationSeries) > 0 {\n\t\treturn atomic.LoadUint64(&m.SignCounter) == uint64(len(m.SignMock.expectationSeries))\n\t}\n\n\t// if main expectation was set then invocations count should be greater than zero\n\tif m.SignMock.mainExpectation != nil {\n\t\treturn atomic.LoadUint64(&m.SignCounter) > 0\n\t}\n\n\t// if func was set then invocations count should be greater than zero\n\tif m.SignFunc != nil {\n\t\treturn atomic.LoadUint64(&m.SignCounter) > 0\n\t}\n\n\treturn true\n}", "func verifySignatures(sectionSender sectionWithSigSender) bool {\n\tsection := sectionSender.Section\n\tkeysNeeded := make(map[rainslib.SignatureMetaData]bool)\n\tsection.NeededKeys(keysNeeded)\n\tpublicKeys, missingKeys, ok := publicKeysPresent(section.GetSubjectZone(), section.GetContext(), keysNeeded)\n\tif ok {\n\t\tlog.Info(\"All public keys are present.\", \"msgSectionWithSig\", section)\n\t\taddZoneAndContextToContainedSections(section)\n\t\treturn validSignature(section, publicKeys)\n\t}\n\thandleMissingKeys(sectionSender, missingKeys)\n\treturn false\n}", "func (fs fakeService) Signature(ctx *context.T, call rpc.ServerCall) ([]signature.Interface, error) {\n\tctx.Infof(\"Fake Service Signature???\")\n\treturn nil, nil\n}", "func (m EncMessage) Sign(k []byte) error {\n\treturn errors.New(\"Sign method must be overridden\")\n}", "func (_RandomBeacon *RandomBeaconTransactor) ReportUnauthorizedSigning(opts *bind.TransactOpts, signedMsgSender []byte, groupId uint64, groupMembers []uint32) (*types.Transaction, error) {\n\treturn _RandomBeacon.contract.Transact(opts, \"reportUnauthorizedSigning\", signedMsgSender, groupId, groupMembers)\n}", "func TestSignature(t *testing.T) {\n\tt.Parallel()\n\n\ttree := writeTree(t, `\n-- go.mod --\nmodule example.com\ngo 1.18\n\n-- a.go --\npackage a\nimport \"fmt\"\nfunc f() {\n\tfmt.Println(123)\n}\n`)\n\t// no arguments\n\t{\n\t\tres := gopls(t, tree, \"signature\")\n\t\tres.checkExit(false)\n\t\tres.checkStderr(\"expects 1 argument\")\n\t}\n\t// at 123 inside fmt.Println() call\n\t{\n\t\tres := gopls(t, tree, \"signature\", \"a.go:4:15\")\n\t\tres.checkExit(true)\n\t\tres.checkStdout(\"Println\\\\(a ...\")\n\t\tres.checkStdout(\"Println formats using the default formats...\")\n\t}\n}", "func (mmSignWith *mDigestHolderMockSignWith) When(signer DigestSigner) *DigestHolderMockSignWithExpectation {\n\tif mmSignWith.mock.funcSignWith != nil {\n\t\tmmSignWith.mock.t.Fatalf(\"DigestHolderMock.SignWith mock is already set by Set\")\n\t}\n\n\texpectation := &DigestHolderMockSignWithExpectation{\n\t\tmock: mmSignWith.mock,\n\t\tparams: &DigestHolderMockSignWithParams{signer},\n\t}\n\tmmSignWith.expectations = append(mmSignWith.expectations, expectation)\n\treturn expectation\n}", "func signatureHelper(t *testing.T, failure bool) {\n\t// Setup\n\tstop, clients, contractPath, contractFilePath := setupSignature(t)\n\tdefer stop()\n\n\tstopBefore, expectedProofFile1, expectedProofFile2 := \"1\", 0, 0\n\tif !failure {\n\t\tstopBefore, expectedProofFile1, expectedProofFile2 = \"2\", 2, 1\n\t}\n\n\t// Configure client3 to be faulty\n\tsetLastArg(clients[2], \"--stopbefore\", true)\n\tsetLastArg(clients[2], stopBefore, false)\n\tsetLastArg(clients[2], \"sign\", false)\n\n\t// Sign!\n\tcloseChannel := make(chan []byte, 3)\n\tfor i := 0; i < 3; i++ {\n\t\tsetLastArg(clients[i], \"sign\", true)\n\t\tsetLastArg(clients[i], contractPath, false)\n\t\tgo func(c *exec.Cmd, i int) {\n\t\t\tc.Stdin = strings.NewReader(contractFilePath + \"\\npassword\\nyes\\n\")\n\t\t\tc.Stderr = bufio.NewWriter(os.Stdout)\n\t\t\toutput, _ := c.Output()\n\t\t\tcloseChannel <- output\n\t\t}(clients[i], i)\n\t}\n\n\tfor i := 0; i < 3; i++ {\n\t\t// TODO check stderr?\n\t\t<-closeChannel\n\t}\n\n\tcheckProofFile(t, expectedProofFile1)\n\tfilename := checkRecoverFile(t, \"client3@example.com\")\n\tcallRecover(newClient(clients[2]), filename)\n\t_ = os.Remove(filename)\n\tcheckProofFile(t, expectedProofFile2)\n\n\ttime.Sleep(time.Second)\n\treturn\n}", "func (s *BaseLittleDuckListener) EnterFactor_sign(ctx *Factor_signContext) {}", "func TestValidateRootRotationMissingNewSig(t *testing.T) {\n\ttestValidateRootRotationMissingNewSig(t, data.ECDSAKey, data.ECDSAx509Key)\n\tif !testing.Short() {\n\t\ttestValidateRootRotationMissingNewSig(t, data.RSAKey, data.RSAx509Key)\n\t}\n}", "func (k *KeyRing) verifySignature(signer string, signee *Key, signature *Signature) error {\n\tmessage := append(signee.Public, byte(signature.Trust))\n\tif !k.cryptoEngine.Verify(k.keys[signer].Public, message, signature.Data) {\n\t\treturn ErrInvalidSignature\n\t}\n\treturn nil\n}", "func (a *Ali) Verify(publicKey, sign []byte, req *NotifyReq) error {\n\tp, _ := pem.Decode(publicKey)\n\tif p == nil {\n\t\tpanic(\"Public key broken!\")\n\t}\n\tpub, err := x509.ParsePKIXPublicKey(p.Bytes)\n\tif err != nil {\n\t\treturn err\n\t}\n\th := crypto.Hash.New(crypto.SHA1)\n\tm := apikit.Params(structs.Map(req))\n\tb := sortedParams(removeKeys(m, \"sign\", \"sign_type\"))\n\th.Write(removeQuote(b.Bytes()))\n\tsum := h.Sum(nil)\n\tif sign, err = base64.StdEncoding.DecodeString(string(sign)); err != nil {\n\t\treturn err\n\t}\n\treturn rsa.VerifyPKCS1v15(pub.(*rsa.PublicKey), crypto.SHA1, sum, sign)\n}", "func (mr *MockSignerDecrypterMockRecorder) Sign(arg0, arg1, arg2 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Sign\", reflect.TypeOf((*MockSignerDecrypter)(nil).Sign), arg0, arg1, arg2)\n}", "func (f *Factory) Sign(name string, txBuilder sdk.TxBuilder) error {\n\tsignMode := f.signMode\n\tif signMode == signing.SignMode_SIGN_MODE_UNSPECIFIED {\n\t\t// use the SignModeHandler's default mode if unspecified\n\t\tsignMode = f.txConfig.SignModeHandler().DefaultMode()\n\t}\n\tsignerData := sdk.SignerData{\n\t\tChainID: f.chainID,\n\t\tAccountNumber: f.accountNumber,\n\t\tSequence: f.sequence,\n\t}\n\n\tpubkey, _, err := f.keyManager.Find(name, f.password)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// For SIGN_MODE_DIRECT, calling SetSignatures calls setSignerInfos on\n\t// Factory under the hood, and SignerInfos is needed to generated the\n\t// sign bytes. This is the reason for setting SetSignatures here, with a\n\t// nil signature.\n\t//\n\t// Note: this line is not needed for SIGN_MODE_LEGACY_AMINO, but putting it\n\t// also doesn't affect its generated sign bytes, so for code's simplicity\n\t// sake, we put it here.\n\tsigData := signing.SingleSignatureData{\n\t\tSignMode: signMode,\n\t\tSignature: nil,\n\t}\n\tsig := signing.SignatureV2{\n\t\tPubKey: pubkey,\n\t\tData: &sigData,\n\t\tSequence: f.Sequence(),\n\t}\n\tif err := txBuilder.SetSignatures(sig); err != nil {\n\t\treturn err\n\t}\n\n\t// Generate the bytes to be signed.\n\tsignBytes, err := f.signModeHandler.GetSignBytes(signMode, signerData, txBuilder.GetTx())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Sign those bytes\n\tsigBytes, _, err := f.keyManager.Sign(name, f.password, signBytes)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Construct the SignatureV2 struct\n\tsigData = signing.SingleSignatureData{\n\t\tSignMode: signMode,\n\t\tSignature: sigBytes,\n\t}\n\tsig = signing.SignatureV2{\n\t\tPubKey: pubkey,\n\t\tData: &sigData,\n\t\tSequence: f.Sequence(),\n\t}\n\n\t// And here the tx is populated with the signature\n\treturn txBuilder.SetSignatures(sig)\n}", "func Test_CanSign_NoUnspentTransactionMatches(t *testing.T) {\n\n\t// prepare input\n\tvar transactionInput *TransactionInput = &TransactionInput{\n\t\tOutputID: \"outID\",\n\t\tOutputIndex: 10,\n\t}\n\tvar unspentTransactions = []*UnspentTransactionOutput{\n\t\t{\n\t\t\tOutputID: \"outID1\",\n\t\t\tOutputIndex: 100,\n\t\t\tAddress: \"addressX\",\n\t\t},\n\t}\n\tvar publicKey = \"public_key\"\n\n\t// call can sign\n\tresult := CanSign(unspentTransactions, transactionInput, publicKey)\n\n\t// result should false\n\tif result {\n\t\tt.Errorf(\"when no unspent transaction matches the result should be false\")\n\t}\n}", "func (s *Service) Sign(ctx context.Context, credentials *checker.Credentials, accountName string, pubKey []byte, data *ruler.SignData) (core.RulesResult, []byte) {\n\tspan, ctx := opentracing.StartSpanFromContext(ctx, \"service.signer.Sign\")\n\tdefer span.Finish()\n\tlog := log.With().Str(\"action\", \"Sign\").Logger()\n\tlog.Debug().Msg(\"Request received\")\n\n\tif data == nil {\n\t\treturn core.DENIED, nil\n\t}\n\twallet, account, checkRes := s.preCheck(ctx, credentials, accountName, pubKey, ruler.ActionSign)\n\tif checkRes != core.APPROVED {\n\t\treturn checkRes, nil\n\t}\n\taccountName = fmt.Sprintf(\"%s/%s\", wallet.Name(), account.Name())\n\tlog = log.With().Str(\"account\", accountName).Logger()\n\n\t// Confirm approval via rules.\n\tresult := s.ruler.RunRules(ctx, ruler.ActionSign, wallet.Name(), account.Name(), account.PublicKey().Marshal(), data)\n\tswitch result {\n\tcase core.DENIED:\n\t\tlog.Debug().Str(\"result\", \"denied\").Msg(\"Denied by rules\")\n\t\treturn core.DENIED, nil\n\tcase core.FAILED:\n\t\tlog.Warn().Str(\"result\", \"failed\").Msg(\"Rules check failed\")\n\t\treturn core.FAILED, nil\n\t}\n\n\t// Sign it.\n\tsigningRoot, err := generateSigningRootFromRoot(ctx, data.Data, data.Domain)\n\tif err != nil {\n\t\tlog.Warn().Err(err).Str(\"result\", \"failed\").Msg(\"Failed to generate signing root\")\n\t\treturn core.FAILED, nil\n\t}\n\tspan, _ = opentracing.StartSpanFromContext(ctx, \"service.signer.Sign/Sign\")\n\tsignature, err := account.Sign(signingRoot[:])\n\tif err != nil {\n\t\tlog.Warn().Err(err).Str(\"result\", \"failed\").Msg(\"Failed to sign\")\n\t\tspan.Finish()\n\t\treturn core.FAILED, nil\n\t}\n\tspan.Finish()\n\n\tlog.Debug().Str(\"result\", \"succeeded\").Msg(\"Success\")\n\treturn core.APPROVED, signature.Marshal()\n}", "func (t *SuiteSuite) VerifyMethodsWrongSignatureSkipped2() int {\n\tt.Fatalf(\"This should never run.\")\n\treturn 0\n}", "func (c CryptoServiceTester) TestSignNoMatchingKeys(t *testing.T) {\n\tcryptoService := c.cryptoServiceFactory()\n\n\tprivKey, err := utils.GenerateECDSAKey(rand.Reader)\n\trequire.NoError(t, err, c.errorMsg(\"error creating key\"))\n\n\t// Test Sign\n\t_, _, err = cryptoService.GetPrivateKey(privKey.ID())\n\trequire.Error(t, err, c.errorMsg(\"Should not have found private key\"))\n}", "func TmSign(publicKey PublicKey, privateKey PrivateKey, digest Digest) Seal { panic(\"\") }", "func (k Keeper) handleValidatorSignature(ctx sdk.Context, addr crypto.Address, power int64, signed bool) {\n\tlogger := ctx.Logger().With(\"module\", \"x/slashing\")\n\theight := ctx.BlockHeight()\n\taddress := sdk.ValAddress(addr)\n\tpubkey, err := k.getPubkey(ctx, addr)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"Validator address %v not found\", addr))\n\t}\n\t// Local index, so counts blocks validator *should* have signed\n\t// Will use the 0-value default signing info if not present, except for start height\n\tsignInfo, found := k.getValidatorSigningInfo(ctx, address)\n\tif !found {\n\t\t// If this validator has never been seen before, construct a new SigningInfo with the correct start height\n\t\tsignInfo = NewValidatorSigningInfo(height, 0, time.Unix(0, 0), 0)\n\t}\n\tindex := signInfo.IndexOffset % k.SignedBlocksWindow(ctx)\n\tsignInfo.IndexOffset++\n\n\t// Update signed block bit array & counter\n\t// This counter just tracks the sum of the bit array\n\t// That way we avoid needing to read/write the whole array each time\n\tprevious := k.getValidatorSigningBitArray(ctx, address, index)\n\tif previous == signed {\n\t\t// Array value at this index has not changed, no need to update counter\n\t} else if previous && !signed {\n\t\t// Array value has changed from signed to unsigned, decrement counter\n\t\tk.setValidatorSigningBitArray(ctx, address, index, false)\n\t\tsignInfo.SignedBlocksCounter--\n\t} else if !previous && signed {\n\t\t// Array value has changed from unsigned to signed, increment counter\n\t\tk.setValidatorSigningBitArray(ctx, address, index, true)\n\t\tsignInfo.SignedBlocksCounter++\n\t}\n\n\tif !signed {\n\t\tlogger.Info(fmt.Sprintf(\"Absent validator %s at height %d, %d signed, threshold %d\", addr, height, signInfo.SignedBlocksCounter, k.MinSignedPerWindow(ctx)))\n\t}\n\tminHeight := signInfo.StartHeight + k.SignedBlocksWindow(ctx)\n\tif height > minHeight && signInfo.SignedBlocksCounter < k.MinSignedPerWindow(ctx) {\n\t\tvalidator := k.validatorSet.ValidatorByPubKey(ctx, pubkey)\n\t\tif validator != nil && !validator.GetRevoked() {\n\t\t\t// Downtime confirmed, slash, revoke, and jail the validator\n\t\t\tlogger.Info(fmt.Sprintf(\"Validator %s past min height of %d and below signed blocks threshold of %d\",\n\t\t\t\tpubkey.Address(), minHeight, k.MinSignedPerWindow(ctx)))\n\t\t\tk.validatorSet.Slash(ctx, pubkey, height, power, k.SlashFractionDowntime(ctx))\n\t\t\tk.validatorSet.Revoke(ctx, pubkey)\n\t\t\tsignInfo.JailedUntil = ctx.BlockHeader().Time.Add(k.DowntimeUnbondDuration(ctx))\n\t\t} else {\n\t\t\t// Validator was (a) not found or (b) already revoked, don't slash\n\t\t\tlogger.Info(fmt.Sprintf(\"Validator %s would have been slashed for downtime, but was either not found in store or already revoked\",\n\t\t\t\tpubkey.Address()))\n\t\t}\n\t}\n\n\t// Set the updated signing info\n\tk.setValidatorSigningInfo(ctx, address, signInfo)\n}", "func (auth *AuthManager) Sign(signables ...msgjson.Signable) error {\n\tfor i, signable := range signables {\n\t\tsigMsg, err := signable.Serialize()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"signature message for signable index %d: %v\", i, err)\n\t\t}\n\t\tsig, err := auth.signer.Sign(sigMsg)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"signature error: %v\", err)\n\t\t}\n\t\tsignable.SetSig(sig.Serialize())\n\t}\n\treturn nil\n}", "func checkMultipleSigners(tx authsigning.Tx) error {\n\tdirectSigners := 0\n\tsigsV2, err := tx.GetSignaturesV2()\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, sig := range sigsV2 {\n\t\tdirectSigners += countDirectSigners(sig.Data)\n\t\tif directSigners > 1 {\n\t\t\treturn sdkerrors.ErrNotSupported.Wrap(\"txs signed with CLI can have maximum 1 DIRECT signer\")\n\t\t}\n\t}\n\n\treturn nil\n}", "func (m *MetricsProvider) WitnessVerifyVCTSignature(value time.Duration) {\n}", "func (m *SignatureKeyHolderMock) CheckMocksCalled() {\n\tm.Finish()\n}", "func verifyTransaction(inc *Transaction) {\n\tif verifySignature(inc) {\n\t\t\texecuteTransaction(inc)\n\t} else {\n\t\treturn\n\t}\n}", "func VerifySigningKeyInput(keyFile string, isPublic bool) string {\n\tkeyFile = verifySigningKeyInputHelper(keyFile, isPublic, false)\n\tif _, err := os.Stat(keyFile); os.IsNotExist(err) {\n\t\tkeyFile = verifySigningKeyInputHelper(keyFile, isPublic, true)\n\t\tif _, err := os.Stat(keyFile); os.IsNotExist(err) {\n\t\t\tFatal(CLI_GENERAL_ERROR, i18n.GetMessagePrinter().Sprintf(\"%v. Please create the signing key.\", err))\n\t\t}\n\t}\n\n\treturn keyFile\n}", "func (mr *MockSignerMockRecorder) Check(arg0, arg1, arg2 interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Check\", reflect.TypeOf((*MockSigner)(nil).Check), arg0, arg1, arg2)\n}", "func (_RandomBeacon *RandomBeaconTransactorSession) ReportUnauthorizedSigning(signedMsgSender []byte, groupId uint64, groupMembers []uint32) (*types.Transaction, error) {\n\treturn _RandomBeacon.Contract.ReportUnauthorizedSigning(&_RandomBeacon.TransactOpts, signedMsgSender, groupId, groupMembers)\n}", "func SignCheckDeliver(\n\tt *testing.T, cdc *codec.Codec, app *baseapp.BaseApp, header abci.Header, msgs []sdk.Msg,\n\taccNums, seq []uint64, expSimPass, expPass bool, priv ...crypto.PrivKey,\n) sdk.Result {\n\n\ttx := GenTx(msgs, accNums, seq, priv...)\n\n\ttxBytes, err := cdc.MarshalBinaryLengthPrefixed(tx)\n\trequire.Nil(t, err)\n\n\t// Must simulate now as CheckTx doesn't run Msgs anymore\n\tres := app.Simulate(txBytes, tx)\n\n\tif expSimPass {\n\t\trequire.Equal(t, sdk.CodeOK, res.Code, res.Log)\n\t} else {\n\t\trequire.NotEqual(t, sdk.CodeOK, res.Code, res.Log)\n\t}\n\n\t// Simulate a sending a transaction and committing a block\n\tapp.BeginBlock(abci.RequestBeginBlock{Header: header})\n\tres = app.Deliver(tx)\n\n\tif expPass {\n\t\trequire.Equal(t, sdk.CodeOK, res.Code, res.Log)\n\t} else {\n\t\trequire.NotEqual(t, sdk.CodeOK, res.Code, res.Log)\n\t}\n\n\tapp.EndBlock(abci.RequestEndBlock{})\n\tapp.Commit()\n\n\treturn res\n}", "func Test_CanSign_UnspentTransactionWrongAddress(t *testing.T) {\n\n\t// prepare input\n\tvar transactionInput *TransactionInput = &TransactionInput{\n\t\tOutputID: \"outID\",\n\t\tOutputIndex: 10,\n\t}\n\tvar unspentTransactions = []*UnspentTransactionOutput{\n\t\t{\n\t\t\tOutputID: \"outID\",\n\t\t\tOutputIndex: 10,\n\t\t\tAddress: \"addressX\",\n\t\t},\n\t}\n\tvar publicKey = \"public_key\"\n\n\t// call can sign\n\tresult := CanSign(unspentTransactions, transactionInput, publicKey)\n\n\t// result should false\n\tif result {\n\t\tt.Errorf(\"when unspent transaction address is not the same as public key the result should be false\")\n\t}\n}", "func Test_CanSign_Correct(t *testing.T) {\n\n\t// prepare input\n\tvar transactionInput *TransactionInput = &TransactionInput{\n\t\tOutputID: \"outID\",\n\t\tOutputIndex: 10,\n\t}\n\tvar unspentTransactions = []*UnspentTransactionOutput{\n\t\t{\n\t\t\tOutputID: \"outID-1\",\n\t\t\tOutputIndex: 1000,\n\t\t\tAddress: \"addressX\",\n\t\t},\n\t\t{\n\t\t\tOutputID: \"outID\",\n\t\t\tOutputIndex: 10,\n\t\t\tAddress: \"public_key\",\n\t\t},\n\t}\n\tvar publicKey = \"public_key\"\n\n\t// call can sign\n\tresult := CanSign(unspentTransactions, transactionInput, publicKey)\n\n\t// result should false\n\tif !result {\n\t\tt.Errorf(\"The result must be true when there is unspent transaction and adddress is the same the public key\")\n\t}\n}", "func TestSenderRequest_Verify(t *testing.T) {\r\n\r\n\t// Create key\r\n\tkey, err := bitcoin.CreatePrivateKeyString()\r\n\tassert.NoError(t, err)\r\n\tassert.NotNil(t, key)\r\n\r\n\t// Create the request / message\r\n\tsenderRequest := &SenderRequest{\r\n\t\tDt: time.Now().UTC().Format(time.RFC3339),\r\n\t\tSenderHandle: testAlias + \"@\" + testDomain,\r\n\t\tSenderName: testName,\r\n\t\tPurpose: testMessage,\r\n\t}\r\n\r\n\t// Sign\r\n\tvar signature string\r\n\tsignature, err = senderRequest.Sign(key)\r\n\tassert.NoError(t, err)\r\n\tassert.NotEqual(t, 0, len(signature))\r\n\r\n\t// Get address from private key\r\n\tvar address string\r\n\taddress, err = bitcoin.GetAddressFromPrivateKeyString(key, false)\r\n\tassert.NoError(t, err)\r\n\tassert.NotNil(t, address)\r\n\r\n\tt.Run(\"valid verification\", func(t *testing.T) {\r\n\t\terr = senderRequest.Verify(address, signature)\r\n\t\tassert.NoError(t, err)\r\n\t})\r\n\r\n\tt.Run(\"invalid - empty address\", func(t *testing.T) {\r\n\t\terr = senderRequest.Verify(\"\", signature)\r\n\t\tassert.Error(t, err)\r\n\t})\r\n\r\n\tt.Run(\"invalid - empty signature\", func(t *testing.T) {\r\n\t\terr = senderRequest.Verify(address, \"\")\r\n\t\tassert.Error(t, err)\r\n\t})\r\n\r\n\tt.Run(\"invalid - wrong signature - hex short\", func(t *testing.T) {\r\n\t\terr = senderRequest.Verify(address, \"0\")\r\n\t\tassert.Error(t, err)\r\n\t})\r\n\r\n\tt.Run(\"invalid - wrong signature\", func(t *testing.T) {\r\n\t\terr = senderRequest.Verify(address, \"73646661736466736466617364667364666173646673646661736466\")\r\n\t\tassert.Error(t, err)\r\n\t})\r\n}", "func (d *identityManager) Sign(message []byte) ([]byte, error) {\n\treturn Sign(d.key.PrivateKey, message)\n}", "func (_RandomBeacon *RandomBeaconSession) ReportUnauthorizedSigning(signedMsgSender []byte, groupId uint64, groupMembers []uint32) (*types.Transaction, error) {\n\treturn _RandomBeacon.Contract.ReportUnauthorizedSigning(&_RandomBeacon.TransactOpts, signedMsgSender, groupId, groupMembers)\n}", "func (ks *Keystore) CheckSignature(prefix string, signed, signature io.ReadSeeker) (*openpgp.Entity, error) {\n\treturn checkSignature(ks, prefix, signed, signature)\n}", "func verify(msgSender msgSectionSender) {\n\tlog.Info(fmt.Sprintf(\"Verify %T\", msgSender.Section), \"msgSection\", msgSender.Section)\n\tswitch msgSender.Section.(type) {\n\tcase *rainslib.AssertionSection, *rainslib.ShardSection, *rainslib.ZoneSection,\n\t\t*rainslib.AddressAssertionSection, *rainslib.AddressZoneSection:\n\t\tsectionSender := sectionWithSigSender{\n\t\t\tSection: msgSender.Section.(rainslib.MessageSectionWithSig),\n\t\t\tSender: msgSender.Sender,\n\t\t\tToken: msgSender.Token,\n\t\t}\n\t\tverifySection(sectionSender)\n\tcase *rainslib.AddressQuerySection, *rainslib.QuerySection:\n\t\tverifyQuery(msgSender.Section.(rainslib.MessageSectionQuery), msgSender)\n\tdefault:\n\t\tlog.Warn(\"Not supported Msg section to verify\", \"msgSection\", msgSender)\n\t}\n}", "func Test_VerifySigFromTass(t *testing.T) {\n\trequire := require.New(t)\n\n\t//c := &sm2.Driver{}\n\n\txBytes := common.FromHex(\"0000000000000000000000000000000000000000000000000000000000000000FD4241057FEC6CBEEC501F7E1763751B8F6DFCFB910FB634FBB76A16639EF172\")\n\tyBytes := common.FromHex(\"00000000000000000000000000000000000000000000000000000000000000001C6DA89F9C1A5EE9B6108E5A2A5FE336962630A34DBA1AF428451E1CE63BB3CF\")\n\tx := new(big.Int).SetBytes(xBytes)\n\ty := new(big.Int).SetBytes(yBytes)\n\n\tpublicKey := &gmsm_sm2.PublicKey{\n\t\tX: x,\n\t\tY: y,\n\t}\n\tvar pubSM2 sm2.PubKeySM2\n\tcopy(pubSM2[:], gmsm_sm2.Compress(publicKey))\n\n\trBytes := common.FromHex(\"00000000000000000000000000000000000000000000000000000000000000003AA29337E7149047FB8AE83F30AA00125E23173C88F284ADDED2E5B59ACAA5B9\")\n\tsBytes := common.FromHex(\"0000000000000000000000000000000000000000000000000000000000000000E2E9338109D74269578216039FD4D1C764E7F6F142CBB2E3035E7E49D375D330\")\n\tr := new(big.Int).SetBytes(rBytes)\n\ts := new(big.Int).SetBytes(sBytes)\n\n\tsignature := sm2.SignatureSM2(sm2.Serialize(r, s))\n\n\tmsg := []byte(\"112233445566112233445566112233445566112233445566\")\n\tok := pubSM2.VerifyBytes(msg, signature)\n\trequire.Equal(true, ok)\n}", "func (a *ActiveDevice) setSigningKey(g *GlobalContext, uv keybase1.UserVersion, deviceID keybase1.DeviceID,\n\tsigKey GenericKey, deviceName string) error {\n\ta.Lock()\n\tdefer a.Unlock()\n\n\tif err := a.internalUpdateUserVersionDeviceID(uv, deviceID); err != nil {\n\t\treturn err\n\t}\n\n\ta.signingKey = sigKey\n\tif len(deviceName) > 0 {\n\t\ta.deviceName = deviceName\n\t}\n\ta.nistFactory = NewNISTFactory(g, uv.Uid, deviceID, sigKey)\n\treturn nil\n}", "func (u *walletIdentity) Verify(msg []byte, sig []byte) error {\n\treturn errors.New(\"not implemented\")\n}", "func (mm *MessageMaker) Signer() *MockSigner {\n\treturn mm.signer\n}", "func (mm *MessageMaker) Signer() *MockSigner {\n\treturn mm.signer\n}", "func strictSignatureCheck(pk PublicKey, signature ByteSlice) error {\n\tswitch pk.Algorithm {\n\tcase SignatureAlgoEd25519:\n\t\tif len(pk.Key) != crypto.PublicKeySize {\n\t\t\treturn errors.New(\"invalid public key size in transaction\")\n\t\t}\n\t\tif len(signature) != crypto.SignatureSize {\n\t\t\treturn errors.New(\"invalid signature size in transaction\")\n\t\t}\n\t\treturn nil\n\tdefault:\n\t\treturn errors.New(\"unrecognized public key type in transaction\")\n\t}\n}", "func VerifyOnChain(msg []byte, signature []byte, signers EthAddresses,\n) (types.OracleID, error) {\n\tauthor, err := crypto.SigToPub(onChainHash(msg), signature)\n\tif err != nil {\n\t\treturn types.OracleID(-1), errors.Wrapf(err, \"while trying to recover \"+\n\t\t\t\"sender from sig %x on msg %+v\", signature, msg)\n\t}\n\toid, ok := signers[(*OnChainPublicKey)(author).Address()]\n\tif ok {\n\t\treturn oid, nil\n\t} else {\n\t\treturn types.OracleID(-1), errors.Errorf(\"signer is not on whitelist\")\n\t}\n}", "func (v *Verifier) Verify(msg []byte, sig []byte) error {\n\treturn errors.New(\"NotImplemented\")\n}", "func (m *SignedMessage) verifySignature(data []byte) error {\n\tsender, err := VerifyMessage(data)\n\tif err != nil {\n\t\treturn err\n\t}\n\tm.Sender = sender\n\treturn nil\n}", "func SignCheckDeliver(\n\tt *testing.T, cdc *codec.Codec, app *bam.BaseApp, header abci.Header, msgs []sdk.Msg,\n\taccNums, seq []uint64, expSimPass, expPass bool, priv ...crypto.PrivKey,\n) (sdk.GasInfo, *sdk.Result, error) {\n\n\ttx := helpers.GenTx(\n\t\tmsgs,\n\t\tsdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, 0)},\n\t\thelpers.DefaultGenTxGas,\n\t\t\"\",\n\t\taccNums,\n\t\tseq,\n\t\tpriv...,\n\t)\n\n\ttxBytes, err := cdc.MarshalBinaryBare(tx)\n\trequire.Nil(t, err)\n\n\t// Must simulate now as CheckTx doesn't run Msgs anymore\n\t_, res, err := app.Simulate(txBytes, tx)\n\n\tif expSimPass {\n\t\trequire.NoError(t, err)\n\t\trequire.NotNil(t, res)\n\t} else {\n\t\trequire.Error(t, err)\n\t\trequire.Nil(t, res)\n\t}\n\n\t// Simulate a sending a transaction and committing a block\n\tapp.BeginBlock(abci.RequestBeginBlock{Header: header})\n\tgInfo, res, err := app.Deliver(tx)\n\n\tif expPass {\n\t\trequire.NoError(t, err)\n\t\trequire.NotNil(t, res)\n\t} else {\n\t\trequire.Error(t, err)\n\t\trequire.Nil(t, res)\n\t}\n\n\tapp.EndBlock(abci.RequestEndBlock{})\n\tapp.Commit()\n\n\treturn gInfo, res, err\n}", "func (m *MetricsProvider) SignerAddLinkedDataProof(value time.Duration) {\n}", "func (mr *MockCertificateSigningRequestEventHandlerMockRecorder) GenericCertificateSigningRequest(obj interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GenericCertificateSigningRequest\", reflect.TypeOf((*MockCertificateSigningRequestEventHandler)(nil).GenericCertificateSigningRequest), obj)\n}", "func Test_CanSign_NilInput(t *testing.T) {\n\n\t// prepare input\n\tvar transactionInput *TransactionInput\n\tvar unspentTransactions []*UnspentTransactionOutput\n\tvar publicKey = \"\"\n\n\t// call can sign\n\tresult := CanSign(unspentTransactions, transactionInput, publicKey)\n\n\t// result should false\n\tif result {\n\t\tt.Errorf(\"result of nil transaction should be false.\")\n\t}\n}", "func DefaultSigVerificationGasConsumer(\n\tmeter sdk.GasMeter, sig signing.SignatureV2, params authtypes.Params,\n) error {\n\tpubkey := sig.PubKey\n\tswitch pubkey := pubkey.(type) {\n\tcase *ethsecp256k1.PubKey:\n\t\tmeter.ConsumeGas(secp256k1VerifyCost, \"ante verify: eth_secp256k1\")\n\t\treturn nil\n\n\tcase multisig.PubKey:\n\t\t// Multisig keys\n\t\tmultisignature, ok := sig.Data.(*signing.MultiSignatureData)\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"expected %T, got, %T\", &signing.MultiSignatureData{}, sig.Data)\n\t\t}\n\t\treturn ConsumeMultisignatureVerificationGas(meter, multisignature, pubkey, params, sig.Sequence)\n\n\tdefault:\n\t\treturn authante.DefaultSigVerificationGasConsumer(meter, sig, params)\n\t}\n}", "func (account *NothingAccount) CheckSignature(message []byte, signature Signature) error {\n\treturn fault.InvalidSignature\n}", "func (s *Service) addSigner(signer network.ServerIdentityID, proof *gpr.SignatureResponse, e int) error {\n\tif proof != nil {\n\t\tif e < 0 {\n\t\t\treturn errors.New(\"Epoch cannot be negative\")\n\t\t}\n\t\ts.storage.Lock()\n\n\t\tif e > len(s.storage.Signers) {\n\t\t\tlog.LLvl1(\" Error in add signer ? \")\n\t\t\treturn errors.New(\"Epoch is too in the future\")\n\t\t}\n\n\t\tif e == len(s.storage.Signers) {\n\t\t\ts.storage.Signers = append(s.storage.Signers, make(SignersSet))\n\t\t}\n\n\t\tif s.e > Epoch(e) {\n\t\t\treturn errors.New(\" Error in add signer - Cannot sign for previous epochs \")\n\t\t}\n\t\tif s.Cycle.GetTimeTillNextEpoch() < TIME_FOR_CONSENCUS || s.Cycle.GetEpoch() >= Epoch(e) {\n\t\t\treturn errors.New(\" Error in add signer - Cannot sign for previous epochs \")\n\t\t}\n\n\t\ts.storage.Signers[Epoch(e)][signer] = *proof\n\t\ts.storage.Unlock()\n\t\treturn nil\n\t}\n\treturn fmt.Errorf(\"Addsigner cannot be completed for %v as %v did not send a signature\", s.Name, signer)\n\n}", "func SignHandler(w http.ResponseWriter, r *http.Request) ErrorResponse {\n\n\t// Check that we have an authorised API key header\n\terr := checkAPIKey(r.Header.Get(\"api-key\"))\n\tif err != nil {\n\t\tlogMessage(\"SIGN\", \"invalid-api-key\", \"Invalid API key used\")\n\t\treturn ErrorInvalidAPIKey\n\t}\n\n\tif r.Body == nil {\n\t\tlogMessage(\"SIGN\", \"invalid-assertion\", \"Uninitialized POST data\")\n\t\treturn ErrorNilData\n\t}\n\n\t// Read the full request body\n\tdata, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\tlogMessage(\"SIGN\", \"invalid-assertion\", err.Error())\n\t\treturn ErrorResponse{false, \"error-sign-read\", \"\", err.Error(), http.StatusBadRequest}\n\t}\n\tif len(data) == 0 {\n\t\tlogMessage(\"SIGN\", \"invalid-assertion\", \"No data supplied for signing\")\n\t\treturn ErrorEmptyData\n\t}\n\n\tdefer r.Body.Close()\n\n\t// Use the snapd assertions module to decode the body and validate\n\tassertion, err := asserts.Decode(data)\n\tif err != nil {\n\t\tlogMessage(\"SIGN\", \"invalid-assertion\", err.Error())\n\t\treturn ErrorResponse{false, \"decode-assertion\", \"\", err.Error(), http.StatusBadRequest}\n\t}\n\n\t// Check that we have a serial-request assertion (the details will have been validated by Decode call)\n\tif assertion.Type() != asserts.SerialRequestType {\n\t\tlogMessage(\"SIGN\", \"invalid-type\", \"The assertion type must be 'serial-request'\")\n\t\treturn ErrorInvalidType\n\t}\n\n\t// Verify that the nonce is valid and has not expired\n\terr = Environ.DB.ValidateDeviceNonce(assertion.HeaderString(\"request-id\"))\n\tif err != nil {\n\t\tlogMessage(\"SIGN\", \"invalid-nonce\", \"Nonce is invalid or expired\")\n\t\treturn ErrorInvalidNonce\n\t}\n\n\t// Validate the model by checking that it exists on the database\n\tmodel, err := Environ.DB.FindModel(assertion.HeaderString(\"brand-id\"), assertion.HeaderString(\"model\"))\n\tif err != nil {\n\t\tlogMessage(\"SIGN\", \"invalid-model\", \"Cannot find model with the matching brand and model\")\n\t\treturn ErrorInvalidModel\n\t}\n\n\t// Check that the model has an active keypair\n\tif !model.KeyActive {\n\t\tlogMessage(\"SIGN\", \"invalid-model\", \"The model is linked with an inactive signing-key\")\n\t\treturn ErrorInactiveModel\n\t}\n\n\t// Create a basic signing log entry (without the serial number)\n\tsigningLog := SigningLog{Make: assertion.HeaderString(\"brand-id\"), Model: assertion.HeaderString(\"model\"), Fingerprint: assertion.SignKeyID()}\n\n\t// Convert the serial-request headers into a serial assertion\n\tserialAssertion, err := serialRequestToSerial(assertion, &signingLog)\n\tif err != nil {\n\t\tlogMessage(\"SIGN\", \"create-assertion\", err.Error())\n\t\treturn ErrorCreateAssertion\n\t}\n\n\t// Sign the assertion with the snapd assertions module\n\tsignedAssertion, err := Environ.KeypairDB.SignAssertion(asserts.SerialType, serialAssertion.Headers(), serialAssertion.Body(), model.AuthorityID, model.KeyID, model.SealedKey)\n\tif err != nil {\n\t\tlogMessage(\"SIGN\", \"signing-assertion\", err.Error())\n\t\treturn ErrorResponse{false, \"signing-assertion\", \"\", err.Error(), http.StatusInternalServerError}\n\t}\n\n\t// Store the serial number and device-key fingerprint in the database\n\terr = Environ.DB.CreateSigningLog(signingLog)\n\tif err != nil {\n\t\tlogMessage(\"SIGN\", \"logging-assertion\", err.Error())\n\t\treturn ErrorResponse{false, \"logging-assertion\", \"\", err.Error(), http.StatusInternalServerError}\n\t}\n\n\t// Return successful JSON response with the signed text\n\tformatSignResponse(true, \"\", \"\", \"\", signedAssertion, w)\n\treturn ErrorResponse{Success: true}\n}", "func TestCryptoSignerInterfaceBehavior(t *testing.T) {\n\tcs := NewCryptoService(trustmanager.NewKeyMemoryStore(passphraseRetriever))\n\tinterfaces.EmptyCryptoServiceInterfaceBehaviorTests(t, cs)\n\tinterfaces.CreateGetKeyCryptoServiceInterfaceBehaviorTests(t, cs, data.ECDSAKey)\n\n\tcs = NewCryptoService(trustmanager.NewKeyMemoryStore(passphraseRetriever))\n\tinterfaces.CreateListKeyCryptoServiceInterfaceBehaviorTests(t, cs, data.ECDSAKey)\n\n\tcs = NewCryptoService(trustmanager.NewKeyMemoryStore(passphraseRetriever))\n\tinterfaces.AddGetKeyCryptoServiceInterfaceBehaviorTests(t, cs, data.ECDSAKey)\n\n\tcs = NewCryptoService(trustmanager.NewKeyMemoryStore(passphraseRetriever))\n\tinterfaces.AddListKeyCryptoServiceInterfaceBehaviorTests(t, cs, data.ECDSAKey)\n}", "func (m *InternalDomainFederation) SetIsSignedAuthenticationRequestRequired(value *bool)() {\n err := m.GetBackingStore().Set(\"isSignedAuthenticationRequestRequired\", value)\n if err != nil {\n panic(err)\n }\n}", "func (c *clientImpl) VerifyTxnProposalSignature(channel sdkApi.Channel, proposalBytes []byte) error {\n\tif channel.MSPManager() == nil {\n\t\treturn errors.Errorf(errors.GeneralError, \"Channel %s GetMSPManager is nil\", channel.Name())\n\t}\n\tmsps, err := channel.MSPManager().GetMSPs()\n\tif err != nil {\n\t\treturn errors.Errorf(errors.GeneralError, \"GetMSPs return error:%v\", err)\n\t}\n\tif len(msps) == 0 {\n\t\treturn errors.Errorf(errors.GeneralError, \"Channel %s MSPManager.GetMSPs is empty\", channel.Name())\n\t}\n\n\tsignedProposal := &pb.SignedProposal{}\n\tif err := proto.Unmarshal(proposalBytes, signedProposal); err != nil {\n\t\treturn errors.Wrap(errors.GeneralError, err, \"Unmarshal clientProposalBytes error\")\n\t}\n\n\tcreatorBytes, err := utils.GetCreatorFromSignedProposal(signedProposal)\n\tif err != nil {\n\t\treturn errors.Wrap(errors.GeneralError, err, \"GetCreatorFromSignedProposal return error\")\n\t}\n\n\tserializedIdentity := &protosMSP.SerializedIdentity{}\n\tif err := proto.Unmarshal(creatorBytes, serializedIdentity); err != nil {\n\t\treturn errors.Wrap(errors.GeneralError, err, \"Unmarshal creatorBytes error\")\n\t}\n\n\tmsp := msps[serializedIdentity.Mspid]\n\tif msp == nil {\n\t\treturn errors.Errorf(errors.GeneralError, \"MSP %s not found\", serializedIdentity.Mspid)\n\t}\n\n\tcreator, err := msp.DeserializeIdentity(creatorBytes)\n\tif err != nil {\n\t\treturn errors.Wrap(errors.GeneralError, err, \"Failed to deserialize creator identity\")\n\t}\n\tlogger.Debugf(\"checkSignatureFromCreator info: creator is %s\", creator.GetIdentifier())\n\t// ensure that creator is a valid certificate\n\terr = creator.Validate()\n\tif err != nil {\n\t\treturn errors.Wrap(errors.GeneralError, err, \"The creator certificate is not valid\")\n\t}\n\n\tlogger.Debugf(\"verifyTPSignature info: creator is valid\")\n\n\t// validate the signature\n\terr = creator.Verify(signedProposal.ProposalBytes, signedProposal.Signature)\n\tif err != nil {\n\t\treturn errors.Wrap(errors.GeneralError, err, \"The creator's signature over the proposal is not valid\")\n\t}\n\n\tlogger.Debugf(\"VerifyTxnProposalSignature exists successfully\")\n\n\treturn nil\n}", "func (v Vote) CheckSignature(pk []byte) error {\n\t// TODO do the actual check\n\treturn nil\n}", "func TestHandleAlreadyInactive(t *testing.T) {\n\t// initial setup\n\tapp := simapp.Setup(false)\n\tctx := app.BaseApp.NewContext(false, tmproto.Header{})\n\n\taddrDels := simapp.AddTestAddrsIncremental(app, ctx, 1, sdk.TokensFromConsensusPower(200, sdk.DefaultPowerReduction))\n\tvalAddrs := simapp.ConvertAddrsToValAddrs(addrDels)\n\tpks := simapp.CreateTestPubKeys(1)\n\taddr, val := valAddrs[0], pks[0]\n\tpower := int64(100)\n\ttstaking := teststaking.NewHelper(t, ctx, app.CustomStakingKeeper, app.CustomGovKeeper)\n\n\ttstaking.CreateValidator(addr, val, true)\n\n\tstaking.EndBlocker(ctx, app.CustomStakingKeeper)\n\n\t// 1000 first blocks OK\n\theight := int64(0)\n\tfor ; height < 1000; height++ {\n\t\tctx = ctx.WithBlockHeight(height)\n\t\tapp.CustomSlashingKeeper.HandleValidatorSignature(ctx, val.Address(), power, true)\n\t}\n\n\tproperties := app.CustomGovKeeper.GetNetworkProperties(ctx)\n\t// miss 11 blocks for mischance confidence\n\tfor ; height < 1000+int64(properties.MischanceConfidence)+1; height++ {\n\t\tctx = ctx.WithBlockHeight(height)\n\t\tapp.CustomSlashingKeeper.HandleValidatorSignature(ctx, val.Address(), power, false)\n\t}\n\n\t// info correctness after the overflow of mischance confidence\n\tinfo, found := app.CustomSlashingKeeper.GetValidatorSigningInfo(ctx, sdk.ConsAddress(val.Address()))\n\trequire.True(t, found)\n\trequire.Equal(t, int64(10), info.MischanceConfidence)\n\trequire.Equal(t, int64(1), info.Mischance)\n\trequire.Equal(t, int64(999), info.LastPresentBlock)\n\n\t// miss 110 blocks after mischance confidence happen\n\tfor ; height < 1000+int64(properties.MaxMischance+properties.MischanceConfidence)+1; height++ {\n\t\tctx = ctx.WithBlockHeight(height)\n\t\tapp.CustomSlashingKeeper.HandleValidatorSignature(ctx, val.Address(), power, false)\n\t}\n\n\t// end block\n\tstaking.EndBlocker(ctx, app.CustomStakingKeeper)\n\n\t// validator should have been inactivated\n\tvalidator, _ := app.CustomStakingKeeper.GetValidatorByConsAddr(ctx, sdk.GetConsAddress(val))\n\trequire.Equal(t, stakingtypes.Inactive, validator.GetStatus())\n\n\t// another block missed\n\tctx = ctx.WithBlockHeight(height)\n\tapp.CustomSlashingKeeper.HandleValidatorSignature(ctx, val.Address(), power, false)\n\n\t// validator should be in inactive status yet\n\tvalidator, _ = app.CustomStakingKeeper.GetValidatorByConsAddr(ctx, sdk.GetConsAddress(val))\n\trequire.Equal(t, stakingtypes.Inactive, validator.GetStatus())\n}", "func (s *KeyStore) verifySignature(signed []byte, role string, signatures []Signature, filename string) error {\n\tif s == nil {\n\t\treturn nil\n\t}\n\n\t// Check for duplicate signatures.\n\thas := make(map[string]struct{})\n\tfor _, sig := range signatures {\n\t\tif _, ok := has[sig.KeyID]; ok {\n\t\t\treturn newSignatureError(filename, errors.Errorf(\"signature section of %s contains duplicate signatures\", filename))\n\t\t}\n\t\thas[sig.KeyID] = struct{}{}\n\t}\n\n\tks, ok := s.Load(role)\n\tif !ok {\n\t\treturn errors.Errorf(\"Unknown role %s\", role)\n\t}\n\tkeys := ks.(roleKeys)\n\n\tvar validSigs uint\n\tfor _, sig := range signatures {\n\t\tkey, ok := keys.keys.Load(sig.KeyID)\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\t\terr := key.(crypto.PubKey).VerifySignature(signed, sig.Sig)\n\t\tif err != nil {\n\t\t\treturn newSignatureError(filename, err)\n\t\t}\n\t\tvalidSigs++\n\t}\n\n\t// We may need to verify the root manifest with old keys. Once the most up to date root is found and verified, then\n\t// the keys used to do so should be checked for expiry.\n\tif role != ManifestTypeRoot {\n\t\tif err := CheckExpiry(filename, keys.expiry); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tif validSigs < keys.threshold {\n\t\treturn newSignatureError(filename, errors.Errorf(\"not enough signatures (%v) for threshold %v in %s\", validSigs, keys.threshold, filename))\n\t}\n\n\treturn nil\n}", "func (wL *wrappedMultiVerifier) VerifySignature(s, _ io.Reader, _ ...signature.VerifyOption) error {\n\tsig, err := io.ReadAll(s)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tenv := dsse.Envelope{}\n\tif err := json.Unmarshal(sig, &env); err != nil {\n\t\treturn err\n\t}\n\n\tenvVerifier, err := dsse.NewMultiEnvelopeVerifier(wL.threshold, wL.vLAdapters...)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = envVerifier.Verify(context.Background(), &env)\n\treturn err\n}", "func TestValidateRootRotationMissingOrigSig(t *testing.T) {\n\ttestValidateRootRotationMissingOrigSig(t, data.ECDSAKey, data.ECDSAx509Key)\n\tif !testing.Short() {\n\t\ttestValidateRootRotationMissingOrigSig(t, data.RSAKey, data.RSAx509Key)\n\t}\n}", "func TestValidateRootSigMissing(t *testing.T) {\n\tkdb, repo, cs := testutils.EmptyRepo()\n\tstore := storage.NewMemStorage()\n\n\tdelete(repo.Root.Signed.Roles, \"snapshot\")\n\n\tr, tg, sn, ts, err := testutils.Sign(repo)\n\tassert.NoError(t, err)\n\n\tr.Signatures = nil\n\n\troot, targets, snapshot, timestamp, err := getUpdates(r, tg, sn, ts)\n\tassert.NoError(t, err)\n\n\tupdates := []storage.MetaUpdate{root, targets, snapshot, timestamp}\n\n\tcopyTimestampKey(t, kdb, store, \"testGUN\")\n\t_, err = validateUpdate(cs, \"testGUN\", updates, store)\n\tassert.Error(t, err)\n\tassert.IsType(t, validation.ErrBadRoot{}, err)\n}", "func (m *MetricsProvider) AddProofSign(value time.Duration) {\n}", "func (mr *MockProvidersMockRecorder) IdentityManager(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"IdentityManager\", reflect.TypeOf((*MockProviders)(nil).IdentityManager), arg0)\n}", "func (m *PacketParserMock) MinimockGetPacketSignatureDone() bool {\n\tfor _, e := range m.GetPacketSignatureMock.expectations {\n\t\tif mm_atomic.LoadUint64(&e.Counter) < 1 {\n\t\t\treturn false\n\t\t}\n\t}\n\n\t// if default expectation was set then invocations count should be greater than zero\n\tif m.GetPacketSignatureMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterGetPacketSignatureCounter) < 1 {\n\t\treturn false\n\t}\n\t// if func was set then invocations count should be greater than zero\n\tif m.funcGetPacketSignature != nil && mm_atomic.LoadUint64(&m.afterGetPacketSignatureCounter) < 1 {\n\t\treturn false\n\t}\n\treturn true\n}", "func Test_CanSign_NoUnspentTransactions(t *testing.T) {\n\n\t// prepare input\n\tvar transactionInput *TransactionInput = &TransactionInput{\n\t\tOutputID: \"outID\",\n\t\tOutputIndex: 10,\n\t}\n\tvar unspentTransactions []*UnspentTransactionOutput\n\tvar publicKey = \"\"\n\n\t// call can sign\n\tresult := CanSign(unspentTransactions, transactionInput, publicKey)\n\n\t// result should false\n\tif result {\n\t\tt.Errorf(\"result when there are no unspent transactions should be false.\")\n\t}\n}", "func (o MfaPingidOutput) UseSignature() pulumi.BoolOutput {\n\treturn o.ApplyT(func(v *MfaPingid) pulumi.BoolOutput { return v.UseSignature }).(pulumi.BoolOutput)\n}", "func (mmSignWith *mDigestHolderMockSignWith) Set(f func(signer DigestSigner) (s1 SignedDigestHolder)) *DigestHolderMock {\n\tif mmSignWith.defaultExpectation != nil {\n\t\tmmSignWith.mock.t.Fatalf(\"Default expectation is already set for the DigestHolder.SignWith method\")\n\t}\n\n\tif len(mmSignWith.expectations) > 0 {\n\t\tmmSignWith.mock.t.Fatalf(\"Some expectations are already set for the DigestHolder.SignWith method\")\n\t}\n\n\tmmSignWith.mock.funcSignWith = f\n\treturn mmSignWith.mock\n}", "func (auth *Manager) Signed(service core.APIService) core.APIService {\n\treturn &wrapped{\n\t\tinfoService: service.InfoService,\n\t\tconfigService: func(ctx context.Context, config *v0.Config) (*v0.Response, error) {\n\t\t\tok, wrongSig, err := auth.Check(config)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tif !ok {\n\t\t\t\treturn response.MSG(v0.Code_BadRequest, fmt.Sprintf(\"incorrect signature for: %s\", wrongSig)), nil\n\t\t\t}\n\t\t\treturn service.ConfigService(ctx, config)\n\t\t},\n\t}\n}", "func (m *ActiveNodeMock) GetSignatureVerifierFinished() bool {\n\t// if expectation series were set then invocations count should be equal to expectations count\n\tif len(m.GetSignatureVerifierMock.expectationSeries) > 0 {\n\t\treturn atomic.LoadUint64(&m.GetSignatureVerifierCounter) == uint64(len(m.GetSignatureVerifierMock.expectationSeries))\n\t}\n\n\t// if main expectation was set then invocations count should be greater than zero\n\tif m.GetSignatureVerifierMock.mainExpectation != nil {\n\t\treturn atomic.LoadUint64(&m.GetSignatureVerifierCounter) > 0\n\t}\n\n\t// if func was set then invocations count should be greater than zero\n\tif m.GetSignatureVerifierFunc != nil {\n\t\treturn atomic.LoadUint64(&m.GetSignatureVerifierCounter) > 0\n\t}\n\n\treturn true\n}", "func (mr *MockTransactionApiMockRecorder) SignWithPrivkey(tx, outpoint, privkey, sighashType, utxoList interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"SignWithPrivkey\", reflect.TypeOf((*MockTransactionApi)(nil).SignWithPrivkey), tx, outpoint, privkey, sighashType, utxoList)\n}", "func TestTokenSignature(t *testing.T) {\n\tdb.InitDB()\n\tvar router *gin.Engine = routes.SetupRouter()\n\n\tvar user models.UserCreate = utils.CreateUser(\"Tom\", \"qwerty1234\", t, router)\n\tuser.Token = utils.ConnectUser(\"Tom\", \"qwerty1234\", t, router)\n\n\tsplittedToken := strings.Split(user.Token, \".\")\n\tif len(splittedToken) != 3 {\n\t\tlog.Fatal(\"Bad token.\")\n\t\tt.Fail()\n\t}\n\n\theader := splittedToken[0]\n\tpayload := splittedToken[1]\n\tsignature := splittedToken[2]\n\tsignature = signature + \"modif\"\n\tmodifiedToken := header + \".\" + payload + \".\" + signature\n\n\tvar url string = \"/v1/user/\" + strconv.Itoa(user.ID)\n\tvar bearer = \"Bearer \" + modifiedToken\n\trecord := httptest.NewRecorder()\n\trequest, _ := http.NewRequest(\"GET\", url, nil)\n\trequest.Header.Add(\"Content-Type\", \"application/json\")\n\trequest.Header.Add(\"Authorization\", bearer)\n\n\trouter.ServeHTTP(record, request)\n\n\tvar message Message\n\terr := json.Unmarshal([]byte(record.Body.String()), &message)\n\tif err != nil {\n\t\tlog.Fatal(\"Bad output: \", err.Error())\n\t\tt.Fail()\n\t}\n\n\tassert.Equal(t, record.Code, 403)\n\tassert.Equal(t, message.Message, \"Bad signature\")\n\n\tuser.Token = utils.ConnectUser(\"Tom\", \"qwerty1234\", t, router)\n\tutils.CleanUser(user.ID, user.Token, t, router)\n\tdb.CloseDB()\n}", "func (_Authority *AuthorityTransactorSession) MarkPubKeySignAsUsed(sha256Sign [32]byte, sender common.Address) (*types.Transaction, error) {\n\treturn _Authority.Contract.MarkPubKeySignAsUsed(&_Authority.TransactOpts, sha256Sign, sender)\n}", "func (manager *ArchivesManager) WasContractSigned() (bool, []byte) {\n\tsignedContract := manager.Archives.SignedContract\n\tif len(signedContract) != 0 {\n\t\treturn true, signedContract\n\t}\n\n\treturn false, []byte{}\n}" ]
[ "0.7239621", "0.6206", "0.6116267", "0.60653776", "0.5916556", "0.56487644", "0.55687886", "0.55571556", "0.5548583", "0.55313104", "0.55269605", "0.5507766", "0.5452651", "0.54315287", "0.54265016", "0.54069215", "0.5389472", "0.5376608", "0.53554356", "0.5310178", "0.5305054", "0.52682096", "0.52449197", "0.5238043", "0.5218279", "0.5202881", "0.5184457", "0.5148464", "0.5143023", "0.5138852", "0.512918", "0.5110945", "0.5106838", "0.50799346", "0.50548714", "0.50413144", "0.50394577", "0.5032544", "0.50295436", "0.50292814", "0.50280833", "0.5023576", "0.50214666", "0.5016491", "0.50006914", "0.49939242", "0.49924472", "0.4991387", "0.49723953", "0.49610764", "0.4944914", "0.49219835", "0.49124408", "0.4907466", "0.4904289", "0.4899503", "0.48971775", "0.48968896", "0.48924273", "0.48877802", "0.4886914", "0.48846844", "0.48776722", "0.48742345", "0.48666823", "0.4866252", "0.4866252", "0.486029", "0.48546064", "0.4853906", "0.48497397", "0.4847141", "0.4840223", "0.4840109", "0.48400268", "0.48342234", "0.4832005", "0.4827139", "0.48241246", "0.4818655", "0.481381", "0.4812616", "0.48107737", "0.48105085", "0.48084962", "0.48080555", "0.48006555", "0.4799268", "0.47986242", "0.4797667", "0.47967172", "0.47896755", "0.47881114", "0.47872669", "0.47849783", "0.47826788", "0.4781949", "0.47806004", "0.47793087", "0.477485" ]
0.7177633
1
UserStore mocks base method
func (m *MockClient) UserStore() msp.UserStore { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "UserStore") ret0, _ := ret[0].(msp.UserStore) return ret0 }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func TestUserstorage(t *testing.T) {\n t.Log(\"*** User data storage and retrieval test ***\")\n\n // initialize user\n u, err := InitUser(\"alice\",\"fubar\")\n if err != nil {\n t.Error(\"Failed to initialize user (\", err, \")\")\n } else {\n t.Log(\"Successfully stored user\", u)\n }\n\n // retrieve user \n v, err := GetUser(\"alice\", \"fubar\")\n if err != nil {\n t.Error(\"Failed to reload user\", err)\n } else {\n t.Log(\"Correctly retrieved user\", v)\n }\n}", "func (m *MockProviders) UserStore() msp.UserStore {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"UserStore\")\n\tret0, _ := ret[0].(msp.UserStore)\n\treturn ret0\n}", "func (m *MockUserRepository) Store(arg0 *sweeper.User) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Store\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockRepository) Store(user *User) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Store\", user)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (_m *UsersRepository) Store(users *entities.User) error {\n\tret := _m.Called(users)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(*entities.User) error); ok {\n\t\tr0 = rf(users)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (userRepo *mockUserRepo) Initialize(ctx context.Context, db *sql.DB) {}", "func TestMySQLStore(t *testing.T) {\n\t//create a new sql mock\n\tdb, mock, err := sqlmock.New()\n\tif err != nil {\n\t\tt.Fatalf(\"error creating sql mock: %v\", err)\n\t}\n\t//ensure it's closed at the end of the test\n\tdefer db.Close()\n\n\tnewUser := CreateNewUser()\n\n\texpectedUser, _ := newUser.ToUser()\n\t//construct a new MySQLStore using the mock db\n\tstore := NewMySQLStore(db)\n\n\trows := sqlmock.NewRows([]string{\"id\", \"email\", \"passhash\", \"username\", \"firstname\", \"lastname\", \"photourl\"})\n\trows.AddRow(expectedUser.ID, expectedUser.Email, expectedUser.PassHash, expectedUser.UserName, expectedUser.FirstName, expectedUser.LastName, expectedUser.PhotoURL)\n\n\t// test insert function\n\tmock.ExpectExec(regexp.QuoteMeta(sqlInsertUser)).\n\t\tWithArgs(expectedUser.Email, expectedUser.PassHash, expectedUser.UserName, expectedUser.FirstName, expectedUser.LastName, expectedUser.PhotoURL).\n\t\tWillReturnResult(sqlmock.NewResult(1, 1))\n\n\t_, err = store.Insert(expectedUser)\n\tif err != nil {\n\t\tt.Errorf(\"unexpected error occurs when inserting new user: %v\", err)\n\t}\n\n\t//ensure we didn't have any unmet expectations\n\tif err := mock.ExpectationsWereMet(); err != nil {\n\t\tt.Errorf(\"unmet sqlmock expectations: %v\", err)\n\t}\n\n\tmock.ExpectExec(regexp.QuoteMeta(sqlInsertUser)).\n\t\tWithArgs(expectedUser.Email, expectedUser.PassHash, expectedUser.UserName, expectedUser.FirstName, expectedUser.LastName, expectedUser.PhotoURL).\n\t\tWillReturnError(fmt.Errorf(\"test DMBS error\"))\n\n\t_, err = store.Insert(expectedUser)\n\tif err == nil {\n\t\tt.Errorf(\"expected error does not occurs when inserting new user: %v\", err)\n\t}\n\n\t//ensure we didn't have any unmet expectations\n\tif err := mock.ExpectationsWereMet(); err != nil {\n\t\tt.Errorf(\"unmet sqlmock expectations: %v\", err)\n\t}\n\n\t// test get function\n\t// test get by id\n\tmock.ExpectQuery(regexp.QuoteMeta(sqlSelectUserByID)).\n\t\tWithArgs(expectedUser.ID).\n\t\tWillReturnRows(rows)\n\n\t_, err = store.GetByID(expectedUser.ID)\n\tif err != nil {\n\t\tt.Errorf(\"unexpected error occurs when get user by ID: %v\", err)\n\t}\n\n\tmock.ExpectQuery(regexp.QuoteMeta(sqlSelectUserByID)).\n\t\tWithArgs(expectedUser.ID).\n\t\tWillReturnError(fmt.Errorf(\"test DMBS error\"))\n\n\t_, err = store.GetByID(expectedUser.ID)\n\tif err == nil {\n\t\tt.Errorf(\"expected does not error occurs when getting user by id: %v\", err)\n\t}\n\n\t//ensure we didn't have any unmet expectations\n\tif err := mock.ExpectationsWereMet(); err != nil {\n\t\tt.Errorf(\"unmet sqlmock expectations: %v\", err)\n\t}\n\n\t// test get by email\n\trows = sqlmock.NewRows([]string{\"id\", \"email\", \"passhash\", \"username\", \"firstname\", \"lastname\", \"photourl\"})\n\trows.AddRow(expectedUser.ID, expectedUser.Email, expectedUser.PassHash, expectedUser.UserName, expectedUser.FirstName, expectedUser.LastName, expectedUser.PhotoURL)\n\n\tmock.ExpectQuery(regexp.QuoteMeta(sqlSelectUserByEmail)).\n\t\tWithArgs(expectedUser.Email).\n\t\tWillReturnRows(rows)\n\n\t_, err = store.GetByEmail(expectedUser.Email)\n\tif err != nil {\n\t\tt.Errorf(\"unexpected error occurs when get user by email: %v\", err)\n\t}\n\n\tmock.ExpectQuery(regexp.QuoteMeta(sqlSelectUserByEmail)).\n\t\tWithArgs(expectedUser.Email).\n\t\tWillReturnError(fmt.Errorf(\"test DMBS error\"))\n\n\t_, err = store.GetByEmail(expectedUser.Email)\n\tif err == nil {\n\t\tt.Errorf(\"expected does not error occurs when getting user by email: %v\", err)\n\t}\n\n\t//ensure we didn't have any unmet expectations\n\tif err := mock.ExpectationsWereMet(); err != nil {\n\t\tt.Errorf(\"unmet sqlmock expectations: %v\", err)\n\t}\n\n\t// test get by user name\n\trows = sqlmock.NewRows([]string{\"id\", \"email\", \"passhash\", \"username\", \"firstname\", \"lastname\", \"photourl\"})\n\trows.AddRow(expectedUser.ID, expectedUser.Email, expectedUser.PassHash, expectedUser.UserName, expectedUser.FirstName, expectedUser.LastName, expectedUser.PhotoURL)\n\n\tmock.ExpectQuery(regexp.QuoteMeta(sqlSelectUserByUserName)).\n\t\tWithArgs(expectedUser.UserName).\n\t\tWillReturnRows(rows)\n\n\t_, err = store.GetByUserName(expectedUser.UserName)\n\tif err != nil {\n\t\tt.Errorf(\"unexpected error occurs when get user by UserName: %v\", err)\n\t}\n\n\tmock.ExpectQuery(regexp.QuoteMeta(sqlSelectUserByUserName)).\n\t\tWithArgs(expectedUser.UserName).\n\t\tWillReturnError(fmt.Errorf(\"test DMBS error\"))\n\n\t_, err = store.GetByUserName(expectedUser.UserName)\n\tif err == nil {\n\t\tt.Errorf(\"expected does not error occurs when getting user by UserName: %v\", err)\n\t}\n\n\t//ensure we didn't have any unmet expectations\n\tif err := mock.ExpectationsWereMet(); err != nil {\n\t\tt.Errorf(\"unmet sqlmock expectations: %v\", err)\n\t}\n\n\t// Test update\n\tupdate := &Updates{\n\t\tFirstName: \"updatedFirstName\",\n\t\tLastName: \"updatedLastName\",\n\t}\n\t// updatedRows := sqlmock.NewRows([]string{\"id\", \"email\", \"passhash\", \"UserName\", \"FirstName\", \"LastName\", \"photourl\"})\n\t// rows.AddRow(expectedUser.ID, expectedUser.Email, expectedUser.PassHash, expectedUser.UserName, update.FirstName, update.LastName, expectedUser.PhotoURL)\n\n\tmock.ExpectExec(regexp.QuoteMeta(sqlUpdate)).\n\t\tWithArgs(update.FirstName, update.LastName, expectedUser.ID).\n\t\tWillReturnResult(sqlmock.NewResult(1, 1))\n\n\terr = store.Update(expectedUser.ID, update)\n\n\tif err != nil {\n\t\tt.Errorf(\"unexpected error occurs when update user: %v\", err)\n\t}\n\n\tmock.ExpectExec(regexp.QuoteMeta(sqlUpdate)).\n\t\tWithArgs(update.FirstName, update.LastName, expectedUser.ID).\n\t\tWillReturnError(fmt.Errorf(\"test DMBS error\"))\n\n\terr = store.Update(expectedUser.ID, update)\n\tif err == nil {\n\t\tt.Errorf(\"expected does not error occurs when update user: %v\", err)\n\t}\n\n\t//ensure we didn't have any unmet expectations\n\tif err := mock.ExpectationsWereMet(); err != nil {\n\t\tt.Errorf(\"unmet sqlmock expectations: %v\", err)\n\t}\n\n\t//Test delete\n\n\tmock.ExpectExec(regexp.QuoteMeta(sqlDelete)).\n\t\tWithArgs(expectedUser.ID).\n\t\tWillReturnResult(sqlmock.NewResult(1, 1))\n\n\terr = store.Delete(expectedUser.ID)\n\tif err != nil {\n\t\tt.Errorf(\"unexpected error occurs when deleting user: %v\", err)\n\t}\n\n\t//ensure we didn't have any unmet expectations\n\tif err := mock.ExpectationsWereMet(); err != nil {\n\t\tt.Errorf(\"unmet sqlmock expectations: %v\", err)\n\t}\n\n\tmock.ExpectExec(regexp.QuoteMeta(sqlDelete)).\n\t\tWithArgs(expectedUser.ID).\n\t\tWillReturnError(fmt.Errorf(\"test DMBS error\"))\n\n\terr = store.Delete(expectedUser.ID)\n\tif err == nil {\n\t\tt.Errorf(\"expected error does not occurs when deleting user: %v\", err)\n\t}\n\n\t//ensure we didn't have any unmet expectations\n\tif err := mock.ExpectationsWereMet(); err != nil {\n\t\tt.Errorf(\"unmet sqlmock expectations: %v\", err)\n\t}\n}", "func MockUserItemStorage() *mongoDB.UserItemStorage {\n\treturn &mongoDB.UserItemStorage{\n\t\tUserID: \"Test\",\n\t\tPrices: make(map[string]models.UserPrices),\n\t\tProfits: make(map[string]models.UserProfits),\n\t}\n}", "func (m *MockUserStore) Get(arg0 context.Context, arg1 *sql.Tx, arg2 []byte) (*proto.User, error) {\n\tret := m.ctrl.Call(m, \"Get\", arg0, arg1, arg2)\n\tret0, _ := ret[0].(*proto.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (suite *StoreTestSuite) Test001_User() {\n\tusername := \"foo\"\n\temail := \"bar\"\n\tpw := \"baz\"\n\trole := 1337\n\n\t// Test CreateUser\n\tnewUser := &schema.User{\n\t\tUsername: &username,\n\t\tEmail: &email,\n\t\tPassword: &pw,\n\t\tRole: &role,\n\t}\n\terr := suite.store.CreateUser(newUser)\n\tsuite.Nil(err)\n\n\t// Test GetUserByUsername\n\tuser, err := suite.store.GetUserByUsername(username)\n\tsuite.Nil(err)\n\tsuite.NotNil(user)\n\tsuite.Equal(username, user.Username)\n\tsuite.Equal(email, user.Email)\n\n\tid := user.ID.Hex()\n\n\t// Test GetUserByEmail\n\tuser, err = suite.store.GetUserByEmail(email)\n\tsuite.Nil(err)\n\tsuite.NotNil(user)\n\tsuite.Equal(username, user.Username)\n\tsuite.Equal(email, user.Email)\n\n\t// Test GetUserByPassword\n\tuser, err = suite.store.GetUserByCreds(username, pw)\n\tsuite.Nil(err)\n\tsuite.NotNil(user)\n\tsuite.Equal(username, user.Username)\n\tsuite.Equal(email, user.Email)\n\n\t// Test CreateUser with conflict\n\terr = suite.store.CreateUser(newUser)\n\tsuite.NotNil(err)\n\tsuite.Equal(\"user with username as foo already exists\", err.Error())\n\n\t// Test UpdateUser\n\tnewUsername := \"foobar\"\n\tuserPatch := &schema.User{Username: &newUsername}\n\tuser, err = suite.store.UpdateUser(id, userPatch)\n\tsuite.Nil(err)\n\tsuite.Equal(newUsername, user.Username)\n\tsuite.Equal(email, user.Email)\n\tsuite.Equal(role, user.Role)\n\n\t// Add second user\n\terr = suite.store.CreateUser(newUser)\n\tsuite.Nil(err)\n\n\t// Try to update second user\n\tu, err := suite.store.GetUserByUsername(*newUser.Username)\n\tsuite.Nil(err)\n\n\tuser, err = suite.store.UpdateUser(u.ID.Hex(), userPatch)\n\tsuite.Nil(user)\n\tsuite.True(mgo.IsDup(err))\n\n\t// Test GetAllUsers\n\tusers, err := suite.store.GetAllUsers()\n\tsuite.Nil(err)\n\tsuite.Equal(len(users), 2)\n\n\t// Test DeleteUser\n\tuser, err = suite.store.DeleteUser(id)\n\tsuite.Nil(err)\n\tsuite.NotNil(user)\n\tsuite.Equal(newUsername, user.Username)\n\tsuite.Equal(email, user.Email)\n}", "func testInMemoryDataStore() IDataStore {\n return NewInMemoryDataStore();\n}", "func NewMockStore() *MockStore {\n\treturn &MockStore{\n\t\tid: map[int]User{},\n\t\tname: map[string]User{},\n\t\temail: map[string]User{},\n\t\tconfirm: map[string]ConfirmToken{},\n\t\trecover: map[string]RecoverToken{},\n\t}\n}", "func TestStore_CreateUser(t *testing.T) {\n\tt.Parallel()\n\ts := MustOpenStore()\n\tdefer s.Close()\n\n\t// Create user.\n\tif ui, err := s.CreateUser(\"susy\", \"pass\", true); err != nil {\n\t\tt.Fatal(err)\n\t} else if ui.Name != \"susy\" || ui.Hash == \"\" || ui.Admin != true {\n\t\tt.Fatalf(\"unexpected user: %#v\", ui)\n\t}\n}", "func TestStore_UpdateUser(t *testing.T) {\n\tt.Parallel()\n\ts := MustOpenStore()\n\tdefer s.Close()\n\n\t// Create users.\n\tif _, err := s.CreateUser(\"susy\", \"pass\", true); err != nil {\n\t\tt.Fatal(err)\n\t} else if _, err := s.CreateUser(\"bob\", \"pass\", true); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// Store password hash for bob.\n\tui, err := s.User(\"bob\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// Update user.\n\tif err := s.UpdateUser(\"bob\", \"XXX\"); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// Verify password hash was updated.\n\tif other, err := s.User(\"bob\"); err != nil {\n\t\tt.Fatal(err)\n\t} else if ui.Hash == other.Hash {\n\t\tt.Fatal(\"password hash did not change\")\n\t}\n}", "func TestDbInterfaceMethods(t *testing.T) {\n\ttestUser := models.User{\n\t\tAccount: models.Account{\n\t\t\tType: \"email\",\n\t\t\tAccountID: \"test@test.com\",\n\t\t\tPassword: \"testhashedpassword-youcantreadme\",\n\t\t},\n\t\tRoles: []string{\"TEST\"},\n\t\tTimestamps: models.Timestamps{\n\t\t\tCreatedAt: time.Now().Unix(),\n\t\t},\n\t}\n\n\tt.Run(\"Testing create user\", func(t *testing.T) {\n\t\tid, err := testDBService.AddUser(testInstanceID, testUser)\n\t\tif err != nil {\n\t\t\tt.Errorf(err.Error())\n\t\t\treturn\n\t\t}\n\t\tif len(id) == 0 {\n\t\t\tt.Errorf(\"id is missing\")\n\t\t\treturn\n\t\t}\n\t\t_id, _ := primitive.ObjectIDFromHex(id)\n\t\ttestUser.ID = _id\n\t})\n\n\tt.Run(\"Testing creating existing user\", func(t *testing.T) {\n\t\ttestUser2 := testUser\n\t\ttestUser2.Roles = []string{\"TEST2\"}\n\t\t_, err := testDBService.AddUser(testInstanceID, testUser2)\n\t\tif err == nil {\n\t\t\tt.Errorf(\"user already existed, but created again\")\n\t\t\treturn\n\t\t}\n\t\tu, e := testDBService.GetUserByAccountID(testInstanceID, testUser2.Account.AccountID)\n\t\tif e != nil {\n\t\t\tt.Errorf(e.Error())\n\t\t\treturn\n\t\t}\n\t\tif len(u.Roles) > 0 && u.Roles[0] == \"TEST2\" {\n\t\t\tt.Error(\"user should not be updated\")\n\t\t}\n\t})\n\n\tt.Run(\"Testing find existing user by id\", func(t *testing.T) {\n\t\tuser, err := testDBService.GetUserByID(testInstanceID, testUser.ID.Hex())\n\t\tif err != nil {\n\t\t\tt.Errorf(err.Error())\n\t\t\treturn\n\t\t}\n\t\tif user.Account.AccountID != testUser.Account.AccountID {\n\t\t\tt.Errorf(\"found user is not matching test user\")\n\t\t\treturn\n\t\t}\n\t})\n\n\tt.Run(\"Testing find not existing user by id\", func(t *testing.T) {\n\t\t_, err := testDBService.GetUserByID(testInstanceID, testUser.ID.Hex()+\"1\")\n\t\tif err == nil {\n\t\t\tt.Errorf(\"user should not be found\")\n\t\t\treturn\n\t\t}\n\t})\n\n\tt.Run(\"Testing find existing user by email\", func(t *testing.T) {\n\t\tuser, err := testDBService.GetUserByAccountID(testInstanceID, testUser.Account.AccountID)\n\t\tif err != nil {\n\t\t\tt.Errorf(err.Error())\n\t\t\treturn\n\t\t}\n\t\tif user.Account.AccountID != testUser.Account.AccountID {\n\t\t\tt.Errorf(\"found user is not matching test user\")\n\t\t\treturn\n\t\t}\n\t})\n\n\tt.Run(\"Testing find not existing user by email\", func(t *testing.T) {\n\t\t_, err := testDBService.GetUserByAccountID(testInstanceID, testUser.Account.AccountID+\"1\")\n\t\tif err == nil {\n\t\t\tt.Errorf(\"user should not be found\")\n\t\t\treturn\n\t\t}\n\t})\n\n\tt.Run(\"Testing updating existing user's attributes\", func(t *testing.T) {\n\t\ttestUser.Account.AccountConfirmedAt = time.Now().Unix()\n\t\t_, err := testDBService.UpdateUser(testInstanceID, testUser)\n\t\tif err != nil {\n\t\t\tt.Errorf(err.Error())\n\t\t\treturn\n\t\t}\n\t})\n\n\tt.Run(\"Testing updating not existing user's attributes\", func(t *testing.T) {\n\t\ttestUser.Account.AccountConfirmedAt = time.Now().Unix()\n\t\tcurrentUser := testUser\n\t\twrongID := testUser.ID.Hex()[:len(testUser.ID.Hex())-2] + \"00\"\n\t\tid, err := primitive.ObjectIDFromHex(wrongID)\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t\treturn\n\t\t}\n\t\tcurrentUser.ID = id\n\t\t_, err = testDBService.UpdateUser(testInstanceID, currentUser)\n\t\tif err == nil {\n\t\t\tt.Errorf(\"cannot update not existing user\")\n\t\t\treturn\n\t\t}\n\t})\n\n\tt.Run(\"Testing counting recently added users\", func(t *testing.T) {\n\t\tcount, err := testDBService.CountRecentlyCreatedUsers(testInstanceID, 20)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"unexpected error: %v\", err)\n\t\t\treturn\n\n\t\t}\n\t\tlogger.Debug.Println(count)\n\t\tif count < 1 {\n\t\t\tt.Error(\"at least one user should be found\")\n\t\t}\n\t})\n\n\tt.Run(\"Testing deleting existing user\", func(t *testing.T) {\n\t\terr := testDBService.DeleteUser(testInstanceID, testUser.ID.Hex())\n\t\tif err != nil {\n\t\t\tt.Errorf(err.Error())\n\t\t\treturn\n\t\t}\n\t})\n\n\tt.Run(\"Testing deleting not existing user\", func(t *testing.T) {\n\t\terr := testDBService.DeleteUser(testInstanceID, testUser.ID.Hex()+\"1\")\n\t\tif err == nil {\n\t\t\tt.Errorf(\"user should not be found - error expected\")\n\t\t\treturn\n\t\t}\n\t})\n}", "func (m *MockRepository) Store(ctx context.Context, data *users.Domain) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Store\", ctx, data)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func Test2(t *testing.T) {\n alice,_ := InitUser(\"alice\",\"fubar\")\n // Having previously created a user \"alice\" with password \"fubar\"...\n alice, _ = GetUser(\"alice\", \"fubar\")\n also_alice, _ := GetUser(\"alice\", \"fubar\")\n\n alice.StoreFile(\"todo\", []byte(\"write tests\"))\n todo, _ := also_alice.LoadFile(\"todo\")\n if string(todo) != \"write tests\" {\n t.Error(\"Same user and password could not access file: \", todo)\n }\n}", "func (m *MockUseCase) Store(ctx context.Context, data *users.Domain) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Store\", ctx, data)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func TestStore_UserCount(t *testing.T) {\n\tt.Parallel()\n\ts := MustOpenStore()\n\tdefer s.Close()\n\n\tif count, err := s.UserCount(); count != 0 && err != nil {\n\t\tt.Fatalf(\"expected user count to be 0 but was %d\", count)\n\t}\n\n\t// Create users.\n\tif _, err := s.CreateUser(\"susy\", \"pass\", true); err != nil {\n\t\tt.Fatal(err)\n\t} else if _, err := s.CreateUser(\"bob\", \"pass\", true); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif count, err := s.UserCount(); count != 2 && err != nil {\n\t\tt.Fatalf(\"expected user count to be 2 but was %d\", count)\n\t}\n}", "func (userAfhRepo *mockUserAfhRepo) Initialize(ctx context.Context, db *sql.DB) {}", "func TestInitAndGetBasics(t *testing.T) {\n\tuserlib.SetDebugStatus(false)\n\tuserlib.DatastoreClear()\n\tuserlib.KeystoreClear()\n\tdatastore := userlib.DatastoreGetMap()\n\tkeystore := userlib.KeystoreGetMap()\n\t_, _ = datastore, keystore\n\n\tbob, err := InitUser(\"bob\", \"fubar\")\n\tif bob == nil || err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\tgetBob, err := GetUser(\"bob\", \"fubar\")\n\tif getBob == nil || err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\n\tbobBytes, _ := json.Marshal(bob)\n\tgetBobBytes, _ := json.Marshal(getBob)\n\tif !reflect.DeepEqual(bobBytes, getBobBytes) {\n\t\tt.Error(\"Init and Get userdata are not the same.\")\n\t\treturn\n\t}\n\n\t_, err = GetUser(\"bob\", \"wrong\")\n\tif err == nil {\n\t\tt.Error(\"Got a user that is suppose to not exist.\")\n\t\treturn\n\t}\n\n\t_, err = GetUser(\"wrong\", \"fubar\")\n\tif err == nil {\n\t\tt.Error(\"Got a user that is suppose to not exist.\")\n\t\treturn\n\t}\n\n\tvar keys []userlib.UUID\n\tvar vals [][]byte\n\tfor k, v := range datastore {\n\t\tkeys = append(keys, k)\n\t\tvals = append(vals, v)\n\t}\n\n\tfor val := range vals {\n\t\tif strings.Contains(\"bob\", string(val)) || strings.Contains(\"alice\", string(val)) {\n\t\t\tt.Error(\"Username is not obscured.\")\n\t\t\treturn\n\t\t}\n\t}\n\n}", "func (m *MockUserLogic) UserGet(userName string) (*domain.User, string, error) {\n\tret := m.ctrl.Call(m, \"UserGet\", userName)\n\tret0, _ := ret[0].(*domain.User)\n\tret1, _ := ret[1].(string)\n\tret2, _ := ret[2].(error)\n\treturn ret0, ret1, ret2\n}", "func TestReadUser(t *testing.T) {\r\n/////////////////////////////////// MOCKING ////////////////////////////////////////////\r\n\tvar batches = []string{\r\n\t\t`CREATE TABLE Users (Id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, Name TEXT NOT NULL UNIQUE);`,\r\n\t\t`INSERT INTO Users (Id,Name) VALUES (1,'anonymous');`,\r\n\t}\r\n\t//open pseudo database for function\r\n\tdb, err := sql.Open(\"ramsql\", \"TestReadUser\")\r\n\tif err != nil {\r\n\t\tt.Fatalf(\"Error creating mock sql : %s\\n\", err)\r\n\t}\r\n\tdefer db.Close()\r\n\r\n\t// Exec every line of batch and create database\r\n\tfor _, b := range batches {\r\n\t\t_, err = db.Exec(b)\r\n\t\tif err != nil {\r\n\t\t\tt.Fatalf(\"Error exec query in query: %s\\n Error:%s\", b, err)\r\n\t\t}\r\n\t}\r\n/////////////////////////////////// MOCKING ////////////////////////////////////////////\r\n\r\n\t// Specify test variables and expected results.\r\n\ttests := []struct {\r\n\t\tid int\r\n\t\t// we need to use models.User for passing to object.This is different with \"database.User\".\r\n\t\tresult models.User\r\n\t\terr error\r\n\t}{\r\n\t\t// When give to first parameter(id) 1 , We expect result :1 error nil\r\n\t\t{id: 1, result: models.User{Id: 1, Name: \"anonymous\"}, err: nil},\r\n\t\t// When give to first parameter(id) 1 , We expect result :1 error nil\r\n\t\t//{id: 2, result: models.User{Id: 2, Name: \"test\"}, err: nil},\r\n\t}\r\n\r\n\t// test all of the variables.\r\n\tfor _, test := range tests {\r\n\t\t//get result after test.\r\n\t\ts, err := u.ReadUser(db, test.id)\r\n\t\t// if expected error type nil we need to compare with actual error different way.\r\n\t\tif test.err == nil {\r\n\t\t\t// If test fails give error.It checks expected result and expected error\r\n\t\t\tif err != test.err || s != test.result {\r\n\t\t\t\t// Compare expected error and actual error\r\n\t\t\t\tt.Errorf(\"Error is: %v . Expected: %v\", err, test.err)\r\n\t\t\t\t// Compare expected result and actual result\r\n\t\t\t\tt.Errorf(\"Result is: %v . Expected: %v\", s, test.result)\r\n\t\t\t}\r\n\t\t\t// if expected error type is not nil we need to compare with actual error different way.\r\n\t\t} else {\r\n\t\t\tif err.Error() != test.err.Error() || s != test.result {\r\n\t\t\t\t// Compare expected error and actual error\r\n\t\t\t\tt.Errorf(\"Error is: %v . Expected: %v\", err, test.err)\r\n\t\t\t\t// Compare expected result and actual result\r\n\t\t\t\tt.Errorf(\"Result is: %v . Expected: %v\", s, test.result)\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}", "func (m *MockHandler) UserGet(userName string) (*domain.User, string, error) {\n\tret := m.ctrl.Call(m, \"UserGet\", userName)\n\tret0, _ := ret[0].(*domain.User)\n\tret1, _ := ret[1].(string)\n\tret2, _ := ret[2].(error)\n\treturn ret0, ret1, ret2\n}", "func TestPostgresStore(t *testing.T) {\n\t//Preparing a Postgres data abstraction for later use\n\tpsdb, err := sql.Open(\"postgres\", \"user=pgstest dbname=devourpg sslmode=disable\")\n\tif err != nil {\n\t\tt.Errorf(\"error starting db: %v\", err)\n\t}\n\t//Creates the store structure\n\tstore := &PGStore{\n\t\tDB: psdb,\n\t}\n\n\tusrStore := &users.PGStore{\n\t\tDB: psdb,\n\t}\n\t//Pings the DB-- establishes a connection to the db\n\terr = psdb.Ping()\n\tif err != nil {\n\t\tt.Errorf(\"error pinging db %v\", err)\n\t}\n\n\tnewUser := &users.NewUser{\n\t\tEmail: \"test@test.com\",\n\t\tPassword: \"password\",\n\t\tPasswordConf: \"password\",\n\t\tDOB: \"12/12/1990\",\n\t\tFirstName: \"test\",\n\t\tLastName: \"tester\",\n\t}\n\tnu2 := &users.NewUser{\n\t\tEmail: \"best@best.com\",\n\t\tPassword: \"password\",\n\t\tPasswordConf: \"password\",\n\t\tDOB: \"12/20/2000\",\n\t\tFirstName: \"best\",\n\t\tLastName: \"bester\",\n\t}\n\n\t//reset the auto increment counter and clears previous test users in the DB\n\t_, err = psdb.Exec(\"ALTER SEQUENCE users_id_seq RESTART\")\n\t_, err = psdb.Exec(\"ALTER SEQUENCE user_diet_type_id_seq RESTART\")\n\t_, err = psdb.Exec(\"ALTER SEQUENCE user_allergy_type_id_seq RESTART\")\n\t_, err = psdb.Exec(\"ALTER SEQUENCE grocery_list_id_seq RESTART\")\n\t_, err = psdb.Exec(\"ALTER SEQUENCE user_like_list_id_seq RESTART\")\n\t_, err = psdb.Exec(\"ALTER SEQUENCE friends_list_id_seq RESTART\")\n\t_, err = psdb.Exec(\"ALTER SEQUENCE event_attendance_id_seq RESTART\")\n\t_, err = psdb.Exec(\"ALTER SEQUENCE events_id_seq RESTART\")\n\t_, err = psdb.Exec(\"ALTER SEQUENCE recipe_suggestions_id_seq RESTART\")\n\t_, err = psdb.Exec(\"DELETE FROM users\")\n\t_, err = psdb.Exec(\"DELETE FROM user_diet_type\")\n\t_, err = psdb.Exec(\"DELETE FROM user_allergy_type\")\n\t_, err = psdb.Exec(\"DELETE FROM grocery_list\")\n\t_, err = psdb.Exec(\"DELETE FROM user_like_list\")\n\t_, err = psdb.Exec(\"DELETE FROM friends_list\")\n\t_, err = psdb.Exec(\"DELETE FROM event_attendance\")\n\t_, err = psdb.Exec(\"DELETE FROM events\")\n\t_, err = psdb.Exec(\"DELETE FROM recipe_suggestions\")\n\n\t//start of insert\n\tuser, err := usrStore.Insert(newUser)\n\tif err != nil {\n\t\tt.Errorf(\"error inserting user: %v\\n\", err)\n\t}\n\t//means that ToUser() probably was not implemented correctly\n\tif nil == user {\n\t\tt.Fatalf(\"Nil returned from store.Insert()\\n\")\n\t}\n\t//start of insert\n\tuser2, err := usrStore.Insert(nu2)\n\tif err != nil {\n\t\tt.Errorf(\"error inserting user: %v\\n\", err)\n\t}\n\t//means that ToUser() probably was not implemented correctly\n\tif nil == user2 {\n\t\tt.Fatalf(\"Nil returned from store.Insert()\\n\")\n\t}\n\n\tnewEvt := &NewEvent{\n\t\tName: \"testEVENT\",\n\t\tDescription: \"testDescription\",\n\t\tStartTime: \"March 5, 2017 at 4:00pm (PST)\",\n\t\tEndTime: \"March 5, 2017 at 7:00pm (PST)\",\n\t\tEventType: \"Formal\",\n\t\tMoodType: \"Fancy\",\n\t}\n\tnewJuneEvt := &NewEvent{\n\t\tName: \"testFutureEVENT\",\n\t\tDescription: \"testFutureDescription\",\n\t\tStartTime: \"June 5, 2017 at 4:00pm (PST)\",\n\t\tEndTime: \"June 5, 2017 at 7:00pm (PST)\",\n\t\tEventType: \"Formal\",\n\t\tMoodType: \"Fancy\",\n\t}\n\n\t//insert event\n\tevt, err := store.InsertEvent(newEvt, user)\n\tif err != nil {\n\t\tt.Errorf(\"error inserting new event %v\\n\", err)\n\t}\n\tif evt.Name != \"testEVENT\" {\n\t\tt.Errorf(\"error making event expected creator %s but got %s\", \"testEvent\", evt.Name)\n\t}\n\n\tevt2, err := store.InsertEvent(newJuneEvt, user)\n\tif err != nil {\n\t\tt.Errorf(\"error inserting new event %v\\n\", err)\n\t}\n\n\t//invite user to the event\n\tatn, err := store.InviteUserToEvent(user2, evt)\n\tif err != nil {\n\t\tt.Errorf(\"error inviting user to event %v\\n\", err)\n\t}\n\n\t//Getting user attendance status\n\tatnStat, err := store.GetUserAttendanceStatus(user2, evt)\n\tif err != nil {\n\t\tt.Errorf(\"Error getting user's attendance status\")\n\t}\n\n\tif atnStat.AttendanceStatus != \"Pending\" {\n\t\tt.Errorf(\"Error getting the attendance status expected %s but got %s\", \"Pending\", atnStat.AttendanceStatus)\n\t}\n\n\tif atn.StatusID != atnStat.ID {\n\t\tt.Errorf(\"Error getting the correct attendance status ID expected %d but got %d\", atn.StatusID, atnStat.ID)\n\t}\n\n\t//Lets first reject that invite\n\terr = store.RejectInvite(evt, user2)\n\tif err != nil {\n\t\tt.Errorf(\"Error rejecting the invite %v\\n\", err)\n\t}\n\n\t//Now invite the user again\n\tatn, err = store.InviteUserToEvent(user2, evt)\n\tif err != nil {\n\t\tt.Errorf(\"error inviting user to event %v\\n\", err)\n\t}\n\n\t//Updating attendance status\n\terr = store.UpdateAttendanceStatus(user2, evt, \"Attending\")\n\tif err != nil {\n\t\tt.Errorf(\"Error getting an updated attendance status\")\n\t}\n\n\t//Getting the updated attendance status\n\tatnStat, err = store.GetUserAttendanceStatus(user2, evt)\n\tif err != nil {\n\t\tt.Errorf(\"Error getting user's attendance status\")\n\t}\n\tif atnStat.AttendanceStatus != \"Attending\" {\n\t\tt.Errorf(\"Error getting the correct UPDATED status: expected Attending but got %s\", atnStat.AttendanceStatus)\n\t}\n\n\t//Updating attendance status\n\terr = store.UpdateAttendanceStatus(user2, evt, \"Pending\")\n\tif err != nil {\n\t\tt.Errorf(\"Error getting an updated attendance status\")\n\t}\n\n\t//updating event stuff\n\terr = store.UpdateEventName(evt, \"UpdatedTestName\")\n\tif err != nil {\n\t\tt.Errorf(\"Error updating event name %v\", err)\n\t}\n\n\terr = store.UpdateEventDescription(evt, \"UpdatedDescription\")\n\tif err != nil {\n\t\tt.Errorf(\"Error updating event description %v\", err)\n\t}\n\n\terr = store.UpdateEventMood(evt, \"Focused\")\n\tif err != nil {\n\t\tt.Errorf(\"Error updating event mood %v\", err)\n\t}\n\n\terr = store.UpdateEventType(evt, \"Other\")\n\tif err != nil {\n\t\tt.Errorf(\"Error updating event type %v\", err)\n\t}\n\n\terr = store.UpdateEventEnd(evt, \"March 6, 2017 at 12:00pm (PST)\")\n\tif err != nil {\n\t\tt.Errorf(\"Error updating event end %v\", err)\n\t}\n\n\terr = store.UpdateEventStart(evt, \"March 1, 2017 at 2:20pm (PST)\")\n\tif err != nil {\n\t\tt.Errorf(\"Error updating event start %v\", err)\n\t}\n\n\tupEvents, err := store.GetAllHostedEvents(user)\n\tif err != nil {\n\t\tt.Errorf(\"Error getting all of the users store: %v\", err)\n\t}\n\tif upEvents[0].Name != \"UpdatedTestName\" {\n\t\tt.Errorf(\"Error updating stuffs %v\", err)\n\t}\n\n\t//Adding a Recipe to an event, recipes are strings\n\tRecipeName := \"French-Onion-Soup\"\n\n\t//Adding two recipes into event\n\tsugg, err := store.AddRecipeToEvent(evt, user, RecipeName)\n\tif err != nil {\n\t\tt.Errorf(\"Error adding recipe to an event: %v\\n\", err)\n\t}\n\t_, err = store.AddRecipeToEvent(evt, user2, RecipeName)\n\tif err != nil {\n\t\tt.Errorf(\"Error adding recipe to an event: %v\\n\", err)\n\t}\n\n\t//Getting all recipes in event\n\trecipes, err := store.GetAllRecipesInEvent(evt)\n\tif err != nil {\n\t\tt.Errorf(\"Error getting all recipes in an event: %v\\n\", err)\n\t}\n\tif recipes[0] != sugg.Recipe {\n\t\tt.Errorf(\"Error with getting recipes expected %s but got %s\", sugg.Recipe, recipes[0])\n\t}\n\n\t//Removing user2's recipe from the event\n\terr = store.RemoveRecipeFromEvent(evt, user2, RecipeName)\n\tif err != nil {\n\t\tt.Errorf(\"Error deleting recipe from the event: %v\\n\", err)\n\t}\n\n\t//Getting all of the users in the event\n\t_, err = store.GetAllUsersInEvent(evt)\n\tif err != nil {\n\t\tt.Errorf(\"Error getting all users %v\\n\", err)\n\t}\n\n\t//Gets all pending events that a user has\n\tpendingEvts, err := store.GetAllPendingEvents(user2)\n\tif err != nil {\n\t\tt.Errorf(\"Error getting all pending events: %v\\n\", err)\n\t}\n\tif pendingEvts[0].ID != evt.ID {\n\t\tt.Errorf(\"Error getting the correct event: expected %d and got %d\", pendingEvts[0].ID, evt.ID)\n\t}\n\n\t//Getting past and upcoming events\n\tpastEvts, err := store.GetPastEvents(user)\n\tif err != nil {\n\t\tt.Errorf(\"Error getting past events %v\\n\", err)\n\t}\n\tupcomingEvts, err := store.GetUpcomingEvents(user)\n\tif err != nil {\n\t\tt.Errorf(\"Error getting upcoming events %v\\n\", err)\n\t}\n\n\tif pastEvts[0].ID != evt.ID {\n\t\tt.Errorf(\"Error getting the correct Event: expected %d but got %d\", evt.ID, pastEvts[0].ID)\n\t}\n\tif upcomingEvts[0].ID != evt2.ID {\n\t\tt.Errorf(\"Error getting the correct Event: expected %d but got %d\", evt2.ID, pastEvts[0].ID)\n\t}\n\n\t//Getting all of the users events (attending or hosting)\n\t_, err = store.GetAllUserEvents(user)\n\tif err != nil {\n\t\tt.Errorf(\"Error getting all user events %v\\n\", err)\n\t}\n\n\t_, err = usrStore.AddFriend(user, user2)\n\tif err != nil {\n\t\tt.Errorf(\"Error adding friend %v\\n\", err)\n\t}\n\n\t//Getting all the friends of a user of user going to the event\n\t_, err = store.GetAllFriendsInEvent(user, evt)\n\tif err != nil {\n\t\tt.Errorf(\"Error getting friends in the event %v\\n\", err)\n\t}\n\n\t//Finished updated all things and now delete\n\terr = store.DeleteEvent(evt)\n\tif err != nil {\n\t\tt.Errorf(\"error deleting event %v\", err)\n\t}\n\n}", "func (m *MockPersister) GetUser(username, password string) (User, error) {\n\tret := m.ctrl.Call(m, \"GetUser\", username, password)\n\tret0, _ := ret[0].(User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (mmGetUser *mStorageMockGetUser) Set(f func(ctx context.Context, userID int64) (up1 *db_storage.User, err error)) *StorageMock {\n\tif mmGetUser.defaultExpectation != nil {\n\t\tmmGetUser.mock.t.Fatalf(\"Default expectation is already set for the storage.GetUser method\")\n\t}\n\n\tif len(mmGetUser.expectations) > 0 {\n\t\tmmGetUser.mock.t.Fatalf(\"Some expectations are already set for the storage.GetUser method\")\n\t}\n\n\tmmGetUser.mock.funcGetUser = f\n\treturn mmGetUser.mock\n}", "func mockNoopStore(id string, key string, value interface{}) {}", "func (m *MockUserStore) BySet(arg0 context.Context, arg1 *sql.Tx, arg2 string) ([]*proto.User, error) {\n\tret := m.ctrl.Call(m, \"BySet\", arg0, arg1, arg2)\n\tret0, _ := ret[0].([]*proto.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockUserStore) Alter(arg0 context.Context, arg1 *sql.Tx, arg2 proto.User) error {\n\tret := m.ctrl.Call(m, \"Alter\", arg0, arg1, arg2)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockUserStore) Create(arg0 context.Context, arg1 *sql.Tx, arg2 proto.User) error {\n\tret := m.ctrl.Call(m, \"Create\", arg0, arg1, arg2)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func TestUser(t *testing.T) {\n\tu := new(entity.User)\n\tu.Userid = \"1111\" //\n\thas, err := Engine.Get(u)\n\tt.Log(has, err)\n}", "func TestCreatingStore(t *testing.T) {\n\tstore := setUp(t)\n\ttearDown(store, t)\n}", "func (m *MockUserUsecase) GetAll() ([]*model.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetAll\")\n\tret0, _ := ret[0].([]*model.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockDB) Get(key string) (*minesweepersvc.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Get\", key)\n\tret0, _ := ret[0].(*minesweepersvc.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockAdmin) User() User {\n\tret := m.ctrl.Call(m, \"User\")\n\tret0, _ := ret[0].(User)\n\treturn ret0\n}", "func (m *MockIUserStore) Save(user *dto.User) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Save\", user)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (mmSaveUser *mStorageMockSaveUser) Set(f func(ctx context.Context, user *db_storage.User) (err error)) *StorageMock {\n\tif mmSaveUser.defaultExpectation != nil {\n\t\tmmSaveUser.mock.t.Fatalf(\"Default expectation is already set for the storage.SaveUser method\")\n\t}\n\n\tif len(mmSaveUser.expectations) > 0 {\n\t\tmmSaveUser.mock.t.Fatalf(\"Some expectations are already set for the storage.SaveUser method\")\n\t}\n\n\tmmSaveUser.mock.funcSaveUser = f\n\treturn mmSaveUser.mock\n}", "func (s MockStore) Put(u User) error {\n\ts.id[u.ID] = u\n\ts.name[u.Name] = u\n\ts.email[u.Email] = u\n\n\treturn nil\n}", "func (userClassesRepo *mockUserClassRepo) Initialize(ctx context.Context, db *sql.DB) {}", "func TestStore(t *testing.T) {\r\n\tsetup()\r\n\tp := Person{\r\n\t\tFirstname: firstname,\r\n\t\tLastname: lastname,\r\n\t}\r\n\tresult, err := p.Store(client)\r\n\t_id = result.InsertedID.(primitive.ObjectID)\r\n\r\n\tif err != nil {\r\n\t\tt.Fatalf(\"Failed store test %s\", err)\r\n\t}\r\n\r\n\tif p.Firstname != firstname {\r\n\t\tt.Fatalf(\"Failed store test %s\", err)\r\n\t}\r\n\r\n\tt.Log(\"Person was successfully stored : \"+p.Firstname+\" \"+p.Lastname+\" inserted id: \", _id)\r\n\r\n\tif err != nil {\r\n\t\tt.Fatalf(\"Failed store test %s\", err)\r\n\t}\r\n\r\n}", "func (as *ActionSuite) TestUserQuery() {\n\tt := as.T()\n\n\tf := fixturesForUserQuery(as)\n\n\ttype testCase struct {\n\t\tName string\n\t\tPayload string\n\t\tTestUser models.User\n\t\tExpectError bool\n\t\tTest func(t *testing.T)\n\t}\n\n\tvar resp UserResponse\n\n\ttestCases := []testCase{\n\t\t{\n\t\t\tName: \"all fields\",\n\t\t\tPayload: `{user(id: \"` + f.Users[1].UUID.String() + `\") {` + allUserFields + \"}}\",\n\t\t\tTestUser: f.Users[0],\n\t\t\tTest: func(t *testing.T) {\n\t\t\t\tif err := as.DB.Load(&(f.Users[1]), \"PhotoFile\"); err != nil {\n\t\t\t\t\tt.Errorf(\"failed to load user fixture, %s\", err)\n\t\t\t\t}\n\t\t\t\tas.Equal(f.Users[1].UUID.String(), resp.User.ID, \"incorrect ID\")\n\t\t\t\tas.Equal(f.Users[1].Email, resp.User.Email, \"incorrect Email\")\n\t\t\t\tas.Equal(f.Users[1].Nickname, resp.User.Nickname, \"incorrect Nickname\")\n\t\t\t\tas.Equal(f.Users[1].AdminRole, resp.User.AdminRole, \"incorrect AdminRole\")\n\t\t\t\tas.Equal(f.Users[1].PhotoFile.URL, resp.User.AvatarURL, \"incorrect AvatarURL\")\n\t\t\t\tas.Equal(f.Users[1].PhotoFile.UUID.String(), resp.User.PhotoID, \"incorrect PhotoID\")\n\t\t\t\tas.Regexp(\"^https?\", resp.User.AvatarURL, \"invalid AvatarURL\")\n\n\t\t\t\tas.Equal(strings.ToUpper(f.UserPreferences[0].Value), *resp.User.Preferences.Language,\n\t\t\t\t\t\"incorrect preference - language\")\n\t\t\t\tas.Equal(f.UserPreferences[1].Value, *resp.User.Preferences.TimeZone,\n\t\t\t\t\t\"incorrect preference - time zone\")\n\t\t\t\tas.Equal(strings.ToUpper(f.UserPreferences[2].Value), *resp.User.Preferences.WeightUnit,\n\t\t\t\t\t\"incorrect preference - weight unit\")\n\n\t\t\t\tas.Equal(f.Locations[1].Description, resp.User.Location.Description, \"incorrect location\")\n\t\t\t\tas.Equal(f.Locations[1].Country, resp.User.Location.Country, \"incorrect country\")\n\t\t\t\tas.InDelta(f.Locations[1].Latitude.Float64, resp.User.Location.Lat, 0.0001, \"incorrect latitude\")\n\t\t\t\tas.InDelta(f.Locations[1].Longitude.Float64, resp.User.Location.Long, 0.0001, \"incorrect longitude\")\n\n\t\t\t\tas.Equal(1, len(resp.User.Organizations), \"wrong number of Organizations\")\n\t\t\t\tas.Equal(f.Organization.UUID.String(), resp.User.Organizations[0].ID, \"incorrect Organization ID\")\n\n\t\t\t\tas.Equal(1, len(resp.User.Requests), \"wrong number of requests\")\n\t\t\t\tas.Equal(f.Requests[0].UUID.String(), resp.User.Requests[0].ID, \"incorrect Request ID\")\n\n\t\t\t\tas.Equal(1, len(resp.User.MeetingsAsParticipant), \"wrong number of meetings\")\n\t\t\t\tas.Equal(f.Meetings[0].UUID.String(), resp.User.MeetingsAsParticipant[0].ID, \"incorrect Meeting ID\")\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName: \"current user\",\n\t\t\tPayload: `{user {` + allUserFields + \"}}\",\n\t\t\tTestUser: f.Users[1],\n\t\t\tTest: func(t *testing.T) {\n\t\t\t\tas.Equal(f.Users[1].UUID.String(), resp.User.ID, \"incorrect ID\")\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName: \"not allowed\",\n\t\t\tPayload: `{user(id: \"` + f.Users[0].UUID.String() + `\"){` + allUserFields + \"}}\",\n\t\t\tTestUser: f.Users[1],\n\t\t\tTest: func(t *testing.T) {},\n\t\t\tExpectError: true,\n\t\t},\n\t}\n\n\tfor _, test := range testCases {\n\t\terr := as.testGqlQuery(test.Payload, test.TestUser.Nickname, &resp)\n\n\t\tif test.ExpectError {\n\t\t\tas.Error(err)\n\t\t} else {\n\t\t\tas.NoError(err)\n\t\t}\n\t\tt.Run(test.Name, test.Test)\n\t}\n}", "func NewUserStore(m *mock.Mocker, db api.IDatabase, q *query.Q) UserStore {\n\treturn UserStore{\n\t\tmock: m,\n\t\tdb: db,\n\t\tQ: q,\n\t}\n}", "func TestLauncher_SetupWithUsers(t *testing.T) {\n\tl := launcher.RunTestLauncherOrFail(t, ctx)\n\tl.SetupOrFail(t)\n\tdefer l.ShutdownOrFail(t, ctx)\n\n\tr, err := nethttp.NewRequest(\"POST\", l.URL()+\"/api/v2/signin\", nil)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tr.SetBasicAuth(\"USER\", \"PASSWORD\")\n\n\tresp, err := nethttp.DefaultClient.Do(r)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif err := resp.Body.Close(); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif resp.StatusCode != nethttp.StatusNoContent {\n\t\tt.Fatalf(\"unexpected status code: %d, body: %s, headers: %v\", resp.StatusCode, body, resp.Header)\n\t}\n\n\tcookies := resp.Cookies()\n\tif len(cookies) != 1 {\n\t\tt.Fatalf(\"expected 1 cookie but received %d\", len(cookies))\n\t}\n\n\tuser2 := &platform.User{\n\t\tName: \"USER2\",\n\t}\n\n\tb, _ := json.Marshal(user2)\n\tr = l.NewHTTPRequestOrFail(t, \"POST\", \"/api/v2/users\", l.Auth.Token, string(b))\n\n\tresp, err = nethttp.DefaultClient.Do(r)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tbody, err = ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif err := resp.Body.Close(); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif resp.StatusCode != nethttp.StatusCreated {\n\t\tt.Fatalf(\"unexpected status code: %d, body: %s, headers: %v\", resp.StatusCode, body, resp.Header)\n\t}\n\n\tr, err = nethttp.NewRequest(\"GET\", l.URL()+\"/api/v2/users\", nil)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tr.AddCookie(cookies[0])\n\n\tresp, err = nethttp.DefaultClient.Do(r)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tbody, err = ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif err := resp.Body.Close(); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif resp.StatusCode != nethttp.StatusOK {\n\t\tt.Fatalf(\"unexpected status code: %d, body: %s, headers: %v\", resp.StatusCode, body, resp.Header)\n\t}\n\n\texp := struct {\n\t\tUsers []platform.User `json:\"users\"`\n\t}{}\n\terr = json.Unmarshal(body, &exp)\n\tif err != nil {\n\t\tt.Fatalf(\"unexpected error unmarshaling user: %v\", err)\n\t}\n\tif len(exp.Users) != 2 {\n\t\tt.Fatalf(\"unexpected 2 users: %#+v\", exp)\n\t}\n}", "func (m *MockHandler) UserCreate(username, email, password string) (*domain.User, string, error) {\n\tret := m.ctrl.Call(m, \"UserCreate\", username, email, password)\n\tret0, _ := ret[0].(*domain.User)\n\tret1, _ := ret[1].(string)\n\tret2, _ := ret[2].(error)\n\treturn ret0, ret1, ret2\n}", "func (m_2 *MockUserRepository) List(m *model.User) (model.Users, error) {\n\tm_2.ctrl.T.Helper()\n\tret := m_2.ctrl.Call(m_2, \"List\", m)\n\tret0, _ := ret[0].(model.Users)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m_2 *MockUserUsecaser) List(c context.Context, m *model.User) (model.Users, error) {\n\tm_2.ctrl.T.Helper()\n\tret := m_2.ctrl.Call(m_2, \"List\", c, m)\n\tret0, _ := ret[0].(model.Users)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockUserLogic) UserCreate(username, email, password string) (*domain.User, string, error) {\n\tret := m.ctrl.Call(m, \"UserCreate\", username, email, password)\n\tret0, _ := ret[0].(*domain.User)\n\tret1, _ := ret[1].(string)\n\tret2, _ := ret[2].(error)\n\treturn ret0, ret1, ret2\n}", "func (m_2 *MockUserUsecaser) Create(c context.Context, m *model.User) (*model.User, error) {\n\tm_2.ctrl.T.Helper()\n\tret := m_2.ctrl.Call(m_2, \"Create\", c, m)\n\tret0, _ := ret[0].(*model.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockDB) GetUser(arg0 uint) (*User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUser\", arg0)\n\tret0, _ := ret[0].(*User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (mmGetUser *mStorageMockGetUser) Return(up1 *db_storage.User, err error) *StorageMock {\n\tif mmGetUser.mock.funcGetUser != nil {\n\t\tmmGetUser.mock.t.Fatalf(\"StorageMock.GetUser mock is already set by Set\")\n\t}\n\n\tif mmGetUser.defaultExpectation == nil {\n\t\tmmGetUser.defaultExpectation = &StorageMockGetUserExpectation{mock: mmGetUser.mock}\n\t}\n\tmmGetUser.defaultExpectation.results = &StorageMockGetUserResults{up1, err}\n\treturn mmGetUser.mock\n}", "func (mmSaveUser *mStorageMockSaveUser) When(ctx context.Context, user *db_storage.User) *StorageMockSaveUserExpectation {\n\tif mmSaveUser.mock.funcSaveUser != nil {\n\t\tmmSaveUser.mock.t.Fatalf(\"StorageMock.SaveUser mock is already set by Set\")\n\t}\n\n\texpectation := &StorageMockSaveUserExpectation{\n\t\tmock: mmSaveUser.mock,\n\t\tparams: &StorageMockSaveUserParams{ctx, user},\n\t}\n\tmmSaveUser.expectations = append(mmSaveUser.expectations, expectation)\n\treturn expectation\n}", "func (s *UserStore) GenericStore() *kallax.Store {\n\treturn s.Store\n}", "func TestInitAndGetWithCorruptDatastore(t *testing.T) {\n\tuserlib.SetDebugStatus(false)\n\tuserlib.DatastoreClear()\n\tuserlib.KeystoreClear()\n\tdatastore := userlib.DatastoreGetMap()\n\tkeystore := userlib.KeystoreGetMap()\n\t_, _ = datastore, keystore\n\n\t_, err := InitUser(\"bob\", \"fubar\")\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\t_, err = InitUser(\"alice\", \"fubar\")\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\n\tvar keys []userlib.UUID\n\tvar vals [][]byte\n\tfor k, v := range datastore {\n\t\tkeys = append(keys, k)\n\t\tvals = append(vals, v)\n\t}\n\tuserlib.DatastoreSet(keys[0], vals[1])\n\tfor i := 1; i < len(keys); i++ {\n\t\tuserlib.DatastoreSet(keys[i], vals[0])\n\t}\n\n\t_, err = GetUser(\"alice\", \"fubar\")\n\tif err == nil {\n\t\tt.Error(\"Datastore was corrupted for alice but still got user.\")\n\t\treturn\n\t}\n\t_, err = GetUser(\"bob\", \"fubar\")\n\tif err == nil {\n\t\tt.Error(\"Datastore was corrupted for bob but still got user.\")\n\t\treturn\n\t}\n\n\tuserlib.DatastoreClear()\n\tuserlib.KeystoreClear()\n\n\t_, err = InitUser(\"bob\", \"fubar\")\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\tuserlib.DatastoreClear()\n\t_, err = GetUser(\"bob\", \"fubar\")\n\tif err == nil {\n\t\tt.Error(\"Datastore was empty but still got user.\")\n\t\treturn\n\t}\n\n\tuserlib.DatastoreClear()\n\tuserlib.KeystoreClear()\n\tdatastore = userlib.DatastoreGetMap()\n\n\t_, err = InitUser(\"bob\", \"fubar\")\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\t_, err = InitUser(\"alice\", \"fubar\")\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\n\tvar keys1 []userlib.UUID\n\tvar vals1 [][]byte\n\tfor k, v := range datastore {\n\t\tkeys1 = append(keys1, k)\n\t\tvals1 = append(vals1, v)\n\t}\n\tdatastore[keys1[0]] = userlib.RandomBytes(len(keys1[0]))\n\n\t_, err0 := GetUser(\"bob\", \"fubar\")\n\t_, err1 := GetUser(\"alice\", \"fubar\")\n\tif err0 == nil && err1 == nil {\n\t\tt.Error(\"successfully got all users when datastore was corrupted.\")\n\t}\n}", "func MockUserBackend() {\n\tdefer wg.Done()\n\t// Define Pluto Server\n\tgrpcSrv := server.New(\n\t\tserver.Addr(\":65080\"),\n\t\tserver.GRPCRegister(func(g *grpc.Server) {\n\t\t\tpbu.RegisterUserServiceServer(g, &MockUser{})\n\t\t}),\n\t)\n\t// Define Pluto Service\n\ts := pluto.New(\n\t\tpluto.Name(\"MockUserBackend\"),\n\t\tpluto.Servers(grpcSrv),\n\t\tpluto.HealthAddr(\":9094\"),\n\t)\n\t// Run service\n\tif err := s.Run(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}", "func (m *MockStore) GetUserByEmail(arg0 context.Context, arg1 string) (db.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUserByEmail\", arg0, arg1)\n\tret0, _ := ret[0].(db.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockStore) GetUserById(arg0 context.Context, arg1 uuid.UUID) (db.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUserById\", arg0, arg1)\n\tret0, _ := ret[0].(db.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m_2 *MockUserRepository) Create(m *model.User) (*model.User, error) {\n\tm_2.ctrl.T.Helper()\n\tret := m_2.ctrl.Call(m_2, \"Create\", m)\n\tret0, _ := ret[0].(*model.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func TestAuthenticate_Success(t *testing.T) {\n\tdb, mock, err := sqlmock.New()\n\tif err != nil {\n\t\tt.Fatalf(\"an error '%s' was not expected when opening a stub database connection\", err)\n\t}\n\tdefer db.Close()\n\n\tuser := models.User{\n\t\tID: 1,\n\t\tEmail: \"personia@personio.com\",\n\t\tPassword: \"personia\",\n\t}\n\n\trows := sqlmock.NewRows([]string{\"id\", \"email\"}).AddRow(user.ID, user.Email)\n\tmock.ExpectQuery(regexp.QuoteMeta(constants.LoginDetailsSelectQuery)).WithArgs(user.Email, user.Password).WillReturnRows(rows)\n\n\tloginRepository := NewLoginRepository(db)\n\n\tloginModel := &models.Login{\n\t\tEmail: \"personia@personio.com\",\n\t\tPassword: \"personia\",\n\t}\n\n\tcntx := context.Background()\n\tdbuser, err := loginRepository.Authenticate(cntx, loginModel)\n\tassert.Nil(t, err)\n\tassert.Equal(t, user.ID, dbuser.ID)\n\tassert.Equal(t, user.Email, dbuser.Email)\n}", "func (m_2 *MockUserUsecaser) Get(c context.Context, m *model.User) (*model.User, error) {\n\tm_2.ctrl.T.Helper()\n\tret := m_2.ctrl.Call(m_2, \"Get\", c, m)\n\tret0, _ := ret[0].(*model.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockStore) UpdateUser(arg0 context.Context, arg1 db.UpdateUserParams) (db.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"UpdateUser\", arg0, arg1)\n\tret0, _ := ret[0].(db.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockUser) Index(filters ...UserFilter) (api.Users, error) {\n\tvarargs := []interface{}{}\n\tfor _, a := range filters {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"Index\", varargs...)\n\tret0, _ := ret[0].(api.Users)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func mockMapStore(storage map[string]interface{}) ResultStoreFn {\n\treturn func(id string, key string, value interface{}) {\n\t\tutil.SetNestedField(storage, value, id, key)\n\t}\n}", "func TestCreateUser(t *testing.T) {\n user := User{\n Name: \"Mohammd Osama\",\n Password: \"helloworld\",\n Email: \"mohammeadosama@ieee.org\",\n }\n if user.ID == 0 {\n t.Errorf(\"Expected ID > 0, Received %d\", user.ID)\n }\n}", "func NewMockUser() sqlmock.Sqlmock {\n\tdb, mock, err := sqlmock.New()\n\tif err != nil {\n\t\tlog.Fatalf(\"an error '%s' was not expected when opening a stub database connection\", err)\n\t}\n\n\tdbMockUsers = db\n\tconnMockUser = &database.Data{\n\t\tDB: dbMockUsers,\n\t}\n\n\tuserRepositoryMock = repo.NewPostgresUserRepo(connMockUser)\n\n\t/*userRepositoryMock = &repo.UserRepository{\n\t\tData: &connMockUser,\n\t}*/\n\n\treturn mock\n}", "func (m *MockUserStore) EXPECT() *MockUserStoreMockRecorder {\n\treturn m.recorder\n}", "func (m *MockUser) Get(userKey api.UserKey) (api.User, error) {\n\tret := m.ctrl.Call(m, \"Get\", userKey)\n\tret0, _ := ret[0].(api.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockIUserService) QueryUserByName(name string) (*model.UserDB, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"QueryUserByName\", name)\n\tret0, _ := ret[0].(*model.UserDB)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (mmSaveUser *mStorageMockSaveUser) Return(err error) *StorageMock {\n\tif mmSaveUser.mock.funcSaveUser != nil {\n\t\tmmSaveUser.mock.t.Fatalf(\"StorageMock.SaveUser mock is already set by Set\")\n\t}\n\n\tif mmSaveUser.defaultExpectation == nil {\n\t\tmmSaveUser.defaultExpectation = &StorageMockSaveUserExpectation{mock: mmSaveUser.mock}\n\t}\n\tmmSaveUser.defaultExpectation.results = &StorageMockSaveUserResults{err}\n\treturn mmSaveUser.mock\n}", "func (m *MockUserRepositoryInterface) GetUsersWhereUserIDs(arg0 []uint64) ([]*db.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUsersWhereUserIDs\", arg0)\n\tret0, _ := ret[0].([]*db.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *Client) GetUser(arg0 context.Context, arg1 int64) (zendesk.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUser\", arg0, arg1)\n\tret0, _ := ret[0].(zendesk.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (cli *Store) User() *UserRepository {\n\t// TODO: add test store for testing\n\tif cli.userRepository != nil {\n\t\treturn cli.userRepository\n\t}\n\n\tcli.userRepository = &UserRepository{\n\t\tstore: cli,\n\t}\n\n\treturn cli.userRepository\n}", "func (accountRepo *mockAccountRepo) Initialize(ctx context.Context, db *sql.DB) {}", "func (su *SimulatedUser) UserMock(s State) Action {\n\treturn su.vsa[s.Get()]\n}", "func (m *MockUser) Create(ctx context.Context, db repo.DB, username string, hashedPassword []byte, now time.Time) (int, *internal.E) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Create\", ctx, db, username, hashedPassword, now)\n\tret0, _ := ret[0].(int)\n\tret1, _ := ret[1].(*internal.E)\n\treturn ret0, ret1\n}", "func (m_2 *MockUserRepository) Get(m *model.User) (*model.User, error) {\n\tm_2.ctrl.T.Helper()\n\tret := m_2.ctrl.Call(m_2, \"Get\", m)\n\tret0, _ := ret[0].(*model.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (_m *Repository) Store(_a0 *account.Account) error {\n\tret := _m.Called(_a0)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(*account.Account) error); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (m *MockIUserRepository) GetUser(arg0 uuid.UUID) *model.User {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUser\", arg0)\n\tret0, _ := ret[0].(*model.User)\n\treturn ret0\n}", "func (m *MockManager) Read(ctx context.Context, token string) (*model.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Read\", ctx, token)\n\tret0, _ := ret[0].(*model.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockUserTokenService) GetUser(arg0 context.Context, arg1 string) (*model.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUser\", arg0, arg1)\n\tret0, _ := ret[0].(*model.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (c *Provider) UserStore() msp.UserStore {\n\treturn c.userStore\n}", "func (_m *MockService) GetUser(ctx context.Context, id string) (*User, error) {\n\tret := _m.ctrl.Call(_m, \"GetUser\", ctx, id)\n\tret0, _ := ret[0].(*User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockUnitOfWork) GetUserRepository() repositories.User {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUserRepository\")\n\tret0, _ := ret[0].(repositories.User)\n\treturn ret0\n}", "func (m *MockPersister) GetUsers() (MultipleUsers, error) {\n\tret := m.ctrl.Call(m, \"GetUsers\")\n\tret0, _ := ret[0].(MultipleUsers)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (transactionRepo *mockTransactionRepo) Initialize(ctx context.Context, db *sql.DB) {}", "func (mmGetUserLocation *mStorageMockGetUserLocation) Set(f func(ctx context.Context, userID int64) (up1 *db_storage.UserLocation, err error)) *StorageMock {\n\tif mmGetUserLocation.defaultExpectation != nil {\n\t\tmmGetUserLocation.mock.t.Fatalf(\"Default expectation is already set for the storage.GetUserLocation method\")\n\t}\n\n\tif len(mmGetUserLocation.expectations) > 0 {\n\t\tmmGetUserLocation.mock.t.Fatalf(\"Some expectations are already set for the storage.GetUserLocation method\")\n\t}\n\n\tmmGetUserLocation.mock.funcGetUserLocation = f\n\treturn mmGetUserLocation.mock\n}", "func (m *MockIUser) GetUser(arg0 uint) (*User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUser\", arg0)\n\tret0, _ := ret[0].(*User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockStore) CreateUser(arg0 context.Context, arg1 db.CreateUserParams) (db.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"CreateUser\", arg0, arg1)\n\tret0, _ := ret[0].(db.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockPersister) AddUser(username, email, password string, isSysAdmin, overwrite bool) error {\n\tret := m.ctrl.Call(m, \"AddUser\", username, email, password, isSysAdmin, overwrite)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockIUserRepository) GetUsers() []*model.User {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUsers\")\n\tret0, _ := ret[0].([]*model.User)\n\treturn ret0\n}", "func (m *MockUserRepository) FindUser(query string, params ...interface{}) (easyalert.User, error) {\n\tvarargs := []interface{}{query}\n\tfor _, a := range params {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"FindUser\", varargs...)\n\tret0, _ := ret[0].(easyalert.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (mmSaveUser *mStorageMockSaveUser) Expect(ctx context.Context, user *db_storage.User) *mStorageMockSaveUser {\n\tif mmSaveUser.mock.funcSaveUser != nil {\n\t\tmmSaveUser.mock.t.Fatalf(\"StorageMock.SaveUser mock is already set by Set\")\n\t}\n\n\tif mmSaveUser.defaultExpectation == nil {\n\t\tmmSaveUser.defaultExpectation = &StorageMockSaveUserExpectation{}\n\t}\n\n\tmmSaveUser.defaultExpectation.params = &StorageMockSaveUserParams{ctx, user}\n\tfor _, e := range mmSaveUser.expectations {\n\t\tif minimock.Equal(e.params, mmSaveUser.defaultExpectation.params) {\n\t\t\tmmSaveUser.mock.t.Fatalf(\"Expectation set by When has same params: %#v\", *mmSaveUser.defaultExpectation.params)\n\t\t}\n\t}\n\n\treturn mmSaveUser\n}", "func (m *MockUserRepo) FindAll() ([]app.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"FindAll\")\n\tret0, _ := ret[0].([]app.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockUserRepositoryInterface) GetUserWhereUsername(arg0 string) (*db.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUserWhereUsername\", arg0)\n\tret0, _ := ret[0].(*db.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockUserRepositoryInterface) GetUserWhereUserID(arg0 uint64) (*db.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUserWhereUserID\", arg0)\n\tret0, _ := ret[0].(*db.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func TestGetUserService (t *testing.T){\n\tuser1, err := GetUserService(user_01.SocialNumber)\n\tassert.Equal(t, 200, err.HTTPStatus)\n\tassert.Equal(t, user_01, user1)\n\n\tuser2, err := GetUserService(user_01.SocialNumber)\n\tassert.Equal(t, 200, err.HTTPStatus)\n\tassert.Equal(t, user_01, user2)\n\n\tuser3, err := GetUserService(user_01.SocialNumber)\n\tassert.Equal(t, 200, err.HTTPStatus)\n\tassert.Equal(t, user_01, user3)\n\n\tuser4, err := GetUserService(user_01.SocialNumber)\n\tassert.Equal(t, 200, err.HTTPStatus)\n\tassert.Equal(t, user_01, user4)\n}", "func (m *MockUserUsecase) GetUser(id int64) entity.User {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUser\", id)\n\tret0, _ := ret[0].(entity.User)\n\treturn ret0\n}", "func TestServer_GetUserById(t *testing.T) {\n\ttests := []struct {\n\t\tName string\n\t\tIn *models.User\n\t\tExp *pb.User\n\t}{\n\t\t{\n\t\t\tName: \"Get a User\",\n\t\t\tIn: &models.User{\n\t\t\t\tModel: gorm.Model{\n\t\t\t\t\tID: 100,\n\t\t\t\t},\n\t\t\t\tFirstName: \"foo\",\n\t\t\t\tLastName: \"bar\",\n\t\t\t},\n\t\t\tExp: &pb.User{\n\t\t\t\tId: 100,\n\t\t\t\tFirstName: \"foo\",\n\t\t\t\tLastName: \"bar\",\n\t\t\t},\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.Name, func(t *testing.T) {\n\n\t\t\t//============ Start Test Setup ============\n\n\t\t\t// Connect to local MYSQL database for testing\n\t\t\tname := fmt.Sprintf(\"./%d.db\", rand.Int())\n\t\t\tr := setupTestDb(t, name)\n\t\t\tdefer os.Remove(name)\n\n\t\t\t// Clean up test data at the end\n\t\t\t// Note: we use Unscoped delete to remove the record permanently\n\t\t\t// - Not using unscoped means the record will still exist and occupy the primary key, even though its marked as deleted\n\t\t\tdefer r.DB.Unscoped().Delete(tt.In)\n\n\t\t\t// Delete user if it exists so we have a clean test\n\t\t\terr := r.DB.Unscoped().Delete(tt.In).Error\n\t\t\trequire.NoError(t, err)\n\t\t\trequire.NoError(t, r.DB.Create(tt.In).Error)\n\t\t\t//============ End Test Setup ============\n\n\t\t\t// ============Start Test ============\n\n\t\t\tserv := grpc.NewServerWithRepo(r, \"\", \"\")\n\n\t\t\tgot, rErr := serv.GetUserById(context.Background(), &pb.Id{Id: int64(tt.In.ID)})\n\t\t\trequire.NoError(t, rErr)\n\t\t\trequire.Equal(t, tt.Exp, got)\n\n\t\t})\n\t}\n}", "func (u *mockUserProfileService) Save(profile decision.UserProfile) {\n}", "func (m_2 *MockUserUsecaser) Update(c context.Context, m *model.User) (*model.User, error) {\n\tm_2.ctrl.T.Helper()\n\tret := m_2.ctrl.Call(m_2, \"Update\", c, m)\n\tret0, _ := ret[0].(*model.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}" ]
[ "0.7232572", "0.70885456", "0.6947042", "0.65885407", "0.6443902", "0.63073105", "0.62877065", "0.6251729", "0.6233818", "0.6186411", "0.61615545", "0.6143569", "0.60569364", "0.6051291", "0.60378027", "0.60374254", "0.6020175", "0.59906864", "0.5951722", "0.59318924", "0.59068274", "0.59052396", "0.59025973", "0.58771396", "0.5852417", "0.58499384", "0.58248997", "0.58199763", "0.5813077", "0.5812539", "0.5803299", "0.5799304", "0.5771078", "0.57254833", "0.5716467", "0.5716214", "0.5708382", "0.569013", "0.56759614", "0.56718093", "0.5670532", "0.5667096", "0.56620353", "0.5645879", "0.5637085", "0.56110173", "0.56083685", "0.56023645", "0.55869335", "0.55812025", "0.557766", "0.5571984", "0.5563085", "0.556144", "0.55489486", "0.5545549", "0.5541322", "0.55294365", "0.5529192", "0.5527929", "0.5524556", "0.5520626", "0.551725", "0.55172104", "0.55025405", "0.5502517", "0.54956985", "0.54736817", "0.5466689", "0.54475605", "0.54468954", "0.54344547", "0.5433548", "0.5423236", "0.5422902", "0.5418866", "0.54109514", "0.53957033", "0.53907", "0.5388381", "0.5388117", "0.538768", "0.53832734", "0.5379956", "0.5378206", "0.5372153", "0.536765", "0.53673494", "0.53641003", "0.5361359", "0.5360361", "0.5349143", "0.5348971", "0.5347519", "0.53410184", "0.53394604", "0.53343034", "0.53261024", "0.53232765", "0.5322061" ]
0.70759726
2
UserStore indicates an expected call of UserStore
func (mr *MockClientMockRecorder) UserStore() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UserStore", reflect.TypeOf((*MockClient)(nil).UserStore)) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (mr *MockProvidersMockRecorder) UserStore() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"UserStore\", reflect.TypeOf((*MockProviders)(nil).UserStore))\n}", "func (mr *MockRepositoryMockRecorder) Store(user interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Store\", reflect.TypeOf((*MockRepository)(nil).Store), user)\n}", "func TestStore_CreateUser(t *testing.T) {\n\tt.Parallel()\n\ts := MustOpenStore()\n\tdefer s.Close()\n\n\t// Create user.\n\tif ui, err := s.CreateUser(\"susy\", \"pass\", true); err != nil {\n\t\tt.Fatal(err)\n\t} else if ui.Name != \"susy\" || ui.Hash == \"\" || ui.Admin != true {\n\t\tt.Fatalf(\"unexpected user: %#v\", ui)\n\t}\n}", "func TestStore_UserCount(t *testing.T) {\n\tt.Parallel()\n\ts := MustOpenStore()\n\tdefer s.Close()\n\n\tif count, err := s.UserCount(); count != 0 && err != nil {\n\t\tt.Fatalf(\"expected user count to be 0 but was %d\", count)\n\t}\n\n\t// Create users.\n\tif _, err := s.CreateUser(\"susy\", \"pass\", true); err != nil {\n\t\tt.Fatal(err)\n\t} else if _, err := s.CreateUser(\"bob\", \"pass\", true); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif count, err := s.UserCount(); count != 2 && err != nil {\n\t\tt.Fatalf(\"expected user count to be 2 but was %d\", count)\n\t}\n}", "func (mr *MockUserRepositoryMockRecorder) Store(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Store\", reflect.TypeOf((*MockUserRepository)(nil).Store), arg0)\n}", "func (suite *StoreTestSuite) Test001_User() {\n\tusername := \"foo\"\n\temail := \"bar\"\n\tpw := \"baz\"\n\trole := 1337\n\n\t// Test CreateUser\n\tnewUser := &schema.User{\n\t\tUsername: &username,\n\t\tEmail: &email,\n\t\tPassword: &pw,\n\t\tRole: &role,\n\t}\n\terr := suite.store.CreateUser(newUser)\n\tsuite.Nil(err)\n\n\t// Test GetUserByUsername\n\tuser, err := suite.store.GetUserByUsername(username)\n\tsuite.Nil(err)\n\tsuite.NotNil(user)\n\tsuite.Equal(username, user.Username)\n\tsuite.Equal(email, user.Email)\n\n\tid := user.ID.Hex()\n\n\t// Test GetUserByEmail\n\tuser, err = suite.store.GetUserByEmail(email)\n\tsuite.Nil(err)\n\tsuite.NotNil(user)\n\tsuite.Equal(username, user.Username)\n\tsuite.Equal(email, user.Email)\n\n\t// Test GetUserByPassword\n\tuser, err = suite.store.GetUserByCreds(username, pw)\n\tsuite.Nil(err)\n\tsuite.NotNil(user)\n\tsuite.Equal(username, user.Username)\n\tsuite.Equal(email, user.Email)\n\n\t// Test CreateUser with conflict\n\terr = suite.store.CreateUser(newUser)\n\tsuite.NotNil(err)\n\tsuite.Equal(\"user with username as foo already exists\", err.Error())\n\n\t// Test UpdateUser\n\tnewUsername := \"foobar\"\n\tuserPatch := &schema.User{Username: &newUsername}\n\tuser, err = suite.store.UpdateUser(id, userPatch)\n\tsuite.Nil(err)\n\tsuite.Equal(newUsername, user.Username)\n\tsuite.Equal(email, user.Email)\n\tsuite.Equal(role, user.Role)\n\n\t// Add second user\n\terr = suite.store.CreateUser(newUser)\n\tsuite.Nil(err)\n\n\t// Try to update second user\n\tu, err := suite.store.GetUserByUsername(*newUser.Username)\n\tsuite.Nil(err)\n\n\tuser, err = suite.store.UpdateUser(u.ID.Hex(), userPatch)\n\tsuite.Nil(user)\n\tsuite.True(mgo.IsDup(err))\n\n\t// Test GetAllUsers\n\tusers, err := suite.store.GetAllUsers()\n\tsuite.Nil(err)\n\tsuite.Equal(len(users), 2)\n\n\t// Test DeleteUser\n\tuser, err = suite.store.DeleteUser(id)\n\tsuite.Nil(err)\n\tsuite.NotNil(user)\n\tsuite.Equal(newUsername, user.Username)\n\tsuite.Equal(email, user.Email)\n}", "func (mr *MockUserLogicMockRecorder) UserGet(userName interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"UserGet\", reflect.TypeOf((*MockUserLogic)(nil).UserGet), userName)\n}", "func TestStore_DropUser(t *testing.T) {\n\tt.Parallel()\n\ts := MustOpenStore()\n\tdefer s.Close()\n\n\t// Create users.\n\tif _, err := s.CreateUser(\"susy\", \"pass\", true); err != nil {\n\t\tt.Fatal(err)\n\t} else if _, err := s.CreateUser(\"bob\", \"pass\", true); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// Remove user.\n\tif err := s.DropUser(\"bob\"); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// Verify user was removed.\n\tif a, err := s.Users(); err != nil {\n\t\tt.Fatal(err)\n\t} else if len(a) != 1 {\n\t\tt.Fatalf(\"unexpected user count: %d\", len(a))\n\t} else if a[0].Name != \"susy\" {\n\t\tt.Fatalf(\"unexpected user: %s\", a[0].Name)\n\t}\n}", "func (m *MockProviders) UserStore() msp.UserStore {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"UserStore\")\n\tret0, _ := ret[0].(msp.UserStore)\n\treturn ret0\n}", "func (m *MockClient) UserStore() msp.UserStore {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"UserStore\")\n\tret0, _ := ret[0].(msp.UserStore)\n\treturn ret0\n}", "func (mr *MockHandlerMockRecorder) UserGet(userName interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"UserGet\", reflect.TypeOf((*MockHandler)(nil).UserGet), userName)\n}", "func TestStore_UpdateUser(t *testing.T) {\n\tt.Parallel()\n\ts := MustOpenStore()\n\tdefer s.Close()\n\n\t// Create users.\n\tif _, err := s.CreateUser(\"susy\", \"pass\", true); err != nil {\n\t\tt.Fatal(err)\n\t} else if _, err := s.CreateUser(\"bob\", \"pass\", true); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// Store password hash for bob.\n\tui, err := s.User(\"bob\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// Update user.\n\tif err := s.UpdateUser(\"bob\", \"XXX\"); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// Verify password hash was updated.\n\tif other, err := s.User(\"bob\"); err != nil {\n\t\tt.Fatal(err)\n\t} else if ui.Hash == other.Hash {\n\t\tt.Fatal(\"password hash did not change\")\n\t}\n}", "func (c *Provider) UserStore() msp.UserStore {\n\treturn c.userStore\n}", "func TestSync_StoreError(t *testing.T) {\n\tcontroller := gomock.NewController(t)\n\tdefer controller.Finish()\n\n\tuser := &core.User{ID: 1}\n\tuserStore := mock.NewMockUserStore(controller)\n\tuserStore.EXPECT().Update(gomock.Any(), user).Return(nil)\n\tuserStore.EXPECT().Update(gomock.Any(), user).Return(nil)\n\n\trepoService := mock.NewMockRepositoryService(controller)\n\trepoService.EXPECT().List(gomock.Any(), user).Return([]*core.Repository{}, nil)\n\n\trepoStore := mock.NewMockRepositoryStore(controller)\n\trepoStore.EXPECT().List(gomock.Any(), gomock.Any()).Return(nil, sql.ErrNoRows)\n\n\ts := Synchronizer{\n\t\trepoz: repoService,\n\t\tusers: userStore,\n\t\trepos: repoStore,\n\t}\n\t_, err := s.Sync(context.Background(), user)\n\tif got, want := err, sql.ErrNoRows; got != want {\n\t\tt.Errorf(\"Want error %s, got %s\", want, got)\n\t}\n}", "func UserOwnsStore(userID, storeID int) (bool, error) {\n\tkey := stringutil.Build(\"userid:\", strconv.Itoa(userID), \":storeids\")\n\treturn IsSetMember(key, storeID)\n}", "func (s *UserSuite) TestUserAttachedToRequestAuthenticatedNoUseridentifierHasBeenRegistered(c *C) {\n\thandler := u.Handler()\n\n\treq, _ := http.NewRequest(\"GET\", \"http://127.0.0.1:8000/auth-status\", nil)\n\tresp := httptest.NewRecorder()\n\thandler(resp, req)\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tc.Assert(err, IsNil)\n\tc.Assert(string(body), Equals, \"false\")\n}", "func TestUserstorage(t *testing.T) {\n t.Log(\"*** User data storage and retrieval test ***\")\n\n // initialize user\n u, err := InitUser(\"alice\",\"fubar\")\n if err != nil {\n t.Error(\"Failed to initialize user (\", err, \")\")\n } else {\n t.Log(\"Successfully stored user\", u)\n }\n\n // retrieve user \n v, err := GetUser(\"alice\", \"fubar\")\n if err != nil {\n t.Error(\"Failed to reload user\", err)\n } else {\n t.Log(\"Correctly retrieved user\", v)\n }\n}", "func TestUser(t *testing.T) {\n\tu := new(entity.User)\n\tu.Userid = \"1111\" //\n\thas, err := Engine.Get(u)\n\tt.Log(has, err)\n}", "func (mr *MockAdminMockRecorder) User() *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"User\", reflect.TypeOf((*MockAdmin)(nil).User))\n}", "func (e *Entity) AssertUser() {\n\tif e.data.Kind != member.User {\n\t\tpanic(\"AssertUser\")\n\t}\n}", "func InitUserDBStore(ds db.IDataStore) {\n\tds.SetIndex(mgo.Index{\n\t\tName: \"email_unqkey\",\n\t\tKey: []string{\"email\"},\n\t\tUnique: true,\n\t\tDropDups: false,\n\t\tBackground: true,\n\t\tSparse: true,\n\t})\n}", "func (_mr *MockServiceMockRecorder) GetUser(arg0, arg1 interface{}) *gomock.Call {\n\treturn _mr.mock.ctrl.RecordCallWithMethodType(_mr.mock, \"GetUser\", reflect.TypeOf((*MockService)(nil).GetUser), arg0, arg1)\n}", "func (e UserRequired) IsUserRequired() {}", "func (mr *MockPersisterMockRecorder) GetUser(username, password interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetUser\", reflect.TypeOf((*MockPersister)(nil).GetUser), username, password)\n}", "func (mr *MockStoreMockRecorder) CreateUser(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"CreateUser\", reflect.TypeOf((*MockStore)(nil).CreateUser), arg0, arg1)\n}", "func ValidateStoredUser(result *StoredUser) (err error) {\n\tswitch result.View {\n\tcase \"default\", \"\":\n\t\terr = ValidateStoredUserView(result.Projected)\n\tdefault:\n\t\terr = goa.InvalidEnumValueError(\"view\", result.View, []interface{}{\"default\"})\n\t}\n\treturn\n}", "func (mr *MockIUserStoreMockRecorder) Save(user interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Save\", reflect.TypeOf((*MockIUserStore)(nil).Save), user)\n}", "func (s *VaultUserStore) Store(user *msp.UserData) error {\n\t_, err := s.client.Logical().Write(\n\t\t\"fabric/kv/users/\"+strings.ToLower(user.ID)+\"@\"+strings.ToLower(user.MSPID),\n\n\t\tmap[string]interface{}{\n\t\t\t\"value\": string(user.EnrollmentCertificate),\n\t\t})\n\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to store user data into vault\")\n\t}\n\n\treturn nil\n}", "func (mr *MockStoreMockRecorder) UpdateUser(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"UpdateUser\", reflect.TypeOf((*MockStore)(nil).UpdateUser), arg0, arg1)\n}", "func (mr *MockDBMockRecorder) GetUser(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetUser\", reflect.TypeOf((*MockDB)(nil).GetUser), arg0)\n}", "func (d *PostgresDatabase) Store(u model.User) error {\n\topMetric.WithLabelValues(\"store-user\").Inc()\n\n\tostart := time.Now()\n\tdefer opDuration.WithLabelValues(\"store-user\").Observe(time.Since(ostart).Seconds())\n\n\tdob, err := time.Parse(\"2006-01-02\", u.DOB)\n\tif err != nil {\n\t\topErrMetric.WithLabelValues(\"store-user\").Inc()\n\t\treturn err\n\t}\n\t_, err = d.Get(u.Username)\n\t// if the user is not present we insert\n\tif err == ErrUserNotFound {\n\t\t_, err := d.db.Query(queryInsertUser, u.Username, dob)\n\t\tif err != nil {\n\t\t\topErrMetric.WithLabelValues(\"store-user\").Inc()\n\t\t\treturn err\n\t\t}\n\t\topMetric.WithLabelValues(\"store-user\").Inc()\n\t\treturn nil\n\t} else if err != nil {\n\t\topErrMetric.WithLabelValues(\"store-user\").Inc()\n\t\treturn err\n\t}\n\n\t// if we got here, the user is already present and we should do an update\n\tstmt, err := d.db.Prepare(queryUpdateUser)\n\t_, err = stmt.Exec(dob, u.Username)\n\tif err != nil {\n\t\topErrMetric.WithLabelValues(\"store-user\").Inc()\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (s *Service) Verify(username string) bool {\n\treturn s.store.FindUser(username) != DoesNotExist\n}", "func storeInContext(ctx *gin.Context, user models.User) error {\n\tctx.Set(utils.TatHeaderUsername, user.Username)\n\tctx.Set(utils.TatCtxIsAdmin, user.IsAdmin)\n\tctx.Set(utils.TatCtxIsSystem, user.IsSystem)\n\n\tif user.IsAdmin {\n\t\tlog.Debugf(\"user %s isAdmin\", user.Username)\n\t}\n\n\tif user.IsSystem {\n\t\tlog.Debugf(\"user %s isSystem\", user.Username)\n\t}\n\n\treturn nil\n}", "func (mr *MockUserRepositoryInterfaceMockRecorder) InsertUser(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"InsertUser\", reflect.TypeOf((*MockUserRepositoryInterface)(nil).InsertUser), arg0)\n}", "func (r *UserRepository) Store(user *model.User) {\n\tr.users = append(r.users, user)\n}", "func (mr *MockStoreMockRecorder) GetUserById(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetUserById\", reflect.TypeOf((*MockStore)(nil).GetUserById), arg0, arg1)\n}", "func (m *MockUserRepository) Store(arg0 *sweeper.User) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Store\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func VerifyStoreAccount(c *gin.Context) {\n\n\tverificationToken := c.Param(\"token\")\n\n\tvar itemUser models.User\n\tvar itemStore models.Store\n\n\tif config.DB.First(&itemStore, \"verification_token = ?\", verificationToken).RecordNotFound() {\n\t\tc.JSON(404, gin.H{\n\t\t\t\"status\": \"error\",\n\t\t\t\"message\": \"record not found\"})\n\t\tc.Abort()\n\t\treturn\n\t}\n\n\tif config.DB.First(&itemUser, \"id = ?\", itemStore.UserID).RecordNotFound() {\n\t\tc.JSON(404, gin.H{\n\t\t\t\"status\": \"error\",\n\t\t\t\"message\": \"user record not found\"})\n\t\tc.Abort()\n\t\treturn\n\t}\n\n\tconfig.DB.Model(&itemUser).Where(\"id = ?\", itemUser.ID).Updates(models.User{\n\t\tIsActivate: true,\n\t\tHaveStore: true,\n\t})\n\n\tconfig.DB.Model(&itemStore).Where(\"id = ?\", itemStore.ID).Updates(models.Store{\n\t\tIsActivate: true,\n\t})\n\n\tc.JSON(200, gin.H{\n\t\t\"status\": \"Success, your account is now active. Please Login to your account\",\n\t})\n\n}", "func (mr *MockEventRepositoryMockRecorder) Store(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Store\", reflect.TypeOf((*MockEventRepository)(nil).Store), arg0)\n}", "func (mr *MockPersisterMockRecorder) AddUser(username, email, password, isSysAdmin, overwrite interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"AddUser\", reflect.TypeOf((*MockPersister)(nil).AddUser), username, email, password, isSysAdmin, overwrite)\n}", "func (_mr *MockServiceMockRecorder) AddUser(arg0, arg1 interface{}) *gomock.Call {\n\treturn _mr.mock.ctrl.RecordCallWithMethodType(_mr.mock, \"AddUser\", reflect.TypeOf((*MockService)(nil).AddUser), arg0, arg1)\n}", "func (l *StandardLogger) NoUserSet(user string) {\n\tl.Errorf(noUserSet.message, user)\n}", "func (mr *MockUserServerMockRecorder) GetUser(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetUser\", reflect.TypeOf((*MockUserServer)(nil).GetUser), arg0, arg1)\n}", "func (mr *MockConnMockRecorder) UserID() *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"UserID\", reflect.TypeOf((*MockConn)(nil).UserID))\n}", "func (e *BadSpotError) IsShowToUser() {}", "func TestIfAddUserInfoToMapChangesInfo(t *testing.T) {\n\tsuite := testsuite.NewTestSuite(t)\n\tMockUserItemStorage := MockUserItemStorage()\n\tMockUserSubmissionData := MockUserSubmissionData()\n\tmongoDB.AddUserInfoToMap(MockUserItemStorage, MockUserSubmissionData)\n\n\t// We need to generate what the result would look like\n\tResultUserItemStorage := mongoDB.UserItemStorage{\n\t\tUserID: \"Test\",\n\t\t// These are the important things that need info\n\t\tPrices: make(map[string]models.UserPrices),\n\t\tProfits: make(map[string]models.UserProfits),\n\t}\n\n\t// If it changes, then that should mean that we're editing info\n\tsuite.AssertNotEqual(ResultUserItemStorage, *MockUserItemStorage)\n}", "func TestUpdateUserNotValid(t *testing.T) {\n\tdb := database.Connect()\n\tu := User{\n\t\tEmail: \"test4@example.com\",\n\t}\n\tr := u.Update(db)\n\tif r != false {\n\t\tt.Errorf(\"Expected failed update, got %t\", r)\n\t}\n}", "func (mr *MockUserLogicMockRecorder) UserLogin(email, password interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"UserLogin\", reflect.TypeOf((*MockUserLogic)(nil).UserLogin), email, password)\n}", "func (mr *MockArticleRepositoryMockRecorder) Store(a interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Store\", reflect.TypeOf((*MockArticleRepository)(nil).Store), a)\n}", "func TestUserIsSet(t *testing.T) {\n\tconfiguration := ReadConfig()\n\tuser := configuration.User\n\n\tif user == \"\" {\n\t\tt.Error(\"User misconfigured\")\n\t} else {\n\t\tt.Log(\"User set\")\n\t}\n}", "func (mr *MockUserLogicMockRecorder) UserCreate(username, email, password interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"UserCreate\", reflect.TypeOf((*MockUserLogic)(nil).UserCreate), username, email, password)\n}", "func (mr *MockIUserRepositoryMockRecorder) GetUser(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetUser\", reflect.TypeOf((*MockIUserRepository)(nil).GetUser), arg0)\n}", "func (mr *MockUserServiceMockRecorder) Save(ctx, user interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Save\", reflect.TypeOf((*MockUserService)(nil).Save), ctx, user)\n}", "func TestStore(t *testing.T) {\r\n\tsetup()\r\n\tp := Person{\r\n\t\tFirstname: firstname,\r\n\t\tLastname: lastname,\r\n\t}\r\n\tresult, err := p.Store(client)\r\n\t_id = result.InsertedID.(primitive.ObjectID)\r\n\r\n\tif err != nil {\r\n\t\tt.Fatalf(\"Failed store test %s\", err)\r\n\t}\r\n\r\n\tif p.Firstname != firstname {\r\n\t\tt.Fatalf(\"Failed store test %s\", err)\r\n\t}\r\n\r\n\tt.Log(\"Person was successfully stored : \"+p.Firstname+\" \"+p.Lastname+\" inserted id: \", _id)\r\n\r\n\tif err != nil {\r\n\t\tt.Fatalf(\"Failed store test %s\", err)\r\n\t}\r\n\r\n}", "func (m *StorageMock) MinimockSaveUserInspect() {\n\tfor _, e := range m.SaveUserMock.expectations {\n\t\tif mm_atomic.LoadUint64(&e.Counter) < 1 {\n\t\t\tm.t.Errorf(\"Expected call to StorageMock.SaveUser with params: %#v\", *e.params)\n\t\t}\n\t}\n\n\t// if default expectation was set then invocations count should be greater than zero\n\tif m.SaveUserMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterSaveUserCounter) < 1 {\n\t\tif m.SaveUserMock.defaultExpectation.params == nil {\n\t\t\tm.t.Error(\"Expected call to StorageMock.SaveUser\")\n\t\t} else {\n\t\t\tm.t.Errorf(\"Expected call to StorageMock.SaveUser with params: %#v\", *m.SaveUserMock.defaultExpectation.params)\n\t\t}\n\t}\n\t// if func was set then invocations count should be greater than zero\n\tif m.funcSaveUser != nil && mm_atomic.LoadUint64(&m.afterSaveUserCounter) < 1 {\n\t\tm.t.Error(\"Expected call to StorageMock.SaveUser\")\n\t}\n}", "func TestInitAndGetWithCorruptDatastore(t *testing.T) {\n\tuserlib.SetDebugStatus(false)\n\tuserlib.DatastoreClear()\n\tuserlib.KeystoreClear()\n\tdatastore := userlib.DatastoreGetMap()\n\tkeystore := userlib.KeystoreGetMap()\n\t_, _ = datastore, keystore\n\n\t_, err := InitUser(\"bob\", \"fubar\")\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\t_, err = InitUser(\"alice\", \"fubar\")\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\n\tvar keys []userlib.UUID\n\tvar vals [][]byte\n\tfor k, v := range datastore {\n\t\tkeys = append(keys, k)\n\t\tvals = append(vals, v)\n\t}\n\tuserlib.DatastoreSet(keys[0], vals[1])\n\tfor i := 1; i < len(keys); i++ {\n\t\tuserlib.DatastoreSet(keys[i], vals[0])\n\t}\n\n\t_, err = GetUser(\"alice\", \"fubar\")\n\tif err == nil {\n\t\tt.Error(\"Datastore was corrupted for alice but still got user.\")\n\t\treturn\n\t}\n\t_, err = GetUser(\"bob\", \"fubar\")\n\tif err == nil {\n\t\tt.Error(\"Datastore was corrupted for bob but still got user.\")\n\t\treturn\n\t}\n\n\tuserlib.DatastoreClear()\n\tuserlib.KeystoreClear()\n\n\t_, err = InitUser(\"bob\", \"fubar\")\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\tuserlib.DatastoreClear()\n\t_, err = GetUser(\"bob\", \"fubar\")\n\tif err == nil {\n\t\tt.Error(\"Datastore was empty but still got user.\")\n\t\treturn\n\t}\n\n\tuserlib.DatastoreClear()\n\tuserlib.KeystoreClear()\n\tdatastore = userlib.DatastoreGetMap()\n\n\t_, err = InitUser(\"bob\", \"fubar\")\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\t_, err = InitUser(\"alice\", \"fubar\")\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\n\tvar keys1 []userlib.UUID\n\tvar vals1 [][]byte\n\tfor k, v := range datastore {\n\t\tkeys1 = append(keys1, k)\n\t\tvals1 = append(vals1, v)\n\t}\n\tdatastore[keys1[0]] = userlib.RandomBytes(len(keys1[0]))\n\n\t_, err0 := GetUser(\"bob\", \"fubar\")\n\t_, err1 := GetUser(\"alice\", \"fubar\")\n\tif err0 == nil && err1 == nil {\n\t\tt.Error(\"successfully got all users when datastore was corrupted.\")\n\t}\n}", "func (c UserInfo) Store(UserSubmission *models.UserSubmission) revel.Result {\n\n\t// AUTHENTICATION\n\t// Checks if there is a session for this user.\n\tuserID, _ := c.Session.Get(\"DiscordUserID\")\n\tif userID == nil {\n\t\t// Forbidden\n\t\tc.Response.Status = 403\n\t\treturn c.Render()\n\t}\n\n\t// STORAGE\n\t// Adds or updates a user's storage.\n\tUserItemStorage := UserStorageCollection.FindUserItemStorage(userID.(string))\n\tif UserItemStorage == nil {\n\t\tUserStorageCollection.InsertNewUserItemStorage(UserSubmission, userID.(string))\n\t} else {\n\t\tUserStorageCollection.AddUserItem(UserItemStorage, userID.(string), UserSubmission)\n\t}\n\n\t// 201 - CREATED\n\tc.Response.Status = 201\n\treturn c.Render()\n}", "func (mr *MockClientMockRecorder) GetUser(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetUser\", reflect.TypeOf((*MockClient)(nil).GetUser), arg0)\n}", "func (mr *MockClientMockRecorder) GetUser(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetUser\", reflect.TypeOf((*MockClient)(nil).GetUser), arg0)\n}", "func NopUserDB() UserDB { return nopUserDB{} }", "func (mr *MockHandlerMockRecorder) UserCreate(username, email, password interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"UserCreate\", reflect.TypeOf((*MockHandler)(nil).UserCreate), username, email, password)\n}", "func (mr *MockIUserMockRecorder) GetUser(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetUser\", reflect.TypeOf((*MockIUser)(nil).GetUser), arg0)\n}", "func (mr *MockHandlerMockRecorder) UserLogin(email, password interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"UserLogin\", reflect.TypeOf((*MockHandler)(nil).UserLogin), email, password)\n}", "func (s *Storage) StoreUser(userID int64, screenName, description string, protected bool, blob []byte) {\n\tchQueryArgs <- &queryArgs{\"INSERT OR IGNORE INTO users (user_id, screen_name, description, protected, blob) VALUES (?, ?, ?, ?, ?)\",\n\t\t[]interface{}{userID, screenName, description, protected, blob}}\n}", "func (s MockStore) Put(u User) error {\n\ts.id[u.ID] = u\n\ts.name[u.Name] = u\n\ts.email[u.Email] = u\n\n\treturn nil\n}", "func (mr *MockRepositoryMockRecorder) Store(ctx, coffeesDomain interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Store\", reflect.TypeOf((*MockRepository)(nil).Store), ctx, coffeesDomain)\n}", "func (mr *MockUserUsecaseMockRecorder) GetUser(id interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetUser\", reflect.TypeOf((*MockUserUsecase)(nil).GetUser), id)\n}", "func (mr *MockDatabaseMockRecorder) SaveUser(user interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"SaveUser\", reflect.TypeOf((*MockDatabase)(nil).SaveUser), user)\n}", "func (mr *MockUserTokenServiceMockRecorder) GetUser(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetUser\", reflect.TypeOf((*MockUserTokenService)(nil).GetUser), arg0, arg1)\n}", "func (mr *MockUnitOfWorkMockRecorder) GetUserRepository() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetUserRepository\", reflect.TypeOf((*MockUnitOfWork)(nil).GetUserRepository))\n}", "func (u *User) StoreUser() error {\n\terr := database.DB.Create(&u).Error\n\treturn err\n}", "func (mr *MockUseCaseMockRecorder) Store(ctx, data interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Store\", reflect.TypeOf((*MockUseCase)(nil).Store), ctx, data)\n}", "func (mr *MockDBMockRecorder) GetOrCreateUser(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetOrCreateUser\", reflect.TypeOf((*MockDB)(nil).GetOrCreateUser), arg0, arg1)\n}", "func (mr *MockUserRepositoryMockRecorder) ExistUser(email interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"ExistUser\", reflect.TypeOf((*MockUserRepository)(nil).ExistUser), email)\n}", "func (s *Store) UserExist(token string) bool {\n\texists, err := s.ES.IndexExists(token).Do()\n\tif err != nil || !exists {\n\t\treturn false\n\t}\n\treturn true\n}", "func (mr *MockContentRepositoryMockRecorder) Store(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Store\", reflect.TypeOf((*MockContentRepository)(nil).Store), arg0)\n}", "func MarkedUser(err error) bool {\n\treturn Marked(err, User)\n}", "func (as *ActionSuite) TestUserQuery() {\n\tt := as.T()\n\n\tf := fixturesForUserQuery(as)\n\n\ttype testCase struct {\n\t\tName string\n\t\tPayload string\n\t\tTestUser models.User\n\t\tExpectError bool\n\t\tTest func(t *testing.T)\n\t}\n\n\tvar resp UserResponse\n\n\ttestCases := []testCase{\n\t\t{\n\t\t\tName: \"all fields\",\n\t\t\tPayload: `{user(id: \"` + f.Users[1].UUID.String() + `\") {` + allUserFields + \"}}\",\n\t\t\tTestUser: f.Users[0],\n\t\t\tTest: func(t *testing.T) {\n\t\t\t\tif err := as.DB.Load(&(f.Users[1]), \"PhotoFile\"); err != nil {\n\t\t\t\t\tt.Errorf(\"failed to load user fixture, %s\", err)\n\t\t\t\t}\n\t\t\t\tas.Equal(f.Users[1].UUID.String(), resp.User.ID, \"incorrect ID\")\n\t\t\t\tas.Equal(f.Users[1].Email, resp.User.Email, \"incorrect Email\")\n\t\t\t\tas.Equal(f.Users[1].Nickname, resp.User.Nickname, \"incorrect Nickname\")\n\t\t\t\tas.Equal(f.Users[1].AdminRole, resp.User.AdminRole, \"incorrect AdminRole\")\n\t\t\t\tas.Equal(f.Users[1].PhotoFile.URL, resp.User.AvatarURL, \"incorrect AvatarURL\")\n\t\t\t\tas.Equal(f.Users[1].PhotoFile.UUID.String(), resp.User.PhotoID, \"incorrect PhotoID\")\n\t\t\t\tas.Regexp(\"^https?\", resp.User.AvatarURL, \"invalid AvatarURL\")\n\n\t\t\t\tas.Equal(strings.ToUpper(f.UserPreferences[0].Value), *resp.User.Preferences.Language,\n\t\t\t\t\t\"incorrect preference - language\")\n\t\t\t\tas.Equal(f.UserPreferences[1].Value, *resp.User.Preferences.TimeZone,\n\t\t\t\t\t\"incorrect preference - time zone\")\n\t\t\t\tas.Equal(strings.ToUpper(f.UserPreferences[2].Value), *resp.User.Preferences.WeightUnit,\n\t\t\t\t\t\"incorrect preference - weight unit\")\n\n\t\t\t\tas.Equal(f.Locations[1].Description, resp.User.Location.Description, \"incorrect location\")\n\t\t\t\tas.Equal(f.Locations[1].Country, resp.User.Location.Country, \"incorrect country\")\n\t\t\t\tas.InDelta(f.Locations[1].Latitude.Float64, resp.User.Location.Lat, 0.0001, \"incorrect latitude\")\n\t\t\t\tas.InDelta(f.Locations[1].Longitude.Float64, resp.User.Location.Long, 0.0001, \"incorrect longitude\")\n\n\t\t\t\tas.Equal(1, len(resp.User.Organizations), \"wrong number of Organizations\")\n\t\t\t\tas.Equal(f.Organization.UUID.String(), resp.User.Organizations[0].ID, \"incorrect Organization ID\")\n\n\t\t\t\tas.Equal(1, len(resp.User.Requests), \"wrong number of requests\")\n\t\t\t\tas.Equal(f.Requests[0].UUID.String(), resp.User.Requests[0].ID, \"incorrect Request ID\")\n\n\t\t\t\tas.Equal(1, len(resp.User.MeetingsAsParticipant), \"wrong number of meetings\")\n\t\t\t\tas.Equal(f.Meetings[0].UUID.String(), resp.User.MeetingsAsParticipant[0].ID, \"incorrect Meeting ID\")\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName: \"current user\",\n\t\t\tPayload: `{user {` + allUserFields + \"}}\",\n\t\t\tTestUser: f.Users[1],\n\t\t\tTest: func(t *testing.T) {\n\t\t\t\tas.Equal(f.Users[1].UUID.String(), resp.User.ID, \"incorrect ID\")\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName: \"not allowed\",\n\t\t\tPayload: `{user(id: \"` + f.Users[0].UUID.String() + `\"){` + allUserFields + \"}}\",\n\t\t\tTestUser: f.Users[1],\n\t\t\tTest: func(t *testing.T) {},\n\t\t\tExpectError: true,\n\t\t},\n\t}\n\n\tfor _, test := range testCases {\n\t\terr := as.testGqlQuery(test.Payload, test.TestUser.Nickname, &resp)\n\n\t\tif test.ExpectError {\n\t\t\tas.Error(err)\n\t\t} else {\n\t\t\tas.NoError(err)\n\t\t}\n\t\tt.Run(test.Name, test.Test)\n\t}\n}", "func (mr *MockIUserMockRecorder) GetOrCreateUser(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetOrCreateUser\", reflect.TypeOf((*MockIUser)(nil).GetOrCreateUser), arg0, arg1)\n}", "func (mr *MockRepositoryMockRecorder) Store(ctx, data interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Store\", reflect.TypeOf((*MockRepository)(nil).Store), ctx, data)\n}", "func (mr *MockUsecaseMockRecorder) Store(ctx, coffeesDomain interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Store\", reflect.TypeOf((*MockUsecase)(nil).Store), ctx, coffeesDomain)\n}", "func (mr *MockUserRepositoryMockRecorder) CreateUser(user interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"CreateUser\", reflect.TypeOf((*MockUserRepository)(nil).CreateUser), user)\n}", "func (u User) StoreLogin(r *http.Request, db *sql.DB) error {\n\t// language=PostgreSQL\n\treturn UpdateErr(tdb.Exec(r, db, `UPDATE users\n\tSET last_login = NOW(), app_version = $1, is_connected = true, firebase_token = $2\n\tWHERE credentials = $3 AND UUID = $4`, u.AppVersion, u.FirebaseToken, crypt.Hash(u.Credentials.Value), crypt.Hash(u.UUID)))\n}", "func (m *StorageMock) MinimockSaveUserDone() bool {\n\tfor _, e := range m.SaveUserMock.expectations {\n\t\tif mm_atomic.LoadUint64(&e.Counter) < 1 {\n\t\t\treturn false\n\t\t}\n\t}\n\n\t// if default expectation was set then invocations count should be greater than zero\n\tif m.SaveUserMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterSaveUserCounter) < 1 {\n\t\treturn false\n\t}\n\t// if func was set then invocations count should be greater than zero\n\tif m.funcSaveUser != nil && mm_atomic.LoadUint64(&m.afterSaveUserCounter) < 1 {\n\t\treturn false\n\t}\n\treturn true\n}", "func (cli *Store) User() *UserRepository {\n\t// TODO: add test store for testing\n\tif cli.userRepository != nil {\n\t\treturn cli.userRepository\n\t}\n\n\tcli.userRepository = &UserRepository{\n\t\tstore: cli,\n\t}\n\n\treturn cli.userRepository\n}", "func (me TxsdImpactSimpleContentExtensionType) IsUser() bool { return me.String() == \"user\" }", "func (mr *MockStorageMockRecorder) UpdateStore(ctx, store interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"UpdateStore\", reflect.TypeOf((*MockStorage)(nil).UpdateStore), ctx, store)\n}", "func (mr *MockInterfaceMockRecorder) AddUser(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"AddUser\", reflect.TypeOf((*MockInterface)(nil).AddUser), arg0)\n}", "func (m *MockRepository) Store(user *User) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Store\", user)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (mr *MockUserStoreMockRecorder) Alter(arg0, arg1, arg2 interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Alter\", reflect.TypeOf((*MockUserStore)(nil).Alter), arg0, arg1, arg2)\n}", "func TestCreateUser(t *testing.T) {\n user := User{\n Name: \"Mohammd Osama\",\n Password: \"helloworld\",\n Email: \"mohammeadosama@ieee.org\",\n }\n if user.ID == 0 {\n t.Errorf(\"Expected ID > 0, Received %d\", user.ID)\n }\n}", "func (userRepo *PostUserRepository) StoreUser(u entity.User) error {\n\n\t_, err := userRepo.conn.Exec(\"INSERT INTO users (firstname,lastname,email,password)\"+\n\t\t\" values($1, $2, $3, $4)\", u.FirstName, u.LastName, u.Email, u.Password)\n\n\tif err != nil {\n\t\t//panic(err)\n\t\treturn errors.New(\"Insertion has failed\")\n\t}\n\n\treturn nil\n}", "func TestTx_SaveUser(t *testing.T) {\n\tdb := NewTestDB()\n\tdefer db.Close()\n\n\tok(t, db.Update(func(tx *gist.Tx) error {\n\t\tok(t, tx.SaveUser(&gist.User{ID: 100, Username: \"john\", AccessToken: \"1234\"}))\n\t\treturn nil\n\t}))\n\n\tok(t, db.View(func(tx *gist.Tx) error {\n\t\tu, _ := tx.User(100)\n\t\tequals(t, &gist.User{ID: 100, Username: \"john\", AccessToken: \"1234\"}, u)\n\t\treturn nil\n\t}))\n}", "func GetUserOrUnexpected(c appengine.Context, w http.ResponseWriter,\n\tr *http.Request) (*user.User, bool) {\n\n\t// Get the current user.\n\tu := user.Current(c)\n\tif u == nil {\n\t\tLogAndUnexpected(c, w, r,\n\t\t\tfmt.Errorf(\"no user found, but auth is required.\"))\n\t\treturn nil, false\n\t}\n\n\treturn u, true\n\n}", "func (mr *MockStorageMockRecorder) GetStore(ctx, storeID interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetStore\", reflect.TypeOf((*MockStorage)(nil).GetStore), ctx, storeID)\n}", "func (mr *MockUserDBMockRecorder) AddUser(user interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"AddUser\", reflect.TypeOf((*MockUserDB)(nil).AddUser), user)\n}", "func (mr *MockStorageMockRecorder) CreateStore(ctx, store interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"CreateStore\", reflect.TypeOf((*MockStorage)(nil).CreateStore), ctx, store)\n}", "func (s *UserStore) GenericStore() *kallax.Store {\n\treturn s.Store\n}", "func (_m *UsersRepository) Store(users *entities.User) error {\n\tret := _m.Called(users)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(*entities.User) error); ok {\n\t\tr0 = rf(users)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (user *User) BeforeCreate(transaction *gorm.DB) error {\n return nil\n}" ]
[ "0.6924725", "0.62631965", "0.62323475", "0.6088104", "0.60815185", "0.58445543", "0.5817375", "0.5799972", "0.57668036", "0.5741914", "0.57245904", "0.5632725", "0.5601425", "0.5558256", "0.5529094", "0.5519546", "0.5519029", "0.549917", "0.5497812", "0.5476435", "0.5436344", "0.53989774", "0.5394878", "0.539177", "0.53701746", "0.5325254", "0.5320164", "0.53116", "0.5294384", "0.5284115", "0.52750415", "0.52717876", "0.52673334", "0.5267185", "0.52623945", "0.52496564", "0.5232178", "0.522674", "0.5226596", "0.5224545", "0.5197441", "0.51943094", "0.517497", "0.5159909", "0.5155208", "0.51437676", "0.51426876", "0.5141414", "0.51366633", "0.5132392", "0.51120055", "0.5110439", "0.5105135", "0.510194", "0.50926703", "0.50836337", "0.507801", "0.5067643", "0.5067643", "0.5066608", "0.50654876", "0.5060749", "0.5060017", "0.5058684", "0.5052396", "0.50492305", "0.50490284", "0.504858", "0.50482917", "0.5045708", "0.50430065", "0.50358236", "0.5033121", "0.5031856", "0.5028932", "0.5026279", "0.5023466", "0.5012662", "0.5012291", "0.50085783", "0.50050175", "0.500117", "0.49974862", "0.49910945", "0.49883524", "0.49810517", "0.49794376", "0.4976392", "0.49713594", "0.49694234", "0.49650607", "0.49499768", "0.49412733", "0.49341124", "0.49312213", "0.49292272", "0.4927065", "0.49193016", "0.49142435", "0.49091893" ]
0.690578
1
Verify mocks base method
func (m *MockClient) Verify(arg0, arg1 []byte) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Verify", arg0, arg1) ret0, _ := ret[0].(error) return ret0 }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (m *MockAuth) Verify(arg0 *common.Context, arg1 *plugin.PermissionRequest) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Verify\", arg0, arg1)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockPostForkBlock) Verify(arg0 context.Context) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Verify\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *IndexBucketModifierMock) CheckMocksCalled() {\n\tm.Finish()\n}", "func (m *MockCommandBase) Validate() error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Validate\")\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockisKey_KeyInfo) isKey_KeyInfo() {\n\tm.ctrl.Call(m, \"isKey_KeyInfo\")\n}", "func (m *RecentIndexStorageMock) CheckMocksCalled() {\n\tm.Finish()\n}", "func (m *MockLedgerClient) Verify(arg0 context.Context, arg1 *ledger.VerifyRequest, arg2 ...grpc.CallOption) (*ledger.VerifyResult, error) {\n\tvarargs := []interface{}{arg0, arg1}\n\tfor _, a := range arg2 {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"Verify\", varargs...)\n\tret0, _ := ret[0].(*ledger.VerifyResult)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockisCryptoAsymApiRespSetupPrivateKey_KeyInfo) isCryptoAsymApiRespSetupPrivateKey_KeyInfo() {\n\tm.ctrl.Call(m, \"isCryptoAsymApiRespSetupPrivateKey_KeyInfo\")\n}", "func (m *ModifierMock) CheckMocksCalled() {\n\tm.Finish()\n}", "func (m *MockManager) UpdateVersion() {\n\tm.ctrl.Call(m, \"UpdateVersion\")\n}", "func (m *TesterMock) CheckMocksCalled() {\n\tm.Finish()\n}", "func (m *MockFileInfo) Sys() interface{} {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Sys\")\n\tret0, _ := ret[0].(interface{})\n\treturn ret0\n}", "func (m *MockAuthService) Validate(arg0 http.ResponseWriter, arg1 *http.Request) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"Validate\", arg0, arg1)\n}", "func (m *MockRouterManager) Reloadable() bool {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Reloadable\")\n\tret0, _ := ret[0].(bool)\n\treturn ret0\n}", "func (m *MockPackClient) Rebase(arg0 context.Context, arg1 client.RebaseOptions) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Rebase\", arg0, arg1)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *ParcelMock) CheckMocksCalled() {\n\tm.Finish()\n}", "func (m *MockCandidatePropertyGetter) TotalMemorySize(arg0 bool) int64 {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"TotalMemorySize\", arg0)\n\tret0, _ := ret[0].(int64)\n\treturn ret0\n}", "func (m *SignatureKeyHolderMock) CheckMocksCalled() {\n\tm.Finish()\n}", "func (m *MockisCryptoApiResponse_CryptoApiResp) isCryptoApiResponse_CryptoApiResp() {\n\tm.ctrl.Call(m, \"isCryptoApiResponse_CryptoApiResp\")\n}", "func (m *MockPostForkBlock) verifyPreForkChild(arg0 context.Context, arg1 *preForkBlock) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"verifyPreForkChild\", arg0, arg1)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockOperation) Refresh() error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Refresh\")\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *IndexCollectionAccessorMock) CheckMocksCalled() {\n\tm.Finish()\n}", "func (m *MockServicer) CalculateHashAndDuration(startTime time.Time, fiveSecTimer *time.Timer, password string) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"CalculateHashAndDuration\", startTime, fiveSecTimer, password)\n}", "func (m *HeavySyncMock) CheckMocksCalled() {\n\tm.Finish()\n}", "func (m *MockisListenResponse_Content) isListenResponse_Content() {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"isListenResponse_Content\")\n}", "func (m *MockPostForkBlock) verifyPostForkChild(arg0 context.Context, arg1 *postForkBlock) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"verifyPostForkChild\", arg0, arg1)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func mockAlwaysRun() bool { return true }", "func (m *OutboundMock) CheckMocksCalled() {\n\tm.Finish()\n}", "func (m *UnsyncListMock) CheckMocksCalled() {\n\tm.Finish()\n}", "func (m *MockVirtualServiceClient) BaseClient() clients.ResourceClient {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"BaseClient\")\n\tret0, _ := ret[0].(clients.ResourceClient)\n\treturn ret0\n}", "func (m *CryptographyServiceMock) CheckMocksCalled() {\n\tm.Finish()\n}", "func (m *MockRemotePeer) Meta() p2pcommon.PeerMeta {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Meta\")\n\tret0, _ := ret[0].(p2pcommon.PeerMeta)\n\treturn ret0\n}", "func (m *MockCommand) Validate() error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Validate\")\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockResponseHandler) NotModified() {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"NotModified\")\n}", "func (m *MockVirtualServiceSet) Length() int {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Length\")\n\tret0, _ := ret[0].(int)\n\treturn ret0\n}", "func (m *MockVerifier) Verify(arg0 context.Context, arg1, arg2 string) (*oidc.IDTokenClaims, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Verify\", arg0, arg1, arg2)\n\tret0, _ := ret[0].(*oidc.IDTokenClaims)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *DelegationTokenFactoryMock) MinimockVerifyInspect() {\n\tfor _, e := range m.VerifyMock.expectations {\n\t\tif mm_atomic.LoadUint64(&e.Counter) < 1 {\n\t\t\tm.t.Errorf(\"Expected call to DelegationTokenFactoryMock.Verify with params: %#v\", *e.params)\n\t\t}\n\t}\n\n\t// if default expectation was set then invocations count should be greater than zero\n\tif m.VerifyMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterVerifyCounter) < 1 {\n\t\tif m.VerifyMock.defaultExpectation.params == nil {\n\t\t\tm.t.Error(\"Expected call to DelegationTokenFactoryMock.Verify\")\n\t\t} else {\n\t\t\tm.t.Errorf(\"Expected call to DelegationTokenFactoryMock.Verify with params: %#v\", *m.VerifyMock.defaultExpectation.params)\n\t\t}\n\t}\n\t// if func was set then invocations count should be greater than zero\n\tif m.funcVerify != nil && mm_atomic.LoadUint64(&m.afterVerifyCounter) < 1 {\n\t\tm.t.Error(\"Expected call to DelegationTokenFactoryMock.Verify\")\n\t}\n}", "func (m *MockShootClients) Version() *version.Info {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Version\")\n\tret0, _ := ret[0].(*version.Info)\n\treturn ret0\n}", "func (m *MockManager) Clear() {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"Clear\")\n}", "func (m *Mockloader) load() error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"load\")\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockmeshProvider) LastVerified() types.LayerID {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"LastVerified\")\n\tret0, _ := ret[0].(types.LayerID)\n\treturn ret0\n}", "func (m *HostNetworkMock) CheckMocksCalled() {\n\tm.Finish()\n}", "func (m *RecentIndexStorageMock) AllMocksCalled() bool {\n\n\tif !m.AddObjectFinished() {\n\t\treturn false\n\t}\n\n\tif !m.AddObjectWithTLLFinished() {\n\t\treturn false\n\t}\n\n\tif !m.DecreaseIndexTTLFinished() {\n\t\treturn false\n\t}\n\n\tif !m.FilterNotExistWithLockFinished() {\n\t\treturn false\n\t}\n\n\tif !m.GetObjectsFinished() {\n\t\treturn false\n\t}\n\n\treturn true\n}", "func (m *MockSystemContract) Exec() error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Exec\")\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockSessionRunner) RetireResetToken(arg0 [16]byte) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"RetireResetToken\", arg0)\n}", "func (m *MockBuilder) Generic() resource.ClusterSnapshot {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Generic\")\n\tret0, _ := ret[0].(resource.ClusterSnapshot)\n\treturn ret0\n}", "func (m *MockUnsafePdfServiceServer) mustEmbedUnimplementedPdfServiceServer() {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"mustEmbedUnimplementedPdfServiceServer\")\n}", "func (m *MockIVerification) CreateVerification(v *Verification) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"CreateVerification\", v)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockRemotePeer) Version() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Version\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func (m *ShifterMock) CheckMocksCalled() {\n\tm.Finish()\n}", "func (m *MockRouterTx) Reloadable() bool {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Reloadable\")\n\tret0, _ := ret[0].(bool)\n\treturn ret0\n}", "func (m *MockFullNode) MinerGetBaseInfo(arg0 context.Context, arg1 address.Address, arg2 abi.ChainEpoch, arg3 types0.TipSetKey) (*types0.MiningBaseInfo, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"MinerGetBaseInfo\", arg0, arg1, arg2, arg3)\n\tret0, _ := ret[0].(*types0.MiningBaseInfo)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockInfoErrorer) Info(arg0 string) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"Info\", arg0)\n}", "func (m *MockVirtualMeshSet) Length() int {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Length\")\n\tret0, _ := ret[0].(int)\n\treturn ret0\n}", "func (m *MockReminds) HandleGetLastRemindCommand(arg0 *discordgo.Session, arg1 *discordgo.MessageCreate) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"HandleGetLastRemindCommand\", arg0, arg1)\n}", "func (m *MockMempool) Size() int {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Size\")\n\tret0, _ := ret[0].(int)\n\treturn ret0\n}", "func (m *MockTaskManager) Handle(Definition *task.Definition) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Handle\", Definition)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *StateSwitcherMock) CheckMocksCalled() {\n\tm.Finish()\n}", "func (m *MockServiceDependencySet) Length() int {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Length\")\n\tret0, _ := ret[0].(int)\n\treturn ret0\n}", "func (m *ConsensusNetworkMock) CheckMocksCalled() {\n\tm.Finish()\n}", "func (m *MockMessageHandler) Sub(arg0 context.Context, arg1 *proto.SubRequest, arg2 *proto.Response) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Sub\", arg0, arg1, arg2)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *ActiveNodeMock) CheckMocksCalled() {\n\tm.Finish()\n}", "func (m *MockMachine) Version() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Version\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func (m *MockisCryptoApiRequest_CryptoApiReq) isCryptoApiRequest_CryptoApiReq() {\n\tm.ctrl.Call(m, \"isCryptoApiRequest_CryptoApiReq\")\n}", "func (m *MockVirtualServiceSet) Has(virtualService ezkube.ResourceId) bool {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Has\", virtualService)\n\tret0, _ := ret[0].(bool)\n\treturn ret0\n}", "func (m *MockClusterDescriber) BaseURI() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"BaseURI\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func (m *MockService) Refresh(arg0 string) (*idp.TokenResponse, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Refresh\", arg0)\n\tret0, _ := ret[0].(*idp.TokenResponse)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockEventLogger) Version() uint64 {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Version\")\n\tret0, _ := ret[0].(uint64)\n\treturn ret0\n}", "func mockNeverRun() bool { return false }", "func (m *MockHash) Reset() {\n\tm.ctrl.Call(m, \"Reset\")\n}", "func (m *MockMempool) Unlock() {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"Unlock\")\n}", "func (m *MockMoby) Info(ctx context.Context) (types.Info, error) {\n\tret := m.ctrl.Call(m, \"Info\", ctx)\n\tret0, _ := ret[0].(types.Info)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockCacheOptions) Validate() error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Validate\")\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockSeriesRefResolver) ReleaseRef() {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"ReleaseRef\")\n}", "func (m *MockDao) Healthy() bool {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Healthy\")\n\tret0, _ := ret[0].(bool)\n\treturn ret0\n}", "func (m *MockDao) Healthy() bool {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Healthy\")\n\tret0, _ := ret[0].(bool)\n\treturn ret0\n}", "func (m *MockDynamicCertPrivate) Run(arg0 context.Context, arg1 int) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"Run\", arg0, arg1)\n}", "func (m *MockProxy) Modify(proxy api.Proxy) (api.Proxy, error) {\n\tret := m.ctrl.Call(m, \"Modify\", proxy)\n\tret0, _ := ret[0].(api.Proxy)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockPodInterface) Bind(arg0 *v1.Binding) error {\n\tret := m.ctrl.Call(m, \"Bind\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockisBarcoGetReqDescrEntryResponse_ReqDescrMsg) isBarcoGetReqDescrEntryResponse_ReqDescrMsg() {\n\tm.ctrl.Call(m, \"isBarcoGetReqDescrEntryResponse_ReqDescrMsg\")\n}", "func (m *MockRemotePeer) ManageNumber() uint32 {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ManageNumber\")\n\tret0, _ := ret[0].(uint32)\n\treturn ret0\n}", "func (m *MockServicer) Complete(arg0 *reminder.Reminder) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Complete\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockResolver) Stop() {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"Stop\")\n}", "func (m *MockSessionRunner) Retire(arg0 protocol.ConnectionID) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"Retire\", arg0)\n}", "func (m *MockQueryer) RegeistMetricMeta(arg0, arg1, arg2 string, arg3 ...*pb.MetricMeta) error {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{arg0, arg1, arg2}\n\tfor _, a := range arg3 {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"RegeistMetricMeta\", varargs...)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockClusterScoper) BaseURI() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"BaseURI\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func (m *MockHook) Run() error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Run\")\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockManagedClusterScoper) BaseURI() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"BaseURI\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func (m *UnsyncListMock) AllMocksCalled() bool {\n\n\tif !m.AddClaimsFinished() {\n\t\treturn false\n\t}\n\n\tif !m.CalculateHashFinished() {\n\t\treturn false\n\t}\n\n\tif !m.GetActiveNodeFinished() {\n\t\treturn false\n\t}\n\n\tif !m.GetActiveNodesFinished() {\n\t\treturn false\n\t}\n\n\tif !m.IndexToRefFinished() {\n\t\treturn false\n\t}\n\n\tif !m.LengthFinished() {\n\t\treturn false\n\t}\n\n\tif !m.RefToIndexFinished() {\n\t\treturn false\n\t}\n\n\tif !m.RemoveClaimsFinished() {\n\t\treturn false\n\t}\n\n\treturn true\n}", "func mockedGranter(kubeutil *kube.Kube, app *v1.RadixRegistration, namespace string, serviceAccount *corev1.ServiceAccount) error {\n\treturn nil\n}", "func (m *MockUnsafeTodoServiceServer) mustEmbedUnimplementedTodoServiceServer() {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"mustEmbedUnimplementedTodoServiceServer\")\n}", "func (m *MockisCryptoAsymApiReqSetupPrivateKeyEx_Key) isCryptoAsymApiReqSetupPrivateKeyEx_Key() {\n\tm.ctrl.Call(m, \"isCryptoAsymApiReqSetupPrivateKeyEx_Key\")\n}", "func (m *mockCommand) Execute(ctx context.Context) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Execute\", ctx)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockRoutingRuleClient) BaseClient() clients.ResourceClient {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"BaseClient\")\n\tret0, _ := ret[0].(clients.ResourceClient)\n\treturn ret0\n}", "func (m *MockResponseHandler) TargetList() {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"TargetList\")\n}", "func (m *MockNotary) Notarize(arg0 string) (map[string]interface{}, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Notarize\", arg0)\n\tret0, _ := ret[0].(map[string]interface{})\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockEventLogger) VersionInitial() uint64 {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"VersionInitial\")\n\tret0, _ := ret[0].(uint64)\n\treturn ret0\n}", "func (m *MockSystemContract) Init(arg0 core.Keepers, arg1 types1.BaseTx, arg2 uint64) core.SystemContract {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Init\", arg0, arg1, arg2)\n\tret0, _ := ret[0].(core.SystemContract)\n\treturn ret0\n}", "func (m *MockStatePollerService) Refresh() error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Refresh\")\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockHealthCheck) RegisterStats() {\n\tm.ctrl.Call(m, \"RegisterStats\")\n}" ]
[ "0.63707566", "0.62389064", "0.6150061", "0.6032797", "0.60263306", "0.6017347", "0.5985903", "0.59731734", "0.59721094", "0.5944645", "0.59345305", "0.5932007", "0.5914505", "0.5902808", "0.58862764", "0.588578", "0.5875451", "0.5839451", "0.58214706", "0.58195907", "0.58038145", "0.58002555", "0.5795736", "0.57779354", "0.5769633", "0.57642823", "0.57620883", "0.5761422", "0.5753439", "0.57477057", "0.5739891", "0.5712142", "0.57024914", "0.57016444", "0.56994826", "0.56981516", "0.5695481", "0.56924266", "0.569206", "0.5688991", "0.56809044", "0.5662457", "0.5649333", "0.5649025", "0.5646003", "0.56456226", "0.5645446", "0.564213", "0.56413203", "0.5640564", "0.56357753", "0.5633503", "0.56244206", "0.5620083", "0.56139964", "0.56121033", "0.5606803", "0.5604503", "0.56029886", "0.560268", "0.56000185", "0.5599852", "0.5599384", "0.5589748", "0.5589126", "0.5587918", "0.5587105", "0.5586546", "0.5584996", "0.5580493", "0.55755186", "0.5569157", "0.5565927", "0.55636644", "0.5563433", "0.5563433", "0.5562591", "0.5555543", "0.5554188", "0.5552612", "0.5552309", "0.5545482", "0.5543662", "0.55413026", "0.55409324", "0.5540882", "0.55402374", "0.5536567", "0.55254936", "0.5522222", "0.55168176", "0.5515758", "0.55124575", "0.5511979", "0.5501415", "0.550105", "0.5498227", "0.54921424", "0.54920983", "0.5487903" ]
0.62211305
2
Verify indicates an expected call of Verify
func (mr *MockClientMockRecorder) Verify(arg0, arg1 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Verify", reflect.TypeOf((*MockClient)(nil).Verify), arg0, arg1) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func Verify() bool {\n\treturn true\n}", "func (mr *MockVerifierMockRecorder) Verify(arg0, arg1, arg2 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Verify\", reflect.TypeOf((*MockVerifier)(nil).Verify), arg0, arg1, arg2)\n}", "func (mr *MockLedgerClientMockRecorder) Verify(arg0, arg1 interface{}, arg2 ...interface{}) *gomock.Call {\n\tvarargs := append([]interface{}{arg0, arg1}, arg2...)\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Verify\", reflect.TypeOf((*MockLedgerClient)(nil).Verify), varargs...)\n}", "func (b *KRMBlueprintTest) Verify(assert *assert.Assertions) {\n\tb.verify(assert)\n}", "func (mr *MockAuthMockRecorder) Verify(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Verify\", reflect.TypeOf((*MockAuth)(nil).Verify), arg0, arg1)\n}", "func (v *Verifier) Verify(msg []byte, sig []byte) error {\n\treturn errors.New(\"NotImplemented\")\n}", "func (mr *MockPostForkBlockMockRecorder) Verify(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Verify\", reflect.TypeOf((*MockPostForkBlock)(nil).Verify), arg0)\n}", "func (b *Benchmark) Verify() {\n\tpanic(\"not implemented\")\n}", "func (b *Benchmark) Verify() {\n\tpanic(\"not implemented\")\n}", "func (_Ethdkg *EthdkgCaller) Verify(opts *bind.CallOpts, message []byte, sig [2]*big.Int, pubK [4]*big.Int) (bool, error) {\n\tvar (\n\t\tret0 = new(bool)\n\t)\n\tout := ret0\n\terr := _Ethdkg.contract.Call(opts, out, \"Verify\", message, sig, pubK)\n\treturn *ret0, err\n}", "func (api *Api) verify() error {\n\treturn nil\n}", "func Verify(candidate *Record) error {\n\treturn nil\n}", "func (t *Trace) Verify(s *logic.S) []error {\n\tvar errors []error\n\ttv, err := newTv(t, s)\n\tif err != nil {\n\t\terrors = append(errors, err)\n\t\treturn errors\n\t}\n\tN := t.n\n\tfor i := 1; i < N; i++ {\n\t\tif err := tv.step(i); err != nil {\n\t\t\terrors = append(errors, err)\n\t\t}\n\t}\n\ts.Eval(tv.vsA)\n\tfor i, m := range t.Watches {\n\t\tif tv.wCounts[i] != 0 {\n\t\t\tcontinue\n\t\t}\n\t\twv := tv.vsA[m.Var()]\n\t\tif !m.IsPos() {\n\t\t\twv = !wv\n\t\t}\n\t\tif !wv {\n\t\t\terrors = append(errors, fmt.Errorf(\"ErrWatchFalse: %s\", m))\n\t\t}\n\t}\n\treturn errors\n}", "func (v *Validator) Verify() error {\n\tswitch {\n\tcase v.Wght == 0: // Ensure the validator has some weight\n\t\treturn ErrWeightTooSmall\n\tdefault:\n\t\treturn nil\n\t}\n}", "func (p *Proxy) Verify() error {\n\treturn nil\n}", "func (u *walletIdentity) Verify(msg []byte, sig []byte) error {\n\treturn errors.New(\"not implemented\")\n}", "func (a *manualActivity) Verify() error {\n\tif a.Start.IsZero() {\n\t\treturn errors.New(\"missing Start\")\n\t}\n\tif a.ActivityType == \"\" {\n\t\treturn errors.New(\"missing Activity Type\")\n\t}\n\tif !validActivityType[a.ActivityType] {\n\t\treturn fmt.Errorf(\"invalid Activity Type %q\", a.ActivityType)\n\t}\n\tif a.Name == \"\" {\n\t\treturn errors.New(\"missing Name\")\n\t}\n\treturn nil\n}", "func (tok RPCToken) Verify() error {\n\tif tok.Kind != TokenKindRPC {\n\t\treturn fmt.Errorf(\"expected rpc token, got %s token\", tok.Kind)\n\t}\n\treturn nil\n}", "func TestVerify(t *testing.T) {\n\t// Run the code\n\tvalidTest := Verify(testFile, validHash)\n\tvalidUpperTest := Verify(testFile, validHashUpper)\n\tinvalidTest := Verify(testFile, invalidHash)\n\n\t// Compare output\n\tif have, want := validTest, true; have != want {\n\t\tt.Errorf(\"Valid hash test: have %v, want %v\", have, want)\n\t}\n\n\tif have, want := validUpperTest, true; have != want {\n\t\tt.Errorf(\"Valid upper hash test: have %v, want %v\", have, want)\n\t}\n\n\t// Compare output\n\tif have, want := invalidTest, false; have != want {\n\t\tt.Errorf(\"Invalid hash test: have %v, want %v\", have, want)\n\t}\n}", "func (req *TPLUpdateVoiceNotifyRequest) Verify() error {\n\tif req.ID == 0 {\n\t\treturn errors.New(\"Miss param: tpl_id\")\n\t}\n\tif len(req.Content) == 0 {\n\t\treturn errors.New(\"Miss param: tpl_content\")\n\t}\n\treturn nil\n}", "func Verify(since string, filterExpr []string, reports []TestReport) (bool, string) {\n\tbw := io.NewBufferWriter()\n\tok, out, err := verify(since, filterExpr, reports)\n\tio.ReplyEitherNL(bw, err, out)\n\treturn ok, bw.String()\n}", "func (a *updatableActivity) Verify(prev *updatableActivity) error {\n\tif !a.Start.Equal(prev.Start) {\n\t\treturn errors.New(\"sorry, can't modify Start\")\n\t}\n\treturn nil\n}", "func (m *DelegationTokenFactoryMock) MinimockVerifyInspect() {\n\tfor _, e := range m.VerifyMock.expectations {\n\t\tif mm_atomic.LoadUint64(&e.Counter) < 1 {\n\t\t\tm.t.Errorf(\"Expected call to DelegationTokenFactoryMock.Verify with params: %#v\", *e.params)\n\t\t}\n\t}\n\n\t// if default expectation was set then invocations count should be greater than zero\n\tif m.VerifyMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterVerifyCounter) < 1 {\n\t\tif m.VerifyMock.defaultExpectation.params == nil {\n\t\t\tm.t.Error(\"Expected call to DelegationTokenFactoryMock.Verify\")\n\t\t} else {\n\t\t\tm.t.Errorf(\"Expected call to DelegationTokenFactoryMock.Verify with params: %#v\", *m.VerifyMock.defaultExpectation.params)\n\t\t}\n\t}\n\t// if func was set then invocations count should be greater than zero\n\tif m.funcVerify != nil && mm_atomic.LoadUint64(&m.afterVerifyCounter) < 1 {\n\t\tm.t.Error(\"Expected call to DelegationTokenFactoryMock.Verify\")\n\t}\n}", "func (req *TPLAddVoiceNotifyRequest) Verify() error {\n\tif len(req.Content) == 0 {\n\t\treturn errors.New(\"Miss param: tpl_content\")\n\t}\n\treturn nil\n}", "func (m *MockLedgerClient) Verify(arg0 context.Context, arg1 *ledger.VerifyRequest, arg2 ...grpc.CallOption) (*ledger.VerifyResult, error) {\n\tvarargs := []interface{}{arg0, arg1}\n\tfor _, a := range arg2 {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"Verify\", varargs...)\n\tret0, _ := ret[0].(*ledger.VerifyResult)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (fm *FieldModelFlagsSimple) Verify() bool { return true }", "func (s BlockchainStatus) Verify() error {\n\tswitch s {\n\tcase UnknownChain, Created, Preferred, Validating, Syncing:\n\t\treturn nil\n\tdefault:\n\t\treturn errUnknownBlockchainStatus\n\t}\n}", "func (v *ModelVerifier) Verify(t *testing.T) {\n\tfor _, verifier := range v.verifiers {\n\t\tverifier.Verify(t)\n\t}\n}", "func (g *NymGenerator) Verify(z *big.Int) bool {\n\treturn g.verifier.Verify(z)\n}", "func Verify(params *Params, attrs AttributeList, signature *Signature, message *big.Int) bool {\n\treturn VerifyPrecomputed(params, PrepareAttributeSet(params, attrs), signature, message)\n}", "func Verify(in interface{}, key, correctSign string) (bool, error) {\n\tparams, err := ToParams(in)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tsign := Sign(params, key)\n\tif sign != correctSign {\n\t\treturn false, fmt.Errorf(\"signed error: wanted %s, got %s\", correctSign, sign)\n\t}\n\treturn true, nil\n}", "func (c *Config) Verify() util.MultiError {\n\treturn util.MultiError{}\n}", "func (a *API) Verify(w http.ResponseWriter, r *http.Request) error {\n\tctx := r.Context()\n\tconfig := a.getConfig(ctx)\n\n\tparams := &VerifyParams{}\n\tcookie := r.Header.Get(useCookieHeader)\n\tjsonDecoder := json.NewDecoder(r.Body)\n\tif err := jsonDecoder.Decode(params); err != nil {\n\t\treturn badRequestError(\"Could not read verification params: %v\", err)\n\t}\n\n\tif params.Token == \"\" {\n\t\treturn unprocessableEntityError(\"Verify requires a token\")\n\t}\n\n\tvar (\n\t\tuser *models.User\n\t\terr error\n\t)\n\n\tswitch params.Type {\n\tcase signupVerification:\n\t\tuser, err = a.signupVerify(ctx, params)\n\tcase recoveryVerification:\n\t\tuser, err = a.recoverVerify(ctx, params)\n\tdefault:\n\t\treturn unprocessableEntityError(\"Verify requires a verification type\")\n\t}\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif cookie != \"\" && config.Cookie.Duration > 0 {\n\t\tif err = a.setCookieToken(config, user, cookie == useSessionCookie, w); err != nil {\n\t\t\treturn internalServerError(\"Failed to set JWT cookie\", err)\n\t\t}\n\t}\n\n\treturn a.sendRefreshToken(ctx, user, w)\n}", "func (m *MockAuth) Verify(arg0 *common.Context, arg1 *plugin.PermissionRequest) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Verify\", arg0, arg1)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (w *Watcher) Verify() error {\n\t_, err := w.DynamicClient.\n\t\tResource(w.GroupVersionResource).\n\t\tNamespace(\"\").\n\t\tList(metav1.ListOptions{})\n\treturn err\n}", "func (_Ethdkg *EthdkgCallerSession) Verify(message []byte, sig [2]*big.Int, pubK [4]*big.Int) (bool, error) {\n\treturn _Ethdkg.Contract.Verify(&_Ethdkg.CallOpts, message, sig, pubK)\n}", "func (cgs *CmdGetSlotNumWithRegNum) Verify() error {\n\tif perror.Empty == cgs.RegistrationNumber {\n\t\treturn perror.ErrInvalidParams\n\t}\n\treturn nil\n}", "func (n *noopRules) Verify(acc *Account, res *Resource, opts ...VerifyOption) error {\n\treturn nil\n}", "func (fm *FinalModelStructOptional) Verify() int {\n fm.buffer.Shift(fm.FBEOffset())\n fbeResult := fm.VerifyFields()\n fm.buffer.Unshift(fm.FBEOffset())\n return fbeResult\n}", "func (p *Pagination) Verify() error {\n\tif p.PageNum < 0 {\n\t\treturn ecode.MerlinIllegalPageNumErr\n\t} else if p.PageNum == 0 {\n\t\tp.PageNum = DefaultPageNum\n\t}\n\tif p.PageSize < 0 {\n\t\treturn ecode.MerlinIllegalPageSizeErr\n\t} else if p.PageSize == 0 {\n\t\tp.PageSize = DefaultPageSize\n\t}\n\treturn nil\n}", "func (b *KRMBlueprintTest) DefineVerify(verify func(*assert.Assertions)) {\n\tb.verify = verify\n}", "func (c *Client) Verify(ctx context.Context, params *VerifyInput, optFns ...func(*Options)) (*VerifyOutput, error) {\n\tif params == nil {\n\t\tparams = &VerifyInput{}\n\t}\n\n\tresult, metadata, err := c.invokeOperation(ctx, \"Verify\", params, optFns, c.addOperationVerifyMiddlewares)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tout := result.(*VerifyOutput)\n\tout.ResultMetadata = metadata\n\treturn out, nil\n}", "func (v *Prover) Verify(V *Point, proof BulletProof) bool {\n\treturn rangeProofVerify(v.n, V, proof, v.ValueGenerator,\n\t\tv.BlindingGenerator, v.G[:v.n], v.H[:v.n])\n}", "func (fm FieldModelState) Verify() bool { return true }", "func (mr *MockTransactionApiMockRecorder) VerifySign(tx, outpoint, amount, txinUtxoList interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"VerifySign\", reflect.TypeOf((*MockTransactionApi)(nil).VerifySign), tx, outpoint, amount, txinUtxoList)\n}", "func (s *ACOSettings) Verify() error {\n\tif s.Evaporation <= 0 || s.Evaporation > 1 {\n\t\treturn errors.New(\"Evaporation must be a value in (0, 1]\")\n\t}\n\treturn nil\n}", "func (r *apiV1Router) Verify(ctx *gin.Context) {\n\tclaims := extractClaimsFromCtx(ctx)\n\tif claims == nil {\n\t\tr.logger.Warn(\"could not extract auth claims from request context\")\n\t\tmodels.SendAPIError(ctx, http.StatusBadRequest, \"missing auth information\")\n\t\treturn\n\t}\n\n\tr.logger.Info(\"claims\", zap.Any(\"claims\", claims))\n\tctx.JSON(http.StatusOK, verifyRes{\n\t\tResponse: models.Response{\n\t\t\tStatus: http.StatusOK,\n\t\t},\n\t\tAuthLevel: claims.AuthLevel,\n\t\tUserID: claims.Id,\n\t})\n}", "func (service *Stainless) Verify(\n\treq *proto.VerificationRequest) (network.Message, error) {\n\tconsole, report, err := verify(req.SourceFiles)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlog.Lvl4(\"Returning\", console, report)\n\n\treturn &proto.VerificationResponse{\n\t\tConsole: console,\n\t\tReport: report,\n\t}, nil\n}", "func (cp *CmdExit) Verify() error {\n\treturn nil\n}", "func (a *Parser) verify() error {\n\tfor n, p := range a.params {\n\t\tif n == p.name {\n\t\t\tvalue := reflValue(p.target)\n\t\t\tswitch value.Kind() {\n\t\t\tcase reflect.Slice:\n\t\t\t\tfor i := p.count; i < reflLen(p.target); i++ {\n\t\t\t\t\tif p.scan != nil {\n\t\t\t\t\t\t// scan remaining initial values to ensure they are okay\n\t\t\t\t\t\te := p.scan(fmt.Sprint(reflElement(i, value)), reflCopy(reflElementAddr(i, value)))\n\t\t\t\t\t\tif e != nil {\n\t\t\t\t\t\t\treturn decorate(fmt.Errorf(\"invalid default value at offset %d: %v\", i, e), n)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\tcase reflect.Array:\n\t\t\t\tif p.count != p.limit {\n\t\t\t\t\treturn decorate(fmt.Errorf(\"%d value%s specified but exactly %d expected\", p.count, plural(p.count), p.limit), n)\n\t\t\t\t}\n\t\t\tdefault:\n\t\t\t\t// single-valued parameter\n\t\t\t\tif p.count < 1 {\n\t\t\t\t\tif p.limit != 0 {\n\t\t\t\t\t\treturn decorate(fmt.Errorf(\"mandatory parameter not set\"), n)\n\t\t\t\t\t}\n\t\t\t\t\t// scan initial value (into a copy) to ensure it's okay\n\t\t\t\t\tif p.scan != nil {\n\t\t\t\t\t\te := p.scan(fmt.Sprint(value), reflCopy(p.target))\n\t\t\t\t\t\tif e != nil {\n\t\t\t\t\t\t\treturn decorate(fmt.Errorf(\"invalid default value: %v\", e), n)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func verify(err error, str interface{}) {\n\tif err != nil {\n\t\tfmt.Printf(\"Error retrieving flag for %s \\n\", str)\n\t\tos.Exit(1)\n\t}\n}", "func (out *TransferableOutput) Verify() error {\n\tswitch {\n\tcase out == nil:\n\t\treturn errNilTransferableOutput\n\tcase out.Out == nil:\n\t\treturn errNilTransferableFxOutput\n\tdefault:\n\t\treturn verify.All(&out.Asset, out.Out)\n\t}\n}", "func (m match) verify() error {\n\tif !(minDistance <= m.distance && m.distance <= maxDistance) {\n\t\treturn errors.New(\"distance out of range\")\n\t}\n\tif !(1 <= m.n && m.n <= maxMatchLen) {\n\t\treturn errors.New(\"length out of range\")\n\t}\n\treturn nil\n}", "func (vlt *FabV14Validator) Verify(address, from string, proof, payload []byte, validators string) (bool, error) {\n\tvar err error\n\tvInfo, ok := vlt.evMap[from]\n\tif !ok {\n\t\tvInfo, err = validatorlib.UnmarshalValidatorInfo([]byte(validators))\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\t\tvlt.evMap[from] = vInfo\n\t}\n\t// Get the validation artifacts that help validate the chaincodeID and policy\n\tartifact, err := validatorlib.PreCheck(proof, payload, vInfo.Cid)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tsignatureSet := validatorlib.GetSignatureSet(artifact)\n\n\tpolicy, ok := vlt.ppMap[vInfo.ChainId]\n\tif !ok {\n\t\tpe, err := validatorlib.NewPolicyEvaluator(vInfo.ConfByte)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\t\tpp := cauthdsl.NewPolicyProvider(pe.IdentityDeserializer)\n\t\tpolicy, _, err = pp.NewPolicy([]byte(vInfo.Policy))\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\t\tvlt.ppMap[vInfo.ChainId] = policy\n\t\tvlt.peMap[vInfo.ChainId] = pe\n\t}\n\n\tpe := vlt.peMap[vInfo.ChainId]\n\treturn vlt.EvaluateSignedData(signatureSet, pe.IdentityDeserializer, policy)\n}", "func (m *CryptographyServiceMock) Verify(p crypto.PublicKey, p1 insolar.Signature, p2 []byte) (r bool) {\n\tcounter := atomic.AddUint64(&m.VerifyPreCounter, 1)\n\tdefer atomic.AddUint64(&m.VerifyCounter, 1)\n\n\tif len(m.VerifyMock.expectationSeries) > 0 {\n\t\tif counter > uint64(len(m.VerifyMock.expectationSeries)) {\n\t\t\tm.t.Fatalf(\"Unexpected call to CryptographyServiceMock.Verify. %v %v %v\", p, p1, p2)\n\t\t\treturn\n\t\t}\n\n\t\tinput := m.VerifyMock.expectationSeries[counter-1].input\n\t\ttestify_assert.Equal(m.t, *input, CryptographyServiceMockVerifyInput{p, p1, p2}, \"CryptographyService.Verify got unexpected parameters\")\n\n\t\tresult := m.VerifyMock.expectationSeries[counter-1].result\n\t\tif result == nil {\n\t\t\tm.t.Fatal(\"No results are set for the CryptographyServiceMock.Verify\")\n\t\t\treturn\n\t\t}\n\n\t\tr = result.r\n\n\t\treturn\n\t}\n\n\tif m.VerifyMock.mainExpectation != nil {\n\n\t\tinput := m.VerifyMock.mainExpectation.input\n\t\tif input != nil {\n\t\t\ttestify_assert.Equal(m.t, *input, CryptographyServiceMockVerifyInput{p, p1, p2}, \"CryptographyService.Verify got unexpected parameters\")\n\t\t}\n\n\t\tresult := m.VerifyMock.mainExpectation.result\n\t\tif result == nil {\n\t\t\tm.t.Fatal(\"No results are set for the CryptographyServiceMock.Verify\")\n\t\t}\n\n\t\tr = result.r\n\n\t\treturn\n\t}\n\n\tif m.VerifyFunc == nil {\n\t\tm.t.Fatalf(\"Unexpected call to CryptographyServiceMock.Verify. %v %v %v\", p, p1, p2)\n\t\treturn\n\t}\n\n\treturn m.VerifyFunc(p, p1, p2)\n}", "func (m *MockPostForkBlock) Verify(arg0 context.Context) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Verify\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func Verify(conf *opti.Config, pre *IndexedStep, ref *IndexedStep, expectedPostStepRoot [32]byte) (ok bool, err error) {\n\tpartial := &partialTrace{Ref: ref, Pre: pre}\n\tout, err := conf.NextStep(partial)\n\tif err != nil {\n\t\treturn false, fmt.Errorf(\"failed to produce next step: %v\", err)\n\t}\n\toutRoot := out.HashTreeRoot(tree.GetHashFn())\n\treturn outRoot == expectedPostStepRoot, nil\n}", "func (rid *ReserveIDRequest) Verify() error {\n\tif rid == nil {\n\t\treturn errors.New(\"rid is nil\")\n\t}\n\n\tif rid.ProposingNID == \"\" {\n\t\treturn errors.New(\"rid.ProposingNID is empty\")\n\t}\n\n\treturn nil\n}", "func Verify(t *testing.T) bool {\n\tif ingressType == SECURE {\n\t\tif PoolVerification(t) == true && VSVerification(t) == true && DNSARecordsVerification(t, ingressHostNames) == true {\n\t\t\tt.Logf(\"Pools, VSes and DNS A Records verified\")\n\t\t\treturn true\n\t\t}\n\t} else if ingressType == MULTIHOST {\n\t\thostName := append(ingressSecureHostNames, ingressInsecureHostNames...)\n\t\tif PoolVerification(t) == true && VSVerification(t) == true && DNSARecordsVerification(t, hostName) == true {\n\t\t\tt.Logf(\"Pools, VSes and DNS A Records verified\")\n\t\t\treturn true\n\t\t}\n\t} else if ingressType == INSECURE {\n\t\tif PoolVerification(t) == true && DNSARecordsVerification(t, ingressHostNames) == true {\n\t\t\tt.Logf(\"Pools and DNS A Records verified\")\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func Verify(suite suites.Suite, X kyber.Point, msg, sig []byte) error {\n\tHM := hashToPoint(suite, msg)\n\ts := suite.G1().Point()\n\tif err := s.UnmarshalBinary(sig); err != nil {\n\t\treturn err\n\t}\n\ts.Neg(s)\n\tif !suite.PairingCheck([]kyber.Point{s, HM}, []kyber.Point{suite.G2().Point().Base(), X}) {\n\t\treturn errors.New(\"bls: invalid signature\")\n\t}\n\treturn nil\n}", "func (mb *tcpPackager) Verify(aduRequest []byte, aduResponse []byte) error {\n\treturn verify(aduRequest, aduResponse)\n}", "func (crc *CmdGetRegNumWithColour) Verify() error {\n\t\tif perror.Empty == crc.Color {\n\t\t\treturn perror.ErrInvalidParams\n\t\t}\n\t\treturn nil\n\t}", "func (a *API) Verify(w http.ResponseWriter, r *http.Request) error {\n\tswitch r.Method {\n\tcase http.MethodGet:\n\t\treturn a.verifyGet(w, r)\n\tcase http.MethodPost:\n\t\treturn a.verifyPost(w, r)\n\tdefault:\n\t\treturn unprocessableEntityError(\"Only GET and POST methods are supported.\")\n\t}\n}", "func (crc *CmdGetRegNumWithColour) Verify() error {\n\tif perror.Empty == crc.Color {\n\t\treturn perror.ErrInvalidParams\n\t}\n\treturn nil\n}", "func Verify(ctx context.Context, provable proof.Provable, provider DIDDocProvider) error {\n\tp := provable.GetProof()\n\tif p == nil {\n\t\treturn fmt.Errorf(\"missing proof\")\n\t}\n\n\tkeyRef := p.GetVerificationMethod()\n\tid := did.ExtractDIDFromKeyRef(keyRef)\n\n\tdidDoc, err := provider(ctx, id)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tkeyDef := didDoc.GetPublicKey(keyRef)\n\tif keyDef == nil {\n\t\treturn fmt.Errorf(\"could not find key with id: %s\", keyRef)\n\t}\n\n\tverifier, err := did.AsVerifier(*keyDef)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsuite, err := proof.SignatureSuites().GetSuiteForProof(p)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn suite.Verify(provable, verifier)\n}", "func (b *Base) Verify(req *VerifyReq) error {\n\treturn ErrFunctionNotSupported\n}", "func TestVerifyForged(t *testing.T) {\n\toptions := iniVerifyOptions(t)\n\toptions.CurrentTime = time.Date(2017, 02, 03, 11, 00, 00, 0, gmt)\n\n\tp := loadProxy(\"test-samples/BadForgedProxy.pem\", t)\n\tif e := p.Verify(options); e == nil {\n\t\tt.Error(\"Must have failed\")\n\t} else {\n\t\tt.Log(e)\n\t}\n}", "func (req *TPLDelRequest) Verify() error {\n\tif req.ID == 0 {\n\t\treturn errors.New(\"Miss param: tpl_id\")\n\t}\n\treturn nil\n}", "func (m EncMessage) Verify(k []byte) error {\n\treturn errors.New(\"Verify method must be overridden\")\n}", "func (validator *validatorImpl) Verify(vkID, signature, message []byte) error {\n\tcert, err := validator.getEnrollmentCert(vkID)\n\tif err != nil {\n\t\tvalidator.peer.node.log.Error(\"Failed getting enrollment cert \", utils.EncodeBase64(vkID), err)\n\t}\n\n\tvk := cert.PublicKey.(*ecdsa.PublicKey)\n\n\tok, err := validator.verify(vk, message, signature)\n\tif err != nil {\n\t\tvalidator.peer.node.log.Error(\"Failed verifying signature for \", utils.EncodeBase64(vkID), err)\n\t}\n\n\tif !ok {\n\t\tvalidator.peer.node.log.Error(\"Failed invalid signature for \", utils.EncodeBase64(vkID))\n\n\t\treturn utils.ErrInvalidSignature\n\t}\n\n\treturn nil\n}", "func (m *MockClient) Verify(arg0, arg1 []byte) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Verify\", arg0, arg1)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func TestVerifyToken(t *testing.T) {\n t.Errorf(\"No tests written yet for VerifyToken()\")\n}", "func (i *Index) Verify(ctx context.Context, store Store) (diff IndexDiff, err error) {\n\treturn i.verify(ctx, store, true)\n}", "func (b *Base) Verify() error {\n\tif !b.VerifyOrderbook {\n\t\treturn nil\n\t}\n\n\t// Checking for both ask and bid lengths being zero has been removed and\n\t// a warning has been put in place for some exchanges that return zero\n\t// level books. In the event that there is a massive liquidity change where\n\t// a book dries up, this will still update so we do not traverse potential\n\t// incorrect old data.\n\tif len(b.Asks) == 0 || len(b.Bids) == 0 {\n\t\tlog.Warnf(log.OrderBook,\n\t\t\tbookLengthIssue,\n\t\t\tb.Exchange,\n\t\t\tb.Pair,\n\t\t\tb.Asset,\n\t\t\tlen(b.Bids),\n\t\t\tlen(b.Asks))\n\t}\n\terr := checkAlignment(b.Bids, b.IsFundingRate, b.PriceDuplication, b.IDAlignment, dsc, b.Exchange)\n\tif err != nil {\n\t\treturn fmt.Errorf(bidLoadBookFailure, b.Exchange, b.Pair, b.Asset, err)\n\t}\n\terr = checkAlignment(b.Asks, b.IsFundingRate, b.PriceDuplication, b.IDAlignment, asc, b.Exchange)\n\tif err != nil {\n\t\treturn fmt.Errorf(askLoadBookFailure, b.Exchange, b.Pair, b.Asset, err)\n\t}\n\treturn nil\n}", "func Verify(p *Protocol) error {\n\tfor _, t := range p.Types {\n\t\tif err := verifyClass(t); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (c *Config) Verify() error {\n\tif c.Lager == nil {\n\t\treturn ErrInvalidLager\n\t}\n\n\tif c.Pool == nil {\n\t\treturn ErrInvalidPool\n\t}\n\n\treturn nil\n}", "func (c MockClient) Verify(matcher RequestMatcher, times Times) error {\n\tpayload := map[string]interface{}{\n\t\t\"httpRequest\": matcher,\n\t\t\"times\": times,\n\t}\n\n\tresp, err := c.restyClient.NewRequest().\n\t\tSetDoNotParseResponse(true).\n\t\tSetBody(payload).\n\t\tPut(\"/mockserver/verify\")\n\n\tif err != nil {\n\t\treturn stacktrace.Propagate(err, \"error calling verify endpoint\")\n\t}\n\tif resp.StatusCode() == http.StatusAccepted {\n\t\treturn nil\n\t}\n\tbuf := new(bytes.Buffer)\n\tbuf.ReadFrom(resp.RawBody())\n\n\treturn stacktrace.Propagate(errors.New(buf.String()), \"verification failed\")\n}", "func (req *TPLUpdateRequest) Verify() error {\n\tif req.ID == 0 {\n\t\treturn errors.New(\"Miss param: tpl_id\")\n\t}\n\tif len(req.Content) == 0 {\n\t\treturn errors.New(\"Miss param: tpl_content\")\n\t}\n\treturn nil\n}", "func (in *Instance) Verify() bool {\n\tx := in.challenge\n\ty := in.y\n\tvar ri *big.Int\n\tfor i := uint64(0); i < uint64(len(in.mu)); i++ {\n\t\tri = in.hash(x, y, in.mu[i], in.T/(1<<i))\n\t\txii := new(big.Int).Exp(x, ri, in.rsaModulus)\n\t\txii.Mul(xii, in.mu[i])\n\t\txii.Mod(xii, in.rsaModulus)\n\t\tx = xii\n\t\tyii := new(big.Int).Exp(in.mu[i], ri, in.rsaModulus)\n\t\tyii.Mul(yii, y)\n\t\tyii.Mod(yii, in.rsaModulus)\n\t\ty = yii\n\t}\n\treturn Square(x, in.rsaModulus, 1).Cmp(y) == 0\n}", "func (_Ethdkg *EthdkgSession) Verify(message []byte, sig [2]*big.Int, pubK [4]*big.Int) (bool, error) {\n\treturn _Ethdkg.Contract.Verify(&_Ethdkg.CallOpts, message, sig, pubK)\n}", "func (in *TransferableInput) Verify() error {\n\tswitch {\n\tcase in == nil:\n\t\treturn errNilTransferableInput\n\tcase in.In == nil:\n\t\treturn errNilTransferableFxInput\n\tdefault:\n\t\treturn verify.All(&in.UTXOID, &in.Asset, in.In)\n\t}\n}", "func (w *ServerInterfaceWrapper) Verify(ctx echo.Context) error {\n\tvar err error\n\n\t// Invoke the callback with all the unmarshalled arguments\n\terr = w.Handler.Verify(ctx)\n\treturn err\n}", "func (fm *FinalModelStructBytes) Verify() int {\n fm.buffer.Shift(fm.FBEOffset())\n fbeResult := fm.VerifyFields()\n fm.buffer.Unshift(fm.FBEOffset())\n return fbeResult\n}", "func TestVerifyElement(t *testing.T) {\n\tv := verifyElement(\"3\")\n\tif v != 3 {\n\t\tt.Error(\"Expected 3, got \", v)\n\t}\n}", "func (v *Verifier) Verify(snapshot *Snapshot) error {\n\tvar err error\n\n\t// Basic timestamp checks.\n\tnow := timeNow()\n\tif snapshot.When.After(now) {\n\t\treturn errors.New(\"snapshot is from the future\")\n\t}\n\tif snapshot.When.Before(now.Add(-maxExportStaleness)) {\n\t\treturn fmt.Errorf(\"snapshot is too old; it is from %v, expected at least %v (%v from now)\", snapshot.When, now.Add(-maxExportStaleness), maxExportStaleness)\n\t}\n\n\t// Start critical section.\n\tv.mu.Lock()\n\tdefer v.mu.Unlock()\n\n\t// Metrics checks.\n\tfieldsSeen := make(map[string]map[string]struct{}, len(v.knownMetrics))\n\tdataToFieldsSeen := make(map[*Data]string, len(snapshot.Data))\n\tfor _, data := range snapshot.Data {\n\t\tmetricName := data.Metric.Name\n\t\tverifiableM, found := v.knownMetrics[metricName]\n\t\tif !found {\n\t\t\treturn fmt.Errorf(\"snapshot contains unknown metric %q\", metricName)\n\t\t}\n\t\tmetricName = globalIntern(metricName)\n\t\tmetricFieldsSeen, found := fieldsSeen[metricName]\n\t\tif !found {\n\t\t\tmetricFieldsSeen = make(map[string]struct{}, verifiableM.numFieldCombinations())\n\t\t\tfieldsSeen[metricName] = metricFieldsSeen\n\t\t}\n\t\tif err = verifiableM.verify(data, metricFieldsSeen, dataToFieldsSeen); err != nil {\n\t\t\treturn fmt.Errorf(\"metric %q: %v\", metricName, err)\n\t\t}\n\t}\n\n\tif v.lastTimestamp.After(snapshot.When) {\n\t\treturn fmt.Errorf(\"consecutive snapshots are not chronologically ordered: last verified snapshot was exported at %v, this one is from %v\", v.lastTimestamp, snapshot.When)\n\t}\n\n\tfor _, data := range snapshot.Data {\n\t\tif err := v.knownMetrics[data.Metric.Name].verifyIncrement(data, dataToFieldsSeen[data], v.lastPacker); err != nil {\n\t\t\treturn fmt.Errorf(\"metric %q: %v\", data.Metric.Name, err)\n\t\t}\n\t}\n\tvar neededPackerCapacity uint64\n\tfor _, data := range snapshot.Data {\n\t\tneededPackerCapacity += v.knownMetrics[data.Metric.Name].packerCapacityNeededForData(data, dataToFieldsSeen[data])\n\t}\n\tfor name, metric := range v.knownMetrics {\n\t\tneededPackerCapacity += metric.packerCapacityNeededForLast(fieldsSeen[name])\n\t}\n\tif neededPackerCapacity > uint64(valueField) {\n\t\treturn fmt.Errorf(\"snapshot contains too many large numbers to fit into packer memory (%d numbers needing indirection)\", neededPackerCapacity)\n\t}\n\n\t// All checks succeeded, update last-seen data.\n\t// We need to be guaranteed to not fail past this point in the function.\n\tnewPacker := &numberPacker{}\n\tif neededPackerCapacity != 0 {\n\t\tnewPacker.data = make([]uint64, 0, neededPackerCapacity)\n\t}\n\tv.lastTimestamp = snapshot.When\n\tfor _, data := range snapshot.Data {\n\t\tv.knownMetrics[globalIntern(data.Metric.Name)].update(data, v.internMap.Intern(dataToFieldsSeen[data]), newPacker)\n\t}\n\tif uint64(len(newPacker.data)) != neededPackerCapacity {\n\t\tfor name, metric := range v.knownMetrics {\n\t\t\tmetric.repackUnseen(fieldsSeen[name], v.lastPacker, newPacker)\n\t\t}\n\t}\n\tif uint64(len(newPacker.data)) != neededPackerCapacity {\n\t\t// We panic here because this represents an internal logic error,\n\t\t// not something the user did wrong.\n\t\tpanic(fmt.Sprintf(\"did not pack the expected number of numbers in numberPacker: packed %d, expected %d; this indicates a logic error in verifyIncrement\", len(newPacker.data), neededPackerCapacity))\n\t}\n\tv.lastPacker = newPacker\n\treturn nil\n}", "func Verify() {\n\tlist, _ := proxyServiceInstance.GetUnVerified()\n\tfor _, p := range list {\n\t\tverifyJob <- p\n\t}\n}", "func (m Manifest) Verify() error {\n\to := m2o(m)\n\tfields := make(map[string]error)\n\n\tif !o.Get(\"kind\").IsStr() {\n\t\tfields[\"kind\"] = ErrInvalidStr\n\t}\n\tif !o.Get(\"apiVersion\").IsStr() {\n\t\tfields[\"apiVersion\"] = ErrInvalidStr\n\t}\n\n\t// Lists don't have `metadata`\n\tif !m.IsList() {\n\t\tif !o.Get(\"metadata\").IsMSI() {\n\t\t\tfields[\"metadata\"] = ErrInvalidMap\n\t\t}\n\t\tif !o.Get(\"metadata.name\").IsStr() && !o.Get(\"metadata.generateName\").IsStr() {\n\t\t\tfields[\"metadata.name\"] = ErrInvalidStr\n\t\t}\n\n\t\tif err := verifyMSS(o.Get(\"metadata.labels\").Data()); err != nil {\n\t\t\tfields[\"metadata.labels\"] = err\n\t\t}\n\t\tif err := verifyMSS(o.Get(\"metadata.annotations\").Data()); err != nil {\n\t\t\tfields[\"metadata.annotations\"] = err\n\t\t}\n\t}\n\n\tif len(fields) == 0 {\n\t\treturn nil\n\t}\n\n\treturn &SchemaError{\n\t\tFields: fields,\n\t\tManifest: m,\n\t}\n}", "func (mr *MockUnsignedTxMockRecorder) SyntacticVerify(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"SyntacticVerify\", reflect.TypeOf((*MockUnsignedTx)(nil).SyntacticVerify), arg0)\n}", "func (u *UsersController) Verify(ctx *gin.Context) {\n\tvar user = &tat.User{}\n\tusername, err := GetParam(ctx, \"username\")\n\tif err != nil {\n\t\treturn\n\t}\n\ttokenVerify, err := GetParam(ctx, \"tokenVerify\")\n\tif err != nil {\n\t\treturn\n\t}\n\tif username != \"\" && tokenVerify != \"\" {\n\t\t_, password, err := userDB.Verify(user, username, tokenVerify)\n\t\tif err != nil {\n\t\t\te := fmt.Sprintf(\"Error on verify token for username %s\", username)\n\t\t\tlog.Errorf(\"%s %s\", e, err.Error())\n\t\t\tctx.JSON(http.StatusInternalServerError, gin.H{\"error\": e})\n\t\t} else {\n\t\t\tctx.JSON(http.StatusOK, gin.H{\n\t\t\t\t\"message\": \"Verification successful\",\n\t\t\t\t\"username\": username,\n\t\t\t\t\"password\": password,\n\t\t\t\t\"url\": fmt.Sprintf(\"%s://%s:%s%s\", viper.GetString(\"exposed_scheme\"), viper.GetString(\"exposed_host\"), viper.GetString(\"exposed_port\"), viper.GetString(\"exposed_path\")),\n\t\t\t})\n\t\t}\n\t} else {\n\t\tctx.JSON(http.StatusBadRequest, gin.H{\"info\": fmt.Sprintf(\"username %s or token empty\", username)})\n\t}\n}", "func (mr *MockMsgSignerMockRecorder) VerifyMsg(msg, senderID interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"VerifyMsg\", reflect.TypeOf((*MockMsgSigner)(nil).VerifyMsg), msg, senderID)\n}", "func Verify(packet *types.Packet) error {\n\tif packet.Type == types.PacketTypeConnect {\n\t\treturn nil // ignore connect\n\t}\n\tmechine := &models.Mechine{Code: packet.Auth.Code}\n\tif err := mechine.Read(\"Code\"); err != nil {\n\t\treturn err\n\t}\n\tif mechine.Code == packet.Auth.Code && mechine.Secret == packet.Auth.Secret {\n\t\treturn nil\n\t}\n\treturn errors.New(\"Verify secret failed\")\n}", "func (l list) Verify() error {\n\tfor _, p := range l.Fields {\n\t\tfor _, s := range p.Values {\n\t\t\tif err := p.Verify(s); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func (req *TPLAddRequest) Verify() error {\n\tif len(req.Content) == 0 {\n\t\treturn errors.New(\"Miss param: tpl_content\")\n\t}\n\treturn nil\n}", "func (task *ParseTask) Verify(content []byte) error {\n\n\ttask.addContent(\"verify\")\n\terr := task.remote.IsValidResponse(content)\n\ttask.finishRequest(err, \"The content is valid\")\n\n\treturn err\n}", "func Verify(s *discordgo.Session, msg *discordgo.MessageCreate) bool {\n\tdiscordTag := msg.Author.Username + \"#\" + msg.Author.Discriminator\n\n\tif msg.Content == \"!verify\" {\n\t\t_, err := s.ChannelMessageSend(msg.ChannelID, fmt.Sprintf(\"To verify your account, first add `%s` as your Discord account on https://notify.moe/settings/accounts, then type `!verify` followed by your username on notify.moe, e.g. `!verify MyName`\", discordTag))\n\n\t\tif err != nil {\n\t\t\tcolor.Red(err.Error())\n\t\t}\n\n\t\treturn true\n\t}\n\n\tif !strings.HasPrefix(msg.Content, \"!verify \") {\n\t\treturn false\n\t}\n\n\tarnUserName := strings.TrimSpace(msg.Content[len(\"!verify \"):])\n\tuser, err := arn.GetUserByNick(arnUserName)\n\n\tif err != nil {\n\t\t_, err := s.ChannelMessageSend(msg.ChannelID, fmt.Sprintf(\"User `%s` doesn't seem to exist on notify.moe\", arnUserName))\n\n\t\tif err != nil {\n\t\t\tcolor.Red(err.Error())\n\t\t}\n\n\t\treturn true\n\t}\n\n\tif user.Accounts.Discord.Nick == \"\" {\n\t\t_, err := s.ChannelMessageSend(msg.ChannelID, fmt.Sprintf(\"You haven't set up your Discord account `%s` on https://notify.moe/settings/accounts yet\", discordTag))\n\n\t\tif err != nil {\n\t\t\tcolor.Red(err.Error())\n\t\t}\n\n\t\treturn true\n\t}\n\n\tif user.Accounts.Discord.Nick != discordTag {\n\t\t_, err := s.ChannelMessageSend(msg.ChannelID, fmt.Sprintf(\"Mismatching Discord accounts: `%s` and `%s`\", user.Accounts.Discord.Nick, discordTag))\n\n\t\tif err != nil {\n\t\t\tcolor.Red(err.Error())\n\t\t}\n\n\t\treturn true\n\t}\n\n\t// Try to set the verified role\n\terr = s.GuildMemberRoleAdd(guildID, msg.Author.ID, verifiedRole)\n\n\tif err != nil {\n\t\t_, err := s.ChannelMessageSend(msg.ChannelID, \"There was an error adding the Verified role to your account!\")\n\n\t\tif err != nil {\n\t\t\tcolor.Red(err.Error())\n\t\t}\n\n\t\treturn true\n\t}\n\n\t// Give editor role\n\tif user.Role == \"editor\" {\n\t\terr := s.GuildMemberRoleAdd(guildID, msg.Author.ID, editorRole)\n\n\t\tif err != nil {\n\t\t\tcolor.Red(err.Error())\n\t\t}\n\n\t\terr = s.GuildMemberRoleAdd(guildID, msg.Author.ID, staffRole)\n\n\t\tif err != nil {\n\t\t\tcolor.Red(err.Error())\n\t\t}\n\t}\n\n\t// Give region role\n\tif user.Location.CountryCode != \"\" {\n\t\tcountry, err := query.FindCountryByAlpha(user.Location.CountryCode)\n\n\t\tif err != nil {\n\t\t\tcolor.Red(\"Error querying country code: %s\", err.Error())\n\t\t} else {\n\t\t\tregionRole, exists := regions[strings.ToLower(country.Region)]\n\n\t\t\tif !exists {\n\t\t\t\tcolor.Red(\"Error getting region role for: %s\", country.Region)\n\t\t\t} else {\n\t\t\t\t// Remove old region role\n\t\t\t\tfor _, roleID := range regions {\n\t\t\t\t\terr := s.GuildMemberRoleRemove(guildID, msg.Author.ID, roleID)\n\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tcolor.Red(err.Error())\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// Add new region role\n\t\t\t\terr := s.GuildMemberRoleAdd(guildID, msg.Author.ID, regionRole)\n\n\t\t\t\tif err != nil {\n\t\t\t\t\tcolor.Red(err.Error())\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Give or remove supporter role\n\tif user.IsPro() {\n\t\terr := s.GuildMemberRoleAdd(guildID, msg.Author.ID, supporterRole)\n\n\t\tif err != nil {\n\t\t\tcolor.Red(err.Error())\n\t\t}\n\t} else {\n\t\terr := s.GuildMemberRoleRemove(guildID, msg.Author.ID, supporterRole)\n\n\t\tif err != nil {\n\t\t\tcolor.Red(err.Error())\n\t\t}\n\t}\n\n\t// Update nickname to notify.moe nick\n\terr = s.GuildMemberNickname(guildID, msg.Author.ID, user.Nick)\n\n\tif err != nil {\n\t\tcolor.Red(\"Error updating nickname: %s\", err.Error())\n\t}\n\n\t// Update notify.moe user account\n\tif !user.Accounts.Discord.Verified {\n\t\tuser.Accounts.Discord.Verified = true\n\t\tuser.Save()\n\t}\n\n\t// Send success message\n\t_, err = s.ChannelMessageSend(msg.ChannelID, fmt.Sprintf(\"%s Thank you, you are now a verified member of the notify.moe community!\", msg.Author.Mention()))\n\n\tif err != nil {\n\t\tcolor.Red(err.Error())\n\t}\n\n\treturn true\n}", "func (v *SubnetValidator) Verify() error {\n\tswitch v.Subnet {\n\tcase constants.PrimaryNetworkID:\n\t\treturn errBadSubnetID\n\tdefault:\n\t\treturn v.Validator.Verify()\n\t}\n}", "func (mr *MockFullNodeMockRecorder) VerifyEntry(arg0, arg1, arg2 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"VerifyEntry\", reflect.TypeOf((*MockFullNode)(nil).VerifyEntry), arg0, arg1, arg2)\n}", "func (cb *callBack) OnVerifyComplete(zcnTxn *zcncore.Transaction, status int) {\n\tcb.sendVerifyCall()\n\n\terr := zcnTxn.GetVerifyError()\n\tif err == \"\" {\n\t\terr = \"no error\"\n\t}\n\n\tlog.Logger.Debug(\"Transaction verified\",\n\t\tzap.String(\"status\", TxnStatus(status).String()),\n\t\tzap.Any(\"txn_hash\", zcnTxn.GetTransactionHash()),\n\t\tzap.String(\"error\", err),\n\t)\n}", "func verifyTransaction(inc *Transaction) {\n\tif verifySignature(inc) {\n\t\t\texecuteTransaction(inc)\n\t} else {\n\t\treturn\n\t}\n}", "func (d *identityManager) Verify(message, sig []byte) error {\n\treturn Verify(d.key.PublicKey, message, sig)\n}" ]
[ "0.74627286", "0.7147746", "0.7128926", "0.7095787", "0.707571", "0.6950006", "0.68977547", "0.68753374", "0.68753374", "0.6839528", "0.67705894", "0.6733762", "0.6675744", "0.6668171", "0.6606623", "0.659429", "0.6587624", "0.6554382", "0.65118235", "0.64971346", "0.6463827", "0.6460278", "0.64447975", "0.6402523", "0.6401324", "0.63697964", "0.6364852", "0.6361219", "0.63591194", "0.63315636", "0.6314909", "0.63148576", "0.6313254", "0.62947595", "0.62761474", "0.6267885", "0.6264144", "0.62214553", "0.62116313", "0.6200559", "0.61935925", "0.618705", "0.61691123", "0.6153319", "0.6132444", "0.61243314", "0.6119282", "0.61014694", "0.60916364", "0.60914636", "0.6086506", "0.607169", "0.6068799", "0.60666645", "0.6060184", "0.60393584", "0.60316366", "0.5999635", "0.5996578", "0.5992393", "0.59808135", "0.59804225", "0.5966425", "0.5963317", "0.59575427", "0.5945827", "0.5941089", "0.5935899", "0.5929241", "0.59242827", "0.5914484", "0.5912684", "0.59116584", "0.5904743", "0.5899981", "0.58987653", "0.5898546", "0.58888835", "0.5885728", "0.587816", "0.58674395", "0.58648527", "0.58542335", "0.58399284", "0.583387", "0.58221924", "0.5811891", "0.5794279", "0.5781475", "0.5769852", "0.57614833", "0.5761476", "0.57516557", "0.5742743", "0.5737254", "0.57335305", "0.5730253", "0.5720821", "0.5718322", "0.5710362" ]
0.7062403
5
/ polymorph Destiny.Definitions.Items.DestinyItemTierTypeInfusionBlock baseQualityTransferRatio false / polymorph Destiny.Definitions.Items.DestinyItemTierTypeInfusionBlock minimumQualityIncrement false Validate validates this destiny definitions items destiny item tier type infusion block
func (m *DestinyDefinitionsItemsDestinyItemTierTypeInfusionBlock) Validate(formats strfmt.Registry) error { var res []error if len(res) > 0 { return errors.CompositeValidationError(res...) } return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (b BaseShip) GetFuelConsumption(techs IResearches, fleetDeutSaveFactor float64, isGeneral bool) int64 {\n\tfuelConsumption := b.FuelConsumption\n\tif b.ID == SmallCargoID && techs.GetImpulseDrive() >= 5 {\n\t\tfuelConsumption *= 2\n\t} else if b.ID == RecyclerID && techs.GetHyperspaceDrive() >= 15 {\n\t\tfuelConsumption *= 3\n\t} else if b.ID == RecyclerID && techs.GetImpulseDrive() >= 17 {\n\t\tfuelConsumption *= 2\n\t}\n\tfuelConsumption = int64(fleetDeutSaveFactor * float64(fuelConsumption))\n\tif isGeneral {\n\t\tfuelConsumption = int64(float64(fuelConsumption) / 2)\n\t}\n\treturn fuelConsumption\n}", "func (fm *FinalModelStructOptional) FBEAllocationSize(fbeValue *StructOptional) int {\n fbeResult := 0 +\n fm.FinalModelStructSimple.FBEAllocationSize(fbeValue.StructSimple) + \n fm.F100.FBEAllocationSize(fbeValue.F100) +\n fm.F101.FBEAllocationSize(fbeValue.F101) +\n fm.F102.FBEAllocationSize(fbeValue.F102) +\n fm.F103.FBEAllocationSize(fbeValue.F103) +\n fm.F104.FBEAllocationSize(fbeValue.F104) +\n fm.F105.FBEAllocationSize(fbeValue.F105) +\n fm.F106.FBEAllocationSize(fbeValue.F106) +\n fm.F107.FBEAllocationSize(fbeValue.F107) +\n fm.F108.FBEAllocationSize(fbeValue.F108) +\n fm.F109.FBEAllocationSize(fbeValue.F109) +\n fm.F110.FBEAllocationSize(fbeValue.F110) +\n fm.F111.FBEAllocationSize(fbeValue.F111) +\n fm.F112.FBEAllocationSize(fbeValue.F112) +\n fm.F113.FBEAllocationSize(fbeValue.F113) +\n fm.F114.FBEAllocationSize(fbeValue.F114) +\n fm.F115.FBEAllocationSize(fbeValue.F115) +\n fm.F116.FBEAllocationSize(fbeValue.F116) +\n fm.F117.FBEAllocationSize(fbeValue.F117) +\n fm.F118.FBEAllocationSize(fbeValue.F118) +\n fm.F119.FBEAllocationSize(fbeValue.F119) +\n fm.F120.FBEAllocationSize(fbeValue.F120) +\n fm.F121.FBEAllocationSize(fbeValue.F121) +\n fm.F122.FBEAllocationSize(fbeValue.F122) +\n fm.F123.FBEAllocationSize(fbeValue.F123) +\n fm.F124.FBEAllocationSize(fbeValue.F124) +\n fm.F125.FBEAllocationSize(fbeValue.F125) +\n fm.F126.FBEAllocationSize(fbeValue.F126) +\n fm.F127.FBEAllocationSize(fbeValue.F127) +\n fm.F128.FBEAllocationSize(fbeValue.F128) +\n fm.F129.FBEAllocationSize(fbeValue.F129) +\n fm.F130.FBEAllocationSize(fbeValue.F130) +\n fm.F131.FBEAllocationSize(fbeValue.F131) +\n fm.F132.FBEAllocationSize(fbeValue.F132) +\n fm.F133.FBEAllocationSize(fbeValue.F133) +\n fm.F134.FBEAllocationSize(fbeValue.F134) +\n fm.F135.FBEAllocationSize(fbeValue.F135) +\n fm.F136.FBEAllocationSize(fbeValue.F136) +\n fm.F137.FBEAllocationSize(fbeValue.F137) +\n fm.F138.FBEAllocationSize(fbeValue.F138) +\n fm.F139.FBEAllocationSize(fbeValue.F139) +\n fm.F140.FBEAllocationSize(fbeValue.F140) +\n fm.F141.FBEAllocationSize(fbeValue.F141) +\n fm.F142.FBEAllocationSize(fbeValue.F142) +\n fm.F143.FBEAllocationSize(fbeValue.F143) +\n fm.F144.FBEAllocationSize(fbeValue.F144) +\n fm.F145.FBEAllocationSize(fbeValue.F145) +\n fm.F146.FBEAllocationSize(fbeValue.F146) +\n fm.F147.FBEAllocationSize(fbeValue.F147) +\n fm.F148.FBEAllocationSize(fbeValue.F148) +\n fm.F149.FBEAllocationSize(fbeValue.F149) +\n fm.F150.FBEAllocationSize(fbeValue.F150) +\n fm.F151.FBEAllocationSize(fbeValue.F151) +\n fm.F152.FBEAllocationSize(fbeValue.F152) +\n fm.F153.FBEAllocationSize(fbeValue.F153) +\n fm.F154.FBEAllocationSize(fbeValue.F154) +\n fm.F155.FBEAllocationSize(fbeValue.F155) +\n fm.F156.FBEAllocationSize(fbeValue.F156) +\n fm.F157.FBEAllocationSize(fbeValue.F157) +\n fm.F158.FBEAllocationSize(fbeValue.F158) +\n fm.F159.FBEAllocationSize(fbeValue.F159) +\n fm.F160.FBEAllocationSize(fbeValue.F160) +\n fm.F161.FBEAllocationSize(fbeValue.F161) +\n fm.F162.FBEAllocationSize(fbeValue.F162) +\n fm.F163.FBEAllocationSize(fbeValue.F163) +\n fm.F164.FBEAllocationSize(fbeValue.F164) +\n fm.F165.FBEAllocationSize(fbeValue.F165) +\n 0\n return fbeResult\n}", "func (me TxsdTextPathTypeMethod) IsStretch() bool { return me.String() == \"stretch\" }", "func minSizeEffective(item LayoutItem) Size {\n\tgeometry := item.Geometry()\n\n\tvar s Size\n\tif msh, ok := item.(MinSizer); ok {\n\t\ts = msh.MinSize()\n\t} else if is, ok := item.(IdealSizer); ok {\n\t\ts = is.IdealSize()\n\t}\n\n\tsize := maxSize(geometry.MinSize, s)\n\n\tmax := geometry.MaxSize\n\tif max.Width > 0 && size.Width > max.Width {\n\t\tsize.Width = max.Width\n\t}\n\tif max.Height > 0 && size.Height > max.Height {\n\t\tsize.Height = max.Height\n\t}\n\n\treturn size\n}", "func (me TxsdConfidenceRating) IsMedium() bool { return me.String() == \"medium\" }", "func (_Univ2 *Univ2Caller) MINIMUMLIQUIDITY(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _Univ2.contract.Call(opts, &out, \"MINIMUM_LIQUIDITY\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (b BaseShip) GetFuelConsumption() int64 {\n\treturn b.FuelConsumption\n}", "func (o QuotaLimitResponseOutput) FreeTier() pulumi.StringOutput {\n\treturn o.ApplyT(func(v QuotaLimitResponse) string { return v.FreeTier }).(pulumi.StringOutput)\n}", "func (d *state) BlockSize() int { return d.rate }", "func PossibleSkuTierValues() []SkuTier {\n return []SkuTier{Burstable,GeneralPurpose,MemoryOptimized}\n }", "func PossibleSkuTierValues() []SkuTier {\n return []SkuTier{Burstable,GeneralPurpose,MemoryOptimized}\n }", "func CalcBaseFee(parent *Header) *big.Int {\n\tvar (\n\t\tparentGasTarget = parent.ToEthHeader().GasLimit / ElasticityMultiplier\n\t\tparentGasTargetBig = new(big.Int).SetUint64(parentGasTarget)\n\t\tbaseFeeChangeDenominator = new(big.Int).SetUint64(BaseFeeChangeDenominator)\n\t)\n\t// If the parent gasUsed is the same as the target, the baseFee remains unchanged.\n\tif parent.ToEthHeader().GasUsed == parentGasTarget {\n\t\treturn new(big.Int).Set(parent.ToEthHeader().BaseFee)\n\t}\n\tif parent.ToEthHeader().GasUsed > parentGasTarget {\n\t\t// If the parent block used more gas than its target, the baseFee should increase.\n\t\tgasUsedDelta := new(big.Int).SetUint64(parent.ToEthHeader().GasUsed - parentGasTarget)\n\t\tx := new(big.Int).Mul(parent.ToEthHeader().BaseFee, gasUsedDelta)\n\t\ty := x.Div(x, parentGasTargetBig)\n\t\tbaseFeeDelta := math.BigMax(\n\t\t\tx.Div(y, baseFeeChangeDenominator),\n\t\t\tcommon.Big1,\n\t\t)\n\n\t\treturn x.Add(parent.ToEthHeader().BaseFee, baseFeeDelta)\n\t} else {\n\t\t// Otherwise if the parent block used less gas than its target, the baseFee should decrease.\n\t\tgasUsedDelta := new(big.Int).SetUint64(parentGasTarget - parent.ToEthHeader().GasUsed)\n\t\tx := new(big.Int).Mul(parent.ToEthHeader().BaseFee, gasUsedDelta)\n\t\ty := x.Div(x, parentGasTargetBig)\n\t\tbaseFeeDelta := x.Div(y, baseFeeChangeDenominator)\n\n\t\treturn math.BigMax(\n\t\t\tx.Sub(parent.ToEthHeader().BaseFee, baseFeeDelta),\n\t\t\tcommon.Big0,\n\t\t)\n\t}\n}", "func storageRemainingAdjustments(entry modules.HostDBEntry) float64 {\n\tbase := float64(1)\n\tif entry.RemainingStorage < 100*requiredStorage {\n\t\tbase = base / 2 // 2x total penalty\n\t}\n\tif entry.RemainingStorage < 80*requiredStorage {\n\t\tbase = base / 2 // 4x total penalty\n\t}\n\tif entry.RemainingStorage < 40*requiredStorage {\n\t\tbase = base / 2 // 8x total penalty\n\t}\n\tif entry.RemainingStorage < 20*requiredStorage {\n\t\tbase = base / 2 // 16x total penalty\n\t}\n\tif entry.RemainingStorage < 15*requiredStorage {\n\t\tbase = base / 2 // 32x total penalty\n\t}\n\tif entry.RemainingStorage < 10*requiredStorage {\n\t\tbase = base / 2 // 64x total penalty\n\t}\n\tif entry.RemainingStorage < 5*requiredStorage {\n\t\tbase = base / 2 // 128x total penalty\n\t}\n\tif entry.RemainingStorage < 3*requiredStorage {\n\t\tbase = base / 2 // 256x total penalty\n\t}\n\tif entry.RemainingStorage < 2*requiredStorage {\n\t\tbase = base / 2 // 512x total penalty\n\t}\n\tif entry.RemainingStorage < requiredStorage {\n\t\tbase = base / 2 // 1024x total penalty\n\t}\n\treturn base\n}", "func (bsn *SubBasin) baseflow(g float64) float64 {\n\t// note: no bypass flow; no partioning to deep aquifer (pg.173)\n\td1 := math.Exp(-1. / bsn.dgw)\n\tbsn.psto += g\n\tbsn.wrch = (1.-d1)*g + d1*bsn.wrch // recharge entering aquifer (pg.172)\n\tbsn.psto -= bsn.wrch // water in \"percolation\" storage\n\tif bsn.aq > bsn.aqt {\n\t\te1 := math.Exp(-bsn.agw) // only applicable for daily simulations\n\t\tbsn.qbf = bsn.qbf*e1 + bsn.wrch*(1.-e1) // pg.174\n\t} else {\n\t\tbsn.qbf = 0.\n\t}\n\tbsn.aq += bsn.wrch - bsn.qbf\n\treturn bsn.qbf // [mm]\n}", "func (m *Monster) BaseDamage() int {\n\tswitch m.id {\n\tcase Bat: // bats deal a base of 1 always\n\t\treturn 1\n\tdefault:\n\t\td := m.Info.Dmg\n\t\tif d < 1 {\n\t\t\td++\n\t\t} else {\n\t\t\td += rand.Intn(d)\n\t\t}\n\t\td += m.Info.Lvl\n\t\treturn d\n\t}\n}", "func (constr Construction) BlockSize() int { return 16 }", "func (r *blockRenderer) MinSize() fyne.Size {\n\treturn r.el.claimed\n}", "func CalcBaseFee(configObj *config.ChainConfig, parent *model.Header) *big.Int {\n\t// If the current block is the first EIP-1559 block, return the InitialBaseFee.\n\tif !configObj.IsLondon(parent.Number) {\n\t\treturn new(big.Int).SetUint64(config.InitialBaseFee)\n\t}\n\n\tparentGasTarget := parent.GasLimit / config.ElasticityMultiplier\n\t// If the parent gasUsed is the same as the target, the baseFee remains unchanged.\n\tif parent.GasUsed == parentGasTarget {\n\t\treturn new(big.Int).Set(parent.BaseFee)\n\t}\n\n\tvar (\n\t\tnum = new(big.Int)\n\t\tdenom = new(big.Int)\n\t)\n\n\tif parent.GasUsed > parentGasTarget {\n\t\t// If the parent block used more gas than its target, the baseFee should increase.\n\t\t// max(1, parentBaseFee * gasUsedDelta / parentGasTarget / baseFeeChangeDenominator)\n\t\tnum.SetUint64(parent.GasUsed - parentGasTarget)\n\t\tnum.Mul(num, parent.BaseFee)\n\t\tnum.Div(num, denom.SetUint64(parentGasTarget))\n\t\tnum.Div(num, denom.SetUint64(config.BaseFeeChangeDenominator))\n\t\tbaseFeeDelta := mathutil.BigMax(num, common.Big1)\n\n\t\treturn num.Add(parent.BaseFee, baseFeeDelta)\n\t} else {\n\t\t// Otherwise if the parent block used less gas than its target, the baseFee should decrease.\n\t\t// max(0, parentBaseFee * gasUsedDelta / parentGasTarget / baseFeeChangeDenominator)\n\t\tnum.SetUint64(parentGasTarget - parent.GasUsed)\n\t\tnum.Mul(num, parent.BaseFee)\n\t\tnum.Div(num, denom.SetUint64(parentGasTarget))\n\t\tnum.Div(num, denom.SetUint64(config.BaseFeeChangeDenominator))\n\t\tbaseFee := num.Sub(parent.BaseFee, num)\n\n\t\treturn mathutil.BigMax(baseFee, common.Big0)\n\t}\n}", "func (me TseverityType) IsMedium() bool { return me.String() == \"medium\" }", "func (mysqlFlavor57) baseShowTablesWithSizes() string {\n\treturn TablesWithSize57\n}", "func (mysqlFlavor56) baseShowTablesWithSizes() string {\n\treturn TablesWithSize56\n}", "func (o QuotaLimitOutput) FreeTier() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v QuotaLimit) *string { return v.FreeTier }).(pulumi.StringPtrOutput)\n}", "func (_IUniswapV2Pair *IUniswapV2PairCaller) MINIMUMLIQUIDITY(opts *bind.CallOpts) (*big.Int, error) {\r\n\tvar out []interface{}\r\n\terr := _IUniswapV2Pair.contract.Call(opts, &out, \"MINIMUM_LIQUIDITY\")\r\n\r\n\tif err != nil {\r\n\t\treturn *new(*big.Int), err\r\n\t}\r\n\r\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\r\n\r\n\treturn out0, err\r\n\r\n}", "func Test_NegativeQuality(t *testing.T) {\n\tsellIn := 2\n\tquality := 0\n\n\titems := []*Item{\n\t\t&Item{\"item1\", sellIn, quality},\n\t}\n\tUpdateQuality(items)\n\n\tif items[0].quality != minQuality {\n\t\tt.Errorf(\"Expected %v as quality, got %v\", minQuality, items[0].quality)\n\t}\n}", "func (o *NiatelemetryEqptcapacityPolUsage5minAllOf) GetPolUsageBaseOk() (*string, bool) {\n\tif o == nil || o.PolUsageBase == nil {\n\t\treturn nil, false\n\t}\n\treturn o.PolUsageBase, true\n}", "func QualityForWeight(size abi.SectorSize, duration abi.ChainEpoch, dealWeight, verifiedWeight abi.DealWeight) abi.SectorQuality {\n\t// sectorSpaceTime = size * duration\n\tsectorSpaceTime := big.Mul(big.NewIntUnsigned(uint64(size)), big.NewInt(int64(duration)))\n\t// totalDealSpaceTime = dealWeight + verifiedWeight\n\ttotalDealSpaceTime := big.Add(dealWeight, verifiedWeight)\n\n\t// Base - all size * duration of non-deals\n\t// weightedBaseSpaceTime = (sectorSpaceTime - totalDealSpaceTime) * QualityBaseMultiplier\n\tweightedBaseSpaceTime := big.Mul(big.Sub(sectorSpaceTime, totalDealSpaceTime), builtin.QualityBaseMultiplier)\n\t// Deal - all deal size * deal duration * 10\n\t// weightedDealSpaceTime = dealWeight * DealWeightMultiplier\n\tweightedDealSpaceTime := big.Mul(dealWeight, builtin.DealWeightMultiplier)\n\t// Verified - all verified deal size * verified deal duration * 100\n\t// weightedVerifiedSpaceTime = verifiedWeight * VerifiedDealWeightMultiplier\n\tweightedVerifiedSpaceTime := big.Mul(verifiedWeight, builtin.VerifiedDealWeightMultiplier)\n\t// Sum - sum of all spacetime\n\t// weightedSumSpaceTime = weightedBaseSpaceTime + weightedDealSpaceTime + weightedVerifiedSpaceTime\n\tweightedSumSpaceTime := big.Sum(weightedBaseSpaceTime, weightedDealSpaceTime, weightedVerifiedSpaceTime)\n\t// scaledUpWeightedSumSpaceTime = weightedSumSpaceTime * 2^20\n\tscaledUpWeightedSumSpaceTime := big.Lsh(weightedSumSpaceTime, builtin.SectorQualityPrecision)\n\n\t// Average of weighted space time: (scaledUpWeightedSumSpaceTime / sectorSpaceTime * 10)\n\treturn big.Div(big.Div(scaledUpWeightedSumSpaceTime, sectorSpaceTime), builtin.QualityBaseMultiplier)\n}", "func (o *NiatelemetryEqptcapacityPolUsage5minAllOf) HasPolUsageBase() bool {\n\tif o != nil && o.PolUsageBase != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (_Univ2 *Univ2CallerSession) MINIMUMLIQUIDITY() (*big.Int, error) {\n\treturn _Univ2.Contract.MINIMUMLIQUIDITY(&_Univ2.CallOpts)\n}", "func (f RatioQtyField) Tag() quickfix.Tag { return tag.RatioQty }", "func (filter *Saturation) IsScalable() {\n}", "func super(s structs.Saiyan) {\n\ts.Power += 1000\n\n}", "func (_IUniswapV2Pair *IUniswapV2PairCallerSession) MINIMUMLIQUIDITY() (*big.Int, error) {\r\n\treturn _IUniswapV2Pair.Contract.MINIMUMLIQUIDITY(&_IUniswapV2Pair.CallOpts)\r\n}", "func (*TopUpGatewayMiningFuelRequest) Descriptor() ([]byte, []int) {\n\treturn file_wallet_proto_rawDescGZIP(), []int{1}\n}", "func (op *SetPropertiesFlags) ShouldTransferTier() bool {\n\treturn (*op)&ESetPropertiesFlags.SetTier() == ESetPropertiesFlags.SetTier()\n}", "func Test_AgedBrie(t *testing.T) {\n\tsellIn := 20\n\tquality := 2\n\n\titems := []*Item{\n\t\t&Item{\"Aged Brie\", sellIn, quality},\n\t}\n\n\tfor i := 0; i < 50; i++ {\n\t\tUpdateQuality(items)\n\t\t// Update expected quality\n\t\tif quality < maxQuality {\n\t\t\tif items[0].sellIn < 0 {\n\t\t\t\t// For some reason, running the test i found out that\n\t\t\t\t// quality increase by 2 when sellIn is negative.\n\t\t\t\t// it's not in the spec, but since there's the same behaviour\n\t\t\t\t// at least in Scala, and i assume that there's no bug in the implementation\n\t\t\t\t// i also test that.\n\t\t\t\tquality = quality + 2\n\t\t\t} else {\n\t\t\t\tquality++\n\t\t\t}\n\t\t}\n\t\tif items[0].quality != quality {\n\t\t\tt.Errorf(\"Expected %v as quality, got %v - sellIn=%v\", quality, items[0].quality, items[0].sellIn)\n\t\t}\n\t}\n}", "func (f MinQtyField) Tag() quickfix.Tag { return tag.MinQty }", "func (o ClusterNodeGroupCostOptimizedConfigOutput) OnDemandPercentageAboveBaseCapacity() pulumi.IntOutput {\n\treturn o.ApplyT(func(v ClusterNodeGroupCostOptimizedConfig) int { return v.OnDemandPercentageAboveBaseCapacity }).(pulumi.IntOutput)\n}", "func ItemRarityHeight(frameType models.FrameType) string {\n\t_, _, heightClass := rarityCharacteritics(frameType)\n\treturn heightClass\n}", "func GetSizeFuel() int64 {\r\n\treturn SysInt64(SizeFuel)\r\n}", "func (f DefBidSizeField) Tag() quickfix.Tag { return tag.DefBidSize }", "func (_L1Block *L1BlockCaller) Basefee(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _L1Block.contract.Call(opts, &out, \"basefee\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (_IUniswapV2Pair *IUniswapV2PairSession) MINIMUMLIQUIDITY() (*big.Int, error) {\r\n\treturn _IUniswapV2Pair.Contract.MINIMUMLIQUIDITY(&_IUniswapV2Pair.CallOpts)\r\n}", "func (_Univ2 *Univ2Session) MINIMUMLIQUIDITY() (*big.Int, error) {\n\treturn _Univ2.Contract.MINIMUMLIQUIDITY(&_Univ2.CallOpts)\n}", "func (me TClipFillRuleType) IsInherit() bool { return me.String() == \"inherit\" }", "func (s *ShortenBlock) Capacity() int {\n\treturn int(math.Pow(float64(s.idsPerNode), float64(s.depth))) * s.shortener.NodeSize()\n}", "func (c *cardRenderer) MinSize() fyne.Size {\n\thasHeader := c.card.Title != \"\"\n\thasSubHeader := c.card.Subtitle != \"\"\n\thasImage := c.card.Image != nil\n\thasContent := c.card.Content != nil\n\n\tif !hasHeader && !hasSubHeader && !hasContent { // just image, or nothing\n\t\tif c.card.Image == nil {\n\t\t\treturn fyne.NewSize(theme.Padding(), theme.Padding()) // empty, just space for border\n\t\t}\n\t\treturn fyne.NewSize(c.card.Image.MinSize().Width+theme.Padding(), cardMediaHeight+theme.Padding())\n\t}\n\n\tcontentPad := theme.Padding()\n\tmin := fyne.NewSize(theme.Padding(), theme.Padding())\n\tif hasImage {\n\t\tmin = fyne.NewSize(min.Width, min.Height+cardMediaHeight)\n\t}\n\n\tif hasHeader || hasSubHeader {\n\t\ttitlePad := theme.Padding() * 2\n\t\tmin = min.Add(fyne.NewSize(0, titlePad*2))\n\t\tif hasHeader {\n\t\t\theaderMin := c.header.MinSize()\n\t\t\tmin = fyne.NewSize(fyne.Max(min.Width, headerMin.Width+titlePad*2+theme.Padding()),\n\t\t\t\tmin.Height+headerMin.Height)\n\t\t\tif hasSubHeader {\n\t\t\t\tmin.Height += theme.Padding()\n\t\t\t}\n\t\t}\n\t\tif hasSubHeader {\n\t\t\tsubHeaderMin := c.subHeader.MinSize()\n\t\t\tmin = fyne.NewSize(fyne.Max(min.Width, subHeaderMin.Width+titlePad*2+theme.Padding()),\n\t\t\t\tmin.Height+subHeaderMin.Height)\n\t\t}\n\t}\n\n\tif hasContent {\n\t\tcontentMin := c.card.Content.MinSize()\n\t\tmin = fyne.NewSize(fyne.Max(min.Width, contentMin.Width+contentPad*2+theme.Padding()),\n\t\t\tmin.Height+contentMin.Height+contentPad*2)\n\t}\n\n\treturn min\n}", "func (m *SecureScoreControlProfile) SetTier(value *string)() {\n m.tier = value\n}", "func (sm3 *SM3) BlockSize() int { return 64 }", "func (b *CapabilityBuilder) Inherited(value bool) *CapabilityBuilder {\n\tb.inherited = value\n\tb.bitmap_ |= 1\n\treturn b\n}", "func (_L1Block *L1BlockCallerSession) Basefee() (*big.Int, error) {\n\treturn _L1Block.Contract.Basefee(&_L1Block.CallOpts)\n}", "func ItemRarityType(frameType models.FrameType) string {\n\t_, frameClass, _ := rarityCharacteritics(frameType)\n\treturn frameClass\n}", "func (_L1Block *L1BlockSession) Basefee() (*big.Int, error) {\n\treturn _L1Block.Contract.Basefee(&_L1Block.CallOpts)\n}", "func (i *menuBarItem) MinSize() fyne.Size {\n\treturn widget.MinSizeOf(i)\n}", "func (f DefOfferSizeField) Tag() quickfix.Tag { return tag.DefOfferSize }", "func GetBronzeBaseDefensePower() int {\n\treturn BronzeBaseDefensePower\n}", "func (bq ByteQuantity) TiB() float64 {\n\treturn float64(bq.Quantity) * 1 / tbConvert\n}", "func (spec *AliyunInstanceTypeSpec) compareAndGetMinimumInstanceTypeSpec(rival AliyunInstanceTypeSpec) {\n\tspecScore := getInstanceTypeSpecScore(*spec)\n\trivalScore := getInstanceTypeSpecScore(rival)\n\tif rivalScore < specScore || spec.InstanceTypeID == \"\" {\n\t\tspec.CPUCoreCount = rival.CPUCoreCount\n\t\tspec.EniPrivateIPAddressQuantity = rival.EniPrivateIPAddressQuantity\n\t\tspec.EniQuantity = rival.EniQuantity\n\t\tspec.GPUAmount = rival.GPUAmount\n\t\tspec.GPUSpec = rival.GPUSpec\n\t\tspec.InstanceFamilyLevel = rival.InstanceFamilyLevel\n\t\tspec.InstanceTypeFamily = rival.InstanceTypeFamily\n\t\tspec.InstanceTypeID = rival.InstanceTypeID\n\t\tspec.LocalStorageCategory = rival.LocalStorageCategory\n\t\tspec.MemorySize = rival.MemorySize\n\t}\n}", "func (d *RabinKarp64) BlockSize() int { return 1 }", "func (b *AutoscalerScaleDownConfigBuilder) UtilizationThreshold(value string) *AutoscalerScaleDownConfigBuilder {\n\tb.utilizationThreshold = value\n\tb.bitmap_ |= 32\n\treturn b\n}", "func (cpu *Mos6502) bmi() uint8 {\n\tif cpu.GetStatusFlag(N) == 1 {\n\t\tcpu.branch()\n\t}\n\treturn 0\n}", "func ItemRarity(frameType models.FrameType) string {\n\trarity, _, _ := rarityCharacteritics(frameType)\n\treturn rarity\n}", "func forceUperBandwidth(bw int64) int64 {\n\n\tif bw > maxBwPerBroker {\n\t\treturn maxBwPerBroker\n\t}\n\treturn bw\n}", "func (me TseverityType) IsLow() bool { return me.String() == \"low\" }", "func (me TxsdConfidenceRating) IsLow() bool { return me.String() == \"low\" }", "func (mysqlFlavor80) baseShowTablesWithSizes() string {\n\treturn TablesWithSize80\n}", "func (r *checkGroupRenderer) MinSize() fyne.Size {\n\twidth := float32(0)\n\theight := float32(0)\n\tfor _, item := range r.items {\n\t\titemMin := item.MinSize()\n\t\tif r.checks.Horizontal {\n\t\t\theight = fyne.Max(height, itemMin.Height)\n\t\t\twidth += itemMin.Width\n\t\t} else {\n\t\t\twidth = fyne.Max(width, itemMin.Width)\n\t\t\theight += itemMin.Height\n\t\t}\n\t}\n\n\treturn fyne.NewSize(width, height)\n}", "func (b Boat) medium() string {\n\treturn \"water\"\n}", "func isMinAllowedPartSize(size int64) bool {\n\treturn size >= minPartSize\n}", "func (fm FinalModelEnumUInt32) FBEAllocationSize(value EnumUInt32) int { return fm.FBESize() }", "func (s *Trainer) GrainSize() int {\n\treturn 500\n}", "func calculateInflatedSize(metadata imagefile.Metadata) int64 {\n\tif metadata.VirtualSizeGB < defaultInflationDiskSizeGB {\n\t\treturn defaultInflationDiskSizeGB\n\t}\n\treturn metadata.VirtualSizeGB\n}", "func PossibleTierValues() []Tier {\n\treturn []Tier{TierPremium, TierStandard}\n}", "func (b *Backend) Tier() int {\n\tb.mu.RLock()\n\tret := b.mu.tier\n\tb.mu.RUnlock()\n\treturn ret\n}", "func (b ExpectedTip) FullBlockTestInstance() {}", "func (b ExpectedTip) FullBlockTestInstance() {}", "func (b BaseShip) GetSpeed(techs Researches) int64 {\n\tvar techDriveLvl int64 = 0\n\tif b.ID == SmallCargoID && techs.ImpulseDrive >= 5 {\n\t\tbaseSpeed := 10000\n\t\treturn int64(float64(baseSpeed) + (float64(baseSpeed)*0.2)*float64(techs.ImpulseDrive))\n\t}\n\tif b.ID == BomberID && techs.HyperspaceDrive >= 8 {\n\t\tbaseSpeed := 5000\n\t\treturn int64(float64(baseSpeed) + (float64(baseSpeed)*0.3)*float64(techs.HyperspaceDrive))\n\t}\n\tif b.ID == RecyclerID && (techs.ImpulseDrive >= 17 || techs.HyperspaceDrive >= 15) {\n\t\tif techs.HyperspaceDrive >= 15 {\n\t\t\treturn int64(float64(b.BaseSpeed)+(float64(b.BaseSpeed)*0.3)*float64(techs.HyperspaceDrive)) * 3\n\t\t}\n\t\treturn int64(float64(b.BaseSpeed)+(float64(b.BaseSpeed)*0.2)*float64(techs.ImpulseDrive)) * 2\n\t}\n\tif minLvl, ok := b.Requirements[CombustionDrive.ID]; ok {\n\t\ttechDriveLvl = techs.CombustionDrive\n\t\tif techDriveLvl < minLvl {\n\t\t\ttechDriveLvl = minLvl\n\t\t}\n\t\treturn int64(float64(b.BaseSpeed) + (float64(b.BaseSpeed)*0.1)*float64(techDriveLvl))\n\t} else if minLvl, ok := b.Requirements[ImpulseDrive.ID]; ok {\n\t\ttechDriveLvl = techs.ImpulseDrive\n\t\tif techDriveLvl < minLvl {\n\t\t\ttechDriveLvl = minLvl\n\t\t}\n\t\treturn int64(float64(b.BaseSpeed) + (float64(b.BaseSpeed)*0.2)*float64(techDriveLvl))\n\t} else if minLvl, ok := b.Requirements[HyperspaceDrive.ID]; ok {\n\t\ttechDriveLvl = techs.HyperspaceDrive\n\t\tif techDriveLvl < minLvl {\n\t\t\ttechDriveLvl = minLvl\n\t\t}\n\t\treturn int64(float64(b.BaseSpeed) + (float64(b.BaseSpeed)*0.3)*float64(techDriveLvl))\n\t}\n\treturn int64(float64(b.BaseSpeed) + (float64(b.BaseSpeed)*0.2)*float64(techDriveLvl))\n}", "func (o *SubDescriptionDto) GetQuantityOverrideOk() (*float32, bool) {\n\tif o == nil || IsNil(o.QuantityOverride) {\n\t\treturn nil, false\n\t}\n\treturn o.QuantityOverride, true\n}", "func (s *StorePaymentPurposeGiftedPremium) TypeInfo() tdp.Type {\n\ttyp := tdp.Type{\n\t\tName: \"storePaymentPurposeGiftedPremium\",\n\t\tID: StorePaymentPurposeGiftedPremiumTypeID,\n\t}\n\tif s == nil {\n\t\ttyp.Null = true\n\t\treturn typ\n\t}\n\ttyp.Fields = []tdp.Field{\n\t\t{\n\t\t\tName: \"UserID\",\n\t\t\tSchemaName: \"user_id\",\n\t\t},\n\t\t{\n\t\t\tName: \"Currency\",\n\t\t\tSchemaName: \"currency\",\n\t\t},\n\t\t{\n\t\t\tName: \"Amount\",\n\t\t\tSchemaName: \"amount\",\n\t\t},\n\t}\n\treturn typ\n}", "func (e Protection) Multiplier(lvl int) float64 {\n\tif lvl > 20 {\n\t\tlvl = 20\n\t}\n\treturn 1 - float64(lvl)/25\n}", "func (o OceanBlockDeviceMappingEbsDynamicVolumeSizeOutput) BaseSize() pulumi.IntOutput {\n\treturn o.ApplyT(func(v OceanBlockDeviceMappingEbsDynamicVolumeSize) int { return v.BaseSize }).(pulumi.IntOutput)\n}", "func (o *AutoscalerScaleDownConfig) UtilizationThreshold() string {\n\tif o != nil && o.bitmap_&32 != 0 {\n\t\treturn o.utilizationThreshold\n\t}\n\treturn \"\"\n}", "func GetGoodBurst(l rate.Limit) int {\n\tif l == rate.Limit(0) {\n\t\treturn MaxBurstSize\n\t}\n\t// We aim for 20 bursts per second to get good precision. Decrease this\n\t// value to get better performance, but less precision.\n\tburstSize := int64(l) / 20\n\tif burstSize < MinBurstSize {\n\t\tburstSize = MinBurstSize\n\t} else if burstSize > MaxBurstSize {\n\t\tburstSize = MaxBurstSize\n\t}\n\treturn int(burstSize)\n}", "func (m *MeterSnapshot) Rate15() float64 { return m.rate15 }", "func (o ClusterNodeGroupCostOptimizedConfigOutput) OnDemandBaseCapacity() pulumi.IntOutput {\n\treturn o.ApplyT(func(v ClusterNodeGroupCostOptimizedConfig) int { return v.OnDemandBaseCapacity }).(pulumi.IntOutput)\n}", "func CreateItemItemsItemWorkbookFunctionsAverageIfPostRequestBodyFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewItemItemsItemWorkbookFunctionsAverageIfPostRequestBody(), nil\n}", "func CreateDeliveryOptimizationBandwidthBusinessHoursLimitFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewDeliveryOptimizationBandwidthBusinessHoursLimit(), nil\n}", "func (c *Card) MinSize() fyne.Size {\n\tc.ExtendBaseWidget(c)\n\treturn c.BaseWidget.MinSize()\n}", "func (c *gcControllerState) effectiveGrowthRatio() float64 {\n\tif !c.test {\n\t\tassertWorldStoppedOrLockHeld(&mheap_.lock)\n\t}\n\n\tegogc := float64(atomic.Load64(&c.heapGoal)-c.heapMarked) / float64(c.heapMarked)\n\tif egogc < 0 {\n\t\t// Shouldn't happen, but just in case.\n\t\tegogc = 0\n\t}\n\treturn egogc\n}", "func (fm *FinalModelStructBytes) FBEAllocationSize(fbeValue *StructBytes) int {\n fbeResult := 0 +\n fm.F1.FBEAllocationSize(fbeValue.F1) +\n fm.F2.FBEAllocationSize(fbeValue.F2) +\n fm.F3.FBEAllocationSize(fbeValue.F3) +\n 0\n return fbeResult\n}", "func (o *NiatelemetryEqptcapacityPolUsage5minAllOf) GetPolUsageBase() string {\n\tif o == nil || o.PolUsageBase == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.PolUsageBase\n}", "func (_ElvTradable *ElvTradableCaller) BaseTransferFee(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _ElvTradable.contract.Call(opts, &out, \"baseTransferFee\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (this *Stats) InputBitRate() float32 { return float32(this.ptr.f_input_bitrate) }", "func (FakeStateBuilder) Weigh(context context.Context, tip *types.TipSet) (big.Int, error) {\n\tparentWeight := big.Zero()\n\tif tip.Defined() {\n\t\tparentWeight = tip.ParentWeight()\n\t}\n\n\treturn big.Add(parentWeight, big.NewInt(int64(tip.Len()))), nil\n}", "func (tt *telloTrackT) deriveScale() (scale float32) {\n\tscale = 1.0 // minimum scale value\n\tif tt.maxX > scale {\n\t\tscale = tt.maxX\n\t}\n\tif -tt.minX > scale {\n\t\tscale = -tt.minX\n\t}\n\tif tt.maxY > scale {\n\t\tscale = tt.maxY\n\t}\n\tif -tt.minY > scale {\n\t\tscale = -tt.minY\n\t}\n\tscale = float32(math.Ceil(float64(scale)))\n\treturn scale\n}", "func (_Mevsky *MevskyTransactor) SetMinBounty(opts *bind.TransactOpts, newMinBounty *big.Int) (*types.Transaction, error) {\n\treturn _Mevsky.contract.Transact(opts, \"setMinBounty\", newMinBounty)\n}", "func (o *LoyaltySubLedger) GetCurrentTier() Tier {\n\tif o == nil || o.CurrentTier == nil {\n\t\tvar ret Tier\n\t\treturn ret\n\t}\n\treturn *o.CurrentTier\n}", "func (p *Player) AddItem(item *Item) bool {\n var totalWeight int\n totalWeight += item.Weight\n if totalWeight + item.Weight > p.MaxWeight {\n return false\n }\n p.Inventory = append(p.Inventory, item)\n if item.Name == \"Rusty Sword\" {\n p.Attack += 2\n }\n if item.Name == \"Small Shield\" {\n p.Armor += 2\n }\n if item.Name == \"Battle Armor\" {\n p.Attack += 2\n p.Armor ++\n }\n if item.Name == \"Heavy Armor\" {\n p.Attack ++\n p.Armor += 3\n }\n if item.Name == \"Lost Sword\" {\n p.Attack += 4\n }\n if item.Name == \"Large Shield\" {\n p.Armor += 4\n }\n return true\n}", "func (*GetBackendTypeByTierRequest) Descriptor() ([]byte, []int) {\n\treturn file_s3_proto_s3_proto_rawDescGZIP(), []int{72}\n}", "func (o OceanLaunchSpecBlockDeviceMappingEbsDynamicVolumeSizeOutput) BaseSize() pulumi.IntOutput {\n\treturn o.ApplyT(func(v OceanLaunchSpecBlockDeviceMappingEbsDynamicVolumeSize) int { return v.BaseSize }).(pulumi.IntOutput)\n}", "func (level DepthOfMarketLevel) GetQty() float64 { return level[1] }" ]
[ "0.4722705", "0.46578714", "0.4643263", "0.4634317", "0.46079737", "0.45513874", "0.45343092", "0.4529244", "0.45269722", "0.4509911", "0.4509911", "0.44835874", "0.44619718", "0.44540906", "0.4439477", "0.44236666", "0.44218728", "0.4420465", "0.4393814", "0.43921787", "0.43902326", "0.4389645", "0.4377302", "0.43711507", "0.43699083", "0.4330321", "0.43266058", "0.43180007", "0.43072692", "0.42890036", "0.42729634", "0.42712963", "0.42712158", "0.4262945", "0.42554355", "0.42541555", "0.4241067", "0.42408216", "0.42359304", "0.42224348", "0.42092007", "0.41986087", "0.41923064", "0.4179264", "0.41732875", "0.41581476", "0.41572344", "0.4154774", "0.4147793", "0.4144584", "0.41392192", "0.41323948", "0.4123452", "0.41224122", "0.41026592", "0.40959534", "0.40938488", "0.4083585", "0.40788448", "0.40733826", "0.40681982", "0.40615657", "0.40603212", "0.40582973", "0.40577933", "0.40562713", "0.4055916", "0.40554574", "0.40553918", "0.4054778", "0.40469778", "0.40446696", "0.4043451", "0.40429482", "0.40429482", "0.4037856", "0.40314397", "0.4027755", "0.4026935", "0.40234652", "0.40191004", "0.40149266", "0.40144357", "0.40135625", "0.40134725", "0.40115178", "0.40101153", "0.39858925", "0.39834568", "0.3983224", "0.3982476", "0.39798233", "0.39794883", "0.3978353", "0.3977069", "0.3972021", "0.3968329", "0.3964333", "0.39621606", "0.39597306" ]
0.55280566
0
perf: 93, 90 time: O(n) space: 1
func oo135(ratings []int) int { sum := 0 left, mid, right := 0, 0, 0 for { for mid = left; mid+1 < len(ratings) && ratings[mid+1] > ratings[mid]; mid += 1 { } for right = mid; right+1 < len(ratings) && ratings[right] > ratings[right+1]; right += 1 { } ll, rr := mid-left, right-mid sum += (ll) * (ll + 1) / 2 sum += (rr) * (rr + 1) / 2 if ll > rr { sum += ll } else { sum += rr } sum += 1 // change left if right == len(ratings)-1 { break } if ratings[right] == ratings[right+1] { left = right + 1 } else { left = right sum -= 1 } } return sum }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func Solution(A []int) int {\n\t// write your code in Go 1.4\n\tn := len(A)\n\tsum := n * (n + 1) / 2\n\n\tisSeen := make(map[int]bool)\n\n\tfor _, el := range A {\n\t\tdup := isSeen[el]\n\t\tif dup {\n\t\t\treturn 0\n\t\t}\n\t\tisSeen[el] = true\n\t\tsum -= el\n\t}\n\tif sum != 0 {\n\t\treturn 0\n\t}\n\treturn 1\n}", "func twoSumEfficient(arr []int, target int) []int {\n\tm := make(map[int]int)\n\tfor i := 0; i < len(arr); i++ {\n\t\tcompliment := target - arr[i]\n\t\tif _, ok := m[compliment]; ok {\n\t\t\treturn []int{m[compliment], i}\n\t\t}\n\t\tm[arr[i]] = i\n\t}\n\treturn []int{}\n}", "func Solution(X int, A []int) int {\n // write your code in Go 1.4\n bucket := make([]bool, X + 1)\n count := 0\n \n for i, n := range A {\n if (bucket[n] == false) {\n bucket[n] = true\n count++\n }\n \n if (count == X) {\n return i\n }\n\t}\n\t\n\treturn -1\n}", "func threeSumSlow(nums []int) [][]int {\n\ttarget := 0\n\t// O(nlogn)\n\tsort.Ints(nums)\n\toutput := [][]int{}\n\n\tusedMap := make(map[int]map[int]int)\n\n\t// -2 since we don't have to iterate last 2 elements, it will check by inner loop\n\t// iterations are n-1 + n-2 + .... 2 => n*(n-1) / 2 => O(n^2)\n\tfor i := 0; i < len(nums)-2; i++ {\n\t\tleft, right := i+1, len(nums)-1\n\n\t\tfor left < right {\n\n\t\t\tleftRightResult := nums[left] + nums[right]\n\t\t\tsum := nums[i] + leftRightResult\n\n\t\t\t_, leftUsed := usedMap[nums[i]][nums[left]]\n\t\t\t_, rightUsed := usedMap[nums[i]][nums[right]]\n\n\t\t\tif leftUsed == true && rightUsed == true {\n\t\t\t\tleft++\n\t\t\t\tright--\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif sum == target {\n\t\t\t\toutput = append(output, []int{nums[i], nums[left], nums[right]})\n\n\t\t\t\t_, ok := usedMap[nums[i]]\n\n\t\t\t\tif ok == false {\n\t\t\t\t\tusedMap[nums[i]] = make(map[int]int)\n\t\t\t\t}\n\n\t\t\t\tusedMap[nums[i]][nums[left]] = nums[left]\n\t\t\t\tusedMap[nums[i]][nums[right]] = nums[right]\n\n\t\t\t\tleft++\n\t\t\t\tright--\n\t\t\t} else if sum > target {\n\t\t\t\tright--\n\t\t\t} else {\n\t\t\t\tleft++\n\t\t\t}\n\t\t}\n\t}\n\n\treturn output\n}", "func singleNumberB(nums []int) int {\n \n mp := make(map[int]int)\n result:= 0\n for _,data := range nums{\n if _,exist := mp[data]; exist{ //if element exist we remove the elemtn\n delete(mp, data)\n \n }else{\n mp[data] = data\n }\n\t}\n\t//really O(1) since there's always one element left\n for _, data := range mp{ \n result = data\n }\n return result \n}", "func repeatedNTimes(A []int) int {\n cache := map[int]bool {}\n for _,a := range A {\n if cache[a] {\n return a\n }\n cache[a] = true\n }\n return -1\n}", "func removeDuplicatesII(nums []int) int {\n\tres := len(nums)\n\tfor i := 0; i < len(nums); {\n\t\tv := nums[i]\n\t\tif i < res-1 && nums[i] == nums[i+1] {\n\t\t\ti++\n\t\t\t// 此处优化为记录t后copy一次,可以100%\n\t\t\tj, t := i+1, 0\n\t\t\tfor ; j < res && nums[j] == v; j++ {\n\t\t\t\tt++\n\t\t\t}\n\t\t\tif t > 0 {\n\t\t\t\tcopy(nums[i+1:], nums[j:])\n\t\t\t\tres -= t\n\t\t\t}\n\t\t\ti++\n\t\t} else {\n\t\t\ti++\n\t\t}\n\t}\n\treturn res\n}", "func d(i, j int, a, b string) int {\n\tmin_v := 100\n\n\tcost := 1\n\tif a[i] == b[j] {\n\t\tcost = 0\n\t}\n\n\tif i == j && j == 0 {\n\t\tmin_v = 0\n\t}\n\tif i > 0 {\n\t\tmin_v = min(min_v, d(i - 1, j, a, b) + 1)\n\t}\n\tif j > 0 {\n\t\tmin_v = min(min_v, d(i, j - 1, a, b) + 1)\n\t}\n\tif i > 0 && j > 0 {\n\t\tmin_v = min(min_v, d(i - 1, j - 1, a, b) + cost)\n\t}\n\tif i > 1 && j > 1 && a[i] == b[j - 1] && a[i - 1] == b[j] {\n\t\tmin_v = min(min_v, d(i - 2, j - 2, a, b) + 1)\n\t}\n\n\treturn min_v\n\n}", "func sol2(nums []int, target int) []int {\n\tmemo := make(map[int]int)\n\tfor i, n := range nums {\n\t\tmemo[n] = i\n\t}\n\tfor i, n := range nums {\n\t\tif _, ok := memo[target-n]; ok && i != memo[target-n] {\n\t\t\treturn []int{i, memo[target-n]}\n\t\t}\n\t}\n\treturn nil\n}", "func find3Sum(nums []int){\n lenS := len(nums)\n fmt.Println(lenS)\n fmt.Println(nums[0: lenS-2])\n sort.Ints(nums)\n fmt.Println(nums)\n numsMap := make(map[int]int)\n var res [] int\n for i,v := range nums[0: lenS-2] {\n if i >= 1 && nums[i] == nums[i-1] {\n continue\n }\n for _,x := range nums[i: lenS] {\n _, ok := numsMap[x]\n if ok {\n res = append(res, v)\n res = append(res, x)\n res = append(res, -v-x)\n } else {\n numsMap[-x-v] = 1\n }\n }\n }\n\n}", "func SortFastest(arr []int, _, _ int) []int {\n max := maxVal(arr)\n len := len(arr)\n \n beads := make([]int, max*len)\n\n for i := 0; i < len; i++ {\n for j := 0; j < arr[i]; j++ {\n beads[i * max + j] = 1\n }\n }\n \n for j := 0; j < max; j++ {\n sum := 0\n \n for i := 0; i < len; i++ {\n sum += beads[i * max + j]\n beads[i*max+j] = 0\n }\n \n for i := len - sum; i < len; i++ {\n beads[i * max + j] = 1\n }\n }\n \n for i := 0; i < len; i++ {\n var j int\n for j = 0; j < max && u.ToBool(beads[i * max + j]); j++ {\n arr[i] = j\n }\n }\n\n return arr\n}", "func part2(arr []int) int {\n\tvar i, j, k int\n\tn := len(arr)\n\n\tvar found bool = false\n\tfor i = 0; i < n; i++ {\n\t\tj = i + 1\n\t\tk = n - 1\n\t\tvar tempTarget int = target - arr[i]\n\t\tfor j < n && k >= 0 {\n\t\t\tif arr[j]+arr[k] == tempTarget {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif arr[j]+arr[k] < tempTarget {\n\t\t\t\tj++\n\t\t\t} else {\n\t\t\t\tk--\n\t\t\t}\n\t\t}\n\t\tif found {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn arr[i] * arr[j] * arr[k]\n}", "func arrayManipulation(n int32, queries [][]int32) int64 {\n\tmax, arr, sum := int64(0), make([]int64, n), int64(0)\n\n\t// Instead of observing increases on each individual value...\n\t// We observe each beginning of range increase, and where it ends.\n\t//\n\t// For example:\n\t// n = 5, m = 3\n\t// a b k\n\t// 1 2 100 -> this will add 100 to n[1 - 1] and -100 to n[2]\n\t// 2 5 100 -> this will add 100 to n[2 - 1] and should add -100 to n[5] or none at all since it is beyond index range\n\t// 3 4 100\n\t// Expected output: 200\n\t//\n\t// Begin with: [5]int64 {0, 0, 0, 0, 0}\n\t// Then we iterate through the queries\n\t// m[0]: {100, 0, -100, 0, 0}\n\t// m[1]: {100, 100, -100, 0, 0}\n\t// m[2]: {100, 100, 0, 0, -100}\n\t//\n\t// Then we'll get sum of the whole array\n\t// while observing the peak sum as max value\n\t// (0)+100 100(+100) 200(+0) 200(+0) 100(-100)\n\n\tfor i := 0; i < len(queries); i++ {\n\t\tquery := queries[i]\n\t\ta := query[0] - 1\n\t\tb := query[1] - 1\n\t\tk := int64(query[2])\n\t\tarr[a] += k\n\t\tif b+1 < n {\n\t\t\tarr[b+1] -= k\n\t\t}\n\t}\n\tfor i := int32(0); i < n; i++ {\n\t\tif arr[i] != 0 {\n\t\t\tsum += arr[i]\n\t\t\tif sum > max {\n\t\t\t\tmax = sum\n\t\t\t}\n\t\t}\n\t}\n\treturn max\n}", "func arrayManipulation(n int32, queries [][]int32) int64 {\n\n\tvar ret int64\n\n\t// create a slice with n amount of zeros\n\tmainSlice := []int32{}\n\tvar i int32\n\tfor i = 0; i <= n; i++ {\n\t\t// append 'n' number of 0's to slice to begin\n\t\tmainSlice = append(mainSlice, 0)\n\t}\n\n\tmainSlice = addKValsToArr(mainSlice, queries)\n\n\ttemp := mainSlice[0]\n\tfor i = 0; i <= n; i++ {\n\t\tif mainSlice[i] > temp {\n\t\t\ttemp = mainSlice[i]\n\t\t}\n\t}\n\n\tret = int64(temp)\n\n\treturn ret\n}", "func findDuplicate(nums []int) int {\n\tif nums == nil || len(nums) == 0 {\n\t\treturn -1\n\t}\n\tslow, fast := nums[0], nums[nums[0]]\n\tfor slow != fast {\n\t\tslow, fast = nums[slow], nums[nums[fast]]\n\t}\n\n\tslow = 0\n\tfor slow != fast {\n\t\tslow, fast = nums[slow], nums[fast]\n\t}\n\treturn slow\n}", "func arrayManipulation(n int32, queries [][]int32) int64 {\n // slice is initialized with zeroes\n // 1-based indices + another element for the decrease\n // if upper bound == n\n arr := make([]int64, n+2)\n\n for _, row := range queries {\n var lhs, rhs, k = row[0], row[1], row[2]\n\n arr[lhs] += int64(k)\n arr[rhs+1] -= int64(k)\n }\n\n // Find maximum by adding up the changes into an accumulator.\n // all k are positive => invariant: acc >= 0.\n var acc, max int64 = 0, 0\n\n for _, val := range arr {\n acc += val\n if acc > max {\n max = acc\n }\n }\n\n return max\n}", "func Solution(A []int) int {\n\n\tN := len(A)\n\n\tsum := make([]int, N)\n\tsum[0] = A[0]\n\tfor i := 1; i < N; i++ {\n\t\tsum[i] = sum[i-1] + A[i]\n\t}\n\n\tif sum[N-1] >= 0 {\n\t\treturn N\n\t}\n\n\t// Now lets look for repitions in sum, basically the next position where a sum repeats\n\t// is indicative of non zero (especially for negative values)\n\tlower := make(map[int]int)\n\tupper := make(map[int]int)\n\tfor i := 0; i < N; i++ {\n\t\ts := sum[i]\n\t\t_, ok := lower[s]\n\t\tif !ok {\n\t\t\tlower[s] = i\n\t\t\tupper[s] = -1 // dummy\n\t\t} else {\n\t\t\tupper[s] = i\n\t\t}\n\t}\n\n\t// fmt.Printf(\"lower: %v\\n\", lower)\n\t// fmt.Printf(\"upper: %v\\n\", upper)\n\n\tvar sum_arr []int\n\tfor s, _ := range lower {\n\t\tsum_arr = append(sum_arr, s)\n\t}\n\n\tsort.Ints(sum_arr)\n\n\tmax_gap := 0\n\tfirst_lower := N\n\tfor i := 0; i < len(sum_arr); i++ {\n\t\ts := sum_arr[i]\n\t\tl := lower[s]\n\t\tif l < first_lower {\n\t\t\tfirst_lower = l\n\t\t\t//fmt.Printf(\"first_lower: %v\\n\", first_lower)\n\t\t}\n\n\t\tu := upper[s]\n\t\t// fmt.Printf(\"u: %v\\n\", u)\n\t\tgap := u - first_lower\n\t\tif s >= 0 {\n\t\t\t// or 0 or more the values are inclusive by 1\n\t\t\tgap++\n\t\t}\n\t\tif gap > max_gap {\n\t\t\tmax_gap = gap\n\t\t}\n\t}\n\n\treturn max_gap\n}", "func twoSum1(nums []int, target int) []int {\n\thashTable := make(map[int]int)\n\tfor i, x := range nums {\n\t\tif j, ok := hashTable[target-x]; ok {\n\t\t\treturn []int{j, i}\n\t\t}\n\t\thashTable[x] = i\n\t}\n\treturn nil\n}", "func part1(arr []int) int {\n\tvar i, j int\n\tn := len(arr)\n\n\ti = 0\n\tj = n - 1\n\n\tfor i < n && j >= 0 {\n\t\tif arr[i]+arr[j] == target {\n\t\t\tbreak\n\t\t}\n\t\tif arr[i]+arr[j] < target {\n\t\t\ti++\n\t\t} else {\n\t\t\tj--\n\t\t}\n\t}\n\treturn arr[i] * arr[j]\n}", "func naive(mappings map[int]map[int][]mapping, data *util.QueryDocumentSet, iterations int) []float64 {\n\tN := data.Size()\n\n\titerations = gomath.MinInt(iterations, N-1)\n\n\ts := &sortable{}\n\n\ts.n = N\n\ts.nodeInfo = make([]wrapper, N)\n\n\tdead := make([]bool, N)\n\tres := make([]float64, N)\n\n\tfor iterations > 0 {\n\n\t\tfor i := 0; i < N; i++ {\n\t\t\ts.nodeInfo[i].outDegree = 0\n\t\t\ts.nodeInfo[i].inDegree = 0\n\t\t}\n\n\t\tcountDegrees(s, dead, mappings)\n\t\tbestIndex, bestRatio := findBestRatio(s)\n\n\t\tdead[bestIndex] = true\n\n\t\tres[bestIndex] = bestRatio\n\n\t\titerations--\n\t}\n\treturn res\n}", "func SortFast(arr []int, arrSize, maxNum int) []int {\n const bead = 'o'\n \n all := make([]byte, maxNum*len(arr))\n\n abacus := make([][]byte, maxNum)\n for pole, space := 0, all; pole < maxNum; pole++ {\n abacus[pole] = space[:len(arr)]\n space = space[len(arr):]\n }\n\n var wg sync.WaitGroup\n wg.Add(len(arr))\n\n for row, n := range arr {\n go func(row, n int) {\n for pole := 0; pole < n; pole++ {\n abacus[pole][row] = bead\n }\n wg.Done()\n }(row, n)\n }\n wg.Wait()\n\n wg.Add(maxNum)\n for _, pole := range abacus {\n go func(pole []byte) {\n top := 0\n for row, space := range pole {\n if space == bead {\n pole[row] = 0\n pole[top] = bead\n top++\n }\n }\n wg.Done()\n }(pole)\n }\n wg.Wait()\n\n for row := range arr {\n x := 0\n for pole := 0; pole < maxNum && abacus[pole][row] == bead; pole++ {\n x++\n }\n arr[len(arr)-1-row] = x\n }\n\n return arr\n}", "func Solution(A []int) int {\n // write your code in Go 1.4\n \n var lenA = len(A);\n \n if(lenA > 100000) {\n return 0;\n }\n \n sort.Ints(A);\n \n for i := 0; i < lenA - 2; i++ {\n \n if(((A[i] + A[i+1]) > A[i+2]) && ((A[i+1] + A[i+2]) > A[i]) && ((A[i+2] + A[i]) > A[i+1])) {\n return 1;\n }\n }\n \n return 0;\n \n}", "func func2(nums []int) int {\n\tn := len(nums);\n\tlength := make([]int, n);\n\tcount := make([]int, n);\n\n\tfor i := 0; i < n; i++ {\n\t\tlength[i] = 1;\n\t\tcount[i] = 1;\n\t}\n\n\tmaxLen := 1;\n\tfor i := 0; i < n; i++ {\n\t\tfor j := i-1; j >= 0; j-- {\n\t\t\tif nums[i] > nums[j] {\n\t\t\t\tif length[j]+1 > length[i] {\n\t\t\t\t\tlength[i] = length[j]+1;\n\t\t\t\t\tcount[i] = count[j]; \n\t\t\t\t} else if length[j]+1 == length[i] {\n\t\t\t\t\tcount[i] += count[j];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif length[i] > maxLen {\n\t\t\tmaxLen = length[i];\n\t\t}\n\t}\n\n\tret := 0;\n\tfor i := 0; i < n; i++ {\n\t\tif length[i] == maxLen {\n\t\t\tret += count[i];\n\t\t}\n\t}\n\n\treturn ret;\n}", "func func1(nums []int) int {\n\tn := len(nums);\n\tlength := make([]int, n);\n\tcount := make([]int, n);\n\n\tfor i := 0; i < n; i++ {\n\t\tlength[i] = 1;\n\t\tcount[i] = 1;\n\t}\n\n\tmaxLen := 1;\n\tfor i := n-1; i >= 0; i-- {\n\t\tfor j := i+1; j < n; j++ {\n\t\t\tif nums[i] < nums[j] {\n\t\t\t\tif length[j]+1 > length[i] {\n\t\t\t\t\tlength[i] = length[j]+1;\n\t\t\t\t\tcount[i] = count[j];\n\t\t\t\t} else if length[j]+1 == length[i] {\n\t\t\t\t\tcount[i] += count[j];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// fmt.Printf(\"i=%d, length=%d, count=%d\\n\", i, length[i], count[i]);\n\t\tif length[i] > maxLen {\n\t\t\tmaxLen = length[i];\n\t\t}\n\t}\n\n\tret := 0;\n\tfor i := 0; i < n; i++ {\n\t\tif length[i] == maxLen {\n\t\t\tret += count[i];\n\t\t}\n\t}\n\n\treturn ret;\n}", "func SortSlow(arr []int, arrSize, maxNum int) []int {\n var twoD = make([][]int, arrSize)\n for i := range twoD {\n twoD[i] = make([]int, maxNum)\n }\n\tfor i := range twoD {\n\t\tfor j := 0; j < arr[i]; j++ {\n\t\t\ttwoD[i][j] = 1\n\t\t}\n\t}\n\n\tfor outIndex := arrSize-1; outIndex >= 0; outIndex-- {\n\t\tfor inIndex := maxNum-1; inIndex >= 0; inIndex-- {\n\t\t\tgo func(i, j int){\n\t\t\t\tif twoD[i][j] == 0 {\n\t\t\t\t\tfor searchIndex := i - 1; searchIndex >= 0; searchIndex-- {\n\t\t\t\t\t\tif twoD[searchIndex][j] == 1 {\n\t\t\t\t\t\t\ttwoD[searchIndex][j] = 0\n\t\t\t\t\t\t\ttwoD[i][j] = 1\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}(outIndex, inIndex)\n\t\t}\n }\n \n return func() []int {\n var out []int\n for _, num := range twoD {\n var count int \n for _, num1 := range num {\n if num1 == 1 {\n count++\n }\n }\n out = append(out, count)\n }\n return out\n }()\n}", "func minIncrementForUnique(A []int) int {\n\tarr := [80000]int{}\n\tfor _, v := range A {\n\t\tarr[v]++\n\t}\n\n\tvar (\n\t\tans int\n\t\ttoken int\n\t)\n\tfor i := 0; i < 80000; i++ {\n\t\tif arr[i] > 1 {\n\t\t\ttoken += arr[i] - 1\n\t\t\tans -= i * (arr[i] - 1)\n\t\t} else if token > 0 && arr[i] == 0 {\n\t\t\ttoken--\n\t\t\tans += i\n\t\t}\n\t}\n\n\treturn ans\n}", "func g(i int) (n int) {\n\tfor n = 1; sf(n) != i; n++ {\n\t}\n\treturn\n}", "func Tianyun_searchRange(nums []int, target int) []int {\n\n\t//O(n)\n//\tstartIndex:=-1\n//\tcount:=0\n//\n//\tfor i:=0;i<len(nums);i++{\n//\t\tif count==0&&nums[i]==target{\n//\t\t\tstartIndex = i\n//\t\t\tcount++\n//\n//\t\t}else if nums[i]==target{\n//\t\t\tcount++\n//\t\t}\n//}\n//\n// if count==0{\n// \treturn []int{-1,-1}\n// }else{\n// \treturn []int{startIndex,startIndex+count}\n// }\n\n\n\n//O(logn)\nif len(nums)==0{\n\treturn []int{-1,-1}\n}\n startIndex:=-1\n left:=0\n right:=len(nums)-1\n\n for left +1 <right{\n \tmid:=(left+right)/2\n \tif nums[mid]>=target{\n right = mid\n\t\t}else{\n\t\t\tleft =mid+1\n\t\t}\n\t }\n\t if nums[left]==target{\n\t \tstartIndex =left\n\t }else if nums[right]==target{\n\t \tstartIndex = right\n\t }else{\n\t \treturn []int{-1,-1}\n\t }\n\n\n\tleft=0\n\tright=len(nums)-1\n\n\tfor left +1 <right{\n\t\tmid:=(left+right)/2\n\t\tif nums[mid]<=target{\n\t\t\tleft = mid\n\t\t}else{\n\t\t\tright = mid\n\t\t}\n\t}\n\n\tif nums[right]==target{\n\t\treturn []int{startIndex,right}\n\t}else if nums[left]==target{\n\t\treturn []int{startIndex,left}\n\t}else{\n\t\treturn []int{-1,-1}\n\t}\n}", "func repeatedNTimes(A []int) int {\n m := make(map[int]int)\n for _, v := range A {\n m[v]++\n if m[v] > 1 {\n return v\n }\n }\n return 0\n}", "func p256OrdSqr(res, in []uint64, n int)", "func p256OrdSqr(res, in []uint64, n int)", "func naiveCount(arr []int32) int64 {\n\t// nested loop algo - will be very inefficient O(n^2)\n\tvar count int64\n\tfor i := 0; i < len(arr); i++ {\n\t\tfor j := i + 1; j < len(arr); j++ {\n\t\t\tif arr[i] > arr[j] {\n\t\t\t\tcount++\n\t\t\t}\n\t\t}\n\t}\n\treturn count\n}", "func search(n int, f func(int) bool) int {\n\tlo := 0\n\tfor hi := n; lo < hi; {\n\t\tif i := int(uint(lo+hi) >> 1); !f(i) {\n\t\t\tlo = i + 1\n\t\t} else {\n\t\t\thi = i\n\t\t}\n\t}\n\treturn lo\n}", "func logdist(a, b common.Hash) int {\n\tlz := 0\n\tfor i := range a {\n\t\tx := a[i] ^ b[i]\n\t\tif x == 0 {\n\t\t\tlz += 8\n\t\t} else {\n\t\t\tlz += lzcount[x]\n\t\t\tbreak\n\t\t}\n\t}\n\treturn len(a)*8 - lz\n}", "func singleNumberA(nums []int) int {\n result:=0\n for _,data := range nums{\n result^=data\n }\n return result\n}", "func naive(a []int) []int {\n\n\t/* if the array has 0 or zero elements, return an empty array */ \n\tif (len(a) < 2) {\n\t\treturn make([]int, 0)\n\t}\n\n\tp := make([]int, len(a))\n\tfor i := 0; i < len(a); i++ {\n\t\n\t\tproduct := 1; \n\t\tfor j := 0; j < len(a); j++ {\n\t\t\tif i != j {\n\t\t\t\tproduct = product * a[j]\n\t\t\t}\n \t\t}\n\t\tp[i] = product;\n\t}\n\n\treturn p\n}", "func recInversionCount(v *array) (*array, int){\r\n\tif len(v.a) == 1{\r\n\t\treturn v, 0\r\n\t}\r\n\tmid := (len(v.a))/2\r\n\tleftHalf, leftInv := recInversionCount(&array{v.a[:mid]})\r\n\trightHalf, rightInv := recInversionCount(&array{v.a[mid:]})\r\n\tsortedArr := []int{}\r\n\tsplitInv := 0\r\n\ti, j := 0, 0\r\n\tfor i < len(leftHalf.a) && j < len(rightHalf.a){\r\n\t\tif leftHalf.a[i] <= rightHalf.a[j]{\r\n\t\t\tsortedArr = append(sortedArr, leftHalf.a[i])\r\n\t\t\ti++\r\n\t\t} else{\r\n\t\t\tsortedArr = append(sortedArr, rightHalf.a[j])\r\n\t\t\tsplitInv += len(leftHalf.a)-i\r\n\t\t\tj++\r\n\t\t}\r\n\t}\r\n\tif i<len(leftHalf.a) {\r\n\t\tsortedArr = append(sortedArr, leftHalf.a[i:]...)\r\n\t} \r\n\tfor j < len(rightHalf.a) {\r\n\t\tsortedArr = append(sortedArr, rightHalf.a[j])\r\n\t\tj++\r\n\t}\r\n\treturn &array{sortedArr}, leftInv+rightInv+splitInv\r\n}", "func minIncrementForUnique(A []int) int {\n \n}", "func containsNearbyDuplicate(nums []int, k int) bool {\n m := make(map[int]int, 0)\n for i := 0; i < len(nums); i++ {\n if _, ok := m[nums[i]]; ok {\n if i - m[nums[i]] <= k {\n return true\n }\n }\n m[nums[i]] = i\n }\n return false\n}", "func goodSolution(nums []int, sum int) int {\n\tresult := 0\n\tsumMap := make(map[int]int)\n\tcum := 0\n\n\tsumMap[0] = 1\n\n\tfor _, v := range nums {\n\t\tcum += v\n\t\tresult += sumMap[cum-sum]\n\t\tsumMap[cum]++\n\t}\n\n\treturn result\n}", "func arrayPairSum(nums []int) int {\n\tcounts := make([]int, 20001)\n\tfor _, n := range nums {\n\t\tcounts[n+10000]++\n\t}\n\tvar sum int\n\tadd := true\n\tfor i, _ := range counts {\n\t\tfor 0 < counts[i] {\n\t\t\tif add {\n\t\t\t\tsum += i - 10000\n\t\t\t}\n\t\t\tcounts[i]--\n\t\t\tadd = !add\n\t\t}\n\t}\n\treturn sum\n}", "func Solution(A []int) int {\n\t// write your code in Go 1.4\n\tsort.Ints(A)\n\tresult := 0\n\tfor p := 0; p < len(A)-2; p++ {\n\t\tr := p + 2\n\t\tfor q := p + 1; q < len(A)-1; q++ {\n\t\t\tfor r < len(A) && A[p]+A[q] > A[r] {\n\t\t\t\tr++\n\t\t\t}\n\t\t\tresult = result + r - q - 1\n\t\t}\n\t}\n\treturn result\n}", "func get1N(indices *[]uint16, start, end int) []uint16 {\n\tif end > cap(*indices) {\n\t\t*indices = make([]uint16, end)\n\t\tfor i := range *indices {\n\t\t\t(*indices)[i] = uint16(i)\n\t\t}\n\t}\n\treturn (*indices)[start:end]\n}", "func computeDistanceCache(pos uint, starting_dist_cache []int, nodes []zopfliNode, dist_cache []int) {\n\tvar idx int = 0\n\tvar p uint = uint(nodes[pos].u.shortcut)\n\tfor idx < 4 && p > 0 {\n\t\tvar ilen uint = uint(nodes[p].dcode_insert_length & 0x7FFFFFF)\n\t\tvar clen uint = uint(zopfliNodeCopyLength(&nodes[p]))\n\t\tvar dist uint = uint(zopfliNodeCopyDistance(&nodes[p]))\n\t\tdist_cache[idx] = int(dist)\n\t\tidx++\n\n\t\t/* Because of prerequisite, p >= clen + ilen >= 2. */\n\t\tp = uint(nodes[p-clen-ilen].u.shortcut)\n\t}\n\n\tfor ; idx < 4; idx++ {\n\t\tdist_cache[idx] = starting_dist_cache[0]\n\t\tstarting_dist_cache = starting_dist_cache[1:]\n\t}\n}", "func computeNj(P string) []int {\n\tn := len(P)\n\tNj := make([]int, n)\n\t// [l, r] is the current Z box.\n\tl := n\n\tr := n - 1\n\tfor i := n - 2; i >= 0; i-- {\n\t\tif i < l {\n\t\t\tj := i\n\t\t\tfor j >= 0 && P[n-1-i+j] == P[j] {\n\t\t\t\tj--\n\t\t\t}\n\t\t\tif j < i {\n\t\t\t\tl = j + 1\n\t\t\t\tr = i\n\t\t\t\tNj[i] = i - j\n\t\t\t}\n\t\t} else {\n\t\t\tbelta := Nj[n-1-r+i]\n\t\t\tif belta <= i-l {\n\t\t\t\tNj[i] = belta\n\t\t\t} else {\n\t\t\t\tj := l - 1\n\t\t\t\tfor ; j >= 0 && P[n-belta-i+j] == P[j]; j-- {\n\t\t\t\t}\n\t\t\t\tl = j + 1\n\t\t\t\tr = i\n\t\t\t\tNj[i] = i - j\n\t\t\t}\n\t\t}\n\t}\n\treturn Nj\n}", "func bgmlogsdist(a, b bgmcommon.Hash) int {\n\tlz := 0\n\tfor i := range a {\n\t\tx := a[i] ^ b[i]\n\t\tif x == 0 {\n\t\t\tlz += 8\n\t\t} else {\n\t\t\tlz += lzcount[x]\n\t\t\tbreak\n\t\t}\n\t}\n\treturn len(a)*8 - lz\n}", "func findEven(b []byte, m int, l int) result {\n\tif 0 == m {\n\t\treturn result{\n\t\t\tb: b[0:1],\n\t\t\tl: 1,\n\t\t}\n\t}\n\tif m == l {\n\t\tv := b[l-1 : l]\n\t\treturn result{\n\t\t\tb: v,\n\t\t\tl: len(v),\n\t\t}\n\t}\n\tmax := m + 1\n\tfmt.Println(\"max?\", max, len(b))\n\tfor d := 1; d < max; d++ {\n\t\txi := m - d\n\t\tx := b[xi : xi+1]\n\t\tyi := m + d - 1\n\t\ty := b[yi : yi+1]\n\t\tfmt.Println(\" m:\", m, string(b[m]))\n\t\tfmt.Println(\" x:\", xi, string(x[0]))\n\t\tfmt.Println(\" y:\", yi, string(y[0]))\n\t\tfmt.Println(\" range:\", string(b[xi:yi+1]))\n\t\tif x[0] != y[0] {\n\t\t\tv := b[m+1-d : m+d-1]\n\t\t\treturn result{\n\t\t\t\tb: v,\n\t\t\t\tl: len(v),\n\t\t\t}\n\t\t}\n\t}\n\tv := b[m-m : m+(m)]\n\treturn result{\n\t\tb: v,\n\t\tl: len(v),\n\t}\n}", "func duplicateZeros1(arr []int) {\n\tvar count int\n\tn := len(arr)\n\tfor _, v := range arr {\n\t\tif v == 0 {\n\t\t\tcount++\n\t\t}\n\t}\n\n\tfor i := n - 1; i >= 0; i-- {\n\t\tif i+count >= n {\n\t\t\tif arr[i] == 0 {\n\t\t\t\tif i+count-1 < n {\n\t\t\t\t\tarr[i+count-1] = 0\n\t\t\t\t}\n\t\t\t\tcount--\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\tif count != 0 {\n\t\t\tarr[i+count] = arr[i]\n\t\t\tif arr[i] == 0 {\n\t\t\t\tarr[i+count-1] = 0\n\t\t\t\tcount--\n\t\t\t}\n\t\t}\n\t}\n}", "func twoSum(nums []int, target int) (out []int) {\n\tN := len(nums)\n\tfor i, n := range nums {\n\t\tt := target - n\n\t\tfor j := i + 1; j < N; j ++ {\n\t\t\tif nums[j] == t {\n\t\t\t\tout = []int{i, j}\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}", "func twoSum(nums []int, target int) []int {\n\tseenNums := make(map[int]int)\n\tfor index, thisNum := range nums {\n\t\tif seenIndex, ok := seenNums[target - thisNum]; ok {\n\t\t\treturn []int{seenIndex, index}\n\t\t}\n\t\tseenNums[thisNum] = index\n\t}\n\treturn []int{0, 0} // Should not happen\n}", "func (t *Tree) query(i int) int {\n\tvar ret int\n\tfor i >= 0 {\n\t\tret += t.bit[i]\n\t\ti = (i & (i + 1)) - 1\n\t}\n\treturn ret\n}", "func product(a, b int) int {\n\tsum := 0\n\tfor i := 0; i < b; i++ { // O(b) operation\n\t\tsum += a // constant O(1) operation\n\t}\n\treturn sum\n}", "func containsNearbyDuplicate(nums []int, k int) bool {\n m := make(map[int]int)\n for i := 0; i < len(nums); i++ {\n index, exists := m[nums[i]]\n if exists {\n if math.Abs(float64(index - i)) <= float64(k) {\n return true\n }\n }\n m[nums[i]] = i \n }\n return false\n}", "func canReach2(arr []int, start int) bool {\n\tif arr[start] == 0 {\n\t\treturn true\n\t}\n\n\tN := len(arr)\n\tdp := make([]bool, N)\n\tstack := make([][]int, 0, N)\n\tstack = append(stack, []int{start, arr[start]})\n\tdp[start] = true\n\n\tfor len(stack) > 0 {\n\t\tnode := stack[len(stack)-1]\n\t\ti, d := node[0], node[1]\n\t\tstack = stack[:len(stack)-1]\n\n\t\tforward, backward := i+d, i-d\n\t\tif forward < N && dp[forward] == false {\n\t\t\tif arr[forward] == 0 {\n\t\t\t\treturn true\n\t\t\t}\n\t\t\tstack = append(stack, []int{forward, arr[forward]})\n\t\t\tdp[forward] = true\n\t\t}\n\t\tif backward >= 0 && dp[backward] == false {\n\t\t\tif arr[backward] == 0 {\n\t\t\t\treturn true\n\t\t\t}\n\t\t\tstack = append(stack, []int{backward, arr[backward]})\n\t\t\tdp[backward] = true\n\t\t}\n\t}\n\treturn false\n}", "func stones(n int32, a int32, b int32) (res []int32) {\n\tn--\n\tresults := make(map[int32]struct{})\n\tfor i := int32(0); i <= n; i++ {\n\t\tv := (i * a) + ((n - i) * b)\n\t\tresults[v] = struct{}{}\n\t}\n\tfor v := range results {\n\t\tres = append(res, v)\n\t}\n\tsort.Slice(res, func(i, j int) bool { return res[i] < res[j] })\n\treturn res\n}", "func Solution(A []int) []int {\n\t// write your code in Go 1.4\n\n\tN := len(A)\n\n\tmymap := make(map[int]int)\n\tfor i := 0; i < N; i++ {\n\t\t_, ok := mymap[A[i]]\n\t\tif !ok {\n\t\t\tmymap[A[i]] = 1\n\t\t} else {\n\t\t\tmymap[A[i]] += 1\n\t\t}\n\t}\n\n\t// construct a custom Eratosthenes sieve\n\t// of factors\n\t// Note we create a custom sieve based on numbers we have\n\t// in the map created above\n\tsieve := make([]int, 2*N+1)\n\tfor i := 1; i <= 2*N; i++ {\n\t\tv, ok := mymap[i]\n\t\tif ok {\n\t\t\tfor k := i; k <= 2*N; k += i {\n\t\t\t\tsieve[k] += v\n\t\t\t}\n\t\t}\n\t}\n\n\t// Now we have every thing computed in the sieve,\n\t// with the help of the sieve.\n\t// We just loop again,\n\t// and return the values from the sive\n\n\tret := make([]int, N)\n\tfor i := 0; i < N; i++ {\n\t\tret[i] = N - sieve[A[i]]\n\t}\n\n\treturn ret\n\n}", "func getLongestIncrease(arr []int) (int, []int) {\n\tvar size = len(arr)\n\tvar current, saved []int\n\tvar noIncrease = true\n\n\t// fmt.Printf(\"\\narr(%v)=%+v\\n\", len(arr), arr)\n\tu.Debug(\"\\narr(%v)=%+v\\n\", len(arr), arr)\n\tfor m := 0; m < size-1; m++ {\n\t\tfor i := m; i < size-1; i++ {\n\t\t\tfor j := i + 1; j < size && (size-j) >= len(saved); j++ {\n\t\t\t\tvar opt = arr[i]\n\t\t\t\tvar previous = opt\n\t\t\t\tcurrent = []int{previous}\n\t\t\t\tfor k := j; k < size; k++ {\n\t\t\t\t\tif arr[k] > previous {\n\t\t\t\t\t\topt = previous\n\t\t\t\t\t\tprevious = arr[k]\n\t\t\t\t\t\tcurrent = append(current, previous)\n\t\t\t\t\t\tnoIncrease = false\n\t\t\t\t\t} else if arr[k] > opt {\n\t\t\t\t\t\tprevious = arr[k]\n\t\t\t\t\t\tcurrent[len(current)-1] = previous\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// fmt.Printf(\"m=%v, i=%v, j=%v, current(%v)=%+v, saved(%v)=%+v\\n\", m, i, j, len(current), current, len(saved), saved)\n\t\t\t\tu.Debug(\"m=%v, i=%v, j=%v, current(%v)=%+v, saved(%v)=%+v\\n\", m, i, j, len(current), current, len(saved), saved)\n\t\t\t\tif len(current) > len(saved) {\n\t\t\t\t\tsaved = current\n\t\t\t\t}\n\t\t\t\t// never true but proves how condition should work in `for j` loop\n\t\t\t\tif len(saved) > (size - j) {\n\t\t\t\t\t// fmt.Println(\"break\")\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif noIncrease {\n\t\treturn 0, []int{}\n\t} else if len(current) > len(saved) {\n\t\treturn len(current), current\n\t}\n\n\treturn len(saved), saved\n}", "func rej(a []int16, buf []byte) int {\n\tctr, buflen, alen := 0, len(buf), len(a)\n\tfor pos := 0; pos+3 <= buflen && ctr < alen; pos += 3 {\n\t\tval0 := (uint16(buf[pos]) | (uint16(buf[pos+1]) << 8)) & 0xfff\n\t\tval1 := (uint16(buf[pos+1]>>4) | (uint16(buf[pos+2]) << 4)) & 0xfff\n\t\tif val0 < uint16(q) {\n\t\t\ta[ctr] = int16(val0)\n\t\t\tctr++\n\t\t}\n\t\tif val1 < uint16(q) && ctr != alen {\n\t\t\ta[ctr] = int16(val1)\n\t\t\tctr++\n\t\t}\n\t}\n\treturn ctr\n}", "func core(out *[64]byte, in *[16]byte, k *[32]byte) {\n\tj0 := uint32(0x61707865)\n\tj1 := uint32(0x3320646e)\n\tj2 := uint32(0x79622d32)\n\tj3 := uint32(0x6b206574)\n\tj4 := binary.LittleEndian.Uint32(k[0:4])\n\tj5 := binary.LittleEndian.Uint32(k[4:8])\n\tj6 := binary.LittleEndian.Uint32(k[8:12])\n\tj7 := binary.LittleEndian.Uint32(k[12:16])\n\tj8 := binary.LittleEndian.Uint32(k[16:20])\n\tj9 := binary.LittleEndian.Uint32(k[20:24])\n\tj10 := binary.LittleEndian.Uint32(k[24:28])\n\tj11 := binary.LittleEndian.Uint32(k[28:32])\n\tj12 := binary.LittleEndian.Uint32(in[0:4])\n\tj13 := binary.LittleEndian.Uint32(in[4:8])\n\tj14 := binary.LittleEndian.Uint32(in[8:12])\n\tj15 := binary.LittleEndian.Uint32(in[12:16])\n\n\tx0, x1, x2, x3, x4, x5, x6, x7 := j0, j1, j2, j3, j4, j5, j6, j7\n\tx8, x9, x10, x11, x12, x13, x14, x15 := j8, j9, j10, j11, j12, j13, j14, j15\n\n\tfor i := 0; i < rounds; i += 2 {\n\t\tx0 += x4\n\t\tx12 ^= x0\n\t\tx12 = (x12 << 16) | (x12 >> (16))\n\t\tx8 += x12\n\t\tx4 ^= x8\n\t\tx4 = (x4 << 12) | (x4 >> (20))\n\t\tx0 += x4\n\t\tx12 ^= x0\n\t\tx12 = (x12 << 8) | (x12 >> (24))\n\t\tx8 += x12\n\t\tx4 ^= x8\n\t\tx4 = (x4 << 7) | (x4 >> (25))\n\t\tx1 += x5\n\t\tx13 ^= x1\n\t\tx13 = (x13 << 16) | (x13 >> 16)\n\t\tx9 += x13\n\t\tx5 ^= x9\n\t\tx5 = (x5 << 12) | (x5 >> 20)\n\t\tx1 += x5\n\t\tx13 ^= x1\n\t\tx13 = (x13 << 8) | (x13 >> 24)\n\t\tx9 += x13\n\t\tx5 ^= x9\n\t\tx5 = (x5 << 7) | (x5 >> 25)\n\t\tx2 += x6\n\t\tx14 ^= x2\n\t\tx14 = (x14 << 16) | (x14 >> 16)\n\t\tx10 += x14\n\t\tx6 ^= x10\n\t\tx6 = (x6 << 12) | (x6 >> 20)\n\t\tx2 += x6\n\t\tx14 ^= x2\n\t\tx14 = (x14 << 8) | (x14 >> 24)\n\t\tx10 += x14\n\t\tx6 ^= x10\n\t\tx6 = (x6 << 7) | (x6 >> 25)\n\t\tx3 += x7\n\t\tx15 ^= x3\n\t\tx15 = (x15 << 16) | (x15 >> 16)\n\t\tx11 += x15\n\t\tx7 ^= x11\n\t\tx7 = (x7 << 12) | (x7 >> 20)\n\t\tx3 += x7\n\t\tx15 ^= x3\n\t\tx15 = (x15 << 8) | (x15 >> 24)\n\t\tx11 += x15\n\t\tx7 ^= x11\n\t\tx7 = (x7 << 7) | (x7 >> 25)\n\t\tx0 += x5\n\t\tx15 ^= x0\n\t\tx15 = (x15 << 16) | (x15 >> 16)\n\t\tx10 += x15\n\t\tx5 ^= x10\n\t\tx5 = (x5 << 12) | (x5 >> 20)\n\t\tx0 += x5\n\t\tx15 ^= x0\n\t\tx15 = (x15 << 8) | (x15 >> 24)\n\t\tx10 += x15\n\t\tx5 ^= x10\n\t\tx5 = (x5 << 7) | (x5 >> 25)\n\t\tx1 += x6\n\t\tx12 ^= x1\n\t\tx12 = (x12 << 16) | (x12 >> 16)\n\t\tx11 += x12\n\t\tx6 ^= x11\n\t\tx6 = (x6 << 12) | (x6 >> 20)\n\t\tx1 += x6\n\t\tx12 ^= x1\n\t\tx12 = (x12 << 8) | (x12 >> 24)\n\t\tx11 += x12\n\t\tx6 ^= x11\n\t\tx6 = (x6 << 7) | (x6 >> 25)\n\t\tx2 += x7\n\t\tx13 ^= x2\n\t\tx13 = (x13 << 16) | (x13 >> 16)\n\t\tx8 += x13\n\t\tx7 ^= x8\n\t\tx7 = (x7 << 12) | (x7 >> 20)\n\t\tx2 += x7\n\t\tx13 ^= x2\n\t\tx13 = (x13 << 8) | (x13 >> 24)\n\t\tx8 += x13\n\t\tx7 ^= x8\n\t\tx7 = (x7 << 7) | (x7 >> 25)\n\t\tx3 += x4\n\t\tx14 ^= x3\n\t\tx14 = (x14 << 16) | (x14 >> 16)\n\t\tx9 += x14\n\t\tx4 ^= x9\n\t\tx4 = (x4 << 12) | (x4 >> 20)\n\t\tx3 += x4\n\t\tx14 ^= x3\n\t\tx14 = (x14 << 8) | (x14 >> 24)\n\t\tx9 += x14\n\t\tx4 ^= x9\n\t\tx4 = (x4 << 7) | (x4 >> 25)\n\t}\n\n\tx0 += j0\n\tx1 += j1\n\tx2 += j2\n\tx3 += j3\n\tx4 += j4\n\tx5 += j5\n\tx6 += j6\n\tx7 += j7\n\tx8 += j8\n\tx9 += j9\n\tx10 += j10\n\tx11 += j11\n\tx12 += j12\n\tx13 += j13\n\tx14 += j14\n\tx15 += j15\n\n\tbinary.LittleEndian.PutUint32(out[0:4], x0)\n\tbinary.LittleEndian.PutUint32(out[4:8], x1)\n\tbinary.LittleEndian.PutUint32(out[8:12], x2)\n\tbinary.LittleEndian.PutUint32(out[12:16], x3)\n\tbinary.LittleEndian.PutUint32(out[16:20], x4)\n\tbinary.LittleEndian.PutUint32(out[20:24], x5)\n\tbinary.LittleEndian.PutUint32(out[24:28], x6)\n\tbinary.LittleEndian.PutUint32(out[28:32], x7)\n\tbinary.LittleEndian.PutUint32(out[32:36], x8)\n\tbinary.LittleEndian.PutUint32(out[36:40], x9)\n\tbinary.LittleEndian.PutUint32(out[40:44], x10)\n\tbinary.LittleEndian.PutUint32(out[44:48], x11)\n\tbinary.LittleEndian.PutUint32(out[48:52], x12)\n\tbinary.LittleEndian.PutUint32(out[52:56], x13)\n\tbinary.LittleEndian.PutUint32(out[56:60], x14)\n\tbinary.LittleEndian.PutUint32(out[60:64], x15)\n}", "func MinimumSwap(arr []int, k int) {\n\tvar smallerElement int\n\tvar ans int = 1e4\n\tfor i := 0; i < len(arr); i++ {\n\t\tif arr[i] <= k {\n\t\t\tsmallerElement++\n\t\t}\n\t}\n\tvar presentElements int\n\tfor i := 0; i < smallerElement; i++ {\n\t\tif arr[i] <= k {\n\t\t\tpresentElements++\n\t\t}\n\t}\n\tans = min(ans, smallerElement-presentElements)\n\ti := 0\n\tfor j := smallerElement; j < len(arr); j++ {\n\t\tif arr[i] <= k {\n\t\t\tpresentElements--\n\t\t}\n\t\tif arr[j] <= k {\n\t\t\tpresentElements++\n\t\t}\n\t\tans = min(ans, smallerElement-presentElements)\n\t\ti++\n\t}\n\tfmt.Println(ans)\n}", "func FourSum(seq []int, target int) [][]int {\n res := [][]int{}\n seqPairMap := map[int][]int{} // { sum1: [i1, j1, i2, j2, ...], sum2: [i3, j3, i4, j4, ...], ... }\n for i := 0; i < len(seq) - 1; i++ {\n for j := i + 1; j < len(seq); j++ {\n sum := seq[i] + seq[j]\n if _, ok := seqPairMap[sum]; !ok { seqPairMap[sum] = []int{}; }\n seqPairMap[sum] = append(seqPairMap[sum], i)\n seqPairMap[sum] = append(seqPairMap[sum], j)\n }\n }\n // example: target = 14, sums are 5 + 9, 3 + 11 (map on smaller of the two i.e. 5, 3; other is implicit)\n sumMap := map[int][][]int{} // { 5: [[i1, j1, ...],[i5, j5, ...]], ...} 5 <-- [i1, j1, ...], 9 <-- [i5, j5, ...]\n for k, _ := range seqPairMap {\n if _, ok := seqPairMap[target-k]; ok {\n if k < target - k {\n sumMap[k] = [][]int{[]int{}, []int{}}\n sumMap[k][0] = seqPairMap[k]; sumMap[k][1] = seqPairMap[target-k];\n } else {\n sumMap[target-k] = [][]int{[]int{}, []int{}}\n sumMap[target-k][0] = seqPairMap[target-k]; sumMap[target-k][1] = seqPairMap[k];\n }\n }\n }\n \n for _, indexArr := range sumMap {\n arr0 := indexArr[0]; arr1 := indexArr[1]\n for m := 0; m < len(arr0); m += 2 {\n for n := 0; n < len(arr1); n += 2 {\n // check for distinctness of arr0[m], arr0[m+1], arr1[n], arr1[n+1]\n if arr0[m] != arr1[n] && arr0[m] != arr1[n+1] &&\n arr0[m+1] != arr1[n] && arr0[m+1] != arr1[n+1] {\n // still allows some dups to go through e.g. indexes [2 5 7 10], [2 7 5 10]\n res = append(res, []int{arr0[m], arr0[m+1], arr1[n], arr1[n+1]})\n }\n }\n }\n }\n // returns arrays of indices, convert to actual values as seq[i] for each i \n return res\n}", "func solution(knows func(a int, b int) bool) func(n int) int {\n\treturn func(n int) int {\n\t\ti := 0\n\t\tj := 0\n\n\t\tindeg := make([]int, n)\n\n\t\tfor i = 0; i < n; i++ {\n\t\t\tfor j = 0; j< n; j++ {\n\t\t\t\tif knows(i, j) && i != j{\n\t\t\t\t\tindeg[i]--\n\t\t\t\t\tindeg[j]++\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfor index, val := range indeg {\n\t\t\tif val == n-1 {\n\t\t\t\treturn index\n\t\t\t}\n\t\t}\n\n\t\treturn -1\n\t}\n}", "func uniquePaths(m int, n int) int {\n\t// dp:一维\n\t//dp := make([]int, n)\n\t//for i := 0; i < m; i++ {\n\t//\tdp[0] = 1\n\t//\tfor j := 1; j < n; j++ {\n\t//\t\tdp[j] += dp[j-1]\n\t//\t}\n\t//}\n\t//return dp[n-1]\n\n\t// dp:二维\n\t//dp := make([][]int, m+1)\n\t//for i := 0; i <= m; i++ {\n\t//\tdp[i] = make([]int, n+1)\n\t//}\n\t//dp[0][1] = 1\n\t//for i := 1; i <= m; i++ {\n\t//\tfor j := 1; j <= n; j++ {\n\t//\t\tdp[i][j] = dp[i-1][j] + dp[i][j-1]\n\t//\t}\n\t//}\n\t//return dp[m][n]\n\n\t// 递归:记忆化\n\tmemo := make(map[int]int)\n\tcount := memoRecursion(m, n, memo)\n\tfmt.Println(len(memo))\n\treturn count\n\n\t// 递归:超时\n\t//if m == 1 || n == 1 {\n\t//\treturn 1\n\t//}\n\t//return uniquePaths(m-1, n) + uniquePaths(m, n-1)\n}", "func Solution(N int, A []int) []int {\n\t// write your code in Go 1.4\n\tcounters := make([]int, N)\n\tvar max, lastMax int\n\tfor _, v := range A {\n\t\tif v <= N {\n\t\t\tif counters[v-1] < lastMax {\n\t\t\t\tcounters[v-1] = lastMax\n\t\t\t}\n\t\t\tcounters[v-1]++\n\t\t\tif counters[v-1] > max {\n\t\t\t\tmax = counters[v-1]\n\t\t\t}\n\t\t} else {\n\t\t\tlastMax = max\n\t\t}\n\t}\n\n\tfor i, v := range counters {\n\t\tif v < lastMax {\n\t\t\tcounters[i] = lastMax\n\t\t}\n\t}\n\n\treturn counters\n}", "func FindPairWithGivenSum(input []int, sum int) []int {\n\tresult := make([]int, 0)\n\t// O(nlogn) solution\n\t//idxMap := map[int]int{}\n\t//for key, val := range input {\n\t//idxMap[val] = key\n\t//}\n\t//sortedInput := sort.Quick(input)\n\t//low, high := 0, len(input)-1\n\t//for low <= high {\n\t//newSum := sortedInput[low] + sortedInput[high]\n\t//if newSum == sum {\n\t//result = append(result, idxMap[sortedInput[low]], idxMap[sortedInput[high]])\n\t//}\n\t//if newSum > sum {\n\t//high--\n\t//} else {\n\t//low++\n\t//}\n\t//}\n\n\t// O(n) hashing\n\thash := make(map[int]int)\n\tfor key, val := range input {\n\t\tdiff := sum - val\n\t\tif idx, ok := hash[diff]; ok {\n\t\t\tresult = append(result, key, idx)\n\t\t}\n\t\thash[val] = key\n\t}\n\treturn result\n}", "func findUnique(r io.Reader, memLimit int) {\n\t// step.1 sort into file chunks, mapping stage\n\tparts := sort2Disk(r, memLimit, new(countMapper))\n\tlog.Println(\"Generated\", parts, \"parts\")\n\t// step2. merge all sstable and provides a continous input\n\tlog.Println(\"Reducing from#\", parts, \"sstable(s)\")\n\treducer := new(uniqueReducer)\n\tReduce(parts, reducer)\n\n\tif reducer.hasUnique {\n\t\tlog.Println(\"Found the first unique element:\", string(reducer.target.bytes()), reducer.target.ord())\n\t} else {\n\t\tlog.Println(\"Unique element not found!\")\n\t}\n}", "func minimumBribes(q []int32) {\n\tvar ret, i int32\n\tvar length = int32(len(q))\n\tvar t1 = make([]int32, length+1)\n\tfor i = 0; i < length+1; i++ {\n\t\tt1[i] = i\n\t}\n\tvar t2 = make([]int32, length+1)\n\tcopy(t2[:], t1)\n\tfor i = 1; i <= length; i++ {\n\t\tv := q[i-1]\n\t\tif v > i+2 {\n\t\t\tret = -1\n\t\t\tbreak\n\t\t} else if t2[v] > i {\n\t\t\tfor j := t2[v] - 1; j >= i; j-- {\n\t\t\t\tt1[j+1] = t1[j]\n\t\t\t\tt2[t1[j]]++\n\t\t\t\tret++\n\t\t\t}\n\t\t\tt2[v] = i\n\t\t}\n\t}\n\tif ret == -1 {\n\t\tfmt.Println(\"Too chaotic\")\n\t} else {\n\t\tfmt.Println(ret)\n\t}\n\n}", "func inversionsBruteForce(v *array) int {\r\n\tvar cnt int\r\n\tfor i:=0; i<len(v.a)-1; i++{\r\n\t\tfor j:=i; j<len(v.a); j++{\r\n\t\t\tif v.a[i] > v.a[j]{\r\n\t\t\t\tcnt += 1\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn cnt\r\n}", "func replace(v []uint64, n int, x uint64) []uint64 {\n\tif n == 0 {\n\t\tif len(v) > 0 && v[0] == x {\n\t\t\treturn v\n\t\t}\n\t\tv = append(v, 0)\n\t\tcopy(v[1:], v)\n\t} else if n < len(v) {\n\t\tcopy(v[1:], v[n:])\n\t\tv = v[:len(v)-(n-1)]\n\t} else if len(v) == 0 {\n\t\treturn []uint64{x}\n\t} else {\n\t\tv = v[:1]\n\t}\n\tv[0] = x\n\treturn v\n}", "func findKey(s []int) int{\n\tn := len(s)\n\tm := make(map[int]int)\n\tvar ans,temp int\n\tans = 0\n\tfor i := 0; i < n; i++ {\n\t\tfor j := i+1; j < n; j++ {\n\t\t\tif true==checkValid(s[i]^s[j]){\n\t\t\t\tm[s[i]]++\n\t\t\t\tm[s[j]]++\n\t\t\t}\n\t\t}\n\t}\n\tfor a,b := range m{\n\t\tif b>temp {\n\t\t\ttemp = b\n\t\t\tans = a\n\t\t}\n\t}\n\tif ans != 0{\n\t\treturn ans^32 \t\n\t}\n\treturn 0\n}", "func twoSum(nums []int, target int) []int {\n\t// 0.\n\thash := make(map[int]int)\n\n\t// 1.\n\tfor i, num := range nums {\n\t\thash[num] = i\n\t}\n\n\t// 2.\n\tfor i, num := range nums {\n\t\tn := target - num\n\t\t// 3.\n\t\tj, ok := hash[n]\n\t\tif ok && j != i {\n\t\t\treturn []int{j, i}\n\t\t}\n\t}\n\treturn []int{}\n}", "func FindDuplicates(input []int) int {\n\t// using XOR\n\tresult := 0\n\t//for _, val := range input {\n\t//result ^= val\n\t//}\n\t//for key, _ := range input {\n\t//result ^= key\n\t//}\n\n\t// using constant space\n\tfor _, val := range input {\n\t\tif input[val] < 0 {\n\t\t\treturn input[val]\n\t\t}\n\t\tinput[val] = input[val] * -1\n\t}\n\treturn result\n}", "func isSum(n int, ab []int) bool {\n i := 0\n j := len(ab) - 1\n for i <= j {\n diff := ab[i] + ab[j]\n if diff == n {\n return true\n } else if diff > n {\n j--\n } else { // diff < n\n i++\n }\n }\n return false\n}", "func findShortestSubArray(nums []int) int {\n \n}", "func MergeSortedUInts(n ...[]uint64) []uint64 {\n\tvar result []uint64\n\tif len(n) == 0 {\n\t\treturn nil\n\t} else if len(n) == 1 {\n\t\t// Special case. Merge single slice with a nil slice, to remove any\n\t\t// duplicates from the single slice.\n\t\treturn MergeSortedUInts(n[0], nil)\n\t}\n\n\tvar maxSize int\n\tfor _, a := range n {\n\t\tif len(a) > maxSize {\n\t\t\tmaxSize = len(a)\n\t\t}\n\t}\n\tresult = make([]uint64, 0, maxSize) // This will likely be too small but it's a start.\n\n\tidxs := make([]int, len(n)) // Indexes we've processed.\n\tvar j int // Index we currently think is minimum.\n\n\tfor {\n\t\tj = -1\n\n\t\t// Find the smallest minimum in all slices.\n\t\tfor i := 0; i < len(n); i++ {\n\t\t\tif idxs[i] >= len(n[i]) {\n\t\t\t\tcontinue // We have completely drained all values in this slice.\n\t\t\t} else if j == -1 {\n\t\t\t\t// We haven't picked the minimum value yet. Pick this one.\n\t\t\t\tj = i\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// It this value key is lower than the candidate.\n\n\t\t\tif n[i][idxs[i]] < n[j][idxs[j]] {\n\t\t\t\tj = i\n\t\t\t} else if n[i][idxs[i]] == n[j][idxs[j]] {\n\t\t\t\t// Duplicate value. Throw it away.\n\t\t\t\tidxs[i]++\n\t\t\t}\n\n\t\t}\n\n\t\t// We could have drained all of the values and be done...\n\t\tif j == -1 {\n\t\t\tbreak\n\t\t}\n\n\t\t// First value to just append it and move on.\n\t\tif len(result) == 0 {\n\t\t\tresult = append(result, n[j][idxs[j]])\n\t\t\tidxs[j]++\n\t\t\tcontinue\n\t\t}\n\n\t\t// Append the minimum value to results if it's not a duplicate of\n\t\t// the existing one.\n\n\t\tif result[len(result)-1] < n[j][idxs[j]] {\n\t\t\tresult = append(result, n[j][idxs[j]])\n\t\t} else if result[len(result)-1] == n[j][idxs[j]] {\n\t\t\t// Duplicate so drop it.\n\t\t} else {\n\t\t\tpanic(\"value being merged out of order.\")\n\t\t}\n\n\t\tidxs[j]++\n\t}\n\treturn result\n}", "func Benchmark_SliceIntIncr2(b *testing.B) {\n\tb.ResetTimer()\n\tfor i := 0; i <= b.N; i++ {\n\t\tn := [10]int{}\n\t\tfor i := range n {\n\t\t\tn[i]++\n\t\t}\n\t}\n}", "func createOrdering(mappings map[int]map[int][]mapping, data *util.QueryDocumentSet, iterations int) []float64 {\n\tN := data.Size()\n\titerations = gomath.MinInt(iterations, N-1)\n\n\tres := make([]float64, N)\n\n\tactive := make([]int, N)\n\tinDegree := make([]int, N)\n\toutDegree := make([][]int, N)\n\n\tfor i := range active {\n\t\tactive[i] = i\n\t}\n\n\t// O(N^3)\n\tfor _, v1 := range mappings {\n\t\tfor _, v2 := range v1 {\n\t\t\tfor _, d := range v2 {\n\t\t\t\tif d.weight > 0 {\n\t\t\t\t\toutDegree[d.from] = append(outDegree[d.from], d.to)\n\t\t\t\t\tinDegree[d.to]++\n\t\t\t\t} else {\n\t\t\t\t\toutDegree[d.to] = append(outDegree[d.to], d.from)\n\t\t\t\t\tinDegree[d.from]++\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// O(N^2)\n\tfor len(active) > 0 {\n\n\t\taIndex := -1\n\t\tbest := -1.0\n\t\tbestIdx := -1\n\t\tfor aI, i := range active {\n\t\t\ttest := float64(len(outDegree[i])) / (float64(inDegree[i]) + 1.0)\n\t\t\tif test > best {\n\t\t\t\tbest = test\n\t\t\t\tbestIdx = i\n\t\t\t\taIndex = aI\n\t\t\t}\n\t\t}\n\n\t\tres[bestIdx] = best\n\n\t\tfor _, v := range outDegree[bestIdx] {\n\t\t\tinDegree[v]--\n\t\t}\n\n\t\tactive[aIndex] = active[len(active)-1]\n\t\tactive = active[:len(active)-1]\n\t}\n\n\treturn res\n}", "func livenesscompact(lv *Liveness) {\n\t// Linear probing hash table of bitmaps seen so far.\n\t// The hash table has 4n entries to keep the linear\n\t// scan short. An entry of -1 indicates an empty slot.\n\tn := len(lv.livepointers)\n\n\ttablesize := 4 * n\n\ttable := make([]int, tablesize)\n\tfor i := range table {\n\t\ttable[i] = -1\n\t}\n\n\t// remap[i] = the new index of the old bit vector #i.\n\tremap := make([]int, n)\n\n\tfor i := range remap {\n\t\tremap[i] = -1\n\t}\n\tuniq := 0 // unique tables found so far\n\n\t// Consider bit vectors in turn.\n\t// If new, assign next number using uniq,\n\t// record in remap, record in lv->livepointers and lv->argslivepointers\n\t// under the new index, and add entry to hash table.\n\t// If already seen, record earlier index in remap and free bitmaps.\n\tvar jarg Bvec\n\tvar j int\n\tvar h uint32\n\tvar arg Bvec\n\tvar jlocal Bvec\n\tvar local Bvec\n\tfor i := 0; i < n; i++ {\n\t\tlocal = lv.livepointers[i]\n\t\targ = lv.argslivepointers[i]\n\t\th = hashbitmap(hashbitmap(H0, local), arg) % uint32(tablesize)\n\n\t\tfor {\n\t\t\tj = table[h]\n\t\t\tif j < 0 {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tjlocal = lv.livepointers[j]\n\t\t\tjarg = lv.argslivepointers[j]\n\t\t\tif bvcmp(local, jlocal) == 0 && bvcmp(arg, jarg) == 0 {\n\t\t\t\tremap[i] = j\n\t\t\t\tgoto Next\n\t\t\t}\n\n\t\t\th++\n\t\t\tif h == uint32(tablesize) {\n\t\t\t\th = 0\n\t\t\t}\n\t\t}\n\n\t\ttable[h] = uniq\n\t\tremap[i] = uniq\n\t\tlv.livepointers[uniq] = local\n\t\tlv.argslivepointers[uniq] = arg\n\t\tuniq++\n\tNext:\n\t}\n\n\t// We've already reordered lv->livepointers[0:uniq]\n\t// and lv->argslivepointers[0:uniq] and freed the bitmaps\n\t// we don't need anymore. Clear the pointers later in the\n\t// array so that we can tell where the coalesced bitmaps stop\n\t// and so that we don't double-free when cleaning up.\n\tfor j := uniq; j < n; j++ {\n\t\tlv.livepointers[j] = Bvec{}\n\t\tlv.argslivepointers[j] = Bvec{}\n\t}\n\n\t// Rewrite PCDATA instructions to use new numbering.\n\tvar i int\n\tfor p := lv.ptxt; p != nil; p = p.Link {\n\t\tif p.As == obj.APCDATA && p.From.Offset == obj.PCDATA_StackMapIndex {\n\t\t\ti = int(p.To.Offset)\n\t\t\tif i >= 0 {\n\t\t\t\tp.To.Offset = int64(remap[i])\n\t\t\t}\n\t\t}\n\t}\n}", "func Solution(A []int) int {\n\t// write your code in Go 1.4\n\tsort.Ints(A)\n\tfor i, a := range A {\n\t\tif i+1 != a {\n\t\t\treturn 0\n\t\t}\n\t}\n\treturn 1\n}", "func twoSum(nums []int, target int) []int {\n\tvar record = make(map[int]int)\n\tfor i, v := range nums {\n\t\tif index, ok := record[target-nums[i]]; ok {\n\t\t\treturn []int{index, i}\n\t\t}\n\t\trecord[v] = i\n\t}\n\n\treturn nil\n}", "func twoSum01(nums []int, target int) []int {\n\tnumMap := map[int]int{}\n\tfor i, v := range nums {\n\t\tnumMap[v] = i\n\t}\n\n\tfor i, v := range nums {\n\t\tif index, ok := numMap[target-v]; ok && index != i {\n\t\t\treturn []int{i, index}\n\t\t}\n\t}\n\n\treturn nil\n}", "func jaccard(a []Recommendation, b []Recommendation) float64 {\n occ := make(map[string]int)\n for _,r := range a {\n occ[r.Item]++\n }\n for _,r := range b {\n occ[r.Item]++\n }\n inter := float64(0)\n for _,v := range occ {\n if v == 2 {\n inter++\n }\n }\n return inter / float64(len(occ))\n}", "func accumulate(nums []int) int {\n\tanswer := 0\n\ttotalLength := len(nums)\n\tfor i := 0; i < totalLength; i++ {\n\t\tif nums[i] == nums[(i+1)%totalLength] {\n\t\t\tanswer += nums[i]\n\t\t}\n\t}\n\treturn answer\n}", "func add(val, n []byte) []byte {\n\n\tnLen, valLen := len(n), len(val)\n\tdiff := valLen - nLen\n\tif diff < 0 {\n\t\tpanic(\"overflow\")\n\t}\n\n\tres := make([]byte, valLen)\n\tcopy(res, val)\n\n\tflag := byte(0x00)\n\tfor i := valLen - 1; i >= 0; i-- {\n\n\t\tif math.MaxUint8-val[i] < flag { // val[i]+flag overflow\n\t\t\tres[i] += flag\n\t\t\tflag = 0x00\n\t\t\tflag++\n\t\t} else {\n\t\t\tres[i] += flag\n\t\t\tflag = 0x00\n\t\t}\n\n\t\tif i >= diff {\n\n\t\t\tif math.MaxUint8-res[i] < n[i-diff] {\n\t\t\t\tflag++\n\t\t\t}\n\t\t\tres[i] += n[i-diff]\n\n\t\t}\n\n\t\tif i-diff <= 0 && flag == 0 {\n\t\t\tbreak\n\t\t}\n\n\t}\n\n\tif flag != 0x00 {\n\t\tpanic(\"overflow\")\n\t}\n\n\treturn res\n}", "func twosum(arr []int, target int) [][]int {\n\tl := len(arr)\n\tif l < 2 {\n\t\treturn [][]int{}\n\t}\n\tdp := map[int]bool{}\n\tfor _, v := range arr {\n\t\tdp[v] = true\n\t}\n\tres := [][]int{}\n\tfor i := 1; i < target; i++ {\n\t\tspec := target - i\n\n\t\tfor j := 0; j < l; j++ {\n\t\t\tif _, ok := dp[spec-arr[j]]; ok {\n\t\t\t\tdelete(dp, arr[j])\n\t\t\t\ttemp := []int{arr[j], spec - arr[j]}\n\t\t\t\tres = append(res, temp)\n\t\t\t}\n\t\t}\n\t\tif len(res) > 0 {\n\t\t\treturn res\n\t\t}\n\t}\n\treturn [][]int{}\n\n}", "func Benchmark_SliceIntIncr4(b *testing.B) {\n\tb.ResetTimer()\n\tfor i := 0; i <= b.N; i++ {\n\t\tn := [10]int{}\n\t\tfor i := range n {\n\t\t\tv := &n[i]\n\t\t\t*v++\n\t\t}\n\t\t// 寫入\n\t}\n}", "func quickUnionWeighted() {\n\tvar (\n\t\tp, q int\n\t\tid = make([]int, N)\n\t\tsz = make([]int, N)\n\t)\n\tfor i := 0; i < N; i++ {\n\t\tid[i] = i\n\t\tsz[i] = 1\n\t}\n\tfor {\n\t\t_, err := fmt.Fscanf(in, \"%d %d\\n\", &p, &q)\n\t\tif err != nil {\n\t\t\tif err != io.EOF {\n\t\t\t\tlog.Fatal(err)\n\t\t\t} else {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tvar i, j int\n\t\tfor i = p; i != id[i]; i = id[i] {\n\t\t\t// do nothing\n\t\t}\n\t\tfor j = q; j != id[j]; j = id[j] {\n\t\t\t// do nothing\n\t\t}\n\t\tif i == j {\n\t\t\tcontinue\n\t\t}\n\t\tif sz[i] < sz[j] {\n\t\t\tid[i] = j\n\t\t\tsz[j] += sz[i]\n\t\t} else {\n\t\t\tid[j] = i\n\t\t\tsz[i] += sz[j]\n\t\t}\n\t\tfmt.Fprintf(out, \"%d %d\\n\", p, q)\n\t}\n}", "func twoSum(nums []int, target int) []int {\n\t// 0.\n\thash := make(map[int]int)\n\t// 1.\n\tfor i, num := range nums {\n\t\tn := target - num\n\t\t// 2.\n\t\tj, ok := hash[n]\n\t\tif ok {\n\t\t\treturn []int{j, i}\n\t\t} else {\n\t\t\t// 3.\n\t\t\thash[num] = i\n\t\t}\n\t}\n\treturn []int{}\n}", "func searchLinear(nums []uint, n uint) int {\n\tfor i := 0; i < len(nums); i++ {\n\t\tif nums[i] == n {\n\t\t\treturn int(n)\n\t\t}\n\t}\n\treturn -1\n}", "func findShortestSubArray(nums []int) int {\n\tn := len(nums)\n\tif n < 2 {\n\t\treturn n\n\t}\n\tfirst := make(map[int]int, n) //第一次出现当前元素的位置\n\tcount := make(map[int]int, n) //记录当前元素出现的个数\n\tmaxCount := 1\n\tminLen := n\n\tfor i, v := range nums {\n\t\tcount[v]++\n\t\tif count[v] == 1 {\n\t\t\tfirst[v] = i\n\t\t} else {\n\t\t\tl := i - first[v] + 1 //度\n\t\t\tif maxCount < count[v] || (maxCount == count[v] && minLen > l) {\n\t\t\t\tmaxCount = count[v]\n\t\t\t\tminLen = l\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(count) == n {\n\t\treturn 1\n\t}\n\treturn minLen\n}", "func main() {\n\t// input := []int{1, 2, 2, 1, 1, 3}\n\t// input := []int{1, 2}\n\tinput := []int{-3, 0, 1, -3, 1, 1, 1, -3, 10, 0}\n\toutput := uniqueOccurrences(input)\n\tfmt.Println(output)\n}", "func order(a, n uint64) int {\n\tk := 1\n\tz, base, mod := big.NewInt(1), big.NewInt(int64(a)), big.NewInt(int64(n))\n\n\tfor {\n\t\t// z = base ** k (mod n)\n\t\tz.Exp(base, big.NewInt(int64(k)), mod)\n\n\t\tif z.Int64() == 1 {\n\t\t\tbreak\n\t\t}\n\n\t\tk++\n\t}\n\n\treturn k\n}", "func icecreamParlor(m int32, arr []int32) []int32 {\n prev := map[int32]int{};\n for i, a := range arr {\n if prev[m-a] != 0 {\n return []int32{int32(prev[m-a]), int32(i+1)}\n }\n\n prev[a] = i+1\n }\n\n return []int32{}\n}", "func fibOptimized(n int64, memMap map[int64]int64) int64{\n\n\tif memMap == nil {\n\t\tmemMap = map[int64]int64{}\n\t}\n\n\tif n <= 0 {\n\t\treturn 0\n\t}\n\n\tif n <= 2 {\n\t\treturn 1\n\t}\n\n\tif val,ok := memMap[n]; ok {\n\t\treturn val\n\t}\n\n\tmemMap[n] = fibOptimized(n-1,memMap) + fibOptimized(n-2,memMap)\n\treturn memMap[n]\n}", "func lengthOfLIS2(nums []int) int {\n\tn:=len(nums)\n\tif n==0{\n\t\treturn 0\n\t}\n\ts:=[]int{nums[0]}\n\n\tfor _, v:=range nums{\n\t\tif v<s[0]{\n\t\t\ts[0]=v\n\t\t}else if v>s[len(s)-1] {\n\t\t\ts=append(s, v)\n\t\t}else{\n\t\t\tl, r:=0, len(s)-1\n\t\t\tfor ;l<=r;{\n\t\t\t\tmid:=l+(r-l)/2\n\t\t\t\tif s[mid] < v{\n\t\t\t\t\tl=mid+1\n\t\t\t\t}else{\n\t\t\t\t\tr=mid-1\n\t\t\t\t}\n\t\t\t}\n\t\t\ts[l]=v\n\t\t}\n\t}\n\n\treturn len(s)\n}", "func FindTriplet(arr []int) {\n\t/*\n\t\t\tAnd they should full fil this condition also\n\t\t\t X = arr[i] ^ arr[i+1] ^ ... ^ arr[j - 1]\n\t\t Y = arr[j] ^ arr[j+1] ^ ... ^ arr[k]\n\t*/\n\n\tvar count int\n\n\tfor i := 0; i < len(arr)-1; i++ {\n\t\tfmt.Println(\"The value of i is \", i)\n\t\tcurrent := arr[i]\n\t\tfor j := i + 1; j < len(arr); j++ {\n\t\t\tcurrent = current ^ arr[j]\n\t\t\tif current == 0 {\n\t\t\t\tcount += j - i\n\t\t\t}\n\t\t}\n\n\t}\n\tfmt.Println(count)\n\n}", "func minimumBribes(q []int32) {\n\tbribes := 0\n\tqbribes := make([]int, len(q))\n\treverse := false\n\tfor i, j := 0, len(q)-1; i < len(q); {\n\t\tif !reverse {\n\t\t\tfor x := 0; x < len(q)-i-1; x++ {\n\t\t\t\tif q[x]-1 == int32(x) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif q[x] > q[x+1] {\n\t\t\t\t\tqbribes[q[x]-1]++\n\t\t\t\t\tif qbribes[q[x]-1] > 2 {\n\t\t\t\t\t\tfmt.Printf(\"Too chaotic\\n\")\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\tq[x], q[x+1] = q[x+1], q[x]\n\t\t\t\t\tbribes++\n\t\t\t\t}\n\t\t\t}\n\t\t\ti++\n\t\t} else {\n\t\t\tfor x := j; x > i; x-- {\n\t\t\t\tif q[x]-1 == int32(x) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif q[x-1] > q[x] {\n\t\t\t\t\tqbribes[q[x-1]-1]++\n\t\t\t\t\tif qbribes[q[x-1]-1] > 2 {\n\t\t\t\t\t\tfmt.Printf(\"Too chaotic\\n\")\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\tq[x-1], q[x] = q[x], q[x-1]\n\t\t\t\t\tbribes++\n\t\t\t\t}\n\t\t\t}\n\t\t\tj--\n\t\t}\n\t\treverse = !reverse\n\t}\n\tfmt.Printf(\"%d\\n\", bribes)\n}", "func twoSum(nums []int, target int) []int {\n\tvar numMap = make(map[int]int)\n\tfor i := range nums {\n\t\tif k, ok := numMap[target-nums[i]]; ok {\n\t\t\treturn []int{k, i}\n\t\t}\n\t\tnumMap[nums[i]] = i\n\t}\n\treturn []int{}\n}", "func majorityElement(nums []int) []int {\n \n}", "func twoSum_best(nums []int, target int) []int {\n\tm := make(map[int]int)\n\tfor i, curr := range nums{\n\t\tcomp := target - curr\n\t\t_, ok := m[comp]\n\t\tif ok {\n\t\t\treturn []int {m[comp], i}\n\t\t\t// When ok is true, the comparison value, comp is going to be the first number, since curr is the second number\n\t\t}\n\t\tm[nums[i]] = i // current difference value is the key , index is the dictionary value\n\t}\n\treturn nil\n}", "func getTotalX(a []int, b []int) int {\n // Write your code here\n var c int\n sort.Ints(a)\n sort.Ints(b)\n for i:=a[0];i<=b[len(b)-1];i++{\n factor:=true\n for _,v:=range a{\n if i % v != 0{\n factor = false\n }\n }\n for _,v:=range b{\n if v%i!=0{\n factor=false\n }\n }\n if factor == true{\n c++\n }\n }\n return c\n}" ]
[ "0.6026805", "0.59555244", "0.5955283", "0.5874953", "0.5791711", "0.5789105", "0.57426083", "0.5728753", "0.57182217", "0.5710362", "0.5696874", "0.5633868", "0.563071", "0.5619188", "0.5603376", "0.55972326", "0.5594419", "0.55728394", "0.55553955", "0.55510426", "0.5535702", "0.5520692", "0.5484304", "0.5481484", "0.5480496", "0.5457255", "0.54463804", "0.5445941", "0.54451317", "0.54337126", "0.54337126", "0.54325956", "0.5423706", "0.54177386", "0.541274", "0.5409981", "0.53973365", "0.537666", "0.5370825", "0.5364281", "0.53425944", "0.53251326", "0.53190804", "0.53052354", "0.5305026", "0.53002715", "0.52983713", "0.52940434", "0.52793777", "0.5274936", "0.5271333", "0.5260924", "0.5253492", "0.5249352", "0.524444", "0.5243615", "0.52348167", "0.5229869", "0.52263683", "0.52191865", "0.52181005", "0.5213058", "0.5208871", "0.52068496", "0.52006036", "0.5197116", "0.51967335", "0.5195536", "0.5194344", "0.51943386", "0.5194155", "0.5192335", "0.51905704", "0.51901954", "0.5188182", "0.5178158", "0.5174688", "0.51741135", "0.51729697", "0.5166623", "0.516513", "0.51600033", "0.5152821", "0.51418364", "0.51384395", "0.51383835", "0.5134588", "0.5125634", "0.51240087", "0.51174295", "0.5111338", "0.5110781", "0.5103148", "0.5100351", "0.5099997", "0.50996387", "0.50973547", "0.50886005", "0.5087272", "0.5083395", "0.5081961" ]
0.0
-1
XXX_OneofFuncs is for the internal use of the proto package.
func (*Oneof) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) { return _Oneof_OneofMarshaler, _Oneof_OneofUnmarshaler, _Oneof_OneofSizer, []interface{}{ (*Oneof_F_Bool)(nil), (*Oneof_F_Int32)(nil), (*Oneof_F_Int64)(nil), (*Oneof_F_Fixed32)(nil), (*Oneof_F_Fixed64)(nil), (*Oneof_F_Uint32)(nil), (*Oneof_F_Uint64)(nil), (*Oneof_F_Float)(nil), (*Oneof_F_Double)(nil), (*Oneof_F_String)(nil), (*Oneof_F_Bytes)(nil), (*Oneof_F_Sint32)(nil), (*Oneof_F_Sint64)(nil), (*Oneof_F_Enum)(nil), (*Oneof_F_Message)(nil), (*Oneof_FGroup)(nil), (*Oneof_F_Largest_Tag)(nil), (*Oneof_Value)(nil), } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (*EncapVal) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _EncapVal_OneofMarshaler, _EncapVal_OneofUnmarshaler, _EncapVal_OneofSizer, []interface{}{\n\t\t(*EncapVal_VlanId)(nil),\n\t\t(*EncapVal_MPLSTag)(nil),\n\t\t(*EncapVal_Vnid)(nil),\n\t\t(*EncapVal_QinQ)(nil),\n\t}\n}", "func (*FlowL4Info) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _FlowL4Info_OneofMarshaler, _FlowL4Info_OneofUnmarshaler, _FlowL4Info_OneofSizer, []interface{}{\n\t\t(*FlowL4Info_TcpUdpInfo)(nil),\n\t\t(*FlowL4Info_IcmpInfo)(nil),\n\t}\n}", "func (*Msg) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _Msg_OneofMarshaler, _Msg_OneofUnmarshaler, _Msg_OneofSizer, []interface{}{\n\t\t(*Msg_Request)(nil),\n\t\t(*Msg_Preprepare)(nil),\n\t\t(*Msg_Prepare)(nil),\n\t\t(*Msg_Commit)(nil),\n\t\t(*Msg_ViewChange)(nil),\n\t\t(*Msg_NewView)(nil),\n\t\t(*Msg_Checkpoint)(nil),\n\t\t(*Msg_Hello)(nil),\n\t}\n}", "func (*RuleL4Match) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _RuleL4Match_OneofMarshaler, _RuleL4Match_OneofUnmarshaler, _RuleL4Match_OneofSizer, []interface{}{\n\t\t(*RuleL4Match_Ports)(nil),\n\t\t(*RuleL4Match_TypeCode)(nil),\n\t}\n}", "func (*Example) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _Example_OneofMarshaler, _Example_OneofUnmarshaler, _Example_OneofSizer, []interface{}{\n\t\t(*Example_ImagePayload)(nil),\n\t\t(*Example_TextPayload)(nil),\n\t\t(*Example_VideoPayload)(nil),\n\t\t(*Example_AudioPayload)(nil),\n\t}\n}", "func (*Metric) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _Metric_OneofMarshaler, _Metric_OneofUnmarshaler, _Metric_OneofSizer, []interface{}{\n\t\t(*Metric_StringData)(nil),\n\t\t(*Metric_Float32Data)(nil),\n\t\t(*Metric_Float64Data)(nil),\n\t\t(*Metric_Int32Data)(nil),\n\t\t(*Metric_Int64Data)(nil),\n\t\t(*Metric_BytesData)(nil),\n\t\t(*Metric_BoolData)(nil),\n\t\t(*Metric_Uint32Data)(nil),\n\t\t(*Metric_Uint64Data)(nil),\n\t}\n}", "func (*Interface) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _Interface_OneofMarshaler, _Interface_OneofUnmarshaler, _Interface_OneofSizer, []interface{}{\n\t\t(*Interface_Sub)(nil),\n\t\t(*Interface_Memif)(nil),\n\t\t(*Interface_Afpacket)(nil),\n\t\t(*Interface_Tap)(nil),\n\t\t(*Interface_Vxlan)(nil),\n\t\t(*Interface_Ipsec)(nil),\n\t\t(*Interface_VmxNet3)(nil),\n\t}\n}", "func (*Metadata) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _Metadata_OneofMarshaler, _Metadata_OneofUnmarshaler, _Metadata_OneofSizer, []interface{}{\n\t\t(*Metadata_DevAddrPrefix)(nil),\n\t\t(*Metadata_AppId)(nil),\n\t\t(*Metadata_AppEui)(nil),\n\t}\n}", "func (*Message) XXX_OneofFuncs() (func(msg proto1.Message, b *proto1.Buffer) error, func(msg proto1.Message, tag, wire int, b *proto1.Buffer) (bool, error), func(msg proto1.Message) (n int), []interface{}) {\n\treturn _Message_OneofMarshaler, _Message_OneofUnmarshaler, _Message_OneofSizer, []interface{}{\n\t\t(*Message_ExecStarted)(nil),\n\t\t(*Message_ExecCompleted)(nil),\n\t\t(*Message_ExecOutput)(nil),\n\t\t(*Message_LogEntry)(nil),\n\t\t(*Message_Error)(nil),\n\t}\n}", "func (*Message) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _Message_OneofMarshaler, _Message_OneofUnmarshaler, _Message_OneofSizer, []interface{}{\n\t\t(*Message_Chunk)(nil),\n\t\t(*Message_Status)(nil),\n\t}\n}", "func (*Message) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _Message_OneofMarshaler, _Message_OneofUnmarshaler, _Message_OneofSizer, []interface{}{\n\t\t(*Message_OpenPayload)(nil),\n\t\t(*Message_ClosePayload)(nil),\n\t\t(*Message_DataPayload)(nil),\n\t}\n}", "func (*BMRPCRequest) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _BMRPCRequest_OneofMarshaler, _BMRPCRequest_OneofUnmarshaler, _BMRPCRequest_OneofSizer, []interface{}{\n\t\t(*BMRPCRequest_Newaddress)(nil),\n\t\t(*BMRPCRequest_Help)(nil),\n\t\t(*BMRPCRequest_Listaddresses)(nil),\n\t}\n}", "func (*Interface) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _Interface_OneofMarshaler, _Interface_OneofUnmarshaler, _Interface_OneofSizer, []interface{}{\n\t\t(*Interface_Sub)(nil),\n\t\t(*Interface_Memif)(nil),\n\t\t(*Interface_Afpacket)(nil),\n\t\t(*Interface_Tap)(nil),\n\t\t(*Interface_Vxlan)(nil),\n\t\t(*Interface_Ipsec)(nil),\n\t\t(*Interface_VmxNet3)(nil),\n\t\t(*Interface_Bond)(nil),\n\t}\n}", "func (*OpenStatusUpdate) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _OpenStatusUpdate_OneofMarshaler, _OpenStatusUpdate_OneofUnmarshaler, _OpenStatusUpdate_OneofSizer, []interface{}{\n\t\t(*OpenStatusUpdate_ChanPending)(nil),\n\t\t(*OpenStatusUpdate_ChanOpen)(nil),\n\t}\n}", "func (*OpenStatusUpdate) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _OpenStatusUpdate_OneofMarshaler, _OpenStatusUpdate_OneofUnmarshaler, _OpenStatusUpdate_OneofSizer, []interface{}{\n\t\t(*OpenStatusUpdate_ChanPending)(nil),\n\t\t(*OpenStatusUpdate_ChanOpen)(nil),\n\t}\n}", "func (*OpenStatusUpdate) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _OpenStatusUpdate_OneofMarshaler, _OpenStatusUpdate_OneofUnmarshaler, _OpenStatusUpdate_OneofSizer, []interface{}{\n\t\t(*OpenStatusUpdate_ChanPending)(nil),\n\t\t(*OpenStatusUpdate_ChanOpen)(nil),\n\t}\n}", "func (*StatTable) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _StatTable_OneofMarshaler, _StatTable_OneofUnmarshaler, _StatTable_OneofSizer, []interface{}{\n\t\t(*StatTable_PodGroup_)(nil),\n\t}\n}", "func (*Bitmessage) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _Bitmessage_OneofMarshaler, _Bitmessage_OneofUnmarshaler, _Bitmessage_OneofSizer, []interface{}{\n\t\t(*Bitmessage_Text)(nil),\n\t}\n}", "func (*WriteReq) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _WriteReq_OneofMarshaler, _WriteReq_OneofUnmarshaler, _WriteReq_OneofSizer, []interface{}{\n\t\t(*WriteReq_Name)(nil),\n\t\t(*WriteReq_Blob)(nil),\n\t}\n}", "func (*RunnerMsg) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _RunnerMsg_OneofMarshaler, _RunnerMsg_OneofUnmarshaler, _RunnerMsg_OneofSizer, []interface{}{\n\t\t(*RunnerMsg_Acknowledged)(nil),\n\t\t(*RunnerMsg_ResultStart)(nil),\n\t\t(*RunnerMsg_Data)(nil),\n\t\t(*RunnerMsg_Finished)(nil),\n\t}\n}", "func (*DiscoveryInfo) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _DiscoveryInfo_OneofMarshaler, _DiscoveryInfo_OneofUnmarshaler, _DiscoveryInfo_OneofSizer, []interface{}{\n\t\t(*DiscoveryInfo_Inflated)(nil),\n\t\t(*DiscoveryInfo_BlobAdded)(nil),\n\t\t(*DiscoveryInfo_BlobRemoved)(nil),\n\t}\n}", "func (*Event) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _Event_OneofMarshaler, _Event_OneofUnmarshaler, _Event_OneofSizer, []interface{}{\n\t\t(*Event_Read_)(nil),\n\t\t(*Event_Write_)(nil),\n\t}\n}", "func (*OpenStatusUpdate) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _OpenStatusUpdate_OneofMarshaler, _OpenStatusUpdate_OneofUnmarshaler, _OpenStatusUpdate_OneofSizer, []interface{}{\n\t\t(*OpenStatusUpdate_ChanPending)(nil),\n\t\t(*OpenStatusUpdate_Confirmation)(nil),\n\t\t(*OpenStatusUpdate_ChanOpen)(nil),\n\t}\n}", "func (*OpenStatusUpdate) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _OpenStatusUpdate_OneofMarshaler, _OpenStatusUpdate_OneofUnmarshaler, _OpenStatusUpdate_OneofSizer, []interface{}{\n\t\t(*OpenStatusUpdate_ChanPending)(nil),\n\t\t(*OpenStatusUpdate_Confirmation)(nil),\n\t\t(*OpenStatusUpdate_ChanOpen)(nil),\n\t}\n}", "func (*OpenStatusUpdate) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _OpenStatusUpdate_OneofMarshaler, _OpenStatusUpdate_OneofUnmarshaler, _OpenStatusUpdate_OneofSizer, []interface{}{\n\t\t(*OpenStatusUpdate_ChanPending)(nil),\n\t\t(*OpenStatusUpdate_Confirmation)(nil),\n\t\t(*OpenStatusUpdate_ChanOpen)(nil),\n\t}\n}", "func (*OpenStatusUpdate) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _OpenStatusUpdate_OneofMarshaler, _OpenStatusUpdate_OneofUnmarshaler, _OpenStatusUpdate_OneofSizer, []interface{}{\n\t\t(*OpenStatusUpdate_ChanPending)(nil),\n\t\t(*OpenStatusUpdate_Confirmation)(nil),\n\t\t(*OpenStatusUpdate_ChanOpen)(nil),\n\t}\n}", "func (*TwoOneofs) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _TwoOneofs_OneofMarshaler, _TwoOneofs_OneofUnmarshaler, _TwoOneofs_OneofSizer, []interface{}{\n\t\t(*TwoOneofs_Field1)(nil),\n\t\t(*TwoOneofs_Field2)(nil),\n\t\t(*TwoOneofs_Field3)(nil),\n\t\t(*TwoOneofs_Field34)(nil),\n\t\t(*TwoOneofs_Field35)(nil),\n\t\t(*TwoOneofs_SubMessage2)(nil),\n\t}\n}", "func (*TwoOneofs) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _TwoOneofs_OneofMarshaler, _TwoOneofs_OneofUnmarshaler, _TwoOneofs_OneofSizer, []interface{}{\n\t\t(*TwoOneofs_Field1)(nil),\n\t\t(*TwoOneofs_Field2)(nil),\n\t\t(*TwoOneofs_Field3)(nil),\n\t\t(*TwoOneofs_Field34)(nil),\n\t\t(*TwoOneofs_Field35)(nil),\n\t\t(*TwoOneofs_SubMessage2)(nil),\n\t}\n}", "func (*TwoOneofs) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _TwoOneofs_OneofMarshaler, _TwoOneofs_OneofUnmarshaler, _TwoOneofs_OneofSizer, []interface{}{\n\t\t(*TwoOneofs_Field1)(nil),\n\t\t(*TwoOneofs_Field2)(nil),\n\t\t(*TwoOneofs_Field3)(nil),\n\t\t(*TwoOneofs_Field34)(nil),\n\t\t(*TwoOneofs_Field35)(nil),\n\t\t(*TwoOneofs_SubMessage2)(nil),\n\t}\n}", "func (*TwoOneofs) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _TwoOneofs_OneofMarshaler, _TwoOneofs_OneofUnmarshaler, _TwoOneofs_OneofSizer, []interface{}{\n\t\t(*TwoOneofs_Field1)(nil),\n\t\t(*TwoOneofs_Field2)(nil),\n\t\t(*TwoOneofs_Field3)(nil),\n\t\t(*TwoOneofs_Field34)(nil),\n\t\t(*TwoOneofs_Field35)(nil),\n\t\t(*TwoOneofs_SubMessage2)(nil),\n\t}\n}", "func (*TwoOneofs) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _TwoOneofs_OneofMarshaler, _TwoOneofs_OneofUnmarshaler, _TwoOneofs_OneofSizer, []interface{}{\n\t\t(*TwoOneofs_Field1)(nil),\n\t\t(*TwoOneofs_Field2)(nil),\n\t\t(*TwoOneofs_Field3)(nil),\n\t\t(*TwoOneofs_Field34)(nil),\n\t\t(*TwoOneofs_Field35)(nil),\n\t\t(*TwoOneofs_SubMessage2)(nil),\n\t}\n}", "func (*TwoOneofs) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _TwoOneofs_OneofMarshaler, _TwoOneofs_OneofUnmarshaler, _TwoOneofs_OneofSizer, []interface{}{\n\t\t(*TwoOneofs_Field1)(nil),\n\t\t(*TwoOneofs_Field2)(nil),\n\t\t(*TwoOneofs_Field3)(nil),\n\t\t(*TwoOneofs_Field34)(nil),\n\t\t(*TwoOneofs_Field35)(nil),\n\t\t(*TwoOneofs_SubMessage2)(nil),\n\t}\n}", "func (*Message) XXX_OneofFuncs() (func(msg proto1.Message, b *proto1.Buffer) error, func(msg proto1.Message, tag, wire int, b *proto1.Buffer) (bool, error), func(msg proto1.Message) (n int), []interface{}) {\n\treturn _Message_OneofMarshaler, _Message_OneofUnmarshaler, _Message_OneofSizer, []interface{}{\n\t\t(*Message_Signin)(nil),\n\t\t(*Message_Chatmsg)(nil),\n\t}\n}", "func (*LoggingPayloadData) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _LoggingPayloadData_OneofMarshaler, _LoggingPayloadData_OneofUnmarshaler, _LoggingPayloadData_OneofSizer, []interface{}{\n\t\t(*LoggingPayloadData_Msg)(nil),\n\t\t(*LoggingPayloadData_Raw)(nil),\n\t}\n}", "func (*EvalRequest) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _EvalRequest_OneofMarshaler, _EvalRequest_OneofUnmarshaler, _EvalRequest_OneofSizer, []interface{}{\n\t\t(*EvalRequest_ParsedExpr)(nil),\n\t\t(*EvalRequest_CheckedExpr)(nil),\n\t}\n}", "func (*Header) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _Header_OneofMarshaler, _Header_OneofUnmarshaler, _Header_OneofSizer, []interface{}{\n\t\t(*Header_Version)(nil),\n\t\t(*Header_SourceType)(nil),\n\t\t(*Header_EventType)(nil),\n\t}\n}", "func (*ReadModifyWriteRule) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _ReadModifyWriteRule_OneofMarshaler, _ReadModifyWriteRule_OneofUnmarshaler, _ReadModifyWriteRule_OneofSizer, []interface{}{\n\t\t(*ReadModifyWriteRule_AppendValue)(nil),\n\t\t(*ReadModifyWriteRule_IncrementAmount)(nil),\n\t}\n}", "func (*BitmessageRPC) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _BitmessageRPC_OneofMarshaler, _BitmessageRPC_OneofUnmarshaler, _BitmessageRPC_OneofSizer, []interface{}{\n\t\t(*BitmessageRPC_Request)(nil),\n\t\t(*BitmessageRPC_Reply)(nil),\n\t\t(*BitmessageRPC_Push)(nil),\n\t}\n}", "func (*SetConfigRequest_Entry) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _SetConfigRequest_Entry_OneofMarshaler, _SetConfigRequest_Entry_OneofUnmarshaler, _SetConfigRequest_Entry_OneofSizer, []interface{}{\n\t\t(*SetConfigRequest_Entry_ValueStr)(nil),\n\t\t(*SetConfigRequest_Entry_ValueInt32)(nil),\n\t\t(*SetConfigRequest_Entry_ValueBool)(nil),\n\t}\n}", "func (*HealthCheck_Payload) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _HealthCheck_Payload_OneofMarshaler, _HealthCheck_Payload_OneofUnmarshaler, _HealthCheck_Payload_OneofSizer, []interface{}{\n\t\t(*HealthCheck_Payload_Text)(nil),\n\t\t(*HealthCheck_Payload_Binary)(nil),\n\t}\n}", "func (*FlowKey) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _FlowKey_OneofMarshaler, _FlowKey_OneofUnmarshaler, _FlowKey_OneofSizer, []interface{}{\n\t\t(*FlowKey_IPFlowKey)(nil),\n\t\t(*FlowKey_MACFlowKey)(nil),\n\t}\n}", "func (*LeafStat) XXX_OneofFuncs() (func(msg proto1.Message, b *proto1.Buffer) error, func(msg proto1.Message, tag, wire int, b *proto1.Buffer) (bool, error), func(msg proto1.Message) (n int), []interface{}) {\n\treturn _LeafStat_OneofMarshaler, _LeafStat_OneofUnmarshaler, _LeafStat_OneofSizer, []interface{}{\n\t\t(*LeafStat_Classification)(nil),\n\t\t(*LeafStat_Regression)(nil),\n\t}\n}", "func (*Metadata) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _Metadata_OneofMarshaler, _Metadata_OneofUnmarshaler, _Metadata_OneofSizer, []interface{}{\n\t\t(*Metadata_GatewayID)(nil),\n\t\t(*Metadata_DevAddrPrefix)(nil),\n\t\t(*Metadata_AppID)(nil),\n\t\t(*Metadata_AppEUI)(nil),\n\t}\n}", "func (*BitcoinRules) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _BitcoinRules_OneofMarshaler, _BitcoinRules_OneofUnmarshaler, _BitcoinRules_OneofSizer, []interface{}{\n\t\t(*BitcoinRules_Address)(nil),\n\t\t(*BitcoinRules_String_)(nil),\n\t}\n}", "func (*PolicyUpdateRequest) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _PolicyUpdateRequest_OneofMarshaler, _PolicyUpdateRequest_OneofUnmarshaler, _PolicyUpdateRequest_OneofSizer, []interface{}{\n\t\t(*PolicyUpdateRequest_Global)(nil),\n\t\t(*PolicyUpdateRequest_ChanPoint)(nil),\n\t}\n}", "func (*PolicyUpdateRequest) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _PolicyUpdateRequest_OneofMarshaler, _PolicyUpdateRequest_OneofUnmarshaler, _PolicyUpdateRequest_OneofSizer, []interface{}{\n\t\t(*PolicyUpdateRequest_Global)(nil),\n\t\t(*PolicyUpdateRequest_ChanPoint)(nil),\n\t}\n}", "func (*PolicyUpdateRequest) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _PolicyUpdateRequest_OneofMarshaler, _PolicyUpdateRequest_OneofUnmarshaler, _PolicyUpdateRequest_OneofSizer, []interface{}{\n\t\t(*PolicyUpdateRequest_Global)(nil),\n\t\t(*PolicyUpdateRequest_ChanPoint)(nil),\n\t}\n}", "func (*PolicyUpdateRequest) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _PolicyUpdateRequest_OneofMarshaler, _PolicyUpdateRequest_OneofUnmarshaler, _PolicyUpdateRequest_OneofSizer, []interface{}{\n\t\t(*PolicyUpdateRequest_Global)(nil),\n\t\t(*PolicyUpdateRequest_ChanPoint)(nil),\n\t}\n}", "func (*TriggerMessage) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _TriggerMessage_OneofMarshaler, _TriggerMessage_OneofUnmarshaler, _TriggerMessage_OneofSizer, []interface{}{\n\t\t(*TriggerMessage_Topic)(nil),\n\t\t(*TriggerMessage_Type)(nil),\n\t\t(*TriggerMessage_Event)(nil),\n\t\t(*TriggerMessage_BodyBytes)(nil),\n\t\t(*TriggerMessage_Offset)(nil),\n\t\t(*TriggerMessage_Extensions)(nil),\n\t\t(*TriggerMessage_Uuid)(nil),\n\t\t(*TriggerMessage_Bid)(nil),\n\t}\n}", "func (*Params) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _Params_OneofMarshaler, _Params_OneofUnmarshaler, _Params_OneofSizer, []interface{}{\n\t\t(*Params_AppCredentials)(nil),\n\t\t(*Params_ApiKey)(nil),\n\t\t(*Params_ServiceAccountPath)(nil),\n\t}\n}", "func (*Component) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _Component_OneofMarshaler, _Component_OneofUnmarshaler, _Component_OneofSizer, []interface{}{\n\t\t(*Component_AppengineModule)(nil),\n\t\t(*Component_GkePod)(nil),\n\t}\n}", "func (*Event) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _Event_OneofMarshaler, _Event_OneofUnmarshaler, _Event_OneofSizer, []interface{}{\n\t\t(*Event_Register)(nil),\n\t\t(*Event_Block)(nil),\n\t\t(*Event_ChaincodeEvent)(nil),\n\t\t(*Event_Rejection)(nil),\n\t\t(*Event_Unregister)(nil),\n\t}\n}", "func (*Event) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _Event_OneofMarshaler, _Event_OneofUnmarshaler, _Event_OneofSizer, []interface{}{\n\t\t(*Event_Register)(nil),\n\t\t(*Event_Block)(nil),\n\t\t(*Event_ChaincodeEvent)(nil),\n\t\t(*Event_Rejection)(nil),\n\t\t(*Event_Unregister)(nil),\n\t}\n}", "func (*StateKey) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _StateKey_OneofMarshaler, _StateKey_OneofUnmarshaler, _StateKey_OneofSizer, []interface{}{\n\t\t(*StateKey_Runner_)(nil),\n\t\t(*StateKey_MultimapSideInput_)(nil),\n\t\t(*StateKey_BagUserState_)(nil),\n\t}\n}", "func (*StateKey) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _StateKey_OneofMarshaler, _StateKey_OneofUnmarshaler, _StateKey_OneofSizer, []interface{}{\n\t\t(*StateKey_Runner_)(nil),\n\t\t(*StateKey_MultimapSideInput_)(nil),\n\t\t(*StateKey_BagUserState_)(nil),\n\t}\n}", "func (*InternalRequest) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _InternalRequest_OneofMarshaler, _InternalRequest_OneofUnmarshaler, _InternalRequest_OneofSizer, []interface{}{\n\t\t(*InternalRequest_PutReq)(nil),\n\t\t(*InternalRequest_GetReq)(nil),\n\t\t(*InternalRequest_DeleteReq)(nil),\n\t}\n}", "func (*Message) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _Message_OneofMarshaler, _Message_OneofUnmarshaler, _Message_OneofSizer, []interface{}{\n\t\t(*Message_Transfer)(nil),\n\t\t(*Message_Account)(nil),\n\t}\n}", "func (*VideoAdInfo) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _VideoAdInfo_OneofMarshaler, _VideoAdInfo_OneofUnmarshaler, _VideoAdInfo_OneofSizer, []interface{}{\n\t\t(*VideoAdInfo_InStream)(nil),\n\t}\n}", "func (*TapEvent) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _TapEvent_OneofMarshaler, _TapEvent_OneofUnmarshaler, _TapEvent_OneofSizer, []interface{}{\n\t\t(*TapEvent_Http_)(nil),\n\t}\n}", "func (*TapEvent) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _TapEvent_OneofMarshaler, _TapEvent_OneofUnmarshaler, _TapEvent_OneofSizer, []interface{}{\n\t\t(*TapEvent_Http_)(nil),\n\t}\n}", "func (*TapEvent) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _TapEvent_OneofMarshaler, _TapEvent_OneofUnmarshaler, _TapEvent_OneofSizer, []interface{}{\n\t\t(*TapEvent_Http_)(nil),\n\t}\n}", "func (*UploadBinaryRequest) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _UploadBinaryRequest_OneofMarshaler, _UploadBinaryRequest_OneofUnmarshaler, _UploadBinaryRequest_OneofSizer, []interface{}{\n\t\t(*UploadBinaryRequest_Key_)(nil),\n\t\t(*UploadBinaryRequest_Chunk_)(nil),\n\t}\n}", "func (*Metric) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _Metric_OneofMarshaler, _Metric_OneofUnmarshaler, _Metric_OneofSizer, []interface{}{\n\t\t(*Metric_I64)(nil),\n\t\t(*Metric_U64)(nil),\n\t\t(*Metric_F64)(nil),\n\t\t(*Metric_String_)(nil),\n\t\t(*Metric_Bool)(nil),\n\t\t(*Metric_Duration)(nil),\n\t}\n}", "func (*SendBitmessageRequest) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _SendBitmessageRequest_OneofMarshaler, _SendBitmessageRequest_OneofUnmarshaler, _SendBitmessageRequest_OneofSizer, []interface{}{\n\t\t(*SendBitmessageRequest_Text)(nil),\n\t}\n}", "func (*Service) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _Service_OneofMarshaler, _Service_OneofUnmarshaler, _Service_OneofSizer, []interface{}{\n\t\t(*Service_DstPort)(nil),\n\t\t(*Service_IcmpMsgType)(nil),\n\t}\n}", "func (*Event) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _Event_OneofMarshaler, _Event_OneofUnmarshaler, _Event_OneofSizer, []interface{}{\n\t\t(*Event_Error)(nil),\n\t\t(*Event_Progress)(nil),\n\t\t(*Event_Match)(nil),\n\t\t(*Event_Pagination)(nil),\n\t}\n}", "func (*Config) XXX_OneofFuncs() (func(msg proto1.Message, b *proto1.Buffer) error, func(msg proto1.Message, tag, wire int, b *proto1.Buffer) (bool, error), func(msg proto1.Message) (n int), []interface{}) {\n\treturn _Config_OneofMarshaler, _Config_OneofUnmarshaler, _Config_OneofSizer, []interface{}{\n\t\t(*Config_Custom)(nil),\n\t\t(*Config_Random)(nil),\n\t\t(*Config_Fixed)(nil),\n\t}\n}", "func (*FetchRequest) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _FetchRequest_OneofMarshaler, _FetchRequest_OneofUnmarshaler, _FetchRequest_OneofSizer, []interface{}{\n\t\t(*FetchRequest_TagMatchers)(nil),\n\t}\n}", "func (*Wrapper) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _Wrapper_OneofMarshaler, _Wrapper_OneofUnmarshaler, _Wrapper_OneofSizer, []interface{}{\n\t\t(*Wrapper_Source)(nil),\n\t\t(*Wrapper_GherkinDocument)(nil),\n\t\t(*Wrapper_Pickle)(nil),\n\t\t(*Wrapper_Attachment)(nil),\n\t\t(*Wrapper_TestCaseStarted)(nil),\n\t\t(*Wrapper_TestStepStarted)(nil),\n\t\t(*Wrapper_TestStepFinished)(nil),\n\t\t(*Wrapper_TestCaseFinished)(nil),\n\t\t(*Wrapper_TestHookStarted)(nil),\n\t\t(*Wrapper_TestHookFinished)(nil),\n\t}\n}", "func (*Message) XXX_OneofFuncs() (func(msg proto1.Message, b *proto1.Buffer) error, func(msg proto1.Message, tag, wire int, b *proto1.Buffer) (bool, error), func(msg proto1.Message) (n int), []interface{}) {\n\treturn _Message_OneofMarshaler, _Message_OneofUnmarshaler, _Message_OneofSizer, []interface{}{\n\t\t(*Message_Bigint)(nil),\n\t\t(*Message_EcGroupElement)(nil),\n\t\t(*Message_Status)(nil),\n\t\t(*Message_PedersenFirst)(nil),\n\t\t(*Message_PedersenDecommitment)(nil),\n\t\t(*Message_SchnorrProofData)(nil),\n\t\t(*Message_SchnorrProofRandomData)(nil),\n\t\t(*Message_SchnorrEcProofRandomData)(nil),\n\t\t(*Message_PseudonymsysCaCertificate)(nil),\n\t\t(*Message_PseudonymsysNymGenProofRandomData)(nil),\n\t\t(*Message_PseudonymsysIssueProofRandomData)(nil),\n\t\t(*Message_DoubleBigint)(nil),\n\t\t(*Message_PseudonymsysTransferCredentialData)(nil),\n\t\t(*Message_PseudonymsysCaCertificateEc)(nil),\n\t\t(*Message_PseudonymsysNymGenProofRandomDataEc)(nil),\n\t\t(*Message_PseudonymsysIssueProofRandomDataEc)(nil),\n\t\t(*Message_PseudonymsysTransferCredentialDataEc)(nil),\n\t\t(*Message_SessionKey)(nil),\n\t}\n}", "func (*StateRequest) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _StateRequest_OneofMarshaler, _StateRequest_OneofUnmarshaler, _StateRequest_OneofSizer, []interface{}{\n\t\t(*StateRequest_Get)(nil),\n\t\t(*StateRequest_Append)(nil),\n\t\t(*StateRequest_Clear)(nil),\n\t}\n}", "func (*StateRequest) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _StateRequest_OneofMarshaler, _StateRequest_OneofUnmarshaler, _StateRequest_OneofSizer, []interface{}{\n\t\t(*StateRequest_Get)(nil),\n\t\t(*StateRequest_Append)(nil),\n\t\t(*StateRequest_Clear)(nil),\n\t}\n}", "func (*Event) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _Event_OneofMarshaler, _Event_OneofUnmarshaler, _Event_OneofSizer, []interface{}{\n\t\t(*Event_ResourceHeader)(nil),\n\t\t(*Event_CertAuthority)(nil),\n\t\t(*Event_StaticTokens)(nil),\n\t\t(*Event_ProvisionToken)(nil),\n\t\t(*Event_ClusterName)(nil),\n\t\t(*Event_ClusterConfig)(nil),\n\t\t(*Event_User)(nil),\n\t\t(*Event_Role)(nil),\n\t\t(*Event_Namespace)(nil),\n\t\t(*Event_Server)(nil),\n\t\t(*Event_ReverseTunnel)(nil),\n\t\t(*Event_TunnelConnection)(nil),\n\t\t(*Event_AccessRequest)(nil),\n\t}\n}", "func (*NetworkAddress) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _NetworkAddress_OneofMarshaler, _NetworkAddress_OneofUnmarshaler, _NetworkAddress_OneofSizer, []interface{}{\n\t\t(*NetworkAddress_Ipv4Address)(nil),\n\t\t(*NetworkAddress_Ipv6Address)(nil),\n\t\t(*NetworkAddress_LocalAddress)(nil),\n\t}\n}", "func (*NetworkAddress) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _NetworkAddress_OneofMarshaler, _NetworkAddress_OneofUnmarshaler, _NetworkAddress_OneofSizer, []interface{}{\n\t\t(*NetworkAddress_Ipv4Address)(nil),\n\t\t(*NetworkAddress_Ipv6Address)(nil),\n\t\t(*NetworkAddress_LocalAddress)(nil),\n\t}\n}", "func (*RPC) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _RPC_OneofMarshaler, _RPC_OneofUnmarshaler, _RPC_OneofSizer, []interface{}{\n\t\t(*RPC_Args)(nil),\n\t\t(*RPC_ByteArgs)(nil),\n\t}\n}", "func (*FeeUpdateRequest) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _FeeUpdateRequest_OneofMarshaler, _FeeUpdateRequest_OneofUnmarshaler, _FeeUpdateRequest_OneofSizer, []interface{}{\n\t\t(*FeeUpdateRequest_Global)(nil),\n\t\t(*FeeUpdateRequest_ChanPoint)(nil),\n\t}\n}", "func (*FeeUpdateRequest) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _FeeUpdateRequest_OneofMarshaler, _FeeUpdateRequest_OneofUnmarshaler, _FeeUpdateRequest_OneofSizer, []interface{}{\n\t\t(*FeeUpdateRequest_Global)(nil),\n\t\t(*FeeUpdateRequest_ChanPoint)(nil),\n\t}\n}", "func (*ServiceSpec) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _ServiceSpec_OneofMarshaler, _ServiceSpec_OneofUnmarshaler, _ServiceSpec_OneofSizer, []interface{}{\n\t\t(*ServiceSpec_Replicated)(nil),\n\t\t(*ServiceSpec_Global)(nil),\n\t}\n}", "func (*ServiceSpec) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _ServiceSpec_OneofMarshaler, _ServiceSpec_OneofUnmarshaler, _ServiceSpec_OneofSizer, []interface{}{\n\t\t(*ServiceSpec_Replicated)(nil),\n\t\t(*ServiceSpec_Global)(nil),\n\t}\n}", "func (*ServiceSpec) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _ServiceSpec_OneofMarshaler, _ServiceSpec_OneofUnmarshaler, _ServiceSpec_OneofSizer, []interface{}{\n\t\t(*ServiceSpec_Replicated)(nil),\n\t\t(*ServiceSpec_Global)(nil),\n\t}\n}", "func (*TestUTF8) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _TestUTF8_OneofMarshaler, _TestUTF8_OneofUnmarshaler, _TestUTF8_OneofSizer, []interface{}{\n\t\t(*TestUTF8_Field)(nil),\n\t}\n}", "func (*TestUTF8) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _TestUTF8_OneofMarshaler, _TestUTF8_OneofUnmarshaler, _TestUTF8_OneofSizer, []interface{}{\n\t\t(*TestUTF8_Field)(nil),\n\t}\n}", "func (*Eos) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _Eos_OneofMarshaler, _Eos_OneofUnmarshaler, _Eos_OneofSizer, []interface{}{\n\t\t(*Eos_GrpcStatusCode)(nil),\n\t\t(*Eos_ResetErrorCode)(nil),\n\t}\n}", "func (*Eos) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _Eos_OneofMarshaler, _Eos_OneofUnmarshaler, _Eos_OneofSizer, []interface{}{\n\t\t(*Eos_GrpcStatusCode)(nil),\n\t\t(*Eos_ResetErrorCode)(nil),\n\t}\n}", "func (*RecordKey) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _RecordKey_OneofMarshaler, _RecordKey_OneofUnmarshaler, _RecordKey_OneofSizer, []interface{}{\n\t\t(*RecordKey_DatastoreKey)(nil),\n\t\t(*RecordKey_BigQueryKey)(nil),\n\t}\n}", "func (*WatchRequest) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _WatchRequest_OneofMarshaler, _WatchRequest_OneofUnmarshaler, _WatchRequest_OneofSizer, []interface{}{\n\t\t(*WatchRequest_CreateRequest)(nil),\n\t\t(*WatchRequest_CancelRequest)(nil),\n\t}\n}", "func (*Node) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _Node_OneofMarshaler, _Node_OneofUnmarshaler, _Node_OneofSizer, []interface{}{\n\t\t(*Node_Src)(nil),\n\t\t(*Node_Snk)(nil),\n\t\t(*Node_ContentHash)(nil),\n\t}\n}", "func (*FeedMapping) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _FeedMapping_OneofMarshaler, _FeedMapping_OneofUnmarshaler, _FeedMapping_OneofSizer, []interface{}{\n\t\t(*FeedMapping_PlaceholderType)(nil),\n\t\t(*FeedMapping_CriterionType)(nil),\n\t}\n}", "func (*Virtual) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _Virtual_OneofMarshaler, _Virtual_OneofUnmarshaler, _Virtual_OneofSizer, []interface{}{\n\t\t(*Virtual_Genesis)(nil),\n\t\t(*Virtual_Child)(nil),\n\t\t(*Virtual_Jet)(nil),\n\t\t(*Virtual_IncomingRequest)(nil),\n\t\t(*Virtual_OutgoingRequest)(nil),\n\t\t(*Virtual_Result)(nil),\n\t\t(*Virtual_Type)(nil),\n\t\t(*Virtual_Code)(nil),\n\t\t(*Virtual_Activate)(nil),\n\t\t(*Virtual_Amend)(nil),\n\t\t(*Virtual_Deactivate)(nil),\n\t\t(*Virtual_PendingFilament)(nil),\n\t}\n}", "func (*CloseStatusUpdate) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _CloseStatusUpdate_OneofMarshaler, _CloseStatusUpdate_OneofUnmarshaler, _CloseStatusUpdate_OneofSizer, []interface{}{\n\t\t(*CloseStatusUpdate_ClosePending)(nil),\n\t\t(*CloseStatusUpdate_Confirmation)(nil),\n\t\t(*CloseStatusUpdate_ChanClose)(nil),\n\t}\n}", "func (*CloseStatusUpdate) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _CloseStatusUpdate_OneofMarshaler, _CloseStatusUpdate_OneofUnmarshaler, _CloseStatusUpdate_OneofSizer, []interface{}{\n\t\t(*CloseStatusUpdate_ClosePending)(nil),\n\t\t(*CloseStatusUpdate_Confirmation)(nil),\n\t\t(*CloseStatusUpdate_ChanClose)(nil),\n\t}\n}", "func (*CloseStatusUpdate) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _CloseStatusUpdate_OneofMarshaler, _CloseStatusUpdate_OneofUnmarshaler, _CloseStatusUpdate_OneofSizer, []interface{}{\n\t\t(*CloseStatusUpdate_ClosePending)(nil),\n\t\t(*CloseStatusUpdate_Confirmation)(nil),\n\t\t(*CloseStatusUpdate_ChanClose)(nil),\n\t}\n}", "func (*CloseStatusUpdate) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _CloseStatusUpdate_OneofMarshaler, _CloseStatusUpdate_OneofUnmarshaler, _CloseStatusUpdate_OneofSizer, []interface{}{\n\t\t(*CloseStatusUpdate_ClosePending)(nil),\n\t\t(*CloseStatusUpdate_Confirmation)(nil),\n\t\t(*CloseStatusUpdate_ChanClose)(nil),\n\t}\n}", "func (*CloseStatusUpdate) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _CloseStatusUpdate_OneofMarshaler, _CloseStatusUpdate_OneofUnmarshaler, _CloseStatusUpdate_OneofSizer, []interface{}{\n\t\t(*CloseStatusUpdate_ClosePending)(nil),\n\t\t(*CloseStatusUpdate_ChanClose)(nil),\n\t}\n}", "func (*CloseStatusUpdate) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _CloseStatusUpdate_OneofMarshaler, _CloseStatusUpdate_OneofUnmarshaler, _CloseStatusUpdate_OneofSizer, []interface{}{\n\t\t(*CloseStatusUpdate_ClosePending)(nil),\n\t\t(*CloseStatusUpdate_ChanClose)(nil),\n\t}\n}", "func (*CloseStatusUpdate) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _CloseStatusUpdate_OneofMarshaler, _CloseStatusUpdate_OneofUnmarshaler, _CloseStatusUpdate_OneofSizer, []interface{}{\n\t\t(*CloseStatusUpdate_ClosePending)(nil),\n\t\t(*CloseStatusUpdate_ChanClose)(nil),\n\t}\n}", "func (*PrintKVRequest) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _PrintKVRequest_OneofMarshaler, _PrintKVRequest_OneofUnmarshaler, _PrintKVRequest_OneofSizer, []interface{}{\n\t\t(*PrintKVRequest_ValueString)(nil),\n\t\t(*PrintKVRequest_ValueInt)(nil),\n\t}\n}", "func (*ChannelEventUpdate) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _ChannelEventUpdate_OneofMarshaler, _ChannelEventUpdate_OneofUnmarshaler, _ChannelEventUpdate_OneofSizer, []interface{}{\n\t\t(*ChannelEventUpdate_OpenChannel)(nil),\n\t\t(*ChannelEventUpdate_ClosedChannel)(nil),\n\t\t(*ChannelEventUpdate_ActiveChannel)(nil),\n\t\t(*ChannelEventUpdate_InactiveChannel)(nil),\n\t}\n}", "func (*ChannelEventUpdate) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _ChannelEventUpdate_OneofMarshaler, _ChannelEventUpdate_OneofUnmarshaler, _ChannelEventUpdate_OneofSizer, []interface{}{\n\t\t(*ChannelEventUpdate_OpenChannel)(nil),\n\t\t(*ChannelEventUpdate_ClosedChannel)(nil),\n\t\t(*ChannelEventUpdate_ActiveChannel)(nil),\n\t\t(*ChannelEventUpdate_InactiveChannel)(nil),\n\t}\n}", "func (*ChannelEventUpdate) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _ChannelEventUpdate_OneofMarshaler, _ChannelEventUpdate_OneofUnmarshaler, _ChannelEventUpdate_OneofSizer, []interface{}{\n\t\t(*ChannelEventUpdate_OpenChannel)(nil),\n\t\t(*ChannelEventUpdate_ClosedChannel)(nil),\n\t\t(*ChannelEventUpdate_ActiveChannel)(nil),\n\t\t(*ChannelEventUpdate_InactiveChannel)(nil),\n\t}\n}" ]
[ "0.8907106", "0.890579", "0.8891233", "0.88697135", "0.8868073", "0.8863467", "0.8863115", "0.8862988", "0.886209", "0.8861827", "0.8859999", "0.88558704", "0.88540995", "0.88527775", "0.88527775", "0.88527775", "0.88480514", "0.8847366", "0.88448733", "0.8844595", "0.8841944", "0.8837193", "0.88370156", "0.88370156", "0.88370156", "0.88370156", "0.8835452", "0.8835452", "0.8835452", "0.8835452", "0.8835452", "0.8835452", "0.88341135", "0.88305503", "0.8830491", "0.8830415", "0.8830316", "0.8829064", "0.88287365", "0.8827809", "0.8824382", "0.8824265", "0.8823733", "0.88221323", "0.88188404", "0.88188404", "0.88188404", "0.88188404", "0.8814617", "0.8813053", "0.8811626", "0.88105947", "0.88105947", "0.880831", "0.880831", "0.88082665", "0.8808227", "0.8805944", "0.8805914", "0.8805914", "0.8805914", "0.88056016", "0.88042617", "0.88038075", "0.88034934", "0.88032365", "0.8802399", "0.880174", "0.87993646", "0.8799361", "0.87975067", "0.87975067", "0.8795369", "0.8795032", "0.8795032", "0.8792591", "0.8791414", "0.8791414", "0.8791351", "0.8791351", "0.8791351", "0.87900233", "0.87900233", "0.8788791", "0.8788791", "0.8788189", "0.8787607", "0.87870103", "0.8787005", "0.8786366", "0.87856686", "0.87856686", "0.87856686", "0.87856686", "0.8785405", "0.8785405", "0.8785405", "0.8784138", "0.87823385", "0.87823385", "0.87823385" ]
0.0
-1
XXX_OneofFuncs is for the internal use of the proto package.
func (*Communique) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) { return _Communique_OneofMarshaler, _Communique_OneofUnmarshaler, _Communique_OneofSizer, []interface{}{ (*Communique_Number)(nil), (*Communique_Name)(nil), (*Communique_Data)(nil), (*Communique_TempC)(nil), (*Communique_Col)(nil), (*Communique_Msg)(nil), } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (*EncapVal) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _EncapVal_OneofMarshaler, _EncapVal_OneofUnmarshaler, _EncapVal_OneofSizer, []interface{}{\n\t\t(*EncapVal_VlanId)(nil),\n\t\t(*EncapVal_MPLSTag)(nil),\n\t\t(*EncapVal_Vnid)(nil),\n\t\t(*EncapVal_QinQ)(nil),\n\t}\n}", "func (*FlowL4Info) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _FlowL4Info_OneofMarshaler, _FlowL4Info_OneofUnmarshaler, _FlowL4Info_OneofSizer, []interface{}{\n\t\t(*FlowL4Info_TcpUdpInfo)(nil),\n\t\t(*FlowL4Info_IcmpInfo)(nil),\n\t}\n}", "func (*Msg) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _Msg_OneofMarshaler, _Msg_OneofUnmarshaler, _Msg_OneofSizer, []interface{}{\n\t\t(*Msg_Request)(nil),\n\t\t(*Msg_Preprepare)(nil),\n\t\t(*Msg_Prepare)(nil),\n\t\t(*Msg_Commit)(nil),\n\t\t(*Msg_ViewChange)(nil),\n\t\t(*Msg_NewView)(nil),\n\t\t(*Msg_Checkpoint)(nil),\n\t\t(*Msg_Hello)(nil),\n\t}\n}", "func (*RuleL4Match) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _RuleL4Match_OneofMarshaler, _RuleL4Match_OneofUnmarshaler, _RuleL4Match_OneofSizer, []interface{}{\n\t\t(*RuleL4Match_Ports)(nil),\n\t\t(*RuleL4Match_TypeCode)(nil),\n\t}\n}", "func (*Example) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _Example_OneofMarshaler, _Example_OneofUnmarshaler, _Example_OneofSizer, []interface{}{\n\t\t(*Example_ImagePayload)(nil),\n\t\t(*Example_TextPayload)(nil),\n\t\t(*Example_VideoPayload)(nil),\n\t\t(*Example_AudioPayload)(nil),\n\t}\n}", "func (*Metric) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _Metric_OneofMarshaler, _Metric_OneofUnmarshaler, _Metric_OneofSizer, []interface{}{\n\t\t(*Metric_StringData)(nil),\n\t\t(*Metric_Float32Data)(nil),\n\t\t(*Metric_Float64Data)(nil),\n\t\t(*Metric_Int32Data)(nil),\n\t\t(*Metric_Int64Data)(nil),\n\t\t(*Metric_BytesData)(nil),\n\t\t(*Metric_BoolData)(nil),\n\t\t(*Metric_Uint32Data)(nil),\n\t\t(*Metric_Uint64Data)(nil),\n\t}\n}", "func (*Interface) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _Interface_OneofMarshaler, _Interface_OneofUnmarshaler, _Interface_OneofSizer, []interface{}{\n\t\t(*Interface_Sub)(nil),\n\t\t(*Interface_Memif)(nil),\n\t\t(*Interface_Afpacket)(nil),\n\t\t(*Interface_Tap)(nil),\n\t\t(*Interface_Vxlan)(nil),\n\t\t(*Interface_Ipsec)(nil),\n\t\t(*Interface_VmxNet3)(nil),\n\t}\n}", "func (*Metadata) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _Metadata_OneofMarshaler, _Metadata_OneofUnmarshaler, _Metadata_OneofSizer, []interface{}{\n\t\t(*Metadata_DevAddrPrefix)(nil),\n\t\t(*Metadata_AppId)(nil),\n\t\t(*Metadata_AppEui)(nil),\n\t}\n}", "func (*Message) XXX_OneofFuncs() (func(msg proto1.Message, b *proto1.Buffer) error, func(msg proto1.Message, tag, wire int, b *proto1.Buffer) (bool, error), func(msg proto1.Message) (n int), []interface{}) {\n\treturn _Message_OneofMarshaler, _Message_OneofUnmarshaler, _Message_OneofSizer, []interface{}{\n\t\t(*Message_ExecStarted)(nil),\n\t\t(*Message_ExecCompleted)(nil),\n\t\t(*Message_ExecOutput)(nil),\n\t\t(*Message_LogEntry)(nil),\n\t\t(*Message_Error)(nil),\n\t}\n}", "func (*Message) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _Message_OneofMarshaler, _Message_OneofUnmarshaler, _Message_OneofSizer, []interface{}{\n\t\t(*Message_Chunk)(nil),\n\t\t(*Message_Status)(nil),\n\t}\n}", "func (*Message) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _Message_OneofMarshaler, _Message_OneofUnmarshaler, _Message_OneofSizer, []interface{}{\n\t\t(*Message_OpenPayload)(nil),\n\t\t(*Message_ClosePayload)(nil),\n\t\t(*Message_DataPayload)(nil),\n\t}\n}", "func (*BMRPCRequest) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _BMRPCRequest_OneofMarshaler, _BMRPCRequest_OneofUnmarshaler, _BMRPCRequest_OneofSizer, []interface{}{\n\t\t(*BMRPCRequest_Newaddress)(nil),\n\t\t(*BMRPCRequest_Help)(nil),\n\t\t(*BMRPCRequest_Listaddresses)(nil),\n\t}\n}", "func (*Interface) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _Interface_OneofMarshaler, _Interface_OneofUnmarshaler, _Interface_OneofSizer, []interface{}{\n\t\t(*Interface_Sub)(nil),\n\t\t(*Interface_Memif)(nil),\n\t\t(*Interface_Afpacket)(nil),\n\t\t(*Interface_Tap)(nil),\n\t\t(*Interface_Vxlan)(nil),\n\t\t(*Interface_Ipsec)(nil),\n\t\t(*Interface_VmxNet3)(nil),\n\t\t(*Interface_Bond)(nil),\n\t}\n}", "func (*OpenStatusUpdate) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _OpenStatusUpdate_OneofMarshaler, _OpenStatusUpdate_OneofUnmarshaler, _OpenStatusUpdate_OneofSizer, []interface{}{\n\t\t(*OpenStatusUpdate_ChanPending)(nil),\n\t\t(*OpenStatusUpdate_ChanOpen)(nil),\n\t}\n}", "func (*OpenStatusUpdate) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _OpenStatusUpdate_OneofMarshaler, _OpenStatusUpdate_OneofUnmarshaler, _OpenStatusUpdate_OneofSizer, []interface{}{\n\t\t(*OpenStatusUpdate_ChanPending)(nil),\n\t\t(*OpenStatusUpdate_ChanOpen)(nil),\n\t}\n}", "func (*OpenStatusUpdate) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _OpenStatusUpdate_OneofMarshaler, _OpenStatusUpdate_OneofUnmarshaler, _OpenStatusUpdate_OneofSizer, []interface{}{\n\t\t(*OpenStatusUpdate_ChanPending)(nil),\n\t\t(*OpenStatusUpdate_ChanOpen)(nil),\n\t}\n}", "func (*StatTable) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _StatTable_OneofMarshaler, _StatTable_OneofUnmarshaler, _StatTable_OneofSizer, []interface{}{\n\t\t(*StatTable_PodGroup_)(nil),\n\t}\n}", "func (*Bitmessage) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _Bitmessage_OneofMarshaler, _Bitmessage_OneofUnmarshaler, _Bitmessage_OneofSizer, []interface{}{\n\t\t(*Bitmessage_Text)(nil),\n\t}\n}", "func (*WriteReq) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _WriteReq_OneofMarshaler, _WriteReq_OneofUnmarshaler, _WriteReq_OneofSizer, []interface{}{\n\t\t(*WriteReq_Name)(nil),\n\t\t(*WriteReq_Blob)(nil),\n\t}\n}", "func (*RunnerMsg) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _RunnerMsg_OneofMarshaler, _RunnerMsg_OneofUnmarshaler, _RunnerMsg_OneofSizer, []interface{}{\n\t\t(*RunnerMsg_Acknowledged)(nil),\n\t\t(*RunnerMsg_ResultStart)(nil),\n\t\t(*RunnerMsg_Data)(nil),\n\t\t(*RunnerMsg_Finished)(nil),\n\t}\n}", "func (*DiscoveryInfo) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _DiscoveryInfo_OneofMarshaler, _DiscoveryInfo_OneofUnmarshaler, _DiscoveryInfo_OneofSizer, []interface{}{\n\t\t(*DiscoveryInfo_Inflated)(nil),\n\t\t(*DiscoveryInfo_BlobAdded)(nil),\n\t\t(*DiscoveryInfo_BlobRemoved)(nil),\n\t}\n}", "func (*OpenStatusUpdate) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _OpenStatusUpdate_OneofMarshaler, _OpenStatusUpdate_OneofUnmarshaler, _OpenStatusUpdate_OneofSizer, []interface{}{\n\t\t(*OpenStatusUpdate_ChanPending)(nil),\n\t\t(*OpenStatusUpdate_Confirmation)(nil),\n\t\t(*OpenStatusUpdate_ChanOpen)(nil),\n\t}\n}", "func (*OpenStatusUpdate) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _OpenStatusUpdate_OneofMarshaler, _OpenStatusUpdate_OneofUnmarshaler, _OpenStatusUpdate_OneofSizer, []interface{}{\n\t\t(*OpenStatusUpdate_ChanPending)(nil),\n\t\t(*OpenStatusUpdate_Confirmation)(nil),\n\t\t(*OpenStatusUpdate_ChanOpen)(nil),\n\t}\n}", "func (*OpenStatusUpdate) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _OpenStatusUpdate_OneofMarshaler, _OpenStatusUpdate_OneofUnmarshaler, _OpenStatusUpdate_OneofSizer, []interface{}{\n\t\t(*OpenStatusUpdate_ChanPending)(nil),\n\t\t(*OpenStatusUpdate_Confirmation)(nil),\n\t\t(*OpenStatusUpdate_ChanOpen)(nil),\n\t}\n}", "func (*OpenStatusUpdate) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _OpenStatusUpdate_OneofMarshaler, _OpenStatusUpdate_OneofUnmarshaler, _OpenStatusUpdate_OneofSizer, []interface{}{\n\t\t(*OpenStatusUpdate_ChanPending)(nil),\n\t\t(*OpenStatusUpdate_Confirmation)(nil),\n\t\t(*OpenStatusUpdate_ChanOpen)(nil),\n\t}\n}", "func (*Event) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _Event_OneofMarshaler, _Event_OneofUnmarshaler, _Event_OneofSizer, []interface{}{\n\t\t(*Event_Read_)(nil),\n\t\t(*Event_Write_)(nil),\n\t}\n}", "func (*TwoOneofs) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _TwoOneofs_OneofMarshaler, _TwoOneofs_OneofUnmarshaler, _TwoOneofs_OneofSizer, []interface{}{\n\t\t(*TwoOneofs_Field1)(nil),\n\t\t(*TwoOneofs_Field2)(nil),\n\t\t(*TwoOneofs_Field3)(nil),\n\t\t(*TwoOneofs_Field34)(nil),\n\t\t(*TwoOneofs_Field35)(nil),\n\t\t(*TwoOneofs_SubMessage2)(nil),\n\t}\n}", "func (*TwoOneofs) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _TwoOneofs_OneofMarshaler, _TwoOneofs_OneofUnmarshaler, _TwoOneofs_OneofSizer, []interface{}{\n\t\t(*TwoOneofs_Field1)(nil),\n\t\t(*TwoOneofs_Field2)(nil),\n\t\t(*TwoOneofs_Field3)(nil),\n\t\t(*TwoOneofs_Field34)(nil),\n\t\t(*TwoOneofs_Field35)(nil),\n\t\t(*TwoOneofs_SubMessage2)(nil),\n\t}\n}", "func (*TwoOneofs) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _TwoOneofs_OneofMarshaler, _TwoOneofs_OneofUnmarshaler, _TwoOneofs_OneofSizer, []interface{}{\n\t\t(*TwoOneofs_Field1)(nil),\n\t\t(*TwoOneofs_Field2)(nil),\n\t\t(*TwoOneofs_Field3)(nil),\n\t\t(*TwoOneofs_Field34)(nil),\n\t\t(*TwoOneofs_Field35)(nil),\n\t\t(*TwoOneofs_SubMessage2)(nil),\n\t}\n}", "func (*TwoOneofs) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _TwoOneofs_OneofMarshaler, _TwoOneofs_OneofUnmarshaler, _TwoOneofs_OneofSizer, []interface{}{\n\t\t(*TwoOneofs_Field1)(nil),\n\t\t(*TwoOneofs_Field2)(nil),\n\t\t(*TwoOneofs_Field3)(nil),\n\t\t(*TwoOneofs_Field34)(nil),\n\t\t(*TwoOneofs_Field35)(nil),\n\t\t(*TwoOneofs_SubMessage2)(nil),\n\t}\n}", "func (*TwoOneofs) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _TwoOneofs_OneofMarshaler, _TwoOneofs_OneofUnmarshaler, _TwoOneofs_OneofSizer, []interface{}{\n\t\t(*TwoOneofs_Field1)(nil),\n\t\t(*TwoOneofs_Field2)(nil),\n\t\t(*TwoOneofs_Field3)(nil),\n\t\t(*TwoOneofs_Field34)(nil),\n\t\t(*TwoOneofs_Field35)(nil),\n\t\t(*TwoOneofs_SubMessage2)(nil),\n\t}\n}", "func (*TwoOneofs) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _TwoOneofs_OneofMarshaler, _TwoOneofs_OneofUnmarshaler, _TwoOneofs_OneofSizer, []interface{}{\n\t\t(*TwoOneofs_Field1)(nil),\n\t\t(*TwoOneofs_Field2)(nil),\n\t\t(*TwoOneofs_Field3)(nil),\n\t\t(*TwoOneofs_Field34)(nil),\n\t\t(*TwoOneofs_Field35)(nil),\n\t\t(*TwoOneofs_SubMessage2)(nil),\n\t}\n}", "func (*Message) XXX_OneofFuncs() (func(msg proto1.Message, b *proto1.Buffer) error, func(msg proto1.Message, tag, wire int, b *proto1.Buffer) (bool, error), func(msg proto1.Message) (n int), []interface{}) {\n\treturn _Message_OneofMarshaler, _Message_OneofUnmarshaler, _Message_OneofSizer, []interface{}{\n\t\t(*Message_Signin)(nil),\n\t\t(*Message_Chatmsg)(nil),\n\t}\n}", "func (*Header) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _Header_OneofMarshaler, _Header_OneofUnmarshaler, _Header_OneofSizer, []interface{}{\n\t\t(*Header_Version)(nil),\n\t\t(*Header_SourceType)(nil),\n\t\t(*Header_EventType)(nil),\n\t}\n}", "func (*LoggingPayloadData) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _LoggingPayloadData_OneofMarshaler, _LoggingPayloadData_OneofUnmarshaler, _LoggingPayloadData_OneofSizer, []interface{}{\n\t\t(*LoggingPayloadData_Msg)(nil),\n\t\t(*LoggingPayloadData_Raw)(nil),\n\t}\n}", "func (*EvalRequest) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _EvalRequest_OneofMarshaler, _EvalRequest_OneofUnmarshaler, _EvalRequest_OneofSizer, []interface{}{\n\t\t(*EvalRequest_ParsedExpr)(nil),\n\t\t(*EvalRequest_CheckedExpr)(nil),\n\t}\n}", "func (*ReadModifyWriteRule) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _ReadModifyWriteRule_OneofMarshaler, _ReadModifyWriteRule_OneofUnmarshaler, _ReadModifyWriteRule_OneofSizer, []interface{}{\n\t\t(*ReadModifyWriteRule_AppendValue)(nil),\n\t\t(*ReadModifyWriteRule_IncrementAmount)(nil),\n\t}\n}", "func (*SetConfigRequest_Entry) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _SetConfigRequest_Entry_OneofMarshaler, _SetConfigRequest_Entry_OneofUnmarshaler, _SetConfigRequest_Entry_OneofSizer, []interface{}{\n\t\t(*SetConfigRequest_Entry_ValueStr)(nil),\n\t\t(*SetConfigRequest_Entry_ValueInt32)(nil),\n\t\t(*SetConfigRequest_Entry_ValueBool)(nil),\n\t}\n}", "func (*BitmessageRPC) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _BitmessageRPC_OneofMarshaler, _BitmessageRPC_OneofUnmarshaler, _BitmessageRPC_OneofSizer, []interface{}{\n\t\t(*BitmessageRPC_Request)(nil),\n\t\t(*BitmessageRPC_Reply)(nil),\n\t\t(*BitmessageRPC_Push)(nil),\n\t}\n}", "func (*HealthCheck_Payload) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _HealthCheck_Payload_OneofMarshaler, _HealthCheck_Payload_OneofUnmarshaler, _HealthCheck_Payload_OneofSizer, []interface{}{\n\t\t(*HealthCheck_Payload_Text)(nil),\n\t\t(*HealthCheck_Payload_Binary)(nil),\n\t}\n}", "func (*FlowKey) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _FlowKey_OneofMarshaler, _FlowKey_OneofUnmarshaler, _FlowKey_OneofSizer, []interface{}{\n\t\t(*FlowKey_IPFlowKey)(nil),\n\t\t(*FlowKey_MACFlowKey)(nil),\n\t}\n}", "func (*LeafStat) XXX_OneofFuncs() (func(msg proto1.Message, b *proto1.Buffer) error, func(msg proto1.Message, tag, wire int, b *proto1.Buffer) (bool, error), func(msg proto1.Message) (n int), []interface{}) {\n\treturn _LeafStat_OneofMarshaler, _LeafStat_OneofUnmarshaler, _LeafStat_OneofSizer, []interface{}{\n\t\t(*LeafStat_Classification)(nil),\n\t\t(*LeafStat_Regression)(nil),\n\t}\n}", "func (*Metadata) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _Metadata_OneofMarshaler, _Metadata_OneofUnmarshaler, _Metadata_OneofSizer, []interface{}{\n\t\t(*Metadata_GatewayID)(nil),\n\t\t(*Metadata_DevAddrPrefix)(nil),\n\t\t(*Metadata_AppID)(nil),\n\t\t(*Metadata_AppEUI)(nil),\n\t}\n}", "func (*BitcoinRules) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _BitcoinRules_OneofMarshaler, _BitcoinRules_OneofUnmarshaler, _BitcoinRules_OneofSizer, []interface{}{\n\t\t(*BitcoinRules_Address)(nil),\n\t\t(*BitcoinRules_String_)(nil),\n\t}\n}", "func (*PolicyUpdateRequest) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _PolicyUpdateRequest_OneofMarshaler, _PolicyUpdateRequest_OneofUnmarshaler, _PolicyUpdateRequest_OneofSizer, []interface{}{\n\t\t(*PolicyUpdateRequest_Global)(nil),\n\t\t(*PolicyUpdateRequest_ChanPoint)(nil),\n\t}\n}", "func (*PolicyUpdateRequest) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _PolicyUpdateRequest_OneofMarshaler, _PolicyUpdateRequest_OneofUnmarshaler, _PolicyUpdateRequest_OneofSizer, []interface{}{\n\t\t(*PolicyUpdateRequest_Global)(nil),\n\t\t(*PolicyUpdateRequest_ChanPoint)(nil),\n\t}\n}", "func (*PolicyUpdateRequest) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _PolicyUpdateRequest_OneofMarshaler, _PolicyUpdateRequest_OneofUnmarshaler, _PolicyUpdateRequest_OneofSizer, []interface{}{\n\t\t(*PolicyUpdateRequest_Global)(nil),\n\t\t(*PolicyUpdateRequest_ChanPoint)(nil),\n\t}\n}", "func (*PolicyUpdateRequest) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _PolicyUpdateRequest_OneofMarshaler, _PolicyUpdateRequest_OneofUnmarshaler, _PolicyUpdateRequest_OneofSizer, []interface{}{\n\t\t(*PolicyUpdateRequest_Global)(nil),\n\t\t(*PolicyUpdateRequest_ChanPoint)(nil),\n\t}\n}", "func (*TriggerMessage) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _TriggerMessage_OneofMarshaler, _TriggerMessage_OneofUnmarshaler, _TriggerMessage_OneofSizer, []interface{}{\n\t\t(*TriggerMessage_Topic)(nil),\n\t\t(*TriggerMessage_Type)(nil),\n\t\t(*TriggerMessage_Event)(nil),\n\t\t(*TriggerMessage_BodyBytes)(nil),\n\t\t(*TriggerMessage_Offset)(nil),\n\t\t(*TriggerMessage_Extensions)(nil),\n\t\t(*TriggerMessage_Uuid)(nil),\n\t\t(*TriggerMessage_Bid)(nil),\n\t}\n}", "func (*Params) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _Params_OneofMarshaler, _Params_OneofUnmarshaler, _Params_OneofSizer, []interface{}{\n\t\t(*Params_AppCredentials)(nil),\n\t\t(*Params_ApiKey)(nil),\n\t\t(*Params_ServiceAccountPath)(nil),\n\t}\n}", "func (*Component) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _Component_OneofMarshaler, _Component_OneofUnmarshaler, _Component_OneofSizer, []interface{}{\n\t\t(*Component_AppengineModule)(nil),\n\t\t(*Component_GkePod)(nil),\n\t}\n}", "func (*Event) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _Event_OneofMarshaler, _Event_OneofUnmarshaler, _Event_OneofSizer, []interface{}{\n\t\t(*Event_Register)(nil),\n\t\t(*Event_Block)(nil),\n\t\t(*Event_ChaincodeEvent)(nil),\n\t\t(*Event_Rejection)(nil),\n\t\t(*Event_Unregister)(nil),\n\t}\n}", "func (*Event) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _Event_OneofMarshaler, _Event_OneofUnmarshaler, _Event_OneofSizer, []interface{}{\n\t\t(*Event_Register)(nil),\n\t\t(*Event_Block)(nil),\n\t\t(*Event_ChaincodeEvent)(nil),\n\t\t(*Event_Rejection)(nil),\n\t\t(*Event_Unregister)(nil),\n\t}\n}", "func (*InternalRequest) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _InternalRequest_OneofMarshaler, _InternalRequest_OneofUnmarshaler, _InternalRequest_OneofSizer, []interface{}{\n\t\t(*InternalRequest_PutReq)(nil),\n\t\t(*InternalRequest_GetReq)(nil),\n\t\t(*InternalRequest_DeleteReq)(nil),\n\t}\n}", "func (*Message) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _Message_OneofMarshaler, _Message_OneofUnmarshaler, _Message_OneofSizer, []interface{}{\n\t\t(*Message_Transfer)(nil),\n\t\t(*Message_Account)(nil),\n\t}\n}", "func (*StateKey) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _StateKey_OneofMarshaler, _StateKey_OneofUnmarshaler, _StateKey_OneofSizer, []interface{}{\n\t\t(*StateKey_Runner_)(nil),\n\t\t(*StateKey_MultimapSideInput_)(nil),\n\t\t(*StateKey_BagUserState_)(nil),\n\t}\n}", "func (*StateKey) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _StateKey_OneofMarshaler, _StateKey_OneofUnmarshaler, _StateKey_OneofSizer, []interface{}{\n\t\t(*StateKey_Runner_)(nil),\n\t\t(*StateKey_MultimapSideInput_)(nil),\n\t\t(*StateKey_BagUserState_)(nil),\n\t}\n}", "func (*VideoAdInfo) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _VideoAdInfo_OneofMarshaler, _VideoAdInfo_OneofUnmarshaler, _VideoAdInfo_OneofSizer, []interface{}{\n\t\t(*VideoAdInfo_InStream)(nil),\n\t}\n}", "func (*TapEvent) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _TapEvent_OneofMarshaler, _TapEvent_OneofUnmarshaler, _TapEvent_OneofSizer, []interface{}{\n\t\t(*TapEvent_Http_)(nil),\n\t}\n}", "func (*TapEvent) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _TapEvent_OneofMarshaler, _TapEvent_OneofUnmarshaler, _TapEvent_OneofSizer, []interface{}{\n\t\t(*TapEvent_Http_)(nil),\n\t}\n}", "func (*TapEvent) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _TapEvent_OneofMarshaler, _TapEvent_OneofUnmarshaler, _TapEvent_OneofSizer, []interface{}{\n\t\t(*TapEvent_Http_)(nil),\n\t}\n}", "func (*UploadBinaryRequest) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _UploadBinaryRequest_OneofMarshaler, _UploadBinaryRequest_OneofUnmarshaler, _UploadBinaryRequest_OneofSizer, []interface{}{\n\t\t(*UploadBinaryRequest_Key_)(nil),\n\t\t(*UploadBinaryRequest_Chunk_)(nil),\n\t}\n}", "func (*Metric) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _Metric_OneofMarshaler, _Metric_OneofUnmarshaler, _Metric_OneofSizer, []interface{}{\n\t\t(*Metric_I64)(nil),\n\t\t(*Metric_U64)(nil),\n\t\t(*Metric_F64)(nil),\n\t\t(*Metric_String_)(nil),\n\t\t(*Metric_Bool)(nil),\n\t\t(*Metric_Duration)(nil),\n\t}\n}", "func (*SendBitmessageRequest) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _SendBitmessageRequest_OneofMarshaler, _SendBitmessageRequest_OneofUnmarshaler, _SendBitmessageRequest_OneofSizer, []interface{}{\n\t\t(*SendBitmessageRequest_Text)(nil),\n\t}\n}", "func (*Service) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _Service_OneofMarshaler, _Service_OneofUnmarshaler, _Service_OneofSizer, []interface{}{\n\t\t(*Service_DstPort)(nil),\n\t\t(*Service_IcmpMsgType)(nil),\n\t}\n}", "func (*Event) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _Event_OneofMarshaler, _Event_OneofUnmarshaler, _Event_OneofSizer, []interface{}{\n\t\t(*Event_Error)(nil),\n\t\t(*Event_Progress)(nil),\n\t\t(*Event_Match)(nil),\n\t\t(*Event_Pagination)(nil),\n\t}\n}", "func (*Config) XXX_OneofFuncs() (func(msg proto1.Message, b *proto1.Buffer) error, func(msg proto1.Message, tag, wire int, b *proto1.Buffer) (bool, error), func(msg proto1.Message) (n int), []interface{}) {\n\treturn _Config_OneofMarshaler, _Config_OneofUnmarshaler, _Config_OneofSizer, []interface{}{\n\t\t(*Config_Custom)(nil),\n\t\t(*Config_Random)(nil),\n\t\t(*Config_Fixed)(nil),\n\t}\n}", "func (*FetchRequest) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _FetchRequest_OneofMarshaler, _FetchRequest_OneofUnmarshaler, _FetchRequest_OneofSizer, []interface{}{\n\t\t(*FetchRequest_TagMatchers)(nil),\n\t}\n}", "func (*Message) XXX_OneofFuncs() (func(msg proto1.Message, b *proto1.Buffer) error, func(msg proto1.Message, tag, wire int, b *proto1.Buffer) (bool, error), func(msg proto1.Message) (n int), []interface{}) {\n\treturn _Message_OneofMarshaler, _Message_OneofUnmarshaler, _Message_OneofSizer, []interface{}{\n\t\t(*Message_Bigint)(nil),\n\t\t(*Message_EcGroupElement)(nil),\n\t\t(*Message_Status)(nil),\n\t\t(*Message_PedersenFirst)(nil),\n\t\t(*Message_PedersenDecommitment)(nil),\n\t\t(*Message_SchnorrProofData)(nil),\n\t\t(*Message_SchnorrProofRandomData)(nil),\n\t\t(*Message_SchnorrEcProofRandomData)(nil),\n\t\t(*Message_PseudonymsysCaCertificate)(nil),\n\t\t(*Message_PseudonymsysNymGenProofRandomData)(nil),\n\t\t(*Message_PseudonymsysIssueProofRandomData)(nil),\n\t\t(*Message_DoubleBigint)(nil),\n\t\t(*Message_PseudonymsysTransferCredentialData)(nil),\n\t\t(*Message_PseudonymsysCaCertificateEc)(nil),\n\t\t(*Message_PseudonymsysNymGenProofRandomDataEc)(nil),\n\t\t(*Message_PseudonymsysIssueProofRandomDataEc)(nil),\n\t\t(*Message_PseudonymsysTransferCredentialDataEc)(nil),\n\t\t(*Message_SessionKey)(nil),\n\t}\n}", "func (*Wrapper) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _Wrapper_OneofMarshaler, _Wrapper_OneofUnmarshaler, _Wrapper_OneofSizer, []interface{}{\n\t\t(*Wrapper_Source)(nil),\n\t\t(*Wrapper_GherkinDocument)(nil),\n\t\t(*Wrapper_Pickle)(nil),\n\t\t(*Wrapper_Attachment)(nil),\n\t\t(*Wrapper_TestCaseStarted)(nil),\n\t\t(*Wrapper_TestStepStarted)(nil),\n\t\t(*Wrapper_TestStepFinished)(nil),\n\t\t(*Wrapper_TestCaseFinished)(nil),\n\t\t(*Wrapper_TestHookStarted)(nil),\n\t\t(*Wrapper_TestHookFinished)(nil),\n\t}\n}", "func (*StateRequest) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _StateRequest_OneofMarshaler, _StateRequest_OneofUnmarshaler, _StateRequest_OneofSizer, []interface{}{\n\t\t(*StateRequest_Get)(nil),\n\t\t(*StateRequest_Append)(nil),\n\t\t(*StateRequest_Clear)(nil),\n\t}\n}", "func (*StateRequest) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _StateRequest_OneofMarshaler, _StateRequest_OneofUnmarshaler, _StateRequest_OneofSizer, []interface{}{\n\t\t(*StateRequest_Get)(nil),\n\t\t(*StateRequest_Append)(nil),\n\t\t(*StateRequest_Clear)(nil),\n\t}\n}", "func (*NetworkAddress) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _NetworkAddress_OneofMarshaler, _NetworkAddress_OneofUnmarshaler, _NetworkAddress_OneofSizer, []interface{}{\n\t\t(*NetworkAddress_Ipv4Address)(nil),\n\t\t(*NetworkAddress_Ipv6Address)(nil),\n\t\t(*NetworkAddress_LocalAddress)(nil),\n\t}\n}", "func (*NetworkAddress) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _NetworkAddress_OneofMarshaler, _NetworkAddress_OneofUnmarshaler, _NetworkAddress_OneofSizer, []interface{}{\n\t\t(*NetworkAddress_Ipv4Address)(nil),\n\t\t(*NetworkAddress_Ipv6Address)(nil),\n\t\t(*NetworkAddress_LocalAddress)(nil),\n\t}\n}", "func (*Event) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _Event_OneofMarshaler, _Event_OneofUnmarshaler, _Event_OneofSizer, []interface{}{\n\t\t(*Event_ResourceHeader)(nil),\n\t\t(*Event_CertAuthority)(nil),\n\t\t(*Event_StaticTokens)(nil),\n\t\t(*Event_ProvisionToken)(nil),\n\t\t(*Event_ClusterName)(nil),\n\t\t(*Event_ClusterConfig)(nil),\n\t\t(*Event_User)(nil),\n\t\t(*Event_Role)(nil),\n\t\t(*Event_Namespace)(nil),\n\t\t(*Event_Server)(nil),\n\t\t(*Event_ReverseTunnel)(nil),\n\t\t(*Event_TunnelConnection)(nil),\n\t\t(*Event_AccessRequest)(nil),\n\t}\n}", "func (*RPC) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _RPC_OneofMarshaler, _RPC_OneofUnmarshaler, _RPC_OneofSizer, []interface{}{\n\t\t(*RPC_Args)(nil),\n\t\t(*RPC_ByteArgs)(nil),\n\t}\n}", "func (*FeeUpdateRequest) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _FeeUpdateRequest_OneofMarshaler, _FeeUpdateRequest_OneofUnmarshaler, _FeeUpdateRequest_OneofSizer, []interface{}{\n\t\t(*FeeUpdateRequest_Global)(nil),\n\t\t(*FeeUpdateRequest_ChanPoint)(nil),\n\t}\n}", "func (*FeeUpdateRequest) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _FeeUpdateRequest_OneofMarshaler, _FeeUpdateRequest_OneofUnmarshaler, _FeeUpdateRequest_OneofSizer, []interface{}{\n\t\t(*FeeUpdateRequest_Global)(nil),\n\t\t(*FeeUpdateRequest_ChanPoint)(nil),\n\t}\n}", "func (*ServiceSpec) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _ServiceSpec_OneofMarshaler, _ServiceSpec_OneofUnmarshaler, _ServiceSpec_OneofSizer, []interface{}{\n\t\t(*ServiceSpec_Replicated)(nil),\n\t\t(*ServiceSpec_Global)(nil),\n\t}\n}", "func (*ServiceSpec) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _ServiceSpec_OneofMarshaler, _ServiceSpec_OneofUnmarshaler, _ServiceSpec_OneofSizer, []interface{}{\n\t\t(*ServiceSpec_Replicated)(nil),\n\t\t(*ServiceSpec_Global)(nil),\n\t}\n}", "func (*ServiceSpec) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _ServiceSpec_OneofMarshaler, _ServiceSpec_OneofUnmarshaler, _ServiceSpec_OneofSizer, []interface{}{\n\t\t(*ServiceSpec_Replicated)(nil),\n\t\t(*ServiceSpec_Global)(nil),\n\t}\n}", "func (*TestUTF8) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _TestUTF8_OneofMarshaler, _TestUTF8_OneofUnmarshaler, _TestUTF8_OneofSizer, []interface{}{\n\t\t(*TestUTF8_Field)(nil),\n\t}\n}", "func (*TestUTF8) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _TestUTF8_OneofMarshaler, _TestUTF8_OneofUnmarshaler, _TestUTF8_OneofSizer, []interface{}{\n\t\t(*TestUTF8_Field)(nil),\n\t}\n}", "func (*RecordKey) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _RecordKey_OneofMarshaler, _RecordKey_OneofUnmarshaler, _RecordKey_OneofSizer, []interface{}{\n\t\t(*RecordKey_DatastoreKey)(nil),\n\t\t(*RecordKey_BigQueryKey)(nil),\n\t}\n}", "func (*Eos) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _Eos_OneofMarshaler, _Eos_OneofUnmarshaler, _Eos_OneofSizer, []interface{}{\n\t\t(*Eos_GrpcStatusCode)(nil),\n\t\t(*Eos_ResetErrorCode)(nil),\n\t}\n}", "func (*Eos) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _Eos_OneofMarshaler, _Eos_OneofUnmarshaler, _Eos_OneofSizer, []interface{}{\n\t\t(*Eos_GrpcStatusCode)(nil),\n\t\t(*Eos_ResetErrorCode)(nil),\n\t}\n}", "func (*WatchRequest) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _WatchRequest_OneofMarshaler, _WatchRequest_OneofUnmarshaler, _WatchRequest_OneofSizer, []interface{}{\n\t\t(*WatchRequest_CreateRequest)(nil),\n\t\t(*WatchRequest_CancelRequest)(nil),\n\t}\n}", "func (*FeedMapping) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _FeedMapping_OneofMarshaler, _FeedMapping_OneofUnmarshaler, _FeedMapping_OneofSizer, []interface{}{\n\t\t(*FeedMapping_PlaceholderType)(nil),\n\t\t(*FeedMapping_CriterionType)(nil),\n\t}\n}", "func (*Node) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _Node_OneofMarshaler, _Node_OneofUnmarshaler, _Node_OneofSizer, []interface{}{\n\t\t(*Node_Src)(nil),\n\t\t(*Node_Snk)(nil),\n\t\t(*Node_ContentHash)(nil),\n\t}\n}", "func (*Virtual) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _Virtual_OneofMarshaler, _Virtual_OneofUnmarshaler, _Virtual_OneofSizer, []interface{}{\n\t\t(*Virtual_Genesis)(nil),\n\t\t(*Virtual_Child)(nil),\n\t\t(*Virtual_Jet)(nil),\n\t\t(*Virtual_IncomingRequest)(nil),\n\t\t(*Virtual_OutgoingRequest)(nil),\n\t\t(*Virtual_Result)(nil),\n\t\t(*Virtual_Type)(nil),\n\t\t(*Virtual_Code)(nil),\n\t\t(*Virtual_Activate)(nil),\n\t\t(*Virtual_Amend)(nil),\n\t\t(*Virtual_Deactivate)(nil),\n\t\t(*Virtual_PendingFilament)(nil),\n\t}\n}", "func (*CloseStatusUpdate) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _CloseStatusUpdate_OneofMarshaler, _CloseStatusUpdate_OneofUnmarshaler, _CloseStatusUpdate_OneofSizer, []interface{}{\n\t\t(*CloseStatusUpdate_ClosePending)(nil),\n\t\t(*CloseStatusUpdate_Confirmation)(nil),\n\t\t(*CloseStatusUpdate_ChanClose)(nil),\n\t}\n}", "func (*CloseStatusUpdate) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _CloseStatusUpdate_OneofMarshaler, _CloseStatusUpdate_OneofUnmarshaler, _CloseStatusUpdate_OneofSizer, []interface{}{\n\t\t(*CloseStatusUpdate_ClosePending)(nil),\n\t\t(*CloseStatusUpdate_Confirmation)(nil),\n\t\t(*CloseStatusUpdate_ChanClose)(nil),\n\t}\n}", "func (*CloseStatusUpdate) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _CloseStatusUpdate_OneofMarshaler, _CloseStatusUpdate_OneofUnmarshaler, _CloseStatusUpdate_OneofSizer, []interface{}{\n\t\t(*CloseStatusUpdate_ClosePending)(nil),\n\t\t(*CloseStatusUpdate_Confirmation)(nil),\n\t\t(*CloseStatusUpdate_ChanClose)(nil),\n\t}\n}", "func (*CloseStatusUpdate) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _CloseStatusUpdate_OneofMarshaler, _CloseStatusUpdate_OneofUnmarshaler, _CloseStatusUpdate_OneofSizer, []interface{}{\n\t\t(*CloseStatusUpdate_ClosePending)(nil),\n\t\t(*CloseStatusUpdate_Confirmation)(nil),\n\t\t(*CloseStatusUpdate_ChanClose)(nil),\n\t}\n}", "func (*CloseStatusUpdate) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _CloseStatusUpdate_OneofMarshaler, _CloseStatusUpdate_OneofUnmarshaler, _CloseStatusUpdate_OneofSizer, []interface{}{\n\t\t(*CloseStatusUpdate_ClosePending)(nil),\n\t\t(*CloseStatusUpdate_ChanClose)(nil),\n\t}\n}", "func (*CloseStatusUpdate) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _CloseStatusUpdate_OneofMarshaler, _CloseStatusUpdate_OneofUnmarshaler, _CloseStatusUpdate_OneofSizer, []interface{}{\n\t\t(*CloseStatusUpdate_ClosePending)(nil),\n\t\t(*CloseStatusUpdate_ChanClose)(nil),\n\t}\n}", "func (*CloseStatusUpdate) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _CloseStatusUpdate_OneofMarshaler, _CloseStatusUpdate_OneofUnmarshaler, _CloseStatusUpdate_OneofSizer, []interface{}{\n\t\t(*CloseStatusUpdate_ClosePending)(nil),\n\t\t(*CloseStatusUpdate_ChanClose)(nil),\n\t}\n}", "func (*PrintKVRequest) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _PrintKVRequest_OneofMarshaler, _PrintKVRequest_OneofUnmarshaler, _PrintKVRequest_OneofSizer, []interface{}{\n\t\t(*PrintKVRequest_ValueString)(nil),\n\t\t(*PrintKVRequest_ValueInt)(nil),\n\t}\n}", "func (*Identity) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _Identity_OneofMarshaler, _Identity_OneofUnmarshaler, _Identity_OneofSizer, []interface{}{\n\t\t(*Identity_ServiceAccount)(nil),\n\t\t(*Identity_Hostname)(nil),\n\t}\n}", "func (*ChannelEventUpdate) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _ChannelEventUpdate_OneofMarshaler, _ChannelEventUpdate_OneofUnmarshaler, _ChannelEventUpdate_OneofSizer, []interface{}{\n\t\t(*ChannelEventUpdate_OpenChannel)(nil),\n\t\t(*ChannelEventUpdate_ClosedChannel)(nil),\n\t\t(*ChannelEventUpdate_ActiveChannel)(nil),\n\t\t(*ChannelEventUpdate_InactiveChannel)(nil),\n\t}\n}", "func (*ChannelEventUpdate) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _ChannelEventUpdate_OneofMarshaler, _ChannelEventUpdate_OneofUnmarshaler, _ChannelEventUpdate_OneofSizer, []interface{}{\n\t\t(*ChannelEventUpdate_OpenChannel)(nil),\n\t\t(*ChannelEventUpdate_ClosedChannel)(nil),\n\t\t(*ChannelEventUpdate_ActiveChannel)(nil),\n\t\t(*ChannelEventUpdate_InactiveChannel)(nil),\n\t}\n}" ]
[ "0.8906545", "0.89049524", "0.88898444", "0.88690525", "0.8867597", "0.8862553", "0.886212", "0.88620526", "0.886116", "0.88607055", "0.88589394", "0.8854383", "0.88530225", "0.8851815", "0.8851815", "0.8851815", "0.8847126", "0.88462305", "0.88442457", "0.8843731", "0.8841164", "0.8835988", "0.8835988", "0.8835988", "0.8835988", "0.8835916", "0.8833987", "0.8833987", "0.8833987", "0.8833987", "0.8833987", "0.8833987", "0.8832893", "0.88300425", "0.8829843", "0.88297045", "0.8829676", "0.8827936", "0.88276094", "0.88268787", "0.8823665", "0.8823105", "0.8822916", "0.88210195", "0.88178575", "0.88178575", "0.88178575", "0.88178575", "0.8813846", "0.8811961", "0.8810305", "0.88092375", "0.88092375", "0.88075525", "0.88073456", "0.8807054", "0.8807054", "0.8805402", "0.8804638", "0.8804638", "0.8804638", "0.8804055", "0.880368", "0.88027626", "0.88023484", "0.88019156", "0.88011354", "0.8800475", "0.8798684", "0.8798424", "0.8796181", "0.8796181", "0.87943184", "0.87943184", "0.8794047", "0.8791536", "0.8790553", "0.8790553", "0.87904984", "0.87904984", "0.87904984", "0.8788805", "0.8788805", "0.8787674", "0.87874645", "0.87874645", "0.8787047", "0.8786051", "0.8785734", "0.87852675", "0.8784568", "0.8784568", "0.8784568", "0.8784568", "0.8784395", "0.8784395", "0.8784395", "0.87834555", "0.87816393", "0.87815166", "0.87815166" ]
0.0
-1
XXX_OneofFuncs is for the internal use of the proto package.
func (*TestUTF8) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) { return _TestUTF8_OneofMarshaler, _TestUTF8_OneofUnmarshaler, _TestUTF8_OneofSizer, []interface{}{ (*TestUTF8_Field)(nil), } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (*EncapVal) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _EncapVal_OneofMarshaler, _EncapVal_OneofUnmarshaler, _EncapVal_OneofSizer, []interface{}{\n\t\t(*EncapVal_VlanId)(nil),\n\t\t(*EncapVal_MPLSTag)(nil),\n\t\t(*EncapVal_Vnid)(nil),\n\t\t(*EncapVal_QinQ)(nil),\n\t}\n}", "func (*FlowL4Info) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _FlowL4Info_OneofMarshaler, _FlowL4Info_OneofUnmarshaler, _FlowL4Info_OneofSizer, []interface{}{\n\t\t(*FlowL4Info_TcpUdpInfo)(nil),\n\t\t(*FlowL4Info_IcmpInfo)(nil),\n\t}\n}", "func (*Msg) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _Msg_OneofMarshaler, _Msg_OneofUnmarshaler, _Msg_OneofSizer, []interface{}{\n\t\t(*Msg_Request)(nil),\n\t\t(*Msg_Preprepare)(nil),\n\t\t(*Msg_Prepare)(nil),\n\t\t(*Msg_Commit)(nil),\n\t\t(*Msg_ViewChange)(nil),\n\t\t(*Msg_NewView)(nil),\n\t\t(*Msg_Checkpoint)(nil),\n\t\t(*Msg_Hello)(nil),\n\t}\n}", "func (*RuleL4Match) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _RuleL4Match_OneofMarshaler, _RuleL4Match_OneofUnmarshaler, _RuleL4Match_OneofSizer, []interface{}{\n\t\t(*RuleL4Match_Ports)(nil),\n\t\t(*RuleL4Match_TypeCode)(nil),\n\t}\n}", "func (*Example) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _Example_OneofMarshaler, _Example_OneofUnmarshaler, _Example_OneofSizer, []interface{}{\n\t\t(*Example_ImagePayload)(nil),\n\t\t(*Example_TextPayload)(nil),\n\t\t(*Example_VideoPayload)(nil),\n\t\t(*Example_AudioPayload)(nil),\n\t}\n}", "func (*Metric) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _Metric_OneofMarshaler, _Metric_OneofUnmarshaler, _Metric_OneofSizer, []interface{}{\n\t\t(*Metric_StringData)(nil),\n\t\t(*Metric_Float32Data)(nil),\n\t\t(*Metric_Float64Data)(nil),\n\t\t(*Metric_Int32Data)(nil),\n\t\t(*Metric_Int64Data)(nil),\n\t\t(*Metric_BytesData)(nil),\n\t\t(*Metric_BoolData)(nil),\n\t\t(*Metric_Uint32Data)(nil),\n\t\t(*Metric_Uint64Data)(nil),\n\t}\n}", "func (*Interface) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _Interface_OneofMarshaler, _Interface_OneofUnmarshaler, _Interface_OneofSizer, []interface{}{\n\t\t(*Interface_Sub)(nil),\n\t\t(*Interface_Memif)(nil),\n\t\t(*Interface_Afpacket)(nil),\n\t\t(*Interface_Tap)(nil),\n\t\t(*Interface_Vxlan)(nil),\n\t\t(*Interface_Ipsec)(nil),\n\t\t(*Interface_VmxNet3)(nil),\n\t}\n}", "func (*Metadata) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _Metadata_OneofMarshaler, _Metadata_OneofUnmarshaler, _Metadata_OneofSizer, []interface{}{\n\t\t(*Metadata_DevAddrPrefix)(nil),\n\t\t(*Metadata_AppId)(nil),\n\t\t(*Metadata_AppEui)(nil),\n\t}\n}", "func (*Message) XXX_OneofFuncs() (func(msg proto1.Message, b *proto1.Buffer) error, func(msg proto1.Message, tag, wire int, b *proto1.Buffer) (bool, error), func(msg proto1.Message) (n int), []interface{}) {\n\treturn _Message_OneofMarshaler, _Message_OneofUnmarshaler, _Message_OneofSizer, []interface{}{\n\t\t(*Message_ExecStarted)(nil),\n\t\t(*Message_ExecCompleted)(nil),\n\t\t(*Message_ExecOutput)(nil),\n\t\t(*Message_LogEntry)(nil),\n\t\t(*Message_Error)(nil),\n\t}\n}", "func (*Message) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _Message_OneofMarshaler, _Message_OneofUnmarshaler, _Message_OneofSizer, []interface{}{\n\t\t(*Message_Chunk)(nil),\n\t\t(*Message_Status)(nil),\n\t}\n}", "func (*Message) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _Message_OneofMarshaler, _Message_OneofUnmarshaler, _Message_OneofSizer, []interface{}{\n\t\t(*Message_OpenPayload)(nil),\n\t\t(*Message_ClosePayload)(nil),\n\t\t(*Message_DataPayload)(nil),\n\t}\n}", "func (*BMRPCRequest) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _BMRPCRequest_OneofMarshaler, _BMRPCRequest_OneofUnmarshaler, _BMRPCRequest_OneofSizer, []interface{}{\n\t\t(*BMRPCRequest_Newaddress)(nil),\n\t\t(*BMRPCRequest_Help)(nil),\n\t\t(*BMRPCRequest_Listaddresses)(nil),\n\t}\n}", "func (*Interface) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _Interface_OneofMarshaler, _Interface_OneofUnmarshaler, _Interface_OneofSizer, []interface{}{\n\t\t(*Interface_Sub)(nil),\n\t\t(*Interface_Memif)(nil),\n\t\t(*Interface_Afpacket)(nil),\n\t\t(*Interface_Tap)(nil),\n\t\t(*Interface_Vxlan)(nil),\n\t\t(*Interface_Ipsec)(nil),\n\t\t(*Interface_VmxNet3)(nil),\n\t\t(*Interface_Bond)(nil),\n\t}\n}", "func (*OpenStatusUpdate) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _OpenStatusUpdate_OneofMarshaler, _OpenStatusUpdate_OneofUnmarshaler, _OpenStatusUpdate_OneofSizer, []interface{}{\n\t\t(*OpenStatusUpdate_ChanPending)(nil),\n\t\t(*OpenStatusUpdate_ChanOpen)(nil),\n\t}\n}", "func (*OpenStatusUpdate) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _OpenStatusUpdate_OneofMarshaler, _OpenStatusUpdate_OneofUnmarshaler, _OpenStatusUpdate_OneofSizer, []interface{}{\n\t\t(*OpenStatusUpdate_ChanPending)(nil),\n\t\t(*OpenStatusUpdate_ChanOpen)(nil),\n\t}\n}", "func (*OpenStatusUpdate) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _OpenStatusUpdate_OneofMarshaler, _OpenStatusUpdate_OneofUnmarshaler, _OpenStatusUpdate_OneofSizer, []interface{}{\n\t\t(*OpenStatusUpdate_ChanPending)(nil),\n\t\t(*OpenStatusUpdate_ChanOpen)(nil),\n\t}\n}", "func (*StatTable) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _StatTable_OneofMarshaler, _StatTable_OneofUnmarshaler, _StatTable_OneofSizer, []interface{}{\n\t\t(*StatTable_PodGroup_)(nil),\n\t}\n}", "func (*Bitmessage) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _Bitmessage_OneofMarshaler, _Bitmessage_OneofUnmarshaler, _Bitmessage_OneofSizer, []interface{}{\n\t\t(*Bitmessage_Text)(nil),\n\t}\n}", "func (*WriteReq) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _WriteReq_OneofMarshaler, _WriteReq_OneofUnmarshaler, _WriteReq_OneofSizer, []interface{}{\n\t\t(*WriteReq_Name)(nil),\n\t\t(*WriteReq_Blob)(nil),\n\t}\n}", "func (*RunnerMsg) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _RunnerMsg_OneofMarshaler, _RunnerMsg_OneofUnmarshaler, _RunnerMsg_OneofSizer, []interface{}{\n\t\t(*RunnerMsg_Acknowledged)(nil),\n\t\t(*RunnerMsg_ResultStart)(nil),\n\t\t(*RunnerMsg_Data)(nil),\n\t\t(*RunnerMsg_Finished)(nil),\n\t}\n}", "func (*DiscoveryInfo) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _DiscoveryInfo_OneofMarshaler, _DiscoveryInfo_OneofUnmarshaler, _DiscoveryInfo_OneofSizer, []interface{}{\n\t\t(*DiscoveryInfo_Inflated)(nil),\n\t\t(*DiscoveryInfo_BlobAdded)(nil),\n\t\t(*DiscoveryInfo_BlobRemoved)(nil),\n\t}\n}", "func (*Event) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _Event_OneofMarshaler, _Event_OneofUnmarshaler, _Event_OneofSizer, []interface{}{\n\t\t(*Event_Read_)(nil),\n\t\t(*Event_Write_)(nil),\n\t}\n}", "func (*OpenStatusUpdate) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _OpenStatusUpdate_OneofMarshaler, _OpenStatusUpdate_OneofUnmarshaler, _OpenStatusUpdate_OneofSizer, []interface{}{\n\t\t(*OpenStatusUpdate_ChanPending)(nil),\n\t\t(*OpenStatusUpdate_Confirmation)(nil),\n\t\t(*OpenStatusUpdate_ChanOpen)(nil),\n\t}\n}", "func (*OpenStatusUpdate) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _OpenStatusUpdate_OneofMarshaler, _OpenStatusUpdate_OneofUnmarshaler, _OpenStatusUpdate_OneofSizer, []interface{}{\n\t\t(*OpenStatusUpdate_ChanPending)(nil),\n\t\t(*OpenStatusUpdate_Confirmation)(nil),\n\t\t(*OpenStatusUpdate_ChanOpen)(nil),\n\t}\n}", "func (*OpenStatusUpdate) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _OpenStatusUpdate_OneofMarshaler, _OpenStatusUpdate_OneofUnmarshaler, _OpenStatusUpdate_OneofSizer, []interface{}{\n\t\t(*OpenStatusUpdate_ChanPending)(nil),\n\t\t(*OpenStatusUpdate_Confirmation)(nil),\n\t\t(*OpenStatusUpdate_ChanOpen)(nil),\n\t}\n}", "func (*OpenStatusUpdate) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _OpenStatusUpdate_OneofMarshaler, _OpenStatusUpdate_OneofUnmarshaler, _OpenStatusUpdate_OneofSizer, []interface{}{\n\t\t(*OpenStatusUpdate_ChanPending)(nil),\n\t\t(*OpenStatusUpdate_Confirmation)(nil),\n\t\t(*OpenStatusUpdate_ChanOpen)(nil),\n\t}\n}", "func (*TwoOneofs) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _TwoOneofs_OneofMarshaler, _TwoOneofs_OneofUnmarshaler, _TwoOneofs_OneofSizer, []interface{}{\n\t\t(*TwoOneofs_Field1)(nil),\n\t\t(*TwoOneofs_Field2)(nil),\n\t\t(*TwoOneofs_Field3)(nil),\n\t\t(*TwoOneofs_Field34)(nil),\n\t\t(*TwoOneofs_Field35)(nil),\n\t\t(*TwoOneofs_SubMessage2)(nil),\n\t}\n}", "func (*TwoOneofs) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _TwoOneofs_OneofMarshaler, _TwoOneofs_OneofUnmarshaler, _TwoOneofs_OneofSizer, []interface{}{\n\t\t(*TwoOneofs_Field1)(nil),\n\t\t(*TwoOneofs_Field2)(nil),\n\t\t(*TwoOneofs_Field3)(nil),\n\t\t(*TwoOneofs_Field34)(nil),\n\t\t(*TwoOneofs_Field35)(nil),\n\t\t(*TwoOneofs_SubMessage2)(nil),\n\t}\n}", "func (*TwoOneofs) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _TwoOneofs_OneofMarshaler, _TwoOneofs_OneofUnmarshaler, _TwoOneofs_OneofSizer, []interface{}{\n\t\t(*TwoOneofs_Field1)(nil),\n\t\t(*TwoOneofs_Field2)(nil),\n\t\t(*TwoOneofs_Field3)(nil),\n\t\t(*TwoOneofs_Field34)(nil),\n\t\t(*TwoOneofs_Field35)(nil),\n\t\t(*TwoOneofs_SubMessage2)(nil),\n\t}\n}", "func (*TwoOneofs) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _TwoOneofs_OneofMarshaler, _TwoOneofs_OneofUnmarshaler, _TwoOneofs_OneofSizer, []interface{}{\n\t\t(*TwoOneofs_Field1)(nil),\n\t\t(*TwoOneofs_Field2)(nil),\n\t\t(*TwoOneofs_Field3)(nil),\n\t\t(*TwoOneofs_Field34)(nil),\n\t\t(*TwoOneofs_Field35)(nil),\n\t\t(*TwoOneofs_SubMessage2)(nil),\n\t}\n}", "func (*TwoOneofs) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _TwoOneofs_OneofMarshaler, _TwoOneofs_OneofUnmarshaler, _TwoOneofs_OneofSizer, []interface{}{\n\t\t(*TwoOneofs_Field1)(nil),\n\t\t(*TwoOneofs_Field2)(nil),\n\t\t(*TwoOneofs_Field3)(nil),\n\t\t(*TwoOneofs_Field34)(nil),\n\t\t(*TwoOneofs_Field35)(nil),\n\t\t(*TwoOneofs_SubMessage2)(nil),\n\t}\n}", "func (*TwoOneofs) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _TwoOneofs_OneofMarshaler, _TwoOneofs_OneofUnmarshaler, _TwoOneofs_OneofSizer, []interface{}{\n\t\t(*TwoOneofs_Field1)(nil),\n\t\t(*TwoOneofs_Field2)(nil),\n\t\t(*TwoOneofs_Field3)(nil),\n\t\t(*TwoOneofs_Field34)(nil),\n\t\t(*TwoOneofs_Field35)(nil),\n\t\t(*TwoOneofs_SubMessage2)(nil),\n\t}\n}", "func (*Message) XXX_OneofFuncs() (func(msg proto1.Message, b *proto1.Buffer) error, func(msg proto1.Message, tag, wire int, b *proto1.Buffer) (bool, error), func(msg proto1.Message) (n int), []interface{}) {\n\treturn _Message_OneofMarshaler, _Message_OneofUnmarshaler, _Message_OneofSizer, []interface{}{\n\t\t(*Message_Signin)(nil),\n\t\t(*Message_Chatmsg)(nil),\n\t}\n}", "func (*LoggingPayloadData) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _LoggingPayloadData_OneofMarshaler, _LoggingPayloadData_OneofUnmarshaler, _LoggingPayloadData_OneofSizer, []interface{}{\n\t\t(*LoggingPayloadData_Msg)(nil),\n\t\t(*LoggingPayloadData_Raw)(nil),\n\t}\n}", "func (*EvalRequest) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _EvalRequest_OneofMarshaler, _EvalRequest_OneofUnmarshaler, _EvalRequest_OneofSizer, []interface{}{\n\t\t(*EvalRequest_ParsedExpr)(nil),\n\t\t(*EvalRequest_CheckedExpr)(nil),\n\t}\n}", "func (*Header) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _Header_OneofMarshaler, _Header_OneofUnmarshaler, _Header_OneofSizer, []interface{}{\n\t\t(*Header_Version)(nil),\n\t\t(*Header_SourceType)(nil),\n\t\t(*Header_EventType)(nil),\n\t}\n}", "func (*ReadModifyWriteRule) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _ReadModifyWriteRule_OneofMarshaler, _ReadModifyWriteRule_OneofUnmarshaler, _ReadModifyWriteRule_OneofSizer, []interface{}{\n\t\t(*ReadModifyWriteRule_AppendValue)(nil),\n\t\t(*ReadModifyWriteRule_IncrementAmount)(nil),\n\t}\n}", "func (*BitmessageRPC) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _BitmessageRPC_OneofMarshaler, _BitmessageRPC_OneofUnmarshaler, _BitmessageRPC_OneofSizer, []interface{}{\n\t\t(*BitmessageRPC_Request)(nil),\n\t\t(*BitmessageRPC_Reply)(nil),\n\t\t(*BitmessageRPC_Push)(nil),\n\t}\n}", "func (*SetConfigRequest_Entry) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _SetConfigRequest_Entry_OneofMarshaler, _SetConfigRequest_Entry_OneofUnmarshaler, _SetConfigRequest_Entry_OneofSizer, []interface{}{\n\t\t(*SetConfigRequest_Entry_ValueStr)(nil),\n\t\t(*SetConfigRequest_Entry_ValueInt32)(nil),\n\t\t(*SetConfigRequest_Entry_ValueBool)(nil),\n\t}\n}", "func (*HealthCheck_Payload) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _HealthCheck_Payload_OneofMarshaler, _HealthCheck_Payload_OneofUnmarshaler, _HealthCheck_Payload_OneofSizer, []interface{}{\n\t\t(*HealthCheck_Payload_Text)(nil),\n\t\t(*HealthCheck_Payload_Binary)(nil),\n\t}\n}", "func (*FlowKey) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _FlowKey_OneofMarshaler, _FlowKey_OneofUnmarshaler, _FlowKey_OneofSizer, []interface{}{\n\t\t(*FlowKey_IPFlowKey)(nil),\n\t\t(*FlowKey_MACFlowKey)(nil),\n\t}\n}", "func (*LeafStat) XXX_OneofFuncs() (func(msg proto1.Message, b *proto1.Buffer) error, func(msg proto1.Message, tag, wire int, b *proto1.Buffer) (bool, error), func(msg proto1.Message) (n int), []interface{}) {\n\treturn _LeafStat_OneofMarshaler, _LeafStat_OneofUnmarshaler, _LeafStat_OneofSizer, []interface{}{\n\t\t(*LeafStat_Classification)(nil),\n\t\t(*LeafStat_Regression)(nil),\n\t}\n}", "func (*Metadata) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _Metadata_OneofMarshaler, _Metadata_OneofUnmarshaler, _Metadata_OneofSizer, []interface{}{\n\t\t(*Metadata_GatewayID)(nil),\n\t\t(*Metadata_DevAddrPrefix)(nil),\n\t\t(*Metadata_AppID)(nil),\n\t\t(*Metadata_AppEUI)(nil),\n\t}\n}", "func (*BitcoinRules) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _BitcoinRules_OneofMarshaler, _BitcoinRules_OneofUnmarshaler, _BitcoinRules_OneofSizer, []interface{}{\n\t\t(*BitcoinRules_Address)(nil),\n\t\t(*BitcoinRules_String_)(nil),\n\t}\n}", "func (*PolicyUpdateRequest) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _PolicyUpdateRequest_OneofMarshaler, _PolicyUpdateRequest_OneofUnmarshaler, _PolicyUpdateRequest_OneofSizer, []interface{}{\n\t\t(*PolicyUpdateRequest_Global)(nil),\n\t\t(*PolicyUpdateRequest_ChanPoint)(nil),\n\t}\n}", "func (*PolicyUpdateRequest) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _PolicyUpdateRequest_OneofMarshaler, _PolicyUpdateRequest_OneofUnmarshaler, _PolicyUpdateRequest_OneofSizer, []interface{}{\n\t\t(*PolicyUpdateRequest_Global)(nil),\n\t\t(*PolicyUpdateRequest_ChanPoint)(nil),\n\t}\n}", "func (*PolicyUpdateRequest) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _PolicyUpdateRequest_OneofMarshaler, _PolicyUpdateRequest_OneofUnmarshaler, _PolicyUpdateRequest_OneofSizer, []interface{}{\n\t\t(*PolicyUpdateRequest_Global)(nil),\n\t\t(*PolicyUpdateRequest_ChanPoint)(nil),\n\t}\n}", "func (*PolicyUpdateRequest) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _PolicyUpdateRequest_OneofMarshaler, _PolicyUpdateRequest_OneofUnmarshaler, _PolicyUpdateRequest_OneofSizer, []interface{}{\n\t\t(*PolicyUpdateRequest_Global)(nil),\n\t\t(*PolicyUpdateRequest_ChanPoint)(nil),\n\t}\n}", "func (*TriggerMessage) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _TriggerMessage_OneofMarshaler, _TriggerMessage_OneofUnmarshaler, _TriggerMessage_OneofSizer, []interface{}{\n\t\t(*TriggerMessage_Topic)(nil),\n\t\t(*TriggerMessage_Type)(nil),\n\t\t(*TriggerMessage_Event)(nil),\n\t\t(*TriggerMessage_BodyBytes)(nil),\n\t\t(*TriggerMessage_Offset)(nil),\n\t\t(*TriggerMessage_Extensions)(nil),\n\t\t(*TriggerMessage_Uuid)(nil),\n\t\t(*TriggerMessage_Bid)(nil),\n\t}\n}", "func (*Params) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _Params_OneofMarshaler, _Params_OneofUnmarshaler, _Params_OneofSizer, []interface{}{\n\t\t(*Params_AppCredentials)(nil),\n\t\t(*Params_ApiKey)(nil),\n\t\t(*Params_ServiceAccountPath)(nil),\n\t}\n}", "func (*Component) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _Component_OneofMarshaler, _Component_OneofUnmarshaler, _Component_OneofSizer, []interface{}{\n\t\t(*Component_AppengineModule)(nil),\n\t\t(*Component_GkePod)(nil),\n\t}\n}", "func (*Event) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _Event_OneofMarshaler, _Event_OneofUnmarshaler, _Event_OneofSizer, []interface{}{\n\t\t(*Event_Register)(nil),\n\t\t(*Event_Block)(nil),\n\t\t(*Event_ChaincodeEvent)(nil),\n\t\t(*Event_Rejection)(nil),\n\t\t(*Event_Unregister)(nil),\n\t}\n}", "func (*Event) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _Event_OneofMarshaler, _Event_OneofUnmarshaler, _Event_OneofSizer, []interface{}{\n\t\t(*Event_Register)(nil),\n\t\t(*Event_Block)(nil),\n\t\t(*Event_ChaincodeEvent)(nil),\n\t\t(*Event_Rejection)(nil),\n\t\t(*Event_Unregister)(nil),\n\t}\n}", "func (*StateKey) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _StateKey_OneofMarshaler, _StateKey_OneofUnmarshaler, _StateKey_OneofSizer, []interface{}{\n\t\t(*StateKey_Runner_)(nil),\n\t\t(*StateKey_MultimapSideInput_)(nil),\n\t\t(*StateKey_BagUserState_)(nil),\n\t}\n}", "func (*StateKey) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _StateKey_OneofMarshaler, _StateKey_OneofUnmarshaler, _StateKey_OneofSizer, []interface{}{\n\t\t(*StateKey_Runner_)(nil),\n\t\t(*StateKey_MultimapSideInput_)(nil),\n\t\t(*StateKey_BagUserState_)(nil),\n\t}\n}", "func (*InternalRequest) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _InternalRequest_OneofMarshaler, _InternalRequest_OneofUnmarshaler, _InternalRequest_OneofSizer, []interface{}{\n\t\t(*InternalRequest_PutReq)(nil),\n\t\t(*InternalRequest_GetReq)(nil),\n\t\t(*InternalRequest_DeleteReq)(nil),\n\t}\n}", "func (*Message) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _Message_OneofMarshaler, _Message_OneofUnmarshaler, _Message_OneofSizer, []interface{}{\n\t\t(*Message_Transfer)(nil),\n\t\t(*Message_Account)(nil),\n\t}\n}", "func (*VideoAdInfo) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _VideoAdInfo_OneofMarshaler, _VideoAdInfo_OneofUnmarshaler, _VideoAdInfo_OneofSizer, []interface{}{\n\t\t(*VideoAdInfo_InStream)(nil),\n\t}\n}", "func (*TapEvent) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _TapEvent_OneofMarshaler, _TapEvent_OneofUnmarshaler, _TapEvent_OneofSizer, []interface{}{\n\t\t(*TapEvent_Http_)(nil),\n\t}\n}", "func (*TapEvent) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _TapEvent_OneofMarshaler, _TapEvent_OneofUnmarshaler, _TapEvent_OneofSizer, []interface{}{\n\t\t(*TapEvent_Http_)(nil),\n\t}\n}", "func (*TapEvent) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _TapEvent_OneofMarshaler, _TapEvent_OneofUnmarshaler, _TapEvent_OneofSizer, []interface{}{\n\t\t(*TapEvent_Http_)(nil),\n\t}\n}", "func (*UploadBinaryRequest) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _UploadBinaryRequest_OneofMarshaler, _UploadBinaryRequest_OneofUnmarshaler, _UploadBinaryRequest_OneofSizer, []interface{}{\n\t\t(*UploadBinaryRequest_Key_)(nil),\n\t\t(*UploadBinaryRequest_Chunk_)(nil),\n\t}\n}", "func (*Metric) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _Metric_OneofMarshaler, _Metric_OneofUnmarshaler, _Metric_OneofSizer, []interface{}{\n\t\t(*Metric_I64)(nil),\n\t\t(*Metric_U64)(nil),\n\t\t(*Metric_F64)(nil),\n\t\t(*Metric_String_)(nil),\n\t\t(*Metric_Bool)(nil),\n\t\t(*Metric_Duration)(nil),\n\t}\n}", "func (*SendBitmessageRequest) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _SendBitmessageRequest_OneofMarshaler, _SendBitmessageRequest_OneofUnmarshaler, _SendBitmessageRequest_OneofSizer, []interface{}{\n\t\t(*SendBitmessageRequest_Text)(nil),\n\t}\n}", "func (*Service) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _Service_OneofMarshaler, _Service_OneofUnmarshaler, _Service_OneofSizer, []interface{}{\n\t\t(*Service_DstPort)(nil),\n\t\t(*Service_IcmpMsgType)(nil),\n\t}\n}", "func (*Event) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _Event_OneofMarshaler, _Event_OneofUnmarshaler, _Event_OneofSizer, []interface{}{\n\t\t(*Event_Error)(nil),\n\t\t(*Event_Progress)(nil),\n\t\t(*Event_Match)(nil),\n\t\t(*Event_Pagination)(nil),\n\t}\n}", "func (*Config) XXX_OneofFuncs() (func(msg proto1.Message, b *proto1.Buffer) error, func(msg proto1.Message, tag, wire int, b *proto1.Buffer) (bool, error), func(msg proto1.Message) (n int), []interface{}) {\n\treturn _Config_OneofMarshaler, _Config_OneofUnmarshaler, _Config_OneofSizer, []interface{}{\n\t\t(*Config_Custom)(nil),\n\t\t(*Config_Random)(nil),\n\t\t(*Config_Fixed)(nil),\n\t}\n}", "func (*FetchRequest) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _FetchRequest_OneofMarshaler, _FetchRequest_OneofUnmarshaler, _FetchRequest_OneofSizer, []interface{}{\n\t\t(*FetchRequest_TagMatchers)(nil),\n\t}\n}", "func (*Wrapper) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _Wrapper_OneofMarshaler, _Wrapper_OneofUnmarshaler, _Wrapper_OneofSizer, []interface{}{\n\t\t(*Wrapper_Source)(nil),\n\t\t(*Wrapper_GherkinDocument)(nil),\n\t\t(*Wrapper_Pickle)(nil),\n\t\t(*Wrapper_Attachment)(nil),\n\t\t(*Wrapper_TestCaseStarted)(nil),\n\t\t(*Wrapper_TestStepStarted)(nil),\n\t\t(*Wrapper_TestStepFinished)(nil),\n\t\t(*Wrapper_TestCaseFinished)(nil),\n\t\t(*Wrapper_TestHookStarted)(nil),\n\t\t(*Wrapper_TestHookFinished)(nil),\n\t}\n}", "func (*Message) XXX_OneofFuncs() (func(msg proto1.Message, b *proto1.Buffer) error, func(msg proto1.Message, tag, wire int, b *proto1.Buffer) (bool, error), func(msg proto1.Message) (n int), []interface{}) {\n\treturn _Message_OneofMarshaler, _Message_OneofUnmarshaler, _Message_OneofSizer, []interface{}{\n\t\t(*Message_Bigint)(nil),\n\t\t(*Message_EcGroupElement)(nil),\n\t\t(*Message_Status)(nil),\n\t\t(*Message_PedersenFirst)(nil),\n\t\t(*Message_PedersenDecommitment)(nil),\n\t\t(*Message_SchnorrProofData)(nil),\n\t\t(*Message_SchnorrProofRandomData)(nil),\n\t\t(*Message_SchnorrEcProofRandomData)(nil),\n\t\t(*Message_PseudonymsysCaCertificate)(nil),\n\t\t(*Message_PseudonymsysNymGenProofRandomData)(nil),\n\t\t(*Message_PseudonymsysIssueProofRandomData)(nil),\n\t\t(*Message_DoubleBigint)(nil),\n\t\t(*Message_PseudonymsysTransferCredentialData)(nil),\n\t\t(*Message_PseudonymsysCaCertificateEc)(nil),\n\t\t(*Message_PseudonymsysNymGenProofRandomDataEc)(nil),\n\t\t(*Message_PseudonymsysIssueProofRandomDataEc)(nil),\n\t\t(*Message_PseudonymsysTransferCredentialDataEc)(nil),\n\t\t(*Message_SessionKey)(nil),\n\t}\n}", "func (*StateRequest) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _StateRequest_OneofMarshaler, _StateRequest_OneofUnmarshaler, _StateRequest_OneofSizer, []interface{}{\n\t\t(*StateRequest_Get)(nil),\n\t\t(*StateRequest_Append)(nil),\n\t\t(*StateRequest_Clear)(nil),\n\t}\n}", "func (*StateRequest) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _StateRequest_OneofMarshaler, _StateRequest_OneofUnmarshaler, _StateRequest_OneofSizer, []interface{}{\n\t\t(*StateRequest_Get)(nil),\n\t\t(*StateRequest_Append)(nil),\n\t\t(*StateRequest_Clear)(nil),\n\t}\n}", "func (*Event) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _Event_OneofMarshaler, _Event_OneofUnmarshaler, _Event_OneofSizer, []interface{}{\n\t\t(*Event_ResourceHeader)(nil),\n\t\t(*Event_CertAuthority)(nil),\n\t\t(*Event_StaticTokens)(nil),\n\t\t(*Event_ProvisionToken)(nil),\n\t\t(*Event_ClusterName)(nil),\n\t\t(*Event_ClusterConfig)(nil),\n\t\t(*Event_User)(nil),\n\t\t(*Event_Role)(nil),\n\t\t(*Event_Namespace)(nil),\n\t\t(*Event_Server)(nil),\n\t\t(*Event_ReverseTunnel)(nil),\n\t\t(*Event_TunnelConnection)(nil),\n\t\t(*Event_AccessRequest)(nil),\n\t}\n}", "func (*NetworkAddress) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _NetworkAddress_OneofMarshaler, _NetworkAddress_OneofUnmarshaler, _NetworkAddress_OneofSizer, []interface{}{\n\t\t(*NetworkAddress_Ipv4Address)(nil),\n\t\t(*NetworkAddress_Ipv6Address)(nil),\n\t\t(*NetworkAddress_LocalAddress)(nil),\n\t}\n}", "func (*NetworkAddress) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _NetworkAddress_OneofMarshaler, _NetworkAddress_OneofUnmarshaler, _NetworkAddress_OneofSizer, []interface{}{\n\t\t(*NetworkAddress_Ipv4Address)(nil),\n\t\t(*NetworkAddress_Ipv6Address)(nil),\n\t\t(*NetworkAddress_LocalAddress)(nil),\n\t}\n}", "func (*RPC) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _RPC_OneofMarshaler, _RPC_OneofUnmarshaler, _RPC_OneofSizer, []interface{}{\n\t\t(*RPC_Args)(nil),\n\t\t(*RPC_ByteArgs)(nil),\n\t}\n}", "func (*FeeUpdateRequest) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _FeeUpdateRequest_OneofMarshaler, _FeeUpdateRequest_OneofUnmarshaler, _FeeUpdateRequest_OneofSizer, []interface{}{\n\t\t(*FeeUpdateRequest_Global)(nil),\n\t\t(*FeeUpdateRequest_ChanPoint)(nil),\n\t}\n}", "func (*FeeUpdateRequest) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _FeeUpdateRequest_OneofMarshaler, _FeeUpdateRequest_OneofUnmarshaler, _FeeUpdateRequest_OneofSizer, []interface{}{\n\t\t(*FeeUpdateRequest_Global)(nil),\n\t\t(*FeeUpdateRequest_ChanPoint)(nil),\n\t}\n}", "func (*ServiceSpec) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _ServiceSpec_OneofMarshaler, _ServiceSpec_OneofUnmarshaler, _ServiceSpec_OneofSizer, []interface{}{\n\t\t(*ServiceSpec_Replicated)(nil),\n\t\t(*ServiceSpec_Global)(nil),\n\t}\n}", "func (*ServiceSpec) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _ServiceSpec_OneofMarshaler, _ServiceSpec_OneofUnmarshaler, _ServiceSpec_OneofSizer, []interface{}{\n\t\t(*ServiceSpec_Replicated)(nil),\n\t\t(*ServiceSpec_Global)(nil),\n\t}\n}", "func (*ServiceSpec) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _ServiceSpec_OneofMarshaler, _ServiceSpec_OneofUnmarshaler, _ServiceSpec_OneofSizer, []interface{}{\n\t\t(*ServiceSpec_Replicated)(nil),\n\t\t(*ServiceSpec_Global)(nil),\n\t}\n}", "func (*Eos) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _Eos_OneofMarshaler, _Eos_OneofUnmarshaler, _Eos_OneofSizer, []interface{}{\n\t\t(*Eos_GrpcStatusCode)(nil),\n\t\t(*Eos_ResetErrorCode)(nil),\n\t}\n}", "func (*Eos) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _Eos_OneofMarshaler, _Eos_OneofUnmarshaler, _Eos_OneofSizer, []interface{}{\n\t\t(*Eos_GrpcStatusCode)(nil),\n\t\t(*Eos_ResetErrorCode)(nil),\n\t}\n}", "func (*RecordKey) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _RecordKey_OneofMarshaler, _RecordKey_OneofUnmarshaler, _RecordKey_OneofSizer, []interface{}{\n\t\t(*RecordKey_DatastoreKey)(nil),\n\t\t(*RecordKey_BigQueryKey)(nil),\n\t}\n}", "func (*WatchRequest) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _WatchRequest_OneofMarshaler, _WatchRequest_OneofUnmarshaler, _WatchRequest_OneofSizer, []interface{}{\n\t\t(*WatchRequest_CreateRequest)(nil),\n\t\t(*WatchRequest_CancelRequest)(nil),\n\t}\n}", "func (*Node) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _Node_OneofMarshaler, _Node_OneofUnmarshaler, _Node_OneofSizer, []interface{}{\n\t\t(*Node_Src)(nil),\n\t\t(*Node_Snk)(nil),\n\t\t(*Node_ContentHash)(nil),\n\t}\n}", "func (*FeedMapping) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _FeedMapping_OneofMarshaler, _FeedMapping_OneofUnmarshaler, _FeedMapping_OneofSizer, []interface{}{\n\t\t(*FeedMapping_PlaceholderType)(nil),\n\t\t(*FeedMapping_CriterionType)(nil),\n\t}\n}", "func (*Virtual) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _Virtual_OneofMarshaler, _Virtual_OneofUnmarshaler, _Virtual_OneofSizer, []interface{}{\n\t\t(*Virtual_Genesis)(nil),\n\t\t(*Virtual_Child)(nil),\n\t\t(*Virtual_Jet)(nil),\n\t\t(*Virtual_IncomingRequest)(nil),\n\t\t(*Virtual_OutgoingRequest)(nil),\n\t\t(*Virtual_Result)(nil),\n\t\t(*Virtual_Type)(nil),\n\t\t(*Virtual_Code)(nil),\n\t\t(*Virtual_Activate)(nil),\n\t\t(*Virtual_Amend)(nil),\n\t\t(*Virtual_Deactivate)(nil),\n\t\t(*Virtual_PendingFilament)(nil),\n\t}\n}", "func (*CloseStatusUpdate) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _CloseStatusUpdate_OneofMarshaler, _CloseStatusUpdate_OneofUnmarshaler, _CloseStatusUpdate_OneofSizer, []interface{}{\n\t\t(*CloseStatusUpdate_ClosePending)(nil),\n\t\t(*CloseStatusUpdate_Confirmation)(nil),\n\t\t(*CloseStatusUpdate_ChanClose)(nil),\n\t}\n}", "func (*CloseStatusUpdate) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _CloseStatusUpdate_OneofMarshaler, _CloseStatusUpdate_OneofUnmarshaler, _CloseStatusUpdate_OneofSizer, []interface{}{\n\t\t(*CloseStatusUpdate_ClosePending)(nil),\n\t\t(*CloseStatusUpdate_Confirmation)(nil),\n\t\t(*CloseStatusUpdate_ChanClose)(nil),\n\t}\n}", "func (*CloseStatusUpdate) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _CloseStatusUpdate_OneofMarshaler, _CloseStatusUpdate_OneofUnmarshaler, _CloseStatusUpdate_OneofSizer, []interface{}{\n\t\t(*CloseStatusUpdate_ClosePending)(nil),\n\t\t(*CloseStatusUpdate_Confirmation)(nil),\n\t\t(*CloseStatusUpdate_ChanClose)(nil),\n\t}\n}", "func (*CloseStatusUpdate) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _CloseStatusUpdate_OneofMarshaler, _CloseStatusUpdate_OneofUnmarshaler, _CloseStatusUpdate_OneofSizer, []interface{}{\n\t\t(*CloseStatusUpdate_ClosePending)(nil),\n\t\t(*CloseStatusUpdate_Confirmation)(nil),\n\t\t(*CloseStatusUpdate_ChanClose)(nil),\n\t}\n}", "func (*CloseStatusUpdate) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _CloseStatusUpdate_OneofMarshaler, _CloseStatusUpdate_OneofUnmarshaler, _CloseStatusUpdate_OneofSizer, []interface{}{\n\t\t(*CloseStatusUpdate_ClosePending)(nil),\n\t\t(*CloseStatusUpdate_ChanClose)(nil),\n\t}\n}", "func (*CloseStatusUpdate) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _CloseStatusUpdate_OneofMarshaler, _CloseStatusUpdate_OneofUnmarshaler, _CloseStatusUpdate_OneofSizer, []interface{}{\n\t\t(*CloseStatusUpdate_ClosePending)(nil),\n\t\t(*CloseStatusUpdate_ChanClose)(nil),\n\t}\n}", "func (*CloseStatusUpdate) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _CloseStatusUpdate_OneofMarshaler, _CloseStatusUpdate_OneofUnmarshaler, _CloseStatusUpdate_OneofSizer, []interface{}{\n\t\t(*CloseStatusUpdate_ClosePending)(nil),\n\t\t(*CloseStatusUpdate_ChanClose)(nil),\n\t}\n}", "func (*PrintKVRequest) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _PrintKVRequest_OneofMarshaler, _PrintKVRequest_OneofUnmarshaler, _PrintKVRequest_OneofSizer, []interface{}{\n\t\t(*PrintKVRequest_ValueString)(nil),\n\t\t(*PrintKVRequest_ValueInt)(nil),\n\t}\n}", "func (*ChannelEventUpdate) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _ChannelEventUpdate_OneofMarshaler, _ChannelEventUpdate_OneofUnmarshaler, _ChannelEventUpdate_OneofSizer, []interface{}{\n\t\t(*ChannelEventUpdate_OpenChannel)(nil),\n\t\t(*ChannelEventUpdate_ClosedChannel)(nil),\n\t\t(*ChannelEventUpdate_ActiveChannel)(nil),\n\t\t(*ChannelEventUpdate_InactiveChannel)(nil),\n\t}\n}", "func (*ChannelEventUpdate) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _ChannelEventUpdate_OneofMarshaler, _ChannelEventUpdate_OneofUnmarshaler, _ChannelEventUpdate_OneofSizer, []interface{}{\n\t\t(*ChannelEventUpdate_OpenChannel)(nil),\n\t\t(*ChannelEventUpdate_ClosedChannel)(nil),\n\t\t(*ChannelEventUpdate_ActiveChannel)(nil),\n\t\t(*ChannelEventUpdate_InactiveChannel)(nil),\n\t}\n}", "func (*ChannelEventUpdate) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {\n\treturn _ChannelEventUpdate_OneofMarshaler, _ChannelEventUpdate_OneofUnmarshaler, _ChannelEventUpdate_OneofSizer, []interface{}{\n\t\t(*ChannelEventUpdate_OpenChannel)(nil),\n\t\t(*ChannelEventUpdate_ClosedChannel)(nil),\n\t\t(*ChannelEventUpdate_ActiveChannel)(nil),\n\t\t(*ChannelEventUpdate_InactiveChannel)(nil),\n\t}\n}" ]
[ "0.8907106", "0.890579", "0.8891233", "0.88697135", "0.8868073", "0.8863467", "0.8863115", "0.8862988", "0.886209", "0.8861827", "0.8859999", "0.88558704", "0.88540995", "0.88527775", "0.88527775", "0.88527775", "0.88480514", "0.8847366", "0.88448733", "0.8844595", "0.8841944", "0.8837193", "0.88370156", "0.88370156", "0.88370156", "0.88370156", "0.8835452", "0.8835452", "0.8835452", "0.8835452", "0.8835452", "0.8835452", "0.88341135", "0.88305503", "0.8830491", "0.8830415", "0.8830316", "0.8829064", "0.88287365", "0.8827809", "0.8824382", "0.8824265", "0.8823733", "0.88221323", "0.88188404", "0.88188404", "0.88188404", "0.88188404", "0.8814617", "0.8813053", "0.8811626", "0.88105947", "0.88105947", "0.880831", "0.880831", "0.88082665", "0.8808227", "0.8805944", "0.8805914", "0.8805914", "0.8805914", "0.88056016", "0.88042617", "0.88038075", "0.88034934", "0.88032365", "0.8802399", "0.880174", "0.87993646", "0.8799361", "0.87975067", "0.87975067", "0.8795369", "0.8795032", "0.8795032", "0.8792591", "0.8791414", "0.8791414", "0.8791351", "0.8791351", "0.8791351", "0.8788791", "0.8788791", "0.8788189", "0.8787607", "0.87870103", "0.8787005", "0.8786366", "0.87856686", "0.87856686", "0.87856686", "0.87856686", "0.8785405", "0.8785405", "0.8785405", "0.8784138", "0.87823385", "0.87823385", "0.87823385" ]
0.87900233
82
Base Vesting Account NewBaseVestingAccount creates a new BaseVestingAccount object. It is the callers responsibility to ensure the base account has sufficient funds with regards to the original vesting amount.
func NewBaseVestingAccount(baseAccount *authtypes.BaseAccount, originalVesting sdk.Coins, endTime int64) *BaseVestingAccount { return &BaseVestingAccount{ BaseAccount: baseAccount, OriginalVesting: originalVesting, DelegatedFree: sdk.NewCoins(), DelegatedVesting: sdk.NewCoins(), EndTime: endTime, } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func NewBase() Base {\r\n\treturn Base{\r\n\t\tActive: \"\",\r\n\t\tTitle: \"Lemonade Stand Supply\",\r\n\t}\r\n}", "func NewClawbackVestingAccount(baseAcc *authtypes.BaseAccount, funder sdk.AccAddress, originalVesting sdk.Coins, startTime int64, lockupPeriods, vestingPeriods Periods) *ClawbackVestingAccount {\n\t// copy and align schedules to avoid mutating inputs\n\tlp := make(Periods, len(lockupPeriods))\n\tcopy(lp, lockupPeriods)\n\tvp := make(Periods, len(vestingPeriods))\n\tcopy(vp, vestingPeriods)\n\t_, endTime := AlignSchedules(startTime, startTime, lp, vp)\n\tbaseVestingAcc := &BaseVestingAccount{\n\t\tBaseAccount: baseAcc,\n\t\tOriginalVesting: originalVesting,\n\t\tEndTime: endTime,\n\t}\n\n\treturn &ClawbackVestingAccount{\n\t\tBaseVestingAccount: baseVestingAcc,\n\t\tFunderAddress: funder.String(),\n\t\tStartTime: startTime,\n\t\tLockupPeriods: lp,\n\t\tVestingPeriods: vp,\n\t}\n}", "func NewPeriodicVestingAccount(baseAcc *authtypes.BaseAccount, originalVesting sdk.Coins, startTime int64, periods Periods) *PeriodicVestingAccount {\n\tendTime := startTime\n\tfor _, p := range periods {\n\t\tendTime += p.Length\n\t}\n\tbaseVestingAcc := &BaseVestingAccount{\n\t\tBaseAccount: baseAcc,\n\t\tOriginalVesting: originalVesting,\n\t\tEndTime: endTime,\n\t}\n\n\treturn &PeriodicVestingAccount{\n\t\tBaseVestingAccount: baseVestingAcc,\n\t\tStartTime: startTime,\n\t\tVestingPeriods: periods,\n\t}\n}", "func NewValidatorVestingAccount(baseAcc *authtypes.BaseAccount, startTime int64, periods vestingtypes.Periods, validatorAddress sdk.ConsAddress, returnAddress sdk.AccAddress, signingThreshold int64) *ValidatorVestingAccount {\n\n\tendTime := startTime\n\tfor _, p := range periods {\n\t\tendTime += p.Length\n\t}\n\tbaseVestingAcc := &vestingtypes.BaseVestingAccount{\n\t\tBaseAccount: baseAcc,\n\t\tOriginalVesting: baseAcc.Coins,\n\t\tEndTime: endTime,\n\t}\n\tpva := &vestingtypes.PeriodicVestingAccount{\n\t\tBaseVestingAccount: baseVestingAcc,\n\t\tStartTime: startTime,\n\t\tVestingPeriods: periods,\n\t}\n\tvar vestingPeriodProgress []VestingProgress\n\tfor i := 0; i < len(periods); i++ {\n\t\tvestingPeriodProgress = append(vestingPeriodProgress, VestingProgress{false, false})\n\t}\n\n\treturn &ValidatorVestingAccount{\n\t\tPeriodicVestingAccount: pva,\n\t\tValidatorAddress: validatorAddress,\n\t\tReturnAddress: returnAddress,\n\t\tSigningThreshold: signingThreshold,\n\t\tCurrentPeriodProgress: CurrentPeriodProgress{0, 0},\n\t\tVestingPeriodProgress: vestingPeriodProgress,\n\t\tDebtAfterFailedVesting: sdk.NewCoins(),\n\t}\n}", "func newBase() *base {\n\treturn &base{shared.NewUUID(), time.Now().UTC(), time.Now().UTC(), false/*, shared.NewUUID()*/}\n}", "func NewBaseViewKeeper(am auth.AccountKeeper) BaseViewKeeper {\n\treturn BaseViewKeeper{am: am}\n}", "func NewBase(name string) *Base {\n\treturn &Base{name}\n}", "func NewBaseKeeper(am auth.AccountKeeper) BaseKeeper {\n\treturn BaseKeeper{am: am}\n}", "func newPeriodicVestingAccount(address sdk.AccAddress, periods vestingtypes.Periods, firstPeriodStartTimestamp int64) *vestingtypes.PeriodicVestingAccount {\n\tbaseAccount := authtypes.NewBaseAccount(address, nil, 0, 0)\n\n\toriginalVesting := sdk.NewCoins()\n\tfor _, p := range periods {\n\t\toriginalVesting = originalVesting.Add(p.Amount...)\n\t}\n\n\tvar totalPeriods int64\n\tfor _, p := range periods {\n\t\ttotalPeriods += p.Length\n\t}\n\tendTime := firstPeriodStartTimestamp + totalPeriods\n\n\tbaseVestingAccount := vestingtypes.NewBaseVestingAccount(baseAccount, originalVesting, endTime)\n\treturn vestingtypes.NewPeriodicVestingAccountRaw(baseVestingAccount, firstPeriodStartTimestamp, periods)\n}", "func NewDelayedVestingAccount(baseAcc *authtypes.BaseAccount, originalVesting sdk.Coins, endTime int64) *DelayedVestingAccount {\n\tbaseVestingAcc := &BaseVestingAccount{\n\t\tBaseAccount: baseAcc,\n\t\tOriginalVesting: originalVesting,\n\t\tEndTime: endTime,\n\t}\n\n\treturn &DelayedVestingAccount{baseVestingAcc}\n}", "func NewKeybase(validatorMoniker, mnemonic, password string) (keyring.Keyring, keyring.Info, error) {\n\tkr := keyring.NewInMemory()\n\thdpath := *hd.NewFundraiserParams(0, sdk.CoinType, 0)\n\tinfo, err := kr.NewAccount(validatorMoniker, mnemonic, password, hdpath.String(), hd.Secp256k1)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treturn kr, info, nil\n}", "func NewBaseCoin(purpose int, coin int, account int) *BaseCoin {\n\treturn &BaseCoin{Purpose: purpose, Coin: coin, Account: account}\n}", "func NewBase(path string, hashName string) (*Base, error) {\n\tfor _, p := range []string{\"blobs/\" + hashName, \"state\", \"tmp\"} {\n\t\tif err := os.MkdirAll(filepath.Join(path, p), 0755); err != nil && !os.IsExist(err) {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn &Base{Path: path, HashName: hashName, Hash: cryptomap.DetermineHash(hashName)}, nil\n}", "func NewValidatorVestingAccountRaw(bva *vestingtypes.BaseVestingAccount,\n\tstartTime int64, periods vestingtypes.Periods, validatorAddress sdk.ConsAddress, returnAddress sdk.AccAddress, signingThreshold int64) *ValidatorVestingAccount {\n\n\tpva := &vestingtypes.PeriodicVestingAccount{\n\t\tBaseVestingAccount: bva,\n\t\tStartTime: startTime,\n\t\tVestingPeriods: periods,\n\t}\n\tvar vestingPeriodProgress []VestingProgress\n\tfor i := 0; i < len(periods); i++ {\n\t\tvestingPeriodProgress = append(vestingPeriodProgress, VestingProgress{false, false})\n\t}\n\n\treturn &ValidatorVestingAccount{\n\t\tPeriodicVestingAccount: pva,\n\t\tValidatorAddress: validatorAddress,\n\t\tReturnAddress: returnAddress,\n\t\tSigningThreshold: signingThreshold,\n\t\tCurrentPeriodProgress: CurrentPeriodProgress{0, 0},\n\t\tVestingPeriodProgress: vestingPeriodProgress,\n\t\tDebtAfterFailedVesting: sdk.NewCoins(),\n\t}\n}", "func NewContinuousVestingAccount(baseAcc *authtypes.BaseAccount, originalVesting sdk.Coins, startTime, endTime int64) *ContinuousVestingAccount {\n\tbaseVestingAcc := &BaseVestingAccount{\n\t\tBaseAccount: baseAcc,\n\t\tOriginalVesting: originalVesting,\n\t\tEndTime: endTime,\n\t}\n\n\treturn &ContinuousVestingAccount{\n\t\tStartTime: startTime,\n\t\tBaseVestingAccount: baseVestingAcc,\n\t}\n}", "func NewInventoryBase(classId string, objectType string) *InventoryBase {\n\tthis := InventoryBase{}\n\tthis.ClassId = classId\n\tthis.ObjectType = objectType\n\treturn &this\n}", "func newAccount() *Account {\n\treturn &Account{\n\t\tblocks: make(map[string]uint64),\n\t}\n}", "func NewRateBarrierBase(rate, base int) *RateBarrier {\n\treturn &RateBarrier{\n\t\tsource: createRandSourceByBase(base),\n\t\trate: rate,\n\t\tbase: base,\n\t}\n}", "func NewCoinbase(proof, score, R []byte) *Coinbase {\n\treturn &Coinbase{\n\t\tProof: proof,\n\t\tScore: score,\n\t\tR: R,\n\t}\n}", "func NewPeriodicVestingAccountRaw(bva *BaseVestingAccount, startTime int64, periods Periods) *PeriodicVestingAccount {\n\treturn &PeriodicVestingAccount{\n\t\tBaseVestingAccount: bva,\n\t\tStartTime: startTime,\n\t\tVestingPeriods: periods,\n\t}\n}", "func (e *GT) Base() *GT {\n\tif e.p == nil {\n\t\te.p = &gfP12{}\n\t}\n\te.p.Set(gfP12Gen)\n\treturn e\n}", "func newBaseClient() *baseClient {\n\treturn &baseClient{\n\t\thttpClient: http.DefaultClient,\n\t\tmethod: \"GET\",\n\t\theader: make(http.Header),\n\t}\n}", "func NewDelayedVestingAccountRaw(bva *BaseVestingAccount) *DelayedVestingAccount {\n\treturn &DelayedVestingAccount{\n\t\tBaseVestingAccount: bva,\n\t}\n}", "func (g *testGenerator) createCoinbaseTx(blockHeight uint32, numVotes uint16) *wire.MsgTx {\n\t// Calculate the subsidy proportions based on the block height and the\n\t// number of votes the block will include.\n\tfullSubsidy := g.calcFullSubsidy(blockHeight)\n\tdevSubsidy := g.calcDevSubsidy(fullSubsidy, blockHeight, numVotes)\n\tpowSubsidy := g.calcPoWSubsidy(fullSubsidy, blockHeight, numVotes)\n\n\ttx := wire.NewMsgTx()\n\ttx.AddTxIn(&wire.TxIn{\n\t\t// Coinbase transactions have no inputs, so previous outpoint is\n\t\t// zero hash and max index.\n\t\tPreviousOutPoint: *wire.NewOutPoint(&chainhash.Hash{},\n\t\t\twire.MaxPrevOutIndex, wire.TxTreeRegular),\n\t\tSequence: wire.MaxTxInSequenceNum,\n\t\tValueIn: int64(devSubsidy + powSubsidy),\n\t\tBlockHeight: wire.NullBlockHeight,\n\t\tBlockIndex: wire.NullBlockIndex,\n\t\tSignatureScript: coinbaseSigScript,\n\t})\n\n\tg.addCoinbaseTxOutputs(tx, blockHeight, devSubsidy, powSubsidy)\n\n\treturn tx\n}", "func newPRSignedBaseLayer(baseLayerIdentity PolicyReferenceMatch) (*prSignedBaseLayer, error) {\n\tif baseLayerIdentity == nil {\n\t\treturn nil, InvalidPolicyFormatError(\"baseLayerIdentity not specified\")\n\t}\n\treturn &prSignedBaseLayer{\n\t\tprCommon: prCommon{Type: prTypeSignedBaseLayer},\n\t\tBaseLayerIdentity: baseLayerIdentity,\n\t}, nil\n}", "func MakeBase(name, key, owner string, defaultValue interface{}, lifetime Lifetime, expose bool) Base {\n\treturn Base{\n\t\tname: name,\n\t\tkey: key,\n\t\towner: owner,\n\t\tdefaultValue: defaultValue,\n\t\tlifetime: lifetime,\n\t\texpose: expose,\n\t}\n}", "func NewWithBaseURL(token string, baseURL string) Client {\n\tnewClient := Client{Token: token, BaseURL: baseURL}\n\n\tnewClient.FreeCompany = FreeCompany{Endpoint: Endpoint{client: &newClient, endpoint: \"FreeCompany/\"}}\n\tnewClient.Group = Group{Endpoint: Endpoint{client: &newClient, endpoint: \"Group/\"}}\n\n\treturn newClient\n\n}", "func newProcBase(name, bin, serviceAddr string, loggers []Logger) *procBase {\n\tlog.Infof(\"%s has addr %s\", name, serviceAddr)\n\treturn &procBase{\n\t\tname: name,\n\t\tbin: bin,\n\t\tserviceAddr: serviceAddr,\n\t\tloggers: loggers,\n\t}\n}", "func newJWTBase(ctx context.Context, cfg Config) (string, error) {\n\tserviceAccount, project, tokenSource, err := getServiceAccountInfo(ctx, cfg)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"unable to get service account from environment\")\n\t}\n\n\tpayload, err := json.Marshal(map[string]interface{}{\n\t\t\"aud\": \"vault/\" + cfg.Role,\n\t\t\"sub\": serviceAccount,\n\t\t\"exp\": time.Now().UTC().Add(5 * time.Minute).Unix(),\n\t})\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"unable to encode JWT payload\")\n\t}\n\n\thc := getHTTPClient(ctx, cfg)\n\t// reuse base transport and timeout but sprinkle on the token source for IAM access\n\thcIAM := &http.Client{\n\t\tTimeout: hc.Timeout,\n\t\tTransport: &oauth2.Transport{\n\t\t\tSource: tokenSource,\n\t\t\tBase: hc.Transport,\n\t\t},\n\t}\n\tiamClient, err := iam.New(hcIAM)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"unable to init IAM client\")\n\t}\n\n\tif cfg.IAMAddress != \"\" {\n\t\tiamClient.BasePath = cfg.IAMAddress\n\t}\n\n\tresp, err := iamClient.Projects.ServiceAccounts.SignJwt(\n\t\tfmt.Sprintf(\"projects/%s/serviceAccounts/%s\",\n\t\t\tproject, serviceAccount),\n\t\t&iam.SignJwtRequest{Payload: string(payload)}).Context(ctx).Do()\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"unable to sign JWT\")\n\t}\n\treturn resp.SignedJwt, nil\n}", "func NewTransportBase(qcfg TransportQueueConfig) (b *TransportBase, p *TransportBasePriv) {\n\tqcfg.ApplyTransportQueueConfigDefaults()\n\trx := make(chan []byte, qcfg.RxQueueSize)\n\ttx := make(chan []byte, qcfg.TxQueueSize)\n\tb = &TransportBase{\n\t\trx: rx,\n\t\ttx: tx,\n\t\tstate: TransportUp,\n\t\temitter: events.NewEmitter(),\n\t}\n\tp = &TransportBasePriv{\n\t\tb: b,\n\t\tRx: rx,\n\t\tTx: tx,\n\t}\n\treturn\n}", "func New() *Base {\n\tb := &Base{}\n\tb.addDefaultKeyConverter()\n\treturn b\n}", "func newBaseRuntime(erp *ECALRuntimeProvider, node *parser.ASTNode) *baseRuntime {\n\tinstanceCounter++\n\treturn &baseRuntime{fmt.Sprint(instanceCounter), erp, node, false}\n}", "func getBase(srcTx ExplorerTxs) blockatlas.Tx {\n\tbase := blockatlas.Tx{\n\t\tID: srcTx.TxHash,\n\t\tCoin: coin.BNB,\n\t\tFrom: srcTx.FromAddr,\n\t\tFee: srcTx.getDexFee(),\n\t\tDate: srcTx.Timestamp / 1000,\n\t\tBlock: srcTx.BlockHeight,\n\t\tMemo: srcTx.Memo,\n\t\tTo: srcTx.ToAddr,\n\t}\n\n\tstatus := srcTx.getStatus()\n\tbase.Status = status\n\tif status == blockatlas.StatusError {\n\t\tbase.Error = srcTx.getError()\n\t}\n\n\treturn base\n}", "func New(OrganisationID string, BaseURL string) *Client {\n\tconfig := config{\n\t\tURL: BaseURL,\n\t\tOrganisationID: OrganisationID,\n\t\tclient: &http.Client{},\n\t}\n\treturn &Client{\n\t\tAccount: AccountEndpoint{\n\t\t\tconfig: &config,\n\t\t},\n\t}\n}", "func (e Account) EntNew() ent.Ent { return &Account{} }", "func (e Account) EntNew() ent.Ent { return &Account{} }", "func NewInventoryBaseAllOf(classId string, objectType string) *InventoryBaseAllOf {\n\tthis := InventoryBaseAllOf{}\n\tthis.ClassId = classId\n\tthis.ObjectType = objectType\n\treturn &this\n}", "func (bva BaseVestingAccount) Validate() error {\n\tif !(bva.DelegatedVesting.IsAllLTE(bva.OriginalVesting)) {\n\t\treturn errors.New(\"delegated vesting amount cannot be greater than original vesting amount\")\n\t}\n\treturn bva.BaseAccount.Validate()\n}", "func NewKeybase(path ...string) *Keybase {\n\tk := &Keybase{}\n\tif len(path) < 1 {\n\t\tk.Path = \"keybase\"\n\t} else {\n\t\tk.Path = path[0]\n\t}\n\n\ts := k.status()\n\tk.Version = k.version()\n\tk.LoggedIn = s.LoggedIn\n\tif k.LoggedIn {\n\t\tk.Username = s.Username\n\t\tk.Device = s.Device.Name\n\t}\n\treturn k\n}", "func NewBaseConn(c Carrier) *BaseConn {\n\treturn &BaseConn{\n\t\tcarrier: c,\n\t\tstream: packet.NewStream(c, c),\n\t}\n}", "func NewBase() (ResultT, ResolverT) {\n\treturn GetCurrentRunner().NewResultT()\n}", "func NewBaseHandler(cfg *config.Config) *baseHandler {\n\t// Created a client by the given node address\n\trpcClient, err := rpc.Dial(cfg.NodeURL)\n\tif err != nil {\n\t\tlog.Fatal(\"failed to deal with ETH node\", err)\n\t}\n\tnodeClient := ethclient.NewClient(rpcClient)\n\n\t// Parse private key\n\td := new(big.Int).SetBytes(common.FromHex(cfg.PrivateKey))\n\tpkX, pkY := crypto.S256().ScalarBaseMult(d.Bytes())\n\tprivateKey := &ecdsa.PrivateKey{\n\t\tPublicKey: ecdsa.PublicKey{\n\t\t\tCurve: crypto.S256(),\n\t\t\tX: pkX,\n\t\t\tY: pkY,\n\t\t},\n\t\tD: d,\n\t}\n\n\t// Init from address\n\tpublicKey := privateKey.Public()\n\tpublicKeyECDSA, ok := publicKey.(*ecdsa.PublicKey)\n\tif !ok {\n\t\tlog.Fatal(\"error casting public key to ECDSA\")\n\t}\n\tfromAddr := crypto.PubkeyToAddress(*publicKeyECDSA)\n\n\t// Create link token wrapper\n\tlinkToken, err := link.NewLinkToken(common.HexToAddress(cfg.LinkTokenAddr), nodeClient)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tapproveAmount := big.NewInt(0)\n\tapproveAmount.SetString(cfg.ApproveAmount, 10)\n\n\treturn &baseHandler{\n\t\tcfg: cfg,\n\t\tclient: nodeClient,\n\t\trpcClient: rpcClient,\n\t\tprivateKey: privateKey,\n\t\tlinkToken: linkToken,\n\t\tfromAddr: fromAddr,\n\t\tapproveAmount: approveAmount,\n\t}\n}", "func New(ctx context.Context, backupTables tablesmap.TablesMapInterface, cfg *config.Config) *basebackup {\n\tb := basebackup{\n\t\tctx: ctx,\n\t\tcfg: cfg,\n\t\twg: &sync.WaitGroup{},\n\t\tbackupTables: backupTables,\n\t\tqueue: queue.New(ctx),\n\t}\n\n\treturn &b\n}", "func NewBaseAccessWallet(address common.Address, backend bind.ContractBackend) (*BaseAccessWallet, error) {\n\tcontract, err := bindBaseAccessWallet(address, backend, backend, backend)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &BaseAccessWallet{BaseAccessWalletCaller: BaseAccessWalletCaller{contract: contract}, BaseAccessWalletTransactor: BaseAccessWalletTransactor{contract: contract}, BaseAccessWalletFilterer: BaseAccessWalletFilterer{contract: contract}}, nil\n}", "func New(s string, base int) (v BigNum) {\n\tv.Input(s, base)\n\treturn\n}", "func NewAgedAccountsPayable()(*AgedAccountsPayable) {\n m := &AgedAccountsPayable{\n }\n m.backingStore = ie8677ce2c7e1b4c22e9c3827ecd078d41185424dd9eeb92b7d971ed2d49a392e.BackingStoreFactoryInstance();\n m.SetAdditionalData(make(map[string]any))\n return m\n}", "func (w *Wallet) NewAccount(index *uint32) (a *Account, err error) {\n\tindex2 := w.nextIndex\n\tif index != nil {\n\t\tindex2 = *index\n\t}\n\ta = &Account{w: w, index: index2}\n\tif err = w.impl.deriveAccount(a); err != nil {\n\t\treturn\n\t}\n\tpubkeyToAddress := util.PubkeyToAddress\n\tif w.isBanano {\n\t\tpubkeyToAddress = util.PubkeyToBananoAddress\n\t}\n\tif a.address, err = pubkeyToAddress(a.pubkey); err != nil {\n\t\treturn\n\t}\n\tif index == nil {\n\t\tw.nextIndex++\n\t}\n\tif _, ok := w.accounts[a.address]; !ok {\n\t\tw.accounts[a.address] = a\n\t} else if index == nil {\n\t\treturn w.NewAccount(nil)\n\t}\n\treturn\n}", "func NewBaseReportTransaction(amount float64, isoCurrencyCode NullableString, unofficialCurrencyCode NullableString, originalDescription NullableString, date string, pending bool) *BaseReportTransaction {\n\tthis := BaseReportTransaction{}\n\tthis.Amount = amount\n\tthis.IsoCurrencyCode = isoCurrencyCode\n\tthis.UnofficialCurrencyCode = unofficialCurrencyCode\n\tthis.OriginalDescription = originalDescription\n\tthis.Date = date\n\tthis.Pending = pending\n\treturn &this\n}", "func (b *basic) CreateBase(r *ecsgen.Root) (string, error) {\n\t// buckets to sort the field names into\n\tscalarFields := []string{}\n\tobjectFields := []string{}\n\n\t// first we need to sort the field names, and separate out Base fields\n\t// from the FieldSets\n\tfor fieldName, fieldNode := range r.TopLevel {\n\t\tif fieldNode.IsObject() {\n\t\t\tobjectFields = append(objectFields, fieldName)\n\t\t\tcontinue\n\t\t}\n\n\t\tscalarFields = append(scalarFields, fieldName)\n\t}\n\n\tsort.Strings(scalarFields)\n\tsort.Strings(objectFields)\n\n\t// now to build the buffer that holds the Go type definition\n\tbuf := new(strings.Builder)\n\n\t// Add the type comment and the definition to the buffer\n\tbuf.WriteString(\"// Base defines the top level Elastic Common Schema (ECS) type. This type should be the default for interacting with ECS data, including the marshaling and unmarshaling of it.\")\n\tbuf.WriteString(\"\\n\")\n\tbuf.WriteString(\"type Base struct {\")\n\tbuf.WriteString(\"\\n\")\n\n\t// Enumerate the scalar fields (the fields that are direct types in the Base fieldset)\n\t// and add them to the type definition\n\tfor _, k := range scalarFields {\n\t\tfield := r.TopLevel[k]\n\t\tbuf.WriteString(\n\t\t\tfmt.Sprintf(\n\t\t\t\t\"\\t%s %s `json:\\\"%s,omitempty\\\" yaml:\\\"%s,omitempty\\\" ecs:\\\"%s\\\"`\",\n\t\t\t\tfield.FieldIdent().Pascal(),\n\t\t\t\tGoFieldType(field),\n\n\t\t\t\t// We don't actually use the \"parsed field name\" here because\n\t\t\t\t// unfortunately we have to account for the @timestamp field name\n\t\t\t\t// because YOLO, that field follows other naming conventions!\n\t\t\t\tk,\n\t\t\t\tk,\n\t\t\t\tk,\n\t\t\t),\n\t\t)\n\t\tbuf.WriteString(\"\\n\")\n\t}\n\n\t// Now enumerate the object fields and add those to the base type\n\tfor _, k := range objectFields {\n\t\tfield := r.TopLevel[k]\n\t\tbuf.WriteString(\n\t\t\tfmt.Sprintf(\n\t\t\t\t\"\\t%s %s `json:\\\"%s,omitempty\\\" yaml:\\\"%s,omitempty\\\" ecs:\\\"%s\\\"`\",\n\t\t\t\tfield.FieldIdent().Pascal(),\n\t\t\t\tGoFieldType(field),\n\t\t\t\tfield.Name,\n\t\t\t\tfield.Name,\n\t\t\t\tfield.Path,\n\t\t\t),\n\t\t)\n\t\tbuf.WriteString(\"\\n\")\n\t}\n\n\t// close the struct\n\tbuf.WriteString(\"}\")\n\tbuf.WriteString(\"\\n\")\n\n\t// if the user indicated they wanted a json.Marshaler implementation,\n\t// then generate that.\n\tif b.IncludeJSONMarshal {\n\t\t// Now we have to create the marshaler to account for Zero values!\n\t\t// this will remove object fields that are empty from the resulting JSON.\n\t\t//\n\t\t// The way we do this is by enumerating every field in the top level Base\n\t\t// and check to see if it's got a zero value.\n\t\tbuf.WriteString(\"\\n\")\n\t\tbuf.WriteString(\"// MarshalJSON implements the json.Marshaler interface and removes zero values from returned JSON.\")\n\t\tbuf.WriteString(\"\\n\")\n\t\tbuf.WriteString(\"func (b Base) MarshalJSON() ([]byte, error) {\")\n\t\tbuf.WriteString(\"\\n\")\n\n\t\t// Define the result struct we will populate non-zero fields with\n\t\tbuf.WriteString(\"\\tres := map[string]interface{}{}\")\n\t\tbuf.WriteString(\"\\n\")\n\t\tbuf.WriteString(\"\\n\")\n\n\t\t// first we enumerate the scalar fields\n\t\tfor _, fieldName := range scalarFields {\n\t\t\tfield := r.TopLevel[fieldName]\n\t\t\tbuf.WriteString(\n\t\t\t\tfmt.Sprintf(\n\t\t\t\t\t\"\\tif val := reflect.ValueOf(b.%s); !val.IsZero() {\", field.FieldIdent().Pascal(),\n\t\t\t\t),\n\t\t\t)\n\t\t\tbuf.WriteString(\n\t\t\t\tfmt.Sprintf(\n\t\t\t\t\t\"\\t\\tres[\\\"%s\\\"] = b.%s\",\n\t\t\t\t\tfieldName,\n\t\t\t\t\tfield.FieldIdent().Pascal(),\n\t\t\t\t),\n\t\t\t)\n\t\t\tbuf.WriteString(\"\\t}\")\n\t\t\tbuf.WriteString(\"\\n\")\n\t\t\tbuf.WriteString(\"\\n\")\n\t\t}\n\n\t\t// now we enumerate the object fields\n\t\tfor _, fieldName := range objectFields {\n\t\t\tfield := r.TopLevel[fieldName]\n\t\t\tbuf.WriteString(\n\t\t\t\tfmt.Sprintf(\n\t\t\t\t\t\"\\tif val := reflect.ValueOf(b.%s); !val.IsZero() {\", field.FieldIdent().Pascal(),\n\t\t\t\t),\n\t\t\t)\n\t\t\tbuf.WriteString(\n\t\t\t\tfmt.Sprintf(\n\t\t\t\t\t\"\\t\\tres[\\\"%s\\\"] = b.%s\",\n\t\t\t\t\tfield.Name,\n\t\t\t\t\tfield.FieldIdent().Pascal(),\n\t\t\t\t),\n\t\t\t)\n\t\t\tbuf.WriteString(\"\\t}\")\n\t\t\tbuf.WriteString(\"\\n\")\n\t\t\tbuf.WriteString(\"\\n\")\n\t\t}\n\n\t\t// add a line spacer and return the marshaled JSON result\n\t\tbuf.WriteString(\"\\n\")\n\t\tbuf.WriteString(\"\\treturn json.Marshal(res)\")\n\t\tbuf.WriteString(\"\\n\")\n\t\tbuf.WriteString(\"}\")\n\t\tbuf.WriteString(\"\\n\")\n\t}\n\n\treturn buf.String(), nil\n}", "func NewBaseSmartContract(parent object.Parent) *BaseSmartContract {\n\t// TODO: NewCompositeHolder\n\treturn &BaseSmartContract{\n\t\tCompositeMap: make(map[string]factory.Composite),\n\t\tChildStorage: storage.NewMapStorage(),\n\t\tParent: parent,\n\t}\n}", "func NewBasePayload(payload []byte, source string, meta *property.Configuration) *BasePayload {\n\tpay := &BasePayload{\n\t\tPayload: payload,\n\t\tSource: source,\n\t}\n\tif meta != nil {\n\t\tpay.Metadata = meta\n\t} else {\n\t\tpay.Metadata = property.NewConfiguration()\n\t}\n\treturn pay\n}", "func (k *Keybase) NewWallet() Wallet {\n\treturn Wallet{\n\t\tkeybase: k,\n\t}\n}", "func createTreasuryBaseTx(subsidyCache *standalone.SubsidyCache, nextBlockHeight int64, voters uint16) (*dcrutil.Tx, error) {\n\t// Create provably pruneable script for the output that encodes the block\n\t// height used to ensure a unique overall transaction hash. This is\n\t// necessary because neither the input nor the output that adds to the\n\t// treasury account balance are unique for a treasurybase.\n\topReturnTreasury, err := standardTreasurybaseOpReturn(uint32(nextBlockHeight))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Create a treasurybase with expected inputs and outputs.\n\t//\n\t// Inputs:\n\t// - A single input with input value set to the total payout amount.\n\t//\n\t// Outputs:\n\t// - Treasury output that adds to the treasury account balance\n\t// - Output that includes the block height to ensure a unique hash\n\t//\n\t// Note that all treasurybase transactions require TxVersionTreasury and\n\t// they must be in the stake transaction tree.\n\tconst withTreasury = true\n\ttrsySubsidy := subsidyCache.CalcTreasurySubsidy(nextBlockHeight, voters,\n\t\twithTreasury)\n\ttx := wire.NewMsgTx()\n\ttx.Version = wire.TxVersionTreasury\n\ttx.AddTxIn(&wire.TxIn{\n\t\t// Treasurybase transactions have no inputs, so previous outpoint\n\t\t// is zero hash and max index.\n\t\tPreviousOutPoint: *wire.NewOutPoint(&chainhash.Hash{},\n\t\t\twire.MaxPrevOutIndex, wire.TxTreeRegular),\n\t\tSequence: wire.MaxTxInSequenceNum,\n\t\tBlockHeight: wire.NullBlockHeight,\n\t\tBlockIndex: wire.NullBlockIndex,\n\t\tSignatureScript: nil, // Must be nil by consensus.\n\t})\n\ttx.TxIn[0].ValueIn = trsySubsidy\n\ttx.AddTxOut(&wire.TxOut{\n\t\tValue: trsySubsidy,\n\t\tVersion: 0,\n\t\tPkScript: []byte{txscript.OP_TADD},\n\t})\n\ttx.AddTxOut(&wire.TxOut{\n\t\tValue: 0,\n\t\tPkScript: opReturnTreasury,\n\t})\n\tretTx := dcrutil.NewTx(tx)\n\tretTx.SetTree(wire.TxTreeStake)\n\treturn retTx, nil\n}", "func NewBase(opt Opts) Dialer {\n\trv := &base{\n\t\tnetDialer: net.Dialer{\n\t\t\tTimeout: opt.GetTimeout(),\n\t\t\tControl: reuseport.Control,\n\t\t},\n\t\ttlsConfigs: cache.New(TLSConfigCacheSize,\n\t\t\tTLSConfigTTL,\n\t\t\tcache.NoopEvictCallback),\n\t\ttlsSkipVerify: opt.GetTLSSkipVerify(),\n\t}\n\n\treturn rv\n}", "func NewBase(bytes []byte) IO {\n\treturn DefaultOption.base.NewFromBytes(bytes)\n}", "func NewContinuousVestingAccountRaw(bva *BaseVestingAccount, startTime int64) *ContinuousVestingAccount {\n\treturn &ContinuousVestingAccount{\n\t\tBaseVestingAccount: bva,\n\t\tStartTime: startTime,\n\t}\n}", "func CreateBaseRequest(method, url string, body []byte, user m.AuthUser, verbose bool) *http.Request {\n\treq, err := http.NewRequest(method, url, bytes.NewBuffer(body))\n\treq.SetBasicAuth(user.Username, user.Password)\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\treq.Header.Set(\"Accept\", \"application/json\")\n\tError(err, \"Error creating the request\")\n\n\tif verbose {\n\t\tfmt.Println(\"Request Url:\", req.URL)\n\t\tfmt.Println(\"Request Headers:\", req.Header)\n\t\tfmt.Println(\"Request Body:\", req.Body)\n\t}\n\n\treturn req\n}", "func NewBaseModel() *BaseModel {\n\tbaseModel := new(BaseModel)\n\n\t// initialize unique id\n\tbaseModel.Id = xid.New().String()\n\tbaseModel.CreatedOn = time.Now()\n\tbaseModel.Persisted = false\n\n\treturn baseModel\n}", "func (account *Account) New() {\n\n\tparams, _ := pbc.NewParamsFromString(crypto.Params)\n\tpairing := params.NewPairing()\n\n\tA := pairing.NewG1()\n\tAT := pairing.NewG1()\n\ta := pairing.NewZr()\n\n\ta.Rand()\n\n\tG := pairing.NewG1()\n\tT := pairing.NewG1()\n\tG.SetString(crypto.G, 10)\n\tT.SetString(crypto.T, 10)\n\n\tA.PowZn(G, a)\n\tAT.PowZn(T, a)\n\n\taccount.a = a.String()\n\taccount.A = A.String()\n\taccount.AT = AT.String()\n}", "func createCoinbaseTx(subsidyCache *standalone.SubsidyCache,\n\tcoinbaseScript []byte, opReturnPkScript []byte, nextBlockHeight int64,\n\taddr stdaddr.Address, voters uint16, params *chaincfg.Params,\n\tisTreasuryEnabled bool,\n\tsubsidySplitVariant standalone.SubsidySplitVariant) *dcrutil.Tx {\n\n\t// Coinbase transactions have no inputs, so previous outpoint is zero hash\n\t// and max index.\n\tcoinbaseInput := &wire.TxIn{\n\t\tPreviousOutPoint: *wire.NewOutPoint(&chainhash.Hash{},\n\t\t\twire.MaxPrevOutIndex, wire.TxTreeRegular),\n\t\tSequence: wire.MaxTxInSequenceNum,\n\t\tBlockHeight: wire.NullBlockHeight,\n\t\tBlockIndex: wire.NullBlockIndex,\n\t\tSignatureScript: coinbaseScript,\n\t}\n\n\t// Block one is a special block that might pay out tokens to a ledger.\n\tif nextBlockHeight == 1 && len(params.BlockOneLedger) != 0 {\n\t\ttx := wire.NewMsgTx()\n\t\ttx.Version = 1\n\t\ttx.AddTxIn(coinbaseInput)\n\t\ttx.TxIn[0].ValueIn = params.BlockOneSubsidy()\n\n\t\tfor _, payout := range params.BlockOneLedger {\n\t\t\ttx.AddTxOut(&wire.TxOut{\n\t\t\t\tValue: payout.Amount,\n\t\t\t\tVersion: payout.ScriptVersion,\n\t\t\t\tPkScript: payout.Script,\n\t\t\t})\n\t\t}\n\n\t\treturn dcrutil.NewTx(tx)\n\t}\n\n\t// Prior to the decentralized treasury agenda, the transaction version must\n\t// be 1 and there is an additional output that either pays to organization\n\t// associated with the treasury or a provably pruneable zero-value output\n\t// script when it is disabled.\n\t//\n\t// Once the decentralized treasury agenda is active, the transaction version\n\t// must be the new expected version and there is no treasury output since it\n\t// is included in the stake tree instead.\n\tvar txVersion = uint16(1)\n\tvar treasuryOutput *wire.TxOut\n\tvar treasurySubsidy int64\n\tif !isTreasuryEnabled {\n\t\tif params.BlockTaxProportion > 0 {\n\t\t\t// Create the treasury output with the correct subsidy and public\n\t\t\t// key script for the organization associated with the treasury.\n\t\t\ttreasurySubsidy = subsidyCache.CalcTreasurySubsidy(nextBlockHeight,\n\t\t\t\tvoters, isTreasuryEnabled)\n\t\t\ttreasuryOutput = &wire.TxOut{\n\t\t\t\tValue: treasurySubsidy,\n\t\t\t\tPkScript: params.OrganizationPkScript,\n\t\t\t}\n\t\t} else {\n\t\t\t// Treasury disabled.\n\t\t\ttreasuryOutput = &wire.TxOut{\n\t\t\t\tValue: 0,\n\t\t\t\tPkScript: opTrueScript,\n\t\t\t}\n\t\t}\n\t} else {\n\t\t// Set the transaction version to the new version required by the\n\t\t// decentralized treasury agenda.\n\t\ttxVersion = wire.TxVersionTreasury\n\t}\n\n\t// Create the script to pay to the provided payment address if one was\n\t// specified. Otherwise create a script that allows the coinbase to be\n\t// redeemable by anyone.\n\tworkSubsidyScriptVer := uint16(0)\n\tworkSubsidyScript := opTrueScript\n\tif addr != nil {\n\t\tworkSubsidyScriptVer, workSubsidyScript = addr.PaymentScript()\n\t}\n\n\t// Create a coinbase with expected inputs and outputs.\n\t//\n\t// Inputs:\n\t// - A single input with input value set to the total payout amount.\n\t//\n\t// Outputs:\n\t// - Potential treasury output prior to the decentralized treasury agenda\n\t// - Output that includes the block height and potential extra nonce used\n\t// to ensure a unique hash\n\t// - Output that pays the work subsidy to the miner\n\tworkSubsidy := subsidyCache.CalcWorkSubsidyV3(nextBlockHeight, voters,\n\t\tsubsidySplitVariant)\n\ttx := wire.NewMsgTx()\n\ttx.Version = txVersion\n\ttx.AddTxIn(coinbaseInput)\n\ttx.TxIn[0].ValueIn = workSubsidy + treasurySubsidy\n\tif treasuryOutput != nil {\n\t\ttx.AddTxOut(treasuryOutput)\n\t}\n\ttx.AddTxOut(&wire.TxOut{\n\t\tValue: 0,\n\t\tPkScript: opReturnPkScript,\n\t})\n\ttx.AddTxOut(&wire.TxOut{\n\t\tValue: workSubsidy,\n\t\tVersion: workSubsidyScriptVer,\n\t\tPkScript: workSubsidyScript,\n\t})\n\treturn dcrutil.NewTx(tx)\n}", "func NewFunctionBase(ctx sctx.Context, funcName string, retType *types.FieldType, args ...Expression) (Expression, error) {\n\treturn newFunctionImpl(ctx, false, funcName, retType, args...)\n}", "func createCoinbaseTx() *Tx {\n\ttxIns := []*TxIn{{\"\", -1, coinbaseAddress}}\n\ttxOuts := []*TxOut{{wallet.Wallet().Address, minerReward}}\n\ttx := Tx{\n\t\tId: \"\",\n\t\tTimestamp: int(time.Now().Unix()),\n\t\tTxIns: txIns,\n\t\tTxOuts: txOuts,\n\t}\n\ttx.getId() // attach an ID to the given transaction via hashing\n\treturn &tx\n}", "func Base() IBase {\n\treturn &base{\n\t\thpadding: BaseHPadding,\n\t\tvpadding: 12,\n\t}\n}", "func NewIdentityProviderBase()(*IdentityProviderBase) {\n m := &IdentityProviderBase{\n Entity: *NewEntity(),\n }\n return m\n}", "func (t *ticket) Base() []byte {\n\tvar expiration string\n\tif !t.expireAt.IsZero() {\n\t\texpiration = strconv.FormatInt(t.expireAt.UnixNano()/1000/1000, 10)\n\t}\n\treturn []byte(t.macPrefix + \"*\" + t.passwordID + \"*\" + string(t.cryptSalt) + \"*\" + t.iv64 + \"*\" + t.encrypted64 + \"*\" + expiration)\n}", "func NewBaseImpl(buf []byte) *BaseImpl {\n\treturn &BaseImpl{bytes: buf}\n}", "func newBaseRunner(collector *resourceStatusCollector) *baseRunner {\n\treturn &baseRunner{\n\t\tcollector: collector,\n\t}\n}", "func NewWithBaseURI(baseURI string, ) BaseClient {\n return BaseClient{\n Client: autorest.NewClientWithUserAgent(UserAgent()),\n BaseURI: baseURI,\n }\n}", "func NewAccount(owner string) *Account {\n\treturn &Account{owner: owner, balance: 0}\n}", "func NewKeybase(dir string) (*Keybase, error) {\n\tkb, err := clientkey.NewKeyBaseFromDir(dir)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Keybase{\n\t\tkb: kb,\n\t\tprivKeysCache: make(map[[sha256.Size]byte]crypto.PrivKey),\n\t}, nil\n}", "func NewBaseNode(\n\tname string, \n\tparent INode, \n\tsceneManager *SceneManager, \n\tposition Vector2d) *BaseNode {\n\n\tlastNodeId++\n\treturn &BaseNode {\n\t\tlastNodeId,\n\t\tname, \n\t\tparent,\n\t\tsceneManager,\n\t\tposition, \n\t\tmake(map[uint]INode), \n\t\tmake(map[uint]*Object)}\n}", "func NewBaseService(srv Service, name string) *BaseService {\n\treturn &BaseService{\n\t\tname: name,\n\t\tqueue: queue.NewQueue(),\n\t\tservice: srv,\n\t}\n}", "func Base(props *BaseProps, children ...Element) *BaseElem {\n\trProps := &_BaseProps{\n\t\tBasicHTMLElement: newBasicHTMLElement(),\n\t}\n\n\tif props != nil {\n\t\tprops.assign(rProps)\n\t}\n\n\treturn &BaseElem{\n\t\tElement: createElement(\"base\", rProps, children...),\n\t}\n}", "func NewAccount(addr, amount string) *Account {\n\tam := big.NewInt(0)\n\tam.SetString(amount, 0)\n\treturn &Account{Address: addr, Amount: am}\n}", "func (ga *GenesisAccount) ToAccount() auth.Account {\n\tbacc := &auth.BaseAccount{\n\t\tAddress: ga.Address,\n\t\tCoins: ga.Coins.Sort(),\n\t\tAccountNumber: ga.AccountNumber,\n\t\tSequence: ga.Sequence,\n\t}\n\n\tif !ga.OriginalVesting.IsZero() {\n\t\tbaseVestingAcc := &auth.BaseVestingAccount{\n\t\t\tBaseAccount: bacc,\n\t\t\tOriginalVesting: ga.OriginalVesting,\n\t\t\tDelegatedFree: ga.DelegatedFree,\n\t\t\tDelegatedVesting: ga.DelegatedVesting,\n\t\t\tEndTime: ga.EndTime,\n\t\t}\n\n\t\tif ga.StartTime != 0 && ga.EndTime != 0 {\n\t\t\treturn &auth.ContinuousVestingAccount{\n\t\t\t\tBaseVestingAccount: baseVestingAcc,\n\t\t\t\tStartTime: ga.StartTime,\n\t\t\t}\n\t\t} else if ga.EndTime != 0 {\n\t\t\treturn &auth.DelayedVestingAccount{\n\t\t\t\tBaseVestingAccount: baseVestingAcc,\n\t\t\t}\n\t\t} else {\n\t\t\tpanic(fmt.Sprintf(\"invalid genesis vesting account: %+v\", ga))\n\t\t}\n\t}\n\n\treturn bacc\n}", "func (ws *WebServer) NewAccount(c *gin.Context) {\n\tnetwork := ws.nodeConfig.GetNetwork()\n\tif network == \"\" {\n\t\tReturnError(c, 500, ErrorNoNetwork.Error())\n\t\treturn\n\t}\n\tn := sdk.Testnet\n\tif network == \"bitmark\" {\n\t\tn = sdk.Livenet\n\t}\n\tseedFile := filepath.Join(ws.rootPath, \"bitmarkd\", network, \"proof.sign\")\n\tif _, err := os.Stat(seedFile); err == nil {\n\t\tReturnError(c, 500, ErrorNoSeedFile.Error())\n\t\treturn\n\t}\n\n\ta, err := sdk.NewAccount(n)\n\tif err != nil {\n\t\tReturnError(c, 500, ErrorCreateAccount.Error())\n\t\treturn\n\t}\n\tseed := a.Seed()\n\n\tf, err := os.OpenFile(seedFile, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0600)\n\tif err != nil {\n\t\tReturnError(c, 500, ErrorOpenSeedFile.Error())\n\t\treturn\n\t}\n\tdefer f.Close()\n\n\t_, err = f.WriteString(fmt.Sprintf(\"SEED:%s\", seed))\n\tif err != nil {\n\t\tReturnError(c, 500, ErrorToWriteSeedFile.Error())\n\t\treturn\n\t}\n\tws.SetAccount(a.AccountNumber(), seed, network) // Record in AccountInfo in memory\n\terr = ws.saveAcct()\n\tif nil != err {\n\t\tReturnError(c, 500, ErrorAutoSaveAccount.Error())\n\t\treturn\n\n\t}\n\tc.JSON(200, map[string]interface{}{\n\t\t\"ok\": 1,\n\t})\n}", "func NewAccount(user, apiKey string) *Account {\n\treturn &Account{user: user, apiKey: apiKey}\n}", "func (b *BaseImpl) New(n Base) Base {\n\treturn n\n}", "func NewBaseElement(c BaseElementConfig) ElementI {\n\tb := BaseElement{}\n\tb.This = ElementI(&b)\n\tb.Style.Parse(c.Style)\n\tb.Events = c.Events\n\tb.SetupChannels()\n\tb.OnCreated()\n\n\treturn ElementI(&b)\n}", "func NewPersonalNameBase() *PersonalNameBase {\n\treturn &PersonalNameBase{}\n}", "func newBaseConn(conn net.Conn) *BaseConn {\n\n\tb := new(BaseConn)\n\tb.conn = conn\n\n\tb.disconnected = make(chan struct{})\n\tb.send = make(chan *baseproto.Message, 5)\n\tb.stop = make(chan struct{})\n\tb.receivedCapabilities = make(chan *baseproto.Message, 1)\n\tb.received = make(chan *baseproto.Message, 5)\n\n\tb.Received = b.received\n\tb.Disconnected = b.disconnected\n\n\tgo b.readLoop()\n\tgo b.writeLoop()\n\n\treturn b\n}", "func (c *CoinTest) newAccount(stub shim.ChaincodeStubInterface, args []string) pb.Response {\r\n\tvar id string\r\n\tvar asset int\r\n\tvar err error\r\n\r\n\tif len(args) == 1{\r\n\t\tid = args[0]\r\n\t\tasset = 0\r\n\t}else if len(args) == 2{\r\n\t\tid = args[0]\r\n\t\t//asset, err = strconv.Atoi(args[1])\r\n\t\t//if err != nil{\r\n\t\t//\treturn shim.Error(\"Invalid asset amount, expecting a integer value\")\r\n\t\t//}\r\n\t\tasset = 0;\r\n\t}else{\r\n\t\treturn shim.Error(\"Incorrect number of arguments.\")\r\n\t}\r\n\r\n\t//deliver 0 number of TolakCoin to user\r\n\ttolakCoin.Token.Deliver(token.Address(id), int(asset))\r\n\r\n\t//write to ledger\r\n\terr = stub.PutState(id, []byte(strconv.Itoa(asset)))\r\n\tif err != nil{\r\n\t\treturn shim.Error(err.Error())\r\n\t}\r\n\r\n\treturn shim.Success(nil)\r\n}", "func NewBaseProvider(no *Options) Provider {\n\treturn &BaseProvider{\n\t\tNewActions(no),\n\t\tNewDuelLinks(no),\n\t\tNewMisc(no),\n\t}\n}", "func newContentBasedVDR(v vdr.Registry, c *contentStore) *walletVDR {\n\treturn &walletVDR{Registry: v, contents: c}\n}", "func (ctx *Context) WithTemplateBase(tmplBase wfv1.TemplateHolder) *Context {\n\treturn NewContext(ctx.wftmplGetter, ctx.cwftmplGetter, tmplBase, ctx.workflow)\n}", "func NewAccount(txr *repository.Transactioner) repository.Account {\n\treturn &account{txr: txr}\n}", "func NewBaseClient(cdc sdk.SDKCodec, pConfig *sdk.ClientConfig) *baseClient {\n\treturn &baseClient{\n\t\tRPCClient: rpcCli.NewHTTP(pConfig.NodeURI, \"/websocket\"),\n\t\tconfig: pConfig,\n\t\tcdc: cdc,\n\t}\n}", "func NewBaseClient(cdc sdk.SDKCodec, pConfig *sdk.ClientConfig) *baseClient {\n\treturn &baseClient{\n\t\tRPCClient: rpcCli.NewHTTP(pConfig.NodeURI, \"/websocket\"),\n\t\tconfig: pConfig,\n\t\tcdc: cdc,\n\t}\n}", "func RenewBaseCosts(lastRev types.FileContractRevision, pt *RPCPriceTable, endHeight types.BlockHeight) (basePrice, baseCollateral types.Currency) {\n\t// Get the height until which the storage is already paid for, the height\n\t// until which we want to pay for storage and the amount of storage that\n\t// needs to be covered.\n\tpaidForUntil := lastRev.NewWindowEnd\n\tpayForUntil := endHeight + pt.WindowSize\n\tstorage := lastRev.NewFileSize\n\t// The base is the rpc cost.\n\tbasePrice = pt.RenewContractCost\n\t// If the storage is already covered, or if there is no data yet, there is\n\t// no base cost associated with this renewal.\n\tif paidForUntil >= payForUntil || storage == 0 {\n\t\treturn\n\t}\n\t// Otherwise we calculate the number of blocks we still need to pay for and\n\t// the amount of cost and collateral expected.\n\ttimeExtension := uint64(payForUntil - paidForUntil)\n\tbasePrice = basePrice.Add(pt.WriteStoreCost.Mul64(storage).Mul64(timeExtension)) // cost of already uploaded data that needs to be covered by the renewed contract.\n\tbaseCollateral = pt.CollateralCost.Mul64(storage).Mul64(timeExtension) // same as basePrice.\n\treturn\n}", "func NewBaseAccessWalletCaller(address common.Address, caller bind.ContractCaller) (*BaseAccessWalletCaller, error) {\n\tcontract, err := bindBaseAccessWallet(address, caller, nil, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &BaseAccessWalletCaller{contract: contract}, nil\n}", "func NewFundedAccount() *keypair.Full {\n\tkp, err := keypair.Random()\n\tif err != nil {\n\t\tlog.Fatal(err, \"generating random keypair\")\n\t}\n\terr = FundAccount(kp.Address())\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tlog.Printf(\"successfully funded %s\", kp.Address())\n\treturn kp\n}", "func New()BaseClient {\n return NewWithBaseURI(DefaultBaseURI, )\n}", "func newFiltBase(n int, mu float64, w []float64) (AdaptiveFilter, error) {\n\tvar err error\n\tp := new(filtBase)\n\tp.kind = \"Base filter\"\n\tp.n = n\n\tp.muMin = 0\n\tp.muMax = 1000\n\tp.mu, err = p.checkFloatParam(mu, p.muMin, p.muMax, \"mu\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = p.initWeights(w, n)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn p, nil\n}", "func (b *Base) NewSerializer() serializers.Serializer {\n\tb.mutex.Lock()\n\n\tb.ReservedStrings.ID = b.FormatAttributeName(ID)\n\tb.ReservedStrings.IDs = b.FormatAttributeName(IDs)\n\tb.ReservedStrings.Links = b.FormatAttributeName(Links)\n\tb.ReservedStrings.Linked = b.FormatAttributeName(Linked)\n\tb.ReservedStrings.Meta = b.FormatAttributeName(Meta)\n\tb.ReservedStrings.Data = b.FormatAttributeName(Data)\n\tb.ReservedStrings.Type = b.FormatAttributeName(Type)\n\tb.ReservedStrings.Href = b.FormatAttributeName(Href)\n\n\tvar serializer = &serializers.Base{\n\t\tTypeNameFormatter: b.TypeNameFormatter,\n\t\tAttributeNameFormatter: b.AttributeNameFormatter,\n\t\tHrefFormatter: b.HrefFormatter,\n\t\tReservedStrings: b.ReservedStrings,\n\t\tLinkedDocuments: make(map[interface{}]struct{}),\n\t}\n\n\tb.mutex.Unlock()\n\n\treturn serializer\n}", "func newPeerBase(origCfg *Config, inbound bool) *Peer {\n\t// Default to the max supported protocol version if not specified by the\n\t// caller.\n\tcfg := *origCfg // Copy to avoid mutating caller.\n\tif cfg.ProtocolVersion == 0 {\n\t\tcfg.ProtocolVersion = MaxProtocolVersion\n\t}\n\n\t// Set the chain parameters to testnet if the caller did not specify any.\n\tif cfg.ChainParams == nil {\n\t\tcfg.ChainParams = &chaincfg.TestNet3Params\n\t}\n\n\t// Set the trickle interval if a non-positive value is specified.\n\tif cfg.TrickleInterval <= 0 {\n\t\tcfg.TrickleInterval = DefaultTrickleInterval\n\t}\n\n\tp := Peer{\n\t\tinbound: inbound,\n\t\twireEncoding: wire.BaseEncoding,\n\t\tknownInventory: lru.NewCache(maxKnownInventory),\n\t\tstallControl: make(chan stallControlMsg, 1), // nonblocking sync\n\t\toutputQueue: make(chan outMsg, outputBufferSize),\n\t\tsendQueue: make(chan outMsg, 1), // nonblocking sync\n\t\tsendDoneQueue: make(chan struct{}, 1), // nonblocking sync\n\t\toutputInvChan: make(chan *wire.InvVect, outputBufferSize),\n\t\tinQuit: make(chan struct{}),\n\t\tqueueQuit: make(chan struct{}),\n\t\toutQuit: make(chan struct{}),\n\t\tquit: make(chan struct{}),\n\t\tcfg: cfg, // Copy so caller can't mutate.\n\t\tservices: cfg.Services,\n\t\tprotocolVersion: cfg.ProtocolVersion,\n\t}\n\treturn &p\n}", "func New(config Config, root *Account) (*Thereum, error) {\n\t// init the configured db\n\tdb := config.DB()\n\t// delay := config.Delayer()\n\n\t// init the genesis block + any accounts designated in config.Allocaiton\n\tgenesis, accounts, err := config.Genesis()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tgenBlock := genesis.MustCommit(db)\n\n\tif root == nil {\n\t\troot, _ = NewAccount(\"defaultRoot\", big.NewInt(100))\n\t}\n\tchainConfig := params.AllEthashProtocolChanges\n\tchainConfig.ChainID = big.NewInt(1)\n\tbc, _ := core.NewBlockChain(db, nil, chainConfig, ethash.NewFaker(), vm.Config{}, nil)\n\tt := &Thereum{\n\t\ttxPool: txpool.NewLinkedPool(),\n\t\tdatabase: db,\n\t\tblockchain: bc,\n\t\tsigner: types.NewEIP155Signer(big.NewInt(1)),\n\t\troot: root,\n\t\tgasLimit: config.GasLimit, // TODO: config and make more flexible\n\t\tDelay: int(config.Delay),\n\t\tEvents: filters.NewEventSystem(&filterBackend{db: db, bc: bc}, false),\n\t\tAccounts: accounts,\n\t}\n\tt.pendingBlock = genBlock\n\tt.chainConfig = chainConfig\n\treturn t, nil\n}", "func NewStarbase(x int, y int) *Starbase {\n\treturn &Starbase{\n\t\tX: x,\n\t\tY: y,\n\t\tShields: 10000}\n}", "func (va ClawbackVestingAccount) Validate() error {\n\tif va.GetStartTime() >= va.GetEndTime() {\n\t\treturn errors.New(\"vesting start-time must be before end-time\")\n\t}\n\n\tlockupEnd := va.StartTime\n\tlockupCoins := sdk.NewCoins()\n\tfor _, p := range va.LockupPeriods {\n\t\tlockupEnd += p.Length\n\t\tlockupCoins = lockupCoins.Add(p.Amount...)\n\t}\n\tif lockupEnd > va.EndTime {\n\t\treturn errors.New(\"lockup schedule extends beyond account end time\")\n\t}\n\tif !coinEq(lockupCoins, va.OriginalVesting) {\n\t\treturn errors.New(\"original vesting coins does not match the sum of all coins in lockup periods\")\n\t}\n\n\tvestingEnd := va.StartTime\n\tvestingCoins := sdk.NewCoins()\n\tfor _, p := range va.VestingPeriods {\n\t\tvestingEnd += p.Length\n\t\tvestingCoins = vestingCoins.Add(p.Amount...)\n\t}\n\tif vestingEnd > va.EndTime {\n\t\treturn errors.New(\"vesting schedule exteds beyond account end time\")\n\t}\n\tif !coinEq(vestingCoins, va.OriginalVesting) {\n\t\treturn errors.New(\"original vesting coins does not match the sum of all coins in vesting periods\")\n\t}\n\n\treturn va.BaseVestingAccount.Validate()\n}", "func TestDepositEthNew(t *testing.T) {\n\tenv, err := loadTestEnv()\n\tif err != nil {\n\t\tt.Errorf(\"error loading test for deposit =: %v\", err)\n\t}\n\tclient, err := ethclient.Dial(env.EthClient)\n\tif err != nil {\n\t\tt.Errorf(\"error initializing Ethereum client for deposit =: %v\", err)\n\t}\n\trc := rootchain.NewClient(client)\n\n\tdepositTx := rc.NewDeposit(common.HexToAddress(env.EthVault), common.HexToAddress(util.DeriveAddress(env.Privatekey)), common.HexToAddress(util.EthCurrency), env.DepositAmount)\n\tprivateKey, err := crypto.HexToECDSA(util.FilterZeroX(env.Privatekey))\n\tif err != nil {\n\t\tt.Errorf(\"bad privatekey: %v\", err)\n\t}\n\tgasPrice, _ := client.SuggestGasPrice(context.Background())\n\ttxopts := bind.NewKeyedTransactor(privateKey)\n\ttxopts.From = common.HexToAddress(util.DeriveAddress(env.Privatekey))\n\ttxopts.GasLimit = 2000000\n\tbvalue, _ := new(big.Int).SetString(env.DepositAmount, 0)\n\ttxopts.Value = bvalue\n\ttxopts.GasPrice = gasPrice\n\tif err := rootchain.Options(depositTx, txopts); err != nil {\n\t\tt.Errorf(\"transaction options invalid, %v\", err)\n\t}\n\tif err := rootchain.Build(depositTx); err != nil {\n\t\tt.Errorf(\"deposit build error, %v\", err)\n\t}\n\ttx, err := rootchain.Submit(depositTx)\n\tif err != nil {\n\t\tt.Errorf(\"error submiting transaction for deposit =: %v\", err)\n\t}\n\n\tfmt.Printf(\"%v\", tx.Hash().Hex())\n\tsleep(t)\n\tstatus := checkReceipt(tx.Hash().Hex(), t)\n\tif status == false {\n\t\tt.Error(\"transaction failed\")\n\t}\n\n}", "func NewBaseEvent(eventType EventType, entities map[string]Entity) BaseEvent {\n\treturn BaseEvent{\n\t\teventType: eventType,\n\t\tentities: entities,\n\t}\n}" ]
[ "0.6104842", "0.6026493", "0.5996286", "0.59705764", "0.59615064", "0.5825349", "0.5822085", "0.5796595", "0.57819426", "0.56177527", "0.5608643", "0.5536669", "0.5514407", "0.5498089", "0.5485557", "0.5421935", "0.5353438", "0.5348021", "0.5331462", "0.5248329", "0.5199846", "0.5198199", "0.5168915", "0.5160545", "0.514945", "0.51182634", "0.5094139", "0.509313", "0.5089542", "0.5077891", "0.5041113", "0.5031927", "0.500226", "0.49546385", "0.49474734", "0.49474734", "0.49224004", "0.49218583", "0.49114257", "0.49019822", "0.48995274", "0.4897829", "0.48873025", "0.48765832", "0.4871402", "0.4859657", "0.48594666", "0.48570257", "0.4856704", "0.48467588", "0.48312774", "0.47948095", "0.47883898", "0.47852182", "0.4781126", "0.47810626", "0.4780635", "0.4775217", "0.47579187", "0.47542924", "0.47539517", "0.47496116", "0.47350693", "0.4727855", "0.4725647", "0.47218212", "0.4721008", "0.47187975", "0.4699738", "0.46978694", "0.46908376", "0.46814722", "0.46808046", "0.4650504", "0.46498668", "0.46431538", "0.46374995", "0.46356693", "0.46348757", "0.46307155", "0.46273223", "0.46134484", "0.46110582", "0.4601954", "0.45971736", "0.45971364", "0.45841745", "0.45841745", "0.45814946", "0.4580058", "0.4579668", "0.45781457", "0.4569585", "0.45633423", "0.45517874", "0.45505178", "0.45442995", "0.45401058", "0.4533243", "0.45331556" ]
0.8610524
0
LockedCoinsFromVesting returns all the coins that are not spendable (i.e. locked) for a vesting account given the current vesting coins. If no coins are locked, an empty slice of Coins is returned. CONTRACT: Delegated vesting coins and vestingCoins must be sorted.
func (bva BaseVestingAccount) LockedCoinsFromVesting(vestingCoins sdk.Coins) sdk.Coins { lockedCoins := vestingCoins.Sub(vestingCoins.Min(bva.DelegatedVesting)) if lockedCoins == nil { return sdk.Coins{} } return lockedCoins }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (pva PeriodicVestingAccount) LockedCoins(ctx sdk.Context) sdk.Coins {\n\treturn pva.BaseVestingAccount.LockedCoinsFromVesting(pva.GetVestingCoins(ctx.BlockTime()))\n}", "func (dva DelayedVestingAccount) LockedCoins(ctx sdk.Context) sdk.Coins {\n\treturn dva.BaseVestingAccount.LockedCoinsFromVesting(dva.GetVestingCoins(ctx.BlockTime()))\n}", "func (va ClawbackVestingAccount) LockedCoins(ctx sdk.Context) sdk.Coins {\n\treturn va.BaseVestingAccount.LockedCoinsFromVesting(va.GetVestingCoins(ctx.BlockTime()))\n}", "func (cva ContinuousVestingAccount) LockedCoins(ctx sdk.Context) sdk.Coins {\n\treturn cva.BaseVestingAccount.LockedCoinsFromVesting(cva.GetVestingCoins(ctx.BlockTime()))\n}", "func (plva PermanentLockedAccount) GetVestingCoins(_ time.Time) sdk.Coins {\n\treturn plva.OriginalVesting\n}", "func (plva PermanentLockedAccount) LockedCoins(_ sdk.Context) sdk.Coins {\n\treturn plva.BaseVestingAccount.LockedCoinsFromVesting(plva.OriginalVesting)\n}", "func (vva ValidatorVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn vva.OriginalVesting.Sub(vva.GetVestedCoins(blockTime))\n}", "func (dva DelayedVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn dva.OriginalVesting.Sub(dva.GetVestedCoins(blockTime))\n}", "func (va ClawbackVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn va.OriginalVesting.Sub(va.GetVestedCoins(blockTime))\n}", "func (pva PeriodicVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn pva.OriginalVesting.Sub(pva.GetVestedCoins(blockTime))\n}", "func (plva PermanentLockedAccount) GetVestedCoins(_ time.Time) sdk.Coins {\n\treturn nil\n}", "func (cva ContinuousVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn cva.OriginalVesting.Sub(cva.GetVestedCoins(blockTime))\n}", "func (vva ValidatorVestingAccount) GetVestedCoins(blockTime time.Time) sdk.Coins {\n\tvar vestedCoins sdk.Coins\n\tif blockTime.Unix() <= vva.StartTime {\n\t\treturn vestedCoins\n\t}\n\tcurrentPeriodStartTime := vva.StartTime\n\tnumberPeriods := len(vva.VestingPeriods)\n\tfor i := 0; i < numberPeriods; i++ {\n\t\tx := blockTime.Unix() - currentPeriodStartTime\n\t\tif x >= vva.VestingPeriods[i].Length {\n\t\t\tif vva.VestingPeriodProgress[i].PeriodComplete {\n\t\t\t\tvestedCoins = vestedCoins.Add(vva.VestingPeriods[i].Amount)\n\t\t\t}\n\t\t\tcurrentPeriodStartTime += vva.VestingPeriods[i].Length\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn vestedCoins\n\n}", "func (cva ContinuousVestingAccount) GetVestedCoins(blockTime time.Time) sdk.Coins {\n\tvar vestedCoins sdk.Coins\n\n\t// We must handle the case where the start time for a vesting account has\n\t// been set into the future or when the start of the chain is not exactly\n\t// known.\n\tif blockTime.Unix() <= cva.StartTime {\n\t\treturn vestedCoins\n\t} else if blockTime.Unix() >= cva.EndTime {\n\t\treturn cva.OriginalVesting\n\t}\n\n\t// calculate the vesting scalar\n\tx := blockTime.Unix() - cva.StartTime\n\ty := cva.EndTime - cva.StartTime\n\ts := sdk.NewDec(x).Quo(sdk.NewDec(y))\n\n\tfor _, ovc := range cva.OriginalVesting {\n\t\tvestedAmt := ovc.Amount.ToDec().Mul(s).RoundInt()\n\t\tvestedCoins = append(vestedCoins, sdk.NewCoin(ovc.Denom, vestedAmt))\n\t}\n\n\treturn vestedCoins\n}", "func (dva DelayedVestingAccount) GetVestedCoins(blockTime time.Time) sdk.Coins {\n\tif blockTime.Unix() >= dva.EndTime {\n\t\treturn dva.OriginalVesting\n\t}\n\n\treturn nil\n}", "func (pva PeriodicVestingAccount) GetVestedCoins(blockTime time.Time) sdk.Coins {\n\tcoins := ReadSchedule(pva.StartTime, pva.EndTime, pva.VestingPeriods, pva.OriginalVesting, blockTime.Unix())\n\tif coins.IsZero() {\n\t\treturn nil\n\t}\n\treturn coins\n}", "func (va ClawbackVestingAccount) GetVestedCoins(blockTime time.Time) sdk.Coins {\n\t// It's likely that one or the other schedule will be nearly trivial,\n\t// so there should be little overhead in recomputing the conjunction each time.\n\tcoins := coinsMin(va.GetUnlockedOnly(blockTime), va.GetVestedOnly(blockTime))\n\tif coins.IsZero() {\n\t\treturn nil\n\t}\n\treturn coins\n}", "func (va ClawbackVestingAccount) GetVestedOnly(blockTime time.Time) sdk.Coins {\n\treturn ReadSchedule(va.StartTime, va.EndTime, va.VestingPeriods, va.OriginalVesting, blockTime.Unix())\n}", "func (vva ValidatorVestingAccount) GetFailedVestedCoins() sdk.Coins {\n\tvar failedVestedCoins sdk.Coins\n\tnumberPeriods := len(vva.VestingPeriods)\n\tfor i := 0; i < numberPeriods; i++ {\n\t\tif vva.VestingPeriodProgress[i].PeriodComplete {\n\t\t\tif !vva.VestingPeriodProgress[i].VestingSuccessful {\n\t\t\t\tfailedVestedCoins = failedVestedCoins.Add(vva.VestingPeriods[i].Amount)\n\t\t\t}\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn failedVestedCoins\n}", "func (vva ValidatorVestingAccount) SpendableCoins(blockTime time.Time) sdk.Coins {\n\treturn vva.BaseVestingAccount.SpendableCoinsVestingAccount(vva.GetVestingCoins(blockTime))\n}", "func (dcr *ExchangeWallet) FundingCoins(ids []dex.Bytes) (asset.Coins, error) {\n\t// First check if we have the coins in cache.\n\tcoins := make(asset.Coins, 0, len(ids))\n\tnotFound := make(map[outPoint]bool)\n\tdcr.fundingMtx.Lock()\n\tdefer dcr.fundingMtx.Unlock() // stay locked until we update the map and lock them in the wallet\n\tfor _, id := range ids {\n\t\ttxHash, vout, err := decodeCoinID(id)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tpt := newOutPoint(txHash, vout)\n\t\tfundingCoin, found := dcr.fundingCoins[pt]\n\t\tif found {\n\t\t\tcoins = append(coins, fundingCoin.op)\n\t\t\tcontinue\n\t\t}\n\t\tnotFound[pt] = true\n\t}\n\tif len(notFound) == 0 {\n\t\treturn coins, nil\n\t}\n\n\t// Check locked outputs for not found coins.\n\tlockedOutputs, err := dcr.lockedOutputs()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor _, output := range lockedOutputs {\n\t\ttxHash, err := chainhash.NewHashFromStr(output.Txid)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error decoding txid from rpc server %s: %w\", output.Txid, err)\n\t\t}\n\t\tpt := newOutPoint(txHash, output.Vout)\n\t\tif !notFound[pt] {\n\t\t\tcontinue\n\t\t}\n\t\ttxOut, err := dcr.node.GetTxOut(dcr.ctx, txHash, output.Vout, true)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"gettxout error for locked output %v: %w\", pt.String(), translateRPCCancelErr(err))\n\t\t}\n\t\tvar address string\n\t\tif len(txOut.ScriptPubKey.Addresses) > 0 {\n\t\t\taddress = txOut.ScriptPubKey.Addresses[0]\n\t\t}\n\t\tcoin := newOutput(txHash, output.Vout, toAtoms(output.Amount), output.Tree)\n\t\tcoins = append(coins, coin)\n\t\tdcr.fundingCoins[pt] = &fundingCoin{\n\t\t\top: coin,\n\t\t\taddr: address,\n\t\t}\n\t\tdelete(notFound, pt)\n\t\tif len(notFound) == 0 {\n\t\t\treturn coins, nil\n\t\t}\n\t}\n\n\t// Some funding coins still not found after checking locked outputs.\n\t// Check wallet unspent outputs as last resort. Lock the coins if found.\n\tunspents, err := dcr.unspents()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcoinsToLock := make([]*wire.OutPoint, 0, len(notFound))\n\tfor _, txout := range unspents {\n\t\ttxHash, err := chainhash.NewHashFromStr(txout.TxID)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error decoding txid from rpc server %s: %w\", txout.TxID, err)\n\t\t}\n\t\tpt := newOutPoint(txHash, txout.Vout)\n\t\tif !notFound[pt] {\n\t\t\tcontinue\n\t\t}\n\t\tcoinsToLock = append(coinsToLock, wire.NewOutPoint(txHash, txout.Vout, txout.Tree))\n\t\tcoin := newOutput(txHash, txout.Vout, toAtoms(txout.Amount), txout.Tree)\n\t\tcoins = append(coins, coin)\n\t\tdcr.fundingCoins[pt] = &fundingCoin{\n\t\t\top: coin,\n\t\t\taddr: txout.Address,\n\t\t}\n\t\tdelete(notFound, pt)\n\t\tif len(notFound) == 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\tif len(notFound) != 0 {\n\t\tids := make([]string, 0, len(notFound))\n\t\tfor pt := range notFound {\n\t\t\tids = append(ids, pt.String())\n\t\t}\n\t\treturn nil, fmt.Errorf(\"funding coins not found: %s\", strings.Join(ids, \", \"))\n\t}\n\tdcr.log.Debugf(\"Locking funding coins that were unlocked %v\", coinsToLock)\n\terr = dcr.node.LockUnspent(dcr.ctx, false, coinsToLock)\n\tif err != nil {\n\t\treturn nil, translateRPCCancelErr(err)\n\t}\n\n\treturn coins, nil\n}", "func (w *Wallet) LockedOutpoints() []btcjson.TransactionInput {\n\tlocked := make([]btcjson.TransactionInput, len(w.lockedOutpoints))\n\ti := 0\n\tfor op := range w.lockedOutpoints {\n\t\tlocked[i] = btcjson.TransactionInput{\n\t\t\tTxid: op.Hash.String(),\n\t\t\tVout: op.Index,\n\t\t}\n\t\ti++\n\t}\n\treturn locked\n}", "func (va ClawbackVestingAccount) GetUnlockedOnly(blockTime time.Time) sdk.Coins {\n\treturn ReadSchedule(va.StartTime, va.EndTime, va.LockupPeriods, va.OriginalVesting, blockTime.Unix())\n}", "func NewQueryLockedCoinsParams(accountID types.AccountID) QueryLockedCoinsParams {\n\treturn QueryLockedCoinsParams{\n\t\tAccountID: accountID,\n\t}\n}", "func (dcr *ExchangeWallet) FundingCoins(ids []dex.Bytes) (asset.Coins, error) {\n\t// First check if we have the coins in cache.\n\tcoins := make(asset.Coins, 0, len(ids))\n\tnotFound := make(map[outPoint]bool)\n\tdcr.fundingMtx.Lock()\n\tdefer dcr.fundingMtx.Unlock() // stay locked until we update the map and lock them in the wallet\n\tfor _, id := range ids {\n\t\ttxHash, vout, err := decodeCoinID(id)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tpt := newOutPoint(txHash, vout)\n\t\tfundingCoin, found := dcr.fundingCoins[pt]\n\t\tif found {\n\t\t\tcoins = append(coins, fundingCoin.op)\n\t\t\tcontinue\n\t\t}\n\t\tnotFound[pt] = true\n\t}\n\tif len(notFound) == 0 {\n\t\treturn coins, nil\n\t}\n\n\t// Check locked outputs for not found coins.\n\tfor _, acct := range dcr.fundingAccounts() {\n\t\tlockedOutputs, err := dcr.wallet.LockedOutputs(dcr.ctx, acct)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfor _, output := range lockedOutputs {\n\t\t\ttxHash, err := chainhash.NewHashFromStr(output.Txid)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"error decoding txid from rpc server %s: %w\", output.Txid, err)\n\t\t\t}\n\t\t\tpt := newOutPoint(txHash, output.Vout)\n\t\t\tif !notFound[pt] {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ttxOut, err := dcr.wallet.UnspentOutput(dcr.ctx, txHash, output.Vout, output.Tree)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"gettxout error for locked output %v: %w\", pt.String(), err)\n\t\t\t}\n\t\t\tvar address string\n\t\t\tif len(txOut.Addresses) > 0 {\n\t\t\t\taddress = txOut.Addresses[0]\n\t\t\t}\n\t\t\tcoin := newOutput(txHash, output.Vout, toAtoms(output.Amount), output.Tree)\n\t\t\tcoins = append(coins, coin)\n\t\t\tdcr.fundingCoins[pt] = &fundingCoin{\n\t\t\t\top: coin,\n\t\t\t\taddr: address,\n\t\t\t}\n\t\t\tdelete(notFound, pt)\n\t\t\tif len(notFound) == 0 {\n\t\t\t\treturn coins, nil\n\t\t\t}\n\t\t}\n\t}\n\n\t// Some funding coins still not found after checking locked outputs.\n\t// Check wallet unspent outputs as last resort. Lock the coins if found.\n\tcoinsToLock := make([]*wire.OutPoint, 0, len(notFound))\n\tfor _, acct := range dcr.fundingAccounts() {\n\t\tunspents, err := dcr.wallet.Unspents(dcr.ctx, acct)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfor _, txout := range unspents {\n\t\t\ttxHash, err := chainhash.NewHashFromStr(txout.TxID)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"error decoding txid from rpc server %s: %w\", txout.TxID, err)\n\t\t\t}\n\t\t\tpt := newOutPoint(txHash, txout.Vout)\n\t\t\tif !notFound[pt] {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tcoinsToLock = append(coinsToLock, wire.NewOutPoint(txHash, txout.Vout, txout.Tree))\n\t\t\tcoin := newOutput(txHash, txout.Vout, toAtoms(txout.Amount), txout.Tree)\n\t\t\tcoins = append(coins, coin)\n\t\t\tdcr.fundingCoins[pt] = &fundingCoin{\n\t\t\t\top: coin,\n\t\t\t\taddr: txout.Address,\n\t\t\t}\n\t\t\tdelete(notFound, pt)\n\t\t\tif len(notFound) == 0 {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\t// Return an error if some coins are still not found.\n\tif len(notFound) != 0 {\n\t\tids := make([]string, 0, len(notFound))\n\t\tfor pt := range notFound {\n\t\t\tids = append(ids, pt.String())\n\t\t}\n\t\treturn nil, fmt.Errorf(\"funding coins not found: %s\", strings.Join(ids, \", \"))\n\t}\n\n\tdcr.log.Debugf(\"Locking funding coins that were unlocked %v\", coinsToLock)\n\terr := dcr.wallet.LockUnspent(dcr.ctx, false, coinsToLock)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn coins, nil\n}", "func (dcr *ExchangeWallet) lockedOutputs() ([]chainjson.TransactionInput, error) {\n\tvar locked []chainjson.TransactionInput\n\terr := dcr.nodeRawRequest(methodListLockUnspent, anylist{dcr.acct}, &locked)\n\treturn locked, err\n}", "func (w *rpcWallet) LockedOutputs(ctx context.Context, acctName string) ([]chainjson.TransactionInput, error) {\n\tvar locked []chainjson.TransactionInput\n\terr := w.rpcClientRawRequest(ctx, methodListLockUnspent, anylist{acctName}, &locked)\n\treturn locked, translateRPCCancelErr(err)\n}", "func (bc *BlockChain) FindUnspentTransactions(addr string) []Transaction {\n\tvar unspentTXs []Transaction\n\tspentTXOutputs := make(map[string][]int)\n\titerator := bc.Iterator()\n\n\tfor {\n\t\t_block := iterator.Next()\n\n\t\tfor _, tx := range _block.Transactions {\n\t\t\ttxID := hex.EncodeToString(tx.ID)\n\n\t\tOutputs:\n\t\t\tfor outIdx, out := range tx.VOut {\n\t\t\t\tif spentTXOutputs[txID] != nil {\n\t\t\t\t\tfor _, spentOut := range spentTXOutputs[txID] {\n\t\t\t\t\t\tif spentOut == outIdx {\n\t\t\t\t\t\t\tcontinue Outputs\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif out.CanBeUnlockedWith(addr) {\n\t\t\t\t\tunspentTXs = append(unspentTXs, *tx)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif !tx.isCoinBaseTx() {\n\t\t\t\tfor _, in := range tx.VIn {\n\t\t\t\t\tif in.CanUnlockOutputWith(addr) {\n\t\t\t\t\t\tinTxID := hex.EncodeToString(in.TxID)\n\t\t\t\t\t\tspentTXOutputs[inTxID] = append(spentTXOutputs[inTxID], in.VOut)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif len(_block.Prev) == 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn unspentTXs\n}", "func (a *Account) LockedOutpoints() []btcjson.TransactionInput {\n\tlocked := make([]btcjson.TransactionInput, len(a.lockedOutpoints))\n\ti := 0\n\tfor op := range a.lockedOutpoints {\n\t\tlocked[i] = btcjson.TransactionInput{\n\t\t\tTxid: op.Hash.String(),\n\t\t\tVout: op.Index,\n\t\t}\n\t\ti++\n\t}\n\treturn locked\n}", "func (r *Ring) InPot() []Box {\n\treturn r.Where(func(s *Seat) bool {\n\t\treturn s.State == seat.Play || s.State == seat.Bet || s.State == seat.AllIn\n\t})\n}", "func (tx *Transaction) GetNewFromCoins() []FromCoin {\n\tnfcs := make([]FromCoin, 0)\n\tfor index, c := range tx.To.Coins {\n\t\tticket := Ticket{}\n\t\tticket.SetTxid(*tx.GetTxID())\n\t\tticket.SetIndex(uint32(index))\n\n\t\tnfc := FromCoin{}\n\t\tnfc.SetId(c.Id)\n\t\tnfc.AddTicket(&ticket)\n\n\t\tnfcs = append(nfcs, nfc)\n\t}\n\n\treturn nfcs\n}", "func (b *Bitcoind) ListLockUnspent() (unspendableOutputs []UnspendableOutput, err error) {\n\tr, err := b.client.call(\"listlockunspent\", nil)\n\tif err = handleError(err, &r); err != nil {\n\t\treturn\n\t}\n\n\terr = json.Unmarshal(r.Result, &unspendableOutputs)\n\treturn\n}", "func (dcr *ExchangeWallet) lockFundingCoins(fCoins []*fundingCoin) error {\n\twireOPs := make([]*wire.OutPoint, 0, len(fCoins))\n\tfor _, c := range fCoins {\n\t\twireOPs = append(wireOPs, wire.NewOutPoint(c.op.txHash(), c.op.vout(), c.op.tree))\n\t}\n\terr := dcr.wallet.LockUnspent(dcr.ctx, false, wireOPs)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, c := range fCoins {\n\t\tdcr.fundingCoins[c.op.pt] = c\n\t}\n\treturn nil\n}", "func (bva BaseVestingAccount) GetOriginalVesting() sdk.Coins {\n\treturn bva.OriginalVesting\n}", "func (w *Wallet) ListUnspent(minconf, maxconf int32,\n\taddresses map[string]struct{}) ([]*btcjson.ListUnspentResult, er.R) {\n\n\tvar results []*btcjson.ListUnspentResult\n\terr := walletdb.View(w.db, func(tx walletdb.ReadTx) er.R {\n\t\taddrmgrNs := tx.ReadBucket(waddrmgrNamespaceKey)\n\t\ttxmgrNs := tx.ReadBucket(wtxmgrNamespaceKey)\n\n\t\tsyncBlock := w.Manager.SyncedTo()\n\n\t\tfilter := len(addresses) != 0\n\t\tunspent, err := w.TxStore.GetUnspentOutputs(txmgrNs)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tsort.Sort(sort.Reverse(creditSlice(unspent)))\n\n\t\tdefaultAccountName := \"default\"\n\n\t\tresults = make([]*btcjson.ListUnspentResult, 0, len(unspent))\n\t\tfor i := range unspent {\n\t\t\toutput := unspent[i]\n\n\t\t\t// Outputs with fewer confirmations than the minimum or more\n\t\t\t// confs than the maximum are excluded.\n\t\t\tconfs := confirms(output.Height, syncBlock.Height)\n\t\t\tif confs < minconf || confs > maxconf {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// Only mature coinbase outputs are included.\n\t\t\tif output.FromCoinBase {\n\t\t\t\ttarget := int32(w.ChainParams().CoinbaseMaturity)\n\t\t\t\tif !confirmed(target, output.Height, syncBlock.Height) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Exclude locked outputs from the result set.\n\t\t\tif w.LockedOutpoint(output.OutPoint) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// Lookup the associated account for the output. Use the\n\t\t\t// default account name in case there is no associated account\n\t\t\t// for some reason, although this should never happen.\n\t\t\t//\n\t\t\t// This will be unnecessary once transactions and outputs are\n\t\t\t// grouped under the associated account in the db.\n\t\t\tacctName := defaultAccountName\n\t\t\tsc, addrs, _, err := txscript.ExtractPkScriptAddrs(\n\t\t\t\toutput.PkScript, w.chainParams)\n\t\t\tif err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif len(addrs) > 0 {\n\t\t\t\tsmgr, acct, err := w.Manager.AddrAccount(addrmgrNs, addrs[0])\n\t\t\t\tif err == nil {\n\t\t\t\t\ts, err := smgr.AccountName(addrmgrNs, acct)\n\t\t\t\t\tif err == nil {\n\t\t\t\t\t\tacctName = s\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif filter {\n\t\t\t\tfor _, addr := range addrs {\n\t\t\t\t\t_, ok := addresses[addr.EncodeAddress()]\n\t\t\t\t\tif ok {\n\t\t\t\t\t\tgoto include\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\tinclude:\n\t\t\t// At the moment watch-only addresses are not supported, so all\n\t\t\t// recorded outputs that are not multisig are \"spendable\".\n\t\t\t// Multisig outputs are only \"spendable\" if all keys are\n\t\t\t// controlled by this wallet.\n\t\t\t//\n\t\t\t// TODO: Each case will need updates when watch-only addrs\n\t\t\t// is added. For P2PK, P2PKH, and P2SH, the address must be\n\t\t\t// looked up and not be watching-only. For multisig, all\n\t\t\t// pubkeys must belong to the manager with the associated\n\t\t\t// private key (currently it only checks whether the pubkey\n\t\t\t// exists, since the private key is required at the moment).\n\t\t\tvar spendable bool\n\t\tscSwitch:\n\t\t\tswitch sc {\n\t\t\tcase txscript.PubKeyHashTy:\n\t\t\t\tspendable = true\n\t\t\tcase txscript.PubKeyTy:\n\t\t\t\tspendable = true\n\t\t\tcase txscript.WitnessV0ScriptHashTy:\n\t\t\t\tspendable = true\n\t\t\tcase txscript.WitnessV0PubKeyHashTy:\n\t\t\t\tspendable = true\n\t\t\tcase txscript.MultiSigTy:\n\t\t\t\tfor _, a := range addrs {\n\t\t\t\t\t_, err := w.Manager.Address(addrmgrNs, a)\n\t\t\t\t\tif err == nil {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tif waddrmgr.ErrAddressNotFound.Is(err) {\n\t\t\t\t\t\tbreak scSwitch\n\t\t\t\t\t}\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tspendable = true\n\t\t\t}\n\n\t\t\tresult := &btcjson.ListUnspentResult{\n\t\t\t\tTxID: output.OutPoint.Hash.String(),\n\t\t\t\tVout: output.OutPoint.Index,\n\t\t\t\tAccount: acctName,\n\t\t\t\tScriptPubKey: hex.EncodeToString(output.PkScript),\n\t\t\t\tAmount: output.Amount.ToBTC(),\n\t\t\t\tConfirmations: int64(confs),\n\t\t\t\tSpendable: spendable,\n\t\t\t}\n\n\t\t\t// BUG: this should be a JSON array so that all\n\t\t\t// addresses can be included, or removed (and the\n\t\t\t// caller extracts addresses from the pkScript).\n\t\t\tif len(addrs) > 0 {\n\t\t\t\tresult.Address = addrs[0].EncodeAddress()\n\t\t\t}\n\n\t\t\tresults = append(results, result)\n\t\t}\n\t\treturn nil\n\t})\n\treturn results, err\n}", "func NotInvoicedGTE(v float32) predicate.Order {\n\treturn predicate.Order(func(s *sql.Selector) {\n\t\ts.Where(sql.GTE(s.C(FieldNotInvoiced), v))\n\t})\n}", "func (dcr *ExchangeWallet) returnCoins(unspents asset.Coins) ([]*fundingCoin, error) {\n\tif len(unspents) == 0 {\n\t\treturn nil, fmt.Errorf(\"cannot return zero coins\")\n\t}\n\n\tops := make([]*wire.OutPoint, 0, len(unspents))\n\tfundingCoins := make([]*fundingCoin, 0, len(unspents))\n\n\tdcr.log.Debugf(\"returning coins %s\", unspents)\n\tfor _, unspent := range unspents {\n\t\top, err := dcr.convertCoin(unspent)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error converting coin: %w\", err)\n\t\t}\n\t\tops = append(ops, op.wireOutPoint()) // op.tree may be wire.TxTreeUnknown, but that's fine since wallet.LockUnspent doesn't rely on it\n\t\tif fCoin, ok := dcr.fundingCoins[op.pt]; ok {\n\t\t\tfundingCoins = append(fundingCoins, fCoin)\n\t\t\tdelete(dcr.fundingCoins, op.pt)\n\t\t} else {\n\t\t\tdcr.log.Warnf(\"returning coin %s that is not cached as a funding coin\", op)\n\t\t\tfundingCoins = append(fundingCoins, &fundingCoin{op: op})\n\t\t}\n\t}\n\n\treturn fundingCoins, dcr.wallet.LockUnspent(dcr.ctx, true, ops)\n}", "func (keeper ViewKeeper) GetCoins(ctx sdk.Context, addr sdk.Address) sdk.Coins {\n\treturn getCoins(ctx, keeper.am, addr)\n}", "func (dcr *ExchangeWallet) lockFundingCoins(fCoins []*fundingCoin) error {\n\twireOPs := make([]*wire.OutPoint, 0, len(fCoins))\n\tfor _, c := range fCoins {\n\t\twireOPs = append(wireOPs, wire.NewOutPoint(c.op.txHash(), c.op.vout(), c.op.tree))\n\t}\n\terr := dcr.node.LockUnspent(dcr.ctx, false, wireOPs)\n\tif err != nil {\n\t\treturn translateRPCCancelErr(err)\n\t}\n\tfor _, c := range fCoins {\n\t\tdcr.fundingCoins[c.op.pt] = c\n\t}\n\treturn nil\n}", "func (chain *BlockChain) FindUnspentTransactions(address string) []Transaction {\n\tvar unspentTxs []Transaction\n\n\tspentTxOs := make(map[string][]int)\n\n\titer := chain.Iterator()\n\n\tfor {\n\t\tblock := iter.Next()\n\n\t\tfor _, tx := range block.Transactions {\n\t\t\ttxID := hex.EncodeToString(tx.ID)\n\n\t\tOutputs:\n\t\t\tfor outIdx, out := range tx.Outputs {\n\t\t\t\tif spentTxOs[txID] != nil {\n\t\t\t\t\tfor _, spentOut := range spentTxOs[txID] {\n\t\t\t\t\t\tif spentOut == outIdx {\n\t\t\t\t\t\t\tcontinue Outputs\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif out.CanBeUnlocked(address) {\n\t\t\t\t\tunspentTxs = append(unspentTxs, *tx)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif tx.IsCoinbase() == false {\n\t\t\t\tfor _, in := range tx.Inputs {\n\t\t\t\t\tif in.CanUnlock(address) {\n\t\t\t\t\t\tinTxID := hex.EncodeToString(in.ID)\n\n\t\t\t\t\t\tspentTxOs[inTxID] = append(spentTxOs[inTxID], in.Out)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif len(block.PrevHash) == 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn unspentTxs\n}", "func (keeper BaseViewKeeper) GetCoins(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins {\n\treturn getCoins(ctx, keeper.am, addr)\n}", "func (o *AccountCollectionGetParams) SetLocked(locked *bool) {\n\to.Locked = locked\n}", "func (secretsManager *SecretsManagerV2) ListSecretVersionLocksWithContext(ctx context.Context, listSecretVersionLocksOptions *ListSecretVersionLocksOptions) (result *SecretVersionLocksPaginatedCollection, response *core.DetailedResponse, err error) {\n\terr = core.ValidateNotNil(listSecretVersionLocksOptions, \"listSecretVersionLocksOptions cannot be nil\")\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.ValidateStruct(listSecretVersionLocksOptions, \"listSecretVersionLocksOptions\")\n\tif err != nil {\n\t\treturn\n\t}\n\n\tpathParamsMap := map[string]string{\n\t\t\"secret_id\": *listSecretVersionLocksOptions.SecretID,\n\t\t\"id\": *listSecretVersionLocksOptions.ID,\n\t}\n\n\tbuilder := core.NewRequestBuilder(core.GET)\n\tbuilder = builder.WithContext(ctx)\n\tbuilder.EnableGzipCompression = secretsManager.GetEnableGzipCompression()\n\t_, err = builder.ResolveRequestURL(secretsManager.Service.Options.URL, `/api/v2/secrets/{secret_id}/versions/{id}/locks`, pathParamsMap)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tfor headerName, headerValue := range listSecretVersionLocksOptions.Headers {\n\t\tbuilder.AddHeader(headerName, headerValue)\n\t}\n\n\tsdkHeaders := common.GetSdkHeaders(\"secrets_manager\", \"V2\", \"ListSecretVersionLocks\")\n\tfor headerName, headerValue := range sdkHeaders {\n\t\tbuilder.AddHeader(headerName, headerValue)\n\t}\n\tbuilder.AddHeader(\"Accept\", \"application/json\")\n\n\tif listSecretVersionLocksOptions.Offset != nil {\n\t\tbuilder.AddQuery(\"offset\", fmt.Sprint(*listSecretVersionLocksOptions.Offset))\n\t}\n\tif listSecretVersionLocksOptions.Limit != nil {\n\t\tbuilder.AddQuery(\"limit\", fmt.Sprint(*listSecretVersionLocksOptions.Limit))\n\t}\n\tif listSecretVersionLocksOptions.Sort != nil {\n\t\tbuilder.AddQuery(\"sort\", fmt.Sprint(*listSecretVersionLocksOptions.Sort))\n\t}\n\tif listSecretVersionLocksOptions.Search != nil {\n\t\tbuilder.AddQuery(\"search\", fmt.Sprint(*listSecretVersionLocksOptions.Search))\n\t}\n\n\trequest, err := builder.Build()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tvar rawResponse map[string]json.RawMessage\n\tresponse, err = secretsManager.Service.Request(request, &rawResponse)\n\tif err != nil {\n\t\treturn\n\t}\n\tif rawResponse != nil {\n\t\terr = core.UnmarshalModel(rawResponse, \"\", &result, UnmarshalSecretVersionLocksPaginatedCollection)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tresponse.Result = result\n\t}\n\n\treturn\n}", "func (b *Bitcoind) LockUnspent(lock bool, outputs []UnspendableOutput) (success bool, err error) {\n\tr, err := b.client.call(\"lockunspent\", []interface{}{lock, outputs})\n\tif err = handleError(err, &r); err != nil {\n\t\treturn\n\t}\n\n\terr = json.Unmarshal(r.Result, &success)\n\treturn\n}", "func (secretsManager *SecretsManagerV2) ListSecretLocksWithContext(ctx context.Context, listSecretLocksOptions *ListSecretLocksOptions) (result *SecretLocksPaginatedCollection, response *core.DetailedResponse, err error) {\n\terr = core.ValidateNotNil(listSecretLocksOptions, \"listSecretLocksOptions cannot be nil\")\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.ValidateStruct(listSecretLocksOptions, \"listSecretLocksOptions\")\n\tif err != nil {\n\t\treturn\n\t}\n\n\tpathParamsMap := map[string]string{\n\t\t\"id\": *listSecretLocksOptions.ID,\n\t}\n\n\tbuilder := core.NewRequestBuilder(core.GET)\n\tbuilder = builder.WithContext(ctx)\n\tbuilder.EnableGzipCompression = secretsManager.GetEnableGzipCompression()\n\t_, err = builder.ResolveRequestURL(secretsManager.Service.Options.URL, `/api/v2/secrets/{id}/locks`, pathParamsMap)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tfor headerName, headerValue := range listSecretLocksOptions.Headers {\n\t\tbuilder.AddHeader(headerName, headerValue)\n\t}\n\n\tsdkHeaders := common.GetSdkHeaders(\"secrets_manager\", \"V2\", \"ListSecretLocks\")\n\tfor headerName, headerValue := range sdkHeaders {\n\t\tbuilder.AddHeader(headerName, headerValue)\n\t}\n\tbuilder.AddHeader(\"Accept\", \"application/json\")\n\n\tif listSecretLocksOptions.Offset != nil {\n\t\tbuilder.AddQuery(\"offset\", fmt.Sprint(*listSecretLocksOptions.Offset))\n\t}\n\tif listSecretLocksOptions.Limit != nil {\n\t\tbuilder.AddQuery(\"limit\", fmt.Sprint(*listSecretLocksOptions.Limit))\n\t}\n\tif listSecretLocksOptions.Sort != nil {\n\t\tbuilder.AddQuery(\"sort\", fmt.Sprint(*listSecretLocksOptions.Sort))\n\t}\n\tif listSecretLocksOptions.Search != nil {\n\t\tbuilder.AddQuery(\"search\", fmt.Sprint(*listSecretLocksOptions.Search))\n\t}\n\n\trequest, err := builder.Build()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tvar rawResponse map[string]json.RawMessage\n\tresponse, err = secretsManager.Service.Request(request, &rawResponse)\n\tif err != nil {\n\t\treturn\n\t}\n\tif rawResponse != nil {\n\t\terr = core.UnmarshalModel(rawResponse, \"\", &result, UnmarshalSecretLocksPaginatedCollection)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tresponse.Result = result\n\t}\n\n\treturn\n}", "func GetUnspentOutputCoinsExceptSpendingUTXO(rpcClient *rpcclient.HttpClient, keyWallet *wallet.KeyWallet) ([]*crypto.InputCoin, error) {\n\tpublicKey := keyWallet.KeySet.PaymentAddress.Pk\n\n\t// check and remove utxo cache (these utxos in txs that were confirmed)\n\t//CheckAndRemoveUTXOFromCache(keyWallet.KeySet.PaymentAddress.Pk, inputCoins)\n\tCheckAndRemoveUTXOFromCacheV2(keyWallet.KeySet.PaymentAddress.Pk, rpcClient)\n\n\t// get unspent output coins from network\n\tutxos, err := GetUnspentOutputCoins(rpcClient, keyWallet)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tinputCoins := ConvertOutputCoinToInputCoin(utxos)\n\n\t// except spending utxos from unspent output coins\n\tutxosInCache := GetUTXOCacheByPublicKey(publicKey)\n\tfor serialNumberStr, _ := range utxosInCache {\n\t\tfor i, inputCoin := range inputCoins {\n\t\t\tsnStrTmp := base58.Base58Check{}.Encode(inputCoin.CoinDetails.GetSerialNumber().ToBytesS(), common.ZeroByte)\n\t\t\tif snStrTmp == serialNumberStr {\n\t\t\t\tinputCoins = removeElementFromSlice(inputCoins, i)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\treturn inputCoins, nil\n}", "func (keeper SendKeeper) GetCoins(ctx sdk.Context, addr sdk.Address) sdk.Coins {\n\treturn getCoins(ctx, keeper.am, addr)\n}", "func (n Network) VestingAccounts(ctx context.Context, launchID uint64) (vestingAccs []networktypes.VestingAccount, err error) {\n\tn.ev.Send(events.New(events.StatusOngoing, \"Fetching genesis vesting accounts\"))\n\tres, err := n.launchQuery.\n\t\tVestingAccountAll(ctx,\n\t\t\t&launchtypes.QueryAllVestingAccountRequest{\n\t\t\t\tLaunchID: launchID,\n\t\t\t},\n\t\t)\n\tif err != nil {\n\t\treturn vestingAccs, err\n\t}\n\n\tfor i, acc := range res.VestingAccount {\n\t\tparsedAcc, err := networktypes.ToVestingAccount(acc)\n\t\tif err != nil {\n\t\t\treturn vestingAccs, errors.Wrapf(err, \"error parsing vesting account %d\", i)\n\t\t}\n\n\t\tvestingAccs = append(vestingAccs, parsedAcc)\n\t}\n\n\treturn vestingAccs, nil\n}", "func distributeLockedAmount(ctx coretypes.Sandbox, bets []*BetInfo, totalLockedAmount int64) bool {\n\tsumsByPlayers := make(map[coretypes.AgentID]int64)\n\ttotalWinningAmount := int64(0)\n\tfor _, bet := range bets {\n\t\tif _, ok := sumsByPlayers[bet.Player]; !ok {\n\t\t\tsumsByPlayers[bet.Player] = 0\n\t\t}\n\t\tsumsByPlayers[bet.Player] += bet.Sum\n\t\ttotalWinningAmount += bet.Sum\n\t}\n\n\t// NOTE 1: float64 was avoided for determinism reasons\n\t// NOTE 2: beware overflows\n\n\tfor player, sum := range sumsByPlayers {\n\t\tsumsByPlayers[player] = (totalLockedAmount * sum) / totalWinningAmount\n\t}\n\n\t// make deterministic sequence by sorting. Eliminate possible rounding effects\n\tseqPlayers := make([]coretypes.AgentID, 0, len(sumsByPlayers))\n\tresultSum := int64(0)\n\tfor player, sum := range sumsByPlayers {\n\t\tseqPlayers = append(seqPlayers, player)\n\t\tresultSum += sum\n\t}\n\tsort.Slice(seqPlayers, func(i, j int) bool {\n\t\treturn bytes.Compare(seqPlayers[i][:], seqPlayers[j][:]) < 0\n\t})\n\n\t// ensure we distribute not more than totalLockedAmount iotas\n\tif resultSum > totalLockedAmount {\n\t\tsumsByPlayers[seqPlayers[0]] -= resultSum - totalLockedAmount\n\t}\n\n\t// filter out those who proportionally got 0\n\tfinalWinners := seqPlayers[:0]\n\tfor _, player := range seqPlayers {\n\t\tif sumsByPlayers[player] <= 0 {\n\t\t\tcontinue\n\t\t}\n\t\tfinalWinners = append(finalWinners, player)\n\t}\n\t// distribute iotas\n\tfor i := range finalWinners {\n\n\t\tavailable := ctx.Balance(balance.ColorIOTA)\n\t\tctx.Event(fmt.Sprintf(\"sending reward iotas %d to the winner %s. Available iotas: %d\",\n\t\t\tsumsByPlayers[finalWinners[i]], finalWinners[i].String(), available))\n\n\t\t//if !ctx.MoveTokens(finalWinners[i], balance.ColorIOTA, sumsByPlayers[finalWinners[i]]) {\n\t\t//\treturn false\n\t\t//}\n\t}\n\treturn true\n}", "func (dcr *ExchangeWallet) returnCoins(unspents asset.Coins) error {\n\tif len(unspents) == 0 {\n\t\treturn fmt.Errorf(\"cannot return zero coins\")\n\t}\n\tops := make([]*wire.OutPoint, 0, len(unspents))\n\n\tdcr.log.Debugf(\"returning coins %s\", unspents)\n\tfor _, unspent := range unspents {\n\t\top, err := dcr.convertCoin(unspent)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error converting coin: %w\", err)\n\t\t}\n\t\tops = append(ops, wire.NewOutPoint(op.txHash(), op.vout(), op.tree))\n\t\tdelete(dcr.fundingCoins, op.pt)\n\t}\n\treturn translateRPCCancelErr(dcr.node.LockUnspent(dcr.ctx, true, ops))\n}", "func (am *AccountManager) ListUnspent(minconf, maxconf int,\n\taddresses map[string]bool) ([]*btcjson.ListUnspentResult, error) {\n\n\tbs, err := GetCurBlock()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfilter := len(addresses) != 0\n\n\tvar results []*btcjson.ListUnspentResult\n\tfor _, a := range am.AllAccounts() {\n\t\tunspent, err := a.TxStore.UnspentOutputs()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfor _, credit := range unspent {\n\t\t\tconfs := credit.Confirmations(bs.Height)\n\t\t\tif int(confs) < minconf || int(confs) > maxconf {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t_, addrs, _, _ := credit.Addresses(cfg.Net())\n\t\t\tif filter {\n\t\t\t\tfor _, addr := range addrs {\n\t\t\t\t\t_, ok := addresses[addr.EncodeAddress()]\n\t\t\t\t\tif ok {\n\t\t\t\t\t\tgoto include\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\t\tinclude:\n\t\t\tresult := &btcjson.ListUnspentResult{\n\t\t\t\tTxId: credit.Tx().Sha().String(),\n\t\t\t\tVout: credit.OutputIndex,\n\t\t\t\tAccount: a.Name(),\n\t\t\t\tScriptPubKey: hex.EncodeToString(credit.TxOut().PkScript),\n\t\t\t\tAmount: credit.Amount().ToUnit(btcutil.AmountBTC),\n\t\t\t\tConfirmations: int64(confs),\n\t\t\t}\n\n\t\t\t// BUG: this should be a JSON array so that all\n\t\t\t// addresses can be included, or removed (and the\n\t\t\t// caller extracts addresses from the pkScript).\n\t\t\tif len(addrs) > 0 {\n\t\t\t\tresult.Address = addrs[0].EncodeAddress()\n\t\t\t}\n\n\t\t\tresults = append(results, result)\n\t\t}\n\t}\n\n\treturn results, nil\n}", "func (b *rpcVestingBalance) unbonding() (sdk.Coins, sdk.Coins, error) {\n\tunbondingCoins, err := b.totalUnbondingDelegations()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tunbonding := unbondingCoins.AmountOf(stakingDenom)\n\tdelegatedFree := b.vacc.GetDelegatedFree().AmountOf(stakingDenom)\n\n\tunbondingFree := sdk.MinInt(delegatedFree, unbonding)\n\tunbondingVesting := unbonding.Sub(unbondingFree)\n\n\tliquidCoins := sdk.NewCoins(newKavaCoin(unbondingFree))\n\tvestingCoins := sdk.NewCoins(newKavaCoin(unbondingVesting))\n\treturn liquidCoins, vestingCoins, nil\n}", "func (btc *ExchangeWallet) ReturnCoins(unspents asset.Coins) error {\n\tif len(unspents) == 0 {\n\t\treturn fmt.Errorf(\"cannot return zero coins\")\n\t}\n\tops := make([]*output, 0, len(unspents))\n\tbtc.fundingMtx.Lock()\n\tdefer btc.fundingMtx.Unlock()\n\tfor _, unspent := range unspents {\n\t\top, err := btc.convertCoin(unspent)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error converting coin: %v\", err)\n\t\t}\n\t\tops = append(ops, op)\n\t\tdelete(btc.fundingCoins, outpointID(op.txHash.String(), op.vout))\n\t}\n\treturn btc.wallet.LockUnspent(true, ops)\n}", "func (keeper Keeper) GetCoins(ctx sdk.Context, addr sdk.Address) sdk.Coins {\n\treturn getCoins(ctx, keeper.am, addr)\n}", "func (btc *ExchangeWallet) FundingCoins(ids []dex.Bytes) (asset.Coins, error) {\n\t// First check if we have the coins in cache.\n\tcoins := make(asset.Coins, 0, len(ids))\n\tnotFound := make(map[string]struct{})\n\tbtc.fundingMtx.RLock()\n\tfor _, id := range ids {\n\t\ttxHash, vout, err := decodeCoinID(id)\n\t\tif err != nil {\n\t\t\tbtc.fundingMtx.RUnlock()\n\t\t\treturn nil, err\n\t\t}\n\t\topID := outpointID(txHash.String(), vout)\n\t\tfundingCoin, found := btc.fundingCoins[opID]\n\t\tif found {\n\t\t\tcoins = append(coins, newOutput(btc.node, txHash, vout, fundingCoin.amount, fundingCoin.redeemScript))\n\t\t\tcontinue\n\t\t}\n\t\tnotFound[opID] = struct{}{}\n\t}\n\tbtc.fundingMtx.RUnlock()\n\tif len(notFound) == 0 {\n\t\treturn coins, nil\n\t}\n\t_, utxoMap, _, err := btc.spendableUTXOs(0)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlockers := make([]*output, 0, len(ids))\n\tbtc.fundingMtx.Lock()\n\tdefer btc.fundingMtx.Unlock()\n\tfor _, id := range ids {\n\t\ttxHash, vout, err := decodeCoinID(id)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\topID := outpointID(txHash.String(), vout)\n\t\tutxo, found := utxoMap[opID]\n\t\tif !found {\n\t\t\treturn nil, fmt.Errorf(\"funding coin %s not found\", opID)\n\t\t}\n\t\tbtc.fundingCoins[opID] = utxo\n\t\tcoin := newOutput(btc.node, utxo.txHash, utxo.vout, utxo.amount, utxo.redeemScript)\n\t\tcoins = append(coins, coin)\n\t\tlockers = append(lockers, coin)\n\t\tdelete(notFound, opID)\n\t\tif len(notFound) == 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\tif len(notFound) != 0 {\n\t\tids := make([]string, 0, len(notFound))\n\t\tfor opID := range notFound {\n\t\t\tids = append(ids, opID)\n\t\t}\n\t\treturn nil, fmt.Errorf(\"coins not found: %s\", strings.Join(ids, \", \"))\n\t}\n\terr = btc.wallet.LockUnspent(false, lockers)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn coins, nil\n}", "func (c *CoordinatorHelper) Coins(\n\tctx context.Context,\n\tdbTx storage.DatabaseTransaction,\n\taccountIdentifier *types.AccountIdentifier,\n\tcurrency *types.Currency,\n) ([]*types.Coin, error) {\n\tcoins, _, err := c.coinStorage.GetCoinsTransactional(\n\t\tctx,\n\t\tdbTx,\n\t\taccountIdentifier,\n\t)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"%w: unable to get coins\", err)\n\t}\n\n\tcoinsToReturn := []*types.Coin{}\n\tfor _, coin := range coins {\n\t\tif types.Hash(coin.Amount.Currency) != types.Hash(currency) {\n\t\t\tcontinue\n\t\t}\n\n\t\tcoinsToReturn = append(coinsToReturn, coin)\n\t}\n\n\treturn coinsToReturn, nil\n}", "func (_Abi *AbiFilterer) FilterLogTokensLocked(opts *bind.FilterOpts, token [][32]byte, sender [][32]byte) (*AbiLogTokensLockedIterator, error) {\n\n\tvar tokenRule []interface{}\n\tfor _, tokenItem := range token {\n\t\ttokenRule = append(tokenRule, tokenItem)\n\t}\n\tvar senderRule []interface{}\n\tfor _, senderItem := range sender {\n\t\tsenderRule = append(senderRule, senderItem)\n\t}\n\n\tlogs, sub, err := _Abi.contract.FilterLogs(opts, \"LogTokensLocked\", tokenRule, senderRule)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &AbiLogTokensLockedIterator{contract: _Abi.contract, event: \"LogTokensLocked\", logs: logs, sub: sub}, nil\n}", "func (txn TxnProbe) CollectLockedKeys() [][]byte {\n\treturn txn.collectLockedKeys()\n}", "func (secretsManager *SecretsManagerV2) ListSecretsLocksWithContext(ctx context.Context, listSecretsLocksOptions *ListSecretsLocksOptions) (result *SecretsLocksPaginatedCollection, response *core.DetailedResponse, err error) {\n\terr = core.ValidateStruct(listSecretsLocksOptions, \"listSecretsLocksOptions\")\n\tif err != nil {\n\t\treturn\n\t}\n\n\tbuilder := core.NewRequestBuilder(core.GET)\n\tbuilder = builder.WithContext(ctx)\n\tbuilder.EnableGzipCompression = secretsManager.GetEnableGzipCompression()\n\t_, err = builder.ResolveRequestURL(secretsManager.Service.Options.URL, `/api/v2/secrets_locks`, nil)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tfor headerName, headerValue := range listSecretsLocksOptions.Headers {\n\t\tbuilder.AddHeader(headerName, headerValue)\n\t}\n\n\tsdkHeaders := common.GetSdkHeaders(\"secrets_manager\", \"V2\", \"ListSecretsLocks\")\n\tfor headerName, headerValue := range sdkHeaders {\n\t\tbuilder.AddHeader(headerName, headerValue)\n\t}\n\tbuilder.AddHeader(\"Accept\", \"application/json\")\n\n\tif listSecretsLocksOptions.Offset != nil {\n\t\tbuilder.AddQuery(\"offset\", fmt.Sprint(*listSecretsLocksOptions.Offset))\n\t}\n\tif listSecretsLocksOptions.Limit != nil {\n\t\tbuilder.AddQuery(\"limit\", fmt.Sprint(*listSecretsLocksOptions.Limit))\n\t}\n\tif listSecretsLocksOptions.Search != nil {\n\t\tbuilder.AddQuery(\"search\", fmt.Sprint(*listSecretsLocksOptions.Search))\n\t}\n\tif listSecretsLocksOptions.Groups != nil {\n\t\tbuilder.AddQuery(\"groups\", strings.Join(listSecretsLocksOptions.Groups, \",\"))\n\t}\n\n\trequest, err := builder.Build()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tvar rawResponse map[string]json.RawMessage\n\tresponse, err = secretsManager.Service.Request(request, &rawResponse)\n\tif err != nil {\n\t\treturn\n\t}\n\tif rawResponse != nil {\n\t\terr = core.UnmarshalModel(rawResponse, \"\", &result, UnmarshalSecretsLocksPaginatedCollection)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tresponse.Result = result\n\t}\n\n\treturn\n}", "func lockBets(ctx coretypes.Sandbox) error {\n\tctx.Event(\"lockBets\")\n\n\tscAddr := coretypes.NewAgentIDFromContractID(ctx.ContractID())\n\tif ctx.Caller() != scAddr {\n\t\t// ignore if request is not from itself\n\t\treturn fmt.Errorf(\"attempt of unauthorised access\")\n\t}\n\tstate := ctx.State()\n\t// append all current bets to the locked bets array\n\tlockedBets := collections.NewArray(state, StateVarLockedBets)\n\tlockedBets.MustExtend(collections.NewArrayReadOnly(state, StateVarBets))\n\tcollections.NewArray(state, StateVarBets).MustErase()\n\n\tnumLockedBets := lockedBets.MustLen()\n\tctx.Event(fmt.Sprintf(\"lockBets: num = %d\", numLockedBets))\n\n\t// clear entropy to be picked in the next request\n\tstate.Del(StateVarEntropyFromLocking)\n\n\t// send request to self for playing the wheel with the entropy whicl will be known\n\t// after signing this state update transaction therefore unpredictable\n\tctx.PostRequest(coretypes.PostRequestParams{\n\t\tTargetContractID: ctx.ContractID(),\n\t\tEntryPoint: RequestPlayAndDistribute,\n\t})\n\n\treturn nil\n}", "func (btc *ExchangeWallet) lockedSats() (uint64, error) {\n\tlockedOutpoints, err := btc.wallet.ListLockUnspent()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tvar sum uint64\n\tbtc.fundingMtx.Lock()\n\tdefer btc.fundingMtx.Unlock()\n\tfor _, outPoint := range lockedOutpoints {\n\t\topID := outpointID(outPoint.TxID, outPoint.Vout)\n\t\tutxo, found := btc.fundingCoins[opID]\n\t\tif found {\n\t\t\tsum += utxo.amount\n\t\t\tcontinue\n\t\t}\n\t\ttxHash, err := chainhash.NewHashFromStr(outPoint.TxID)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\ttxOut, err := btc.node.GetTxOut(txHash, outPoint.Vout, true)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\tif txOut == nil {\n\t\t\t// Must be spent now?\n\t\t\tbtc.log.Debugf(\"ignoring output from listlockunspent that wasn't found with gettxout. %s\", opID)\n\t\t\tcontinue\n\t\t}\n\t\tsum += toSatoshi(txOut.Value)\n\t}\n\treturn sum, nil\n}", "func (w *WorkloadGenerator) GetDistilledBlocks_for_window_level_test(block_size, member_size, tx_size uint64) []*DistilledBlock {\n\tblocks := make([]*DistilledBlock, block_size)\n\n\tmembers := make([]string, member_size)\n\tfor i := 0; i < int(member_size); i++ {\n\t\tmembers[i] = fmt.Sprintf(\"%s%d\", \"client\", (i + 1))\n\t}\n\n\tcnt := 0\n\tmemberIndex := 0\n\n\tfor i := 0; i < int(block_size); i++ {\n\t\tvar TxSet []*SpecialTransaction\n\n\t\tfor j := 0; j < int(tx_size); j++ {\n\n\t\t\tif memberIndex%int(member_size) == 0 {\n\t\t\t\tmemberIndex = 0\n\t\t\t\tcnt++\n\t\t\t}\n\n\t\t\ttx := &SpecialTransaction{\n\t\t\t\tChainID: \"basschain\",\n\t\t\t\tNumber: uint64(i),\n\t\t\t\tHash: \"0xabcdef\",\n\t\t\t\tMember: members[memberIndex],\n\t\t\t}\n\n\t\t\tTxSet = append(TxSet, tx)\n\t\t\tmemberIndex++\n\n\t\t}\n\n\t\tblock := &DistilledBlock{\n\t\t\tNumber: uint64(i + 1),\n\t\t\tChainID: \"mychannel\",\n\t\t\tHash: \"0xbeef\",\n\t\t\tPrevHash: \"0xdead\",\n\t\t\tTxSet: TxSet,\n\t\t}\n\t\tblocks[i] = block\n\t}\n\n\treturn blocks\n}", "func (dcr *ExchangeWallet) ReturnCoins(unspents asset.Coins) error {\n\tdcr.fundingMtx.Lock()\n\treturnedCoins, err := dcr.returnCoins(unspents)\n\tdcr.fundingMtx.Unlock()\n\tif err != nil || dcr.unmixedAccount == \"\" {\n\t\treturn err\n\t}\n\n\t// If any of these coins belong to the trading account, transfer them to the\n\t// unmixed account to be re-mixed into the primary account before being\n\t// re-selected for funding future orders. This doesn't apply to unspent\n\t// split tx outputs, which should remain in the trading account and be\n\t// selected from there for funding future orders.\n\tvar coinsToTransfer []asset.Coin\n\tfor _, coin := range returnedCoins {\n\t\tif coin.addr == \"\" {\n\t\t\ttxOut, err := dcr.wallet.UnspentOutput(dcr.ctx, coin.op.txHash(), coin.op.vout(), coin.op.tree)\n\t\t\tif err != nil {\n\t\t\t\tdcr.log.Errorf(\"wallet.UnspentOutput error for returned coin %s: %v\", coin.op, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif len(txOut.Addresses) == 0 {\n\t\t\t\tdcr.log.Errorf(\"no address in gettxout response for returned coin %s\", coin.op)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tcoin.addr = txOut.Addresses[0]\n\t\t}\n\t\taddrInfo, err := dcr.wallet.AddressInfo(dcr.ctx, coin.addr)\n\t\tif err != nil {\n\t\t\tdcr.log.Errorf(\"wallet.AddressInfo error for returned coin %s: %v\", coin.op, err)\n\t\t\tcontinue\n\t\t}\n\t\t// Move this coin to the unmixed account if it was sent to the internal\n\t\t// branch of the trading account. This excludes unspent split tx outputs\n\t\t// which are sent to the external branch of the trading account.\n\t\tif addrInfo.Branch == acctInternalBranch && addrInfo.Account == dcr.tradingAccount {\n\t\t\tcoinsToTransfer = append(coinsToTransfer, coin.op)\n\t\t}\n\t}\n\n\tif len(coinsToTransfer) > 0 {\n\t\ttx, totalSent, err := dcr.sendAll(coinsToTransfer, dcr.unmixedAccount)\n\t\tif err != nil {\n\t\t\tdcr.log.Errorf(\"unable to transfer unlocked swapped change from temp trading \"+\n\t\t\t\t\"account to unmixed account: %v\", err)\n\t\t} else {\n\t\t\tdcr.log.Infof(\"Transferred %s from temp trading account to unmixed account in tx %s.\",\n\t\t\t\tdcrutil.Amount(totalSent), tx.TxHash())\n\t\t}\n\t}\n\n\treturn nil\n}", "func WithoutBlocking(ctx context.Context) context.Context {\n\treturn context.WithValue(ctx, nonBlockingTxnCtxKey, &nonBlockingTxnOpt{})\n}", "func (dcr *ExchangeWallet) ReturnCoins(unspents asset.Coins) error {\n\tdcr.fundingMtx.Lock()\n\tdefer dcr.fundingMtx.Unlock()\n\treturn dcr.returnCoins(unspents)\n}", "func (w *Wallet) Locked() bool {\n\treturn <-w.lockState\n}", "func CreateGetLockedBalancesRequest(walletID uint64) *GetLockedBalanceRequest {\n\treq := request.Get(\"balance/locked\")\n\treq.AddQueryParam(\"wallet_id\", strconv.FormatUint(walletID, 10))\n\n\treturn &GetLockedBalanceRequest{BaseRequest: req}\n}", "func (b *BlockChain) GetUnspentTxns(address string) []Transaction {\n\tvar unspentTxns []Transaction\n\tvar spentTxnMap = make(map[string][]int) // map txnID -> output index\n\n\t// go over blocks one by one\n\titer := b.GetIterator()\n\tfor {\n\t\tblck := iter.Next()\n\n\t\t// go over all Transactions in this block\n\t\tfor _, txn := range blck.Transactions {\n\t\t\t// get string identifying this transaction\n\t\t\ttxID := hex.EncodeToString(txn.ID)\n\n\t\tOutputLoop:\n\t\t\t// go over all outputs in this Txn\n\t\t\tfor outIndex, output := range txn.Out {\n\n\t\t\t\t// check if this output is spent.\n\t\t\t\tif spentTxnMap[txID] != nil {\n\t\t\t\t\tfor _, indx := range spentTxnMap[txID] {\n\t\t\t\t\t\tif indx == outIndex {\n\t\t\t\t\t\t\tcontinue OutputLoop\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// check if this output belongs to this address\n\t\t\t\tif output.CheckOutputUnlock(address) {\n\t\t\t\t\tunspentTxns = append(unspentTxns, *txn)\n\t\t\t\t}\n\n\t\t\t\t// if this is not genesis block, go over all inputs\n\t\t\t\t// that refers to output that belongs to this address\n\t\t\t\t// and mark them as unspent\n\t\t\t\tif txn.IsCoinbase() == false {\n\t\t\t\t\tfor _, inp := range txn.In {\n\t\t\t\t\t\tif inp.CheckInputUnlock(address) {\n\t\t\t\t\t\t\tspentTxnMap[txID] = append(spentTxnMap[txID], inp.Out)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif len(blck.PrevBlockHash) == 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn unspentTxns\n}", "func GetUnspentOutputCoins(rpcClient *rpcclient.HttpClient, keyWallet *wallet.KeyWallet) ([]*crypto.OutputCoin, error) {\n\tprivateKey := &keyWallet.KeySet.PrivateKey\n\tpaymentAddressStr := keyWallet.Base58CheckSerialize(wallet.PaymentAddressType)\n\tviewingKeyStr := keyWallet.Base58CheckSerialize(wallet.ReadonlyKeyType)\n\n\toutputCoins, err := GetListOutputCoins(rpcClient, paymentAddressStr, viewingKeyStr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tserialNumbers, err := DeriveSerialNumbers(privateKey, outputCoins)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tisExisted, err := CheckExistenceSerialNumber(rpcClient, paymentAddressStr, serialNumbers)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tutxos := make([]*crypto.OutputCoin, 0)\n\tfor i, out := range outputCoins {\n\t\tif !isExisted[i] {\n\t\t\tutxos = append(utxos, out)\n\t\t}\n\t}\n\n\treturn utxos, nil\n}", "func (b *Bitcoind) ListUnspent(minconf, maxconf uint32) (transactions []Transaction, err error) {\n\tif maxconf > 999999 {\n\t\tmaxconf = 999999\n\t}\n\n\tr, err := b.client.call(\"listunspent\", []interface{}{minconf, maxconf})\n\tif err = handleError(err, &r); err != nil {\n\t\treturn\n\t}\n\n\terr = json.Unmarshal(r.Result, &transactions)\n\treturn\n}", "func (w *Wallet) ListTransactions(from, count int) ([]btcjson.ListTransactionsResult, er.R) {\n\ttxList := []btcjson.ListTransactionsResult{}\n\n\terr := walletdb.View(w.db, func(tx walletdb.ReadTx) er.R {\n\t\ttxmgrNs := tx.ReadBucket(wtxmgrNamespaceKey)\n\n\t\t// Get current block. The block height used for calculating\n\t\t// the number of tx confirmations.\n\t\tsyncBlock := w.Manager.SyncedTo()\n\n\t\t// Need to skip the first from transactions, and after those, only\n\t\t// include the next count transactions.\n\t\tskipped := 0\n\t\tn := 0\n\n\t\trangeFn := func(details []wtxmgr.TxDetails) (bool, er.R) {\n\t\t\t// Iterate over transactions at this height in reverse order.\n\t\t\t// This does nothing for unmined transactions, which are\n\t\t\t// unsorted, but it will process mined transactions in the\n\t\t\t// reverse order they were marked mined.\n\t\t\tfor i := len(details) - 1; i >= 0; i-- {\n\t\t\t\tif from > skipped {\n\t\t\t\t\tskipped++\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tn++\n\t\t\t\tif n > count {\n\t\t\t\t\treturn true, nil\n\t\t\t\t}\n\n\t\t\t\tjsonResults := listTransactions(tx, &details[i],\n\t\t\t\t\tw.Manager, syncBlock.Height, w.chainParams)\n\t\t\t\ttxList = append(txList, jsonResults...)\n\n\t\t\t\tif len(jsonResults) > 0 {\n\t\t\t\t\tn++\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn false, nil\n\t\t}\n\n\t\t// Return newer results first by starting at mempool height and working\n\t\t// down to the genesis block.\n\t\treturn w.TxStore.RangeTransactions(txmgrNs, -1, 0, rangeFn)\n\t})\n\treturn txList, err\n}", "func (wt *Wallet) Locked() bool {\n\treturn <-wt.lockState\n}", "func (dcr *ExchangeWallet) Locked() bool {\n\tfor _, acct := range dcr.fundingAccounts() {\n\t\tunlocked, err := dcr.wallet.AccountUnlocked(dcr.ctx, acct)\n\t\tif err != nil {\n\t\t\tdcr.log.Errorf(\"error checking account lock status %v\", err)\n\t\t\tunlocked = false // assume wallet is unlocked?\n\t\t}\n\t\tif !unlocked {\n\t\t\treturn true // Locked is true if any of the funding accounts is locked.\n\t\t}\n\t}\n\treturn false\n}", "func (va ClawbackVestingAccount) GetVestingPeriods() Periods {\n\treturn va.VestingPeriods\n}", "func (ck CoinKeeper) GetCoins(ctx sdk.Context, addr sdk.Address, amt sdk.Coins) sdk.Coins {\n\tacc := ck.am.GetAccount(ctx, addr)\n\treturn acc.GetCoins()\n}", "func GetCoins(accCoins []types.Coin) AccountCoins {\n\tcoins := make(AccountCoins, 0)\n\tfor _, coin := range accCoins {\n\t\tcoins = append(coins, AccountCoin{Amount: uint64(coin.Amount), Denom: coin.Denom})\n\t}\n\treturn coins\n}", "func GetCoins() (coins []Coin, error error) {\n\tvar c = []Coin{}\n\tvar d struct {\n\t\tCrypto []Coin `json:\"crypto\"`\n\t}\n\tjsonData, err := doTauRequest(1, \"GET\", \"data/coins\", nil)\n\tif err != nil {\n\t\treturn c, err\n\t}\n\tif err := json.Unmarshal(jsonData, &d); err != nil {\n\t\treturn c, err\n\t}\n\treturn d.Crypto, nil\n}", "func (dcr *ExchangeWallet) spendableUTXOs() ([]*compositeUTXO, error) {\n\tunspents, err := dcr.unspents()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(unspents) == 0 {\n\t\treturn nil, fmt.Errorf(\"insufficient funds. 0 DCR available to spend in %q account\", dcr.acct)\n\t}\n\n\t// Parse utxos to include script size for spending input.\n\t// Returned utxos will be sorted in ascending order by amount (smallest first).\n\tutxos, err := dcr.parseUTXOs(unspents)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error parsing unspent outputs: %w\", err)\n\t}\n\tif len(utxos) == 0 {\n\t\treturn nil, fmt.Errorf(\"no funds available\")\n\t}\n\treturn utxos, nil\n}", "func (k Keeper) coinsFromUnstakedToStaked(ctx sdk.Ctx, address sdk.Address, amount sdk.BigInt) sdk.Error {\n\tif amount.LT(sdk.ZeroInt()) {\n\t\treturn sdk.ErrInternal(\"cannot send a negative\")\n\t}\n\tcoins := sdk.NewCoins(sdk.NewCoin(k.StakeDenom(ctx), amount))\n\terr := k.AccountKeeper.SendCoinsFromAccountToModule(ctx, address, types.StakedPoolName, coins)\n\treturn err\n}", "func (pager *SecretVersionLocksPager) GetAllWithContext(ctx context.Context) (allItems []SecretLock, err error) {\n\tfor pager.HasNext() {\n\t\tvar nextPage []SecretLock\n\t\tnextPage, err = pager.GetNextWithContext(ctx)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tallItems = append(allItems, nextPage...)\n\t}\n\treturn\n}", "func winningTickets(voteBlock *wire.MsgBlock, liveTickets []*stakeTicket, numVotes uint16) ([]*stakeTicket, chainhash.Hash, error) {\n\t// Serialize the parent block header used as the seed to the\n\t// deterministic pseudo random number generator for vote selection.\n\tvar buf bytes.Buffer\n\tif err := voteBlock.Header.Serialize(&buf); err != nil {\n\t\treturn nil, chainhash.Hash{}, err\n\t}\n\n\t// Ensure the number of live tickets is within the allowable range.\n\tnumLiveTickets := uint32(len(liveTickets))\n\tif numLiveTickets > math.MaxUint32 {\n\t\treturn nil, chainhash.Hash{}, fmt.Errorf(\"live ticket pool \"+\n\t\t\t\"has %d tickets which is more than the max allowed of \"+\n\t\t\t\"%d\", len(liveTickets), math.MaxUint32)\n\t}\n\tif uint32(numVotes) > numLiveTickets {\n\t\treturn nil, chainhash.Hash{}, fmt.Errorf(\"live ticket pool \"+\n\t\t\t\"has %d tickets, while %d are needed to vote\",\n\t\t\tlen(liveTickets), numVotes)\n\t}\n\n\t// Construct list of winners by generating successive values from the\n\t// deterministic prng and using them as indices into the sorted live\n\t// ticket pool while skipping any duplicates that might occur.\n\tprng := newHash256PRNG(buf.Bytes())\n\twinners := make([]*stakeTicket, 0, numVotes)\n\tusedOffsets := make(map[uint32]struct{})\n\tfor uint16(len(winners)) < numVotes {\n\t\tticketIndex := prng.uniformRandom(numLiveTickets)\n\t\tif _, exists := usedOffsets[ticketIndex]; !exists {\n\t\t\tusedOffsets[ticketIndex] = struct{}{}\n\t\t\twinners = append(winners, liveTickets[ticketIndex])\n\t\t}\n\t}\n\treturn winners, prng.State(), nil\n}", "func GetLockedDistributionAddresses() []string {\n\t// TODO -- once we reach 30% distribution, we can hardcode the\n\t// initial timestamp for releasing more coins\n\taddrs := make([]string, DistributionAddressesTotal-InitialUnlockedCount)\n\tfor i := range distributionAddresses[InitialUnlockedCount:] {\n\t\taddrs[i] = distributionAddresses[InitialUnlockedCount+uint64(i)]\n\t}\n\n\treturn addrs\n}", "func (bva BaseVestingAccount) GetDelegatedVesting() sdk.Coins {\n\treturn bva.DelegatedVesting\n}", "func (cb CommitteeBits) FilterNonParticipants(committee []ValidatorIndex) []ValidatorIndex {\n\tbitLen := cb.BitLen()\n\tout := committee[:0]\n\tif bitLen != uint64(len(committee)) {\n\t\tpanic(\"committee mismatch, bitfield length does not match\")\n\t}\n\tfor i := uint64(0); i < bitLen; i++ {\n\t\tif !cb.GetBit(i) {\n\t\t\tout = append(out, committee[i])\n\t\t}\n\t}\n\treturn out\n}", "func ConvertSdkCoinsToWasmCoins(coins []sdk.Coin) wasmvmtypes.Coins {\n\tconverted := make(wasmvmtypes.Coins, len(coins))\n\tfor i, c := range coins {\n\t\tconverted[i] = ConvertSdkCoinToWasmCoin(c)\n\t}\n\treturn converted\n}", "func (t *TauAPI) GetCoins() (coins []Coin, error error) {\n\tvar c = []Coin{}\n\tvar d struct {\n\t\tCrypto []Coin `json:\"cryto\"` //typo from api\n\t\tFiat []Coin `json:\"fiat\"`\n\t}\n\tjsonData, err := t.doTauRequest(&TauReq{\n\t\tVersion: 2,\n\t\tMethod: \"GET\",\n\t\tPath: \"coins\",\n\t})\n\tif err != nil {\n\t\treturn c, err\n\t}\n\tif err := json.Unmarshal(jsonData, &d); err != nil {\n\t\treturn c, err\n\t}\n\tc = append(d.Crypto, d.Fiat...)\n\treturn c, nil\n}", "func (_Lmc *LmcFilterer) FilterStakedAndLocked(opts *bind.FilterOpts, _userAddress []common.Address) (*LmcStakedAndLockedIterator, error) {\n\n\tvar _userAddressRule []interface{}\n\tfor _, _userAddressItem := range _userAddress {\n\t\t_userAddressRule = append(_userAddressRule, _userAddressItem)\n\t}\n\n\tlogs, sub, err := _Lmc.contract.FilterLogs(opts, \"StakedAndLocked\", _userAddressRule)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &LmcStakedAndLockedIterator{contract: _Lmc.contract, event: \"StakedAndLocked\", logs: logs, sub: sub}, nil\n}", "func (_DelegationController *DelegationControllerTransactor) GetAndUpdateLockedAmount(opts *bind.TransactOpts, wallet common.Address) (*types.Transaction, error) {\n\treturn _DelegationController.contract.Transact(opts, \"getAndUpdateLockedAmount\", wallet)\n}", "func (pager *SecretVersionLocksPager) GetAll() (allItems []SecretLock, err error) {\n\treturn pager.GetAllWithContext(context.Background())\n}", "func newCoins() sdk.Coins {\n\treturn sdk.Coins{\n\t\tsdk.NewInt64Coin(\"atom\", 10000000),\n\t}\n}", "func (_DelegationController *DelegationControllerTransactorSession) GetAndUpdateLockedAmount(wallet common.Address) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.GetAndUpdateLockedAmount(&_DelegationController.TransactOpts, wallet)\n}", "func (dcr *ExchangeWallet) spendableUTXOs() ([]*compositeUTXO, error) {\n\tunspents, err := dcr.wallet.Unspents(dcr.ctx, dcr.primaryAcct)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif dcr.tradingAccount != \"\" {\n\t\t// Trading account may contain spendable utxos such as unspent split tx\n\t\t// outputs that are unlocked/returned. TODO: Care should probably be\n\t\t// taken to ensure only unspent split tx outputs are selected and other\n\t\t// unmixed outputs in the trading account are ignored.\n\t\ttradingAcctSpendables, err := dcr.wallet.Unspents(dcr.ctx, dcr.tradingAccount)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tunspents = append(unspents, tradingAcctSpendables...)\n\t}\n\tif len(unspents) == 0 {\n\t\treturn nil, fmt.Errorf(\"insufficient funds. 0 DCR available to spend in account %q\", dcr.primaryAcct)\n\t}\n\n\t// Parse utxos to include script size for spending input. Returned utxos\n\t// will be sorted in ascending order by amount (smallest first).\n\tutxos, err := dcr.parseUTXOs(unspents)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error parsing unspent outputs: %w\", err)\n\t}\n\tif len(utxos) == 0 {\n\t\treturn nil, fmt.Errorf(\"no funds available\")\n\t}\n\treturn utxos, nil\n}", "func (_DelegationController *DelegationControllerSession) GetAndUpdateLockedAmount(wallet common.Address) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.GetAndUpdateLockedAmount(&_DelegationController.TransactOpts, wallet)\n}", "func (u UTXOSet) FindUnspentTransactions(pubKeyHash []byte) []TxOutput {\n\tvar UTXOs []TxOutput\n\n\tdb := u.Blockchain.Database\n\n\terr := db.View(func(txn *badger.Txn) error {\n\t\topts := badger.DefaultIteratorOptions\n\n\t\tit := txn.NewIterator(opts)\n\t\tdefer it.Close()\n\n\t\t// iterate through UTXOS prefixes\n\t\tfor it.Seek(utxoPrefix); it.ValidForPrefix(utxoPrefix); it.Next() {\n\t\t\t// get the value of each utxo prefixed item\n\t\t\tv := valueHash(it.Item())\n\t\t\touts := DeserializeOutputs(v)\n\n\t\t\t// iterate through each output, check to see if it is locked by the provided hash address\n\t\t\tfor _, out := range outs.Outputs {\n\t\t\t\tif out.IsLockedWithKey(pubKeyHash) {\n\t\t\t\t\tUTXOs = append(UTXOs, out)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn nil\n\t})\n\thandle(err)\n\n\treturn UTXOs\n}", "func (s *Service) FilterPayments(accountID int64, goroutines int) ([]types.Payment, error) {\n\n\taccount, err := s.FindAccountByID(accountID)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\twg := sync.WaitGroup{}\n\tmu := sync.Mutex{}\n\tkol := 0\n\ti := 0\n\tvar ps []types.Payment\n\tif goroutines == 0 {\n\t\tkol = len(s.payments)\n\t} else {\n\t\tkol = int(len(s.payments) / goroutines)\n\t}\n\tfor i = 0; i < goroutines-1; i++ {\n\t\twg.Add(1)\n\t\tgo func(index int) {\n\t\t\tdefer wg.Done()\n\t\t\tvar pays []types.Payment\n\t\t\tpayments := s.payments[index*kol : (index+1)*kol]\n\t\t\tfor _, v := range payments {\n\t\t\t\tif v.AccountID == account.ID {\n\t\t\t\t\tpays = append(pays, types.Payment{\n\t\t\t\t\t\tID: v.ID,\n\t\t\t\t\t\tAccountID: v.AccountID,\n\t\t\t\t\t\tAmount: v.Amount,\n\t\t\t\t\t\tCategory: v.Category,\n\t\t\t\t\t\tStatus: v.Status,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\t\t\tmu.Lock()\n\t\t\tps = append(ps, pays...)\n\t\t\tmu.Unlock()\n\n\t\t}(i)\n\t}\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\tvar pays []types.Payment\n\t\tpayments := s.payments[i*kol:]\n\t\tfor _, v := range payments {\n\t\t\tif v.AccountID == account.ID {\n\t\t\t\tpays = append(pays, types.Payment{\n\t\t\t\t\tID: v.ID,\n\t\t\t\t\tAccountID: v.AccountID,\n\t\t\t\t\tAmount: v.Amount,\n\t\t\t\t\tCategory: v.Category,\n\t\t\t\t\tStatus: v.Status,\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t\tmu.Lock()\n\t\tps = append(ps, pays...)\n\t\tmu.Unlock()\n\n\t}()\n\twg.Wait()\n\tif len(ps) == 0 {\n\t\treturn nil, nil\n\t}\n\treturn ps, nil\n}", "func NewValidatorVestingAccountRaw(bva *vestingtypes.BaseVestingAccount,\n\tstartTime int64, periods vestingtypes.Periods, validatorAddress sdk.ConsAddress, returnAddress sdk.AccAddress, signingThreshold int64) *ValidatorVestingAccount {\n\n\tpva := &vestingtypes.PeriodicVestingAccount{\n\t\tBaseVestingAccount: bva,\n\t\tStartTime: startTime,\n\t\tVestingPeriods: periods,\n\t}\n\tvar vestingPeriodProgress []VestingProgress\n\tfor i := 0; i < len(periods); i++ {\n\t\tvestingPeriodProgress = append(vestingPeriodProgress, VestingProgress{false, false})\n\t}\n\n\treturn &ValidatorVestingAccount{\n\t\tPeriodicVestingAccount: pva,\n\t\tValidatorAddress: validatorAddress,\n\t\tReturnAddress: returnAddress,\n\t\tSigningThreshold: signingThreshold,\n\t\tCurrentPeriodProgress: CurrentPeriodProgress{0, 0},\n\t\tVestingPeriodProgress: vestingPeriodProgress,\n\t\tDebtAfterFailedVesting: sdk.NewCoins(),\n\t}\n}", "func (k Keeper) coinsFromStakedToUnstaked(ctx sdk.Ctx, validator types.Validator) error {\n\tcoins := sdk.NewCoins(sdk.NewCoin(k.StakeDenom(ctx), validator.StakedTokens))\n\toutput, _ := k.GetValidatorOutputAddress(ctx, validator.Address)\n\terr := k.AccountKeeper.SendCoinsFromModuleToAccount(ctx, types.StakedPoolName, output, coins)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to send coins from staked to unstaked for address: %s\", validator.Address)\n\t}\n\treturn nil\n}", "func (cs *Coins) CoinSelect(amount uint64, asset string) (unspents []explorer.Utxo, change uint64, err error) {\n\tchange = 0\n\tunspents = []explorer.Utxo{}\n\tavailableSats := uint64(0)\n\n\tfor index, unspent := range cs.Utxos {\n\t\tu := unspent\n\t\tassetHash := u.Asset()\n\t\tamountSatoshis := u.Value()\n\t\tif len(u.AssetCommitment()) > 0 && len(u.ValueCommitment()) > 0 {\n\t\t\tbk := cs.BlindingKey\n\t\t\tif len(cs.BlindingKeys) > 0 {\n\t\t\t\tbk = cs.BlindingKeys[index]\n\t\t\t}\n\t\t\tav, err := unblindUxto(u, bk)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, 0, err\n\t\t\t}\n\t\t\tassetHash = av.asset\n\t\t\tamountSatoshis = av.value\n\t\t}\n\t\tif asset == assetHash {\n\t\t\tunspents = append(unspents, unspent)\n\t\t\tavailableSats += amountSatoshis\n\n\t\t\tif availableSats >= amount {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\tif availableSats < amount {\n\t\treturn nil, 0, errors.New(\"You do not have enough coins\")\n\t}\n\n\tchange = availableSats - amount\n\n\treturn unspents, change, nil\n}", "func (m *Client) GetCoins() ([]string, error) {\n\tresp, err := m.Service.GetCoins()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error requesting coin list: %s\", err)\n\t}\n\tdefer resp.Body.Close()\n\n\tvar response []string\n\terr = json.NewDecoder(resp.Body).Decode(&response)\n\tif err != nil {\n\t\tmsg, _ := ioutil.ReadAll(resp.Body)\n\t\treturn nil, fmt.Errorf(\"error decoding coin list: %s: %s\", msg, err)\n\t}\n\n\treturn response, nil\n}", "func ListUnspentWithAsset(ctx context.Context, rpcClient RpcClient, filter []Address, asset string) ([]TransactionInfo, error) {\n\treturn ListUnspentMinMaxAddressesAndOptions(ctx, rpcClient, AddressInfoMinConfirmation, AddressInfoMaxConfirmation, filter, ListUnspentOption{\n\t\tAsset: asset,\n\t})\n}" ]
[ "0.7522999", "0.7444621", "0.7421999", "0.73869133", "0.73509336", "0.6998124", "0.6757025", "0.6743434", "0.66449594", "0.6587789", "0.6478109", "0.6473024", "0.629536", "0.6076974", "0.6073959", "0.58224916", "0.5766373", "0.54533124", "0.54496396", "0.51249546", "0.49122313", "0.48747206", "0.48611894", "0.48413375", "0.48395702", "0.48340192", "0.48318133", "0.48020262", "0.47913572", "0.4782506", "0.47811475", "0.4765673", "0.46473348", "0.46009314", "0.45744163", "0.45577896", "0.45571733", "0.45503837", "0.45405298", "0.45196232", "0.4498849", "0.44980028", "0.44460115", "0.4440476", "0.44116846", "0.44097015", "0.44069836", "0.43833417", "0.43741685", "0.43506482", "0.43465245", "0.43032023", "0.42897624", "0.42840245", "0.4280523", "0.42715314", "0.42678326", "0.42580086", "0.42445654", "0.4231539", "0.42272356", "0.42246404", "0.42239937", "0.42043647", "0.4162037", "0.4151652", "0.4145284", "0.41450456", "0.41395262", "0.4124186", "0.40838888", "0.40807757", "0.4067383", "0.40649495", "0.40613195", "0.4058844", "0.40470135", "0.40430883", "0.40374714", "0.40301853", "0.40260902", "0.40046787", "0.40045047", "0.39776295", "0.3961546", "0.39594465", "0.39537182", "0.39464465", "0.39435944", "0.39277348", "0.39242154", "0.39238617", "0.39216614", "0.39192048", "0.3918111", "0.39164534", "0.39135006", "0.3907506", "0.38988355", "0.38958386" ]
0.8314347
0
TrackDelegation tracks a delegation amount for any given vesting account type given the amount of coins currently vesting and the current account balance of the delegation denominations. CONTRACT: The account's coins, delegation coins, vesting coins, and delegated vesting coins must be sorted.
func (bva *BaseVestingAccount) TrackDelegation(balance, vestingCoins, amount sdk.Coins) { for _, coin := range amount { baseAmt := balance.AmountOf(coin.Denom) vestingAmt := vestingCoins.AmountOf(coin.Denom) delVestingAmt := bva.DelegatedVesting.AmountOf(coin.Denom) // Panic if the delegation amount is zero or if the base coins does not // exceed the desired delegation amount. if coin.Amount.IsZero() || baseAmt.LT(coin.Amount) { panic("delegation attempt with zero coins or insufficient funds") } // compute x and y per the specification, where: // X := min(max(V - DV, 0), D) // Y := D - X x := sdk.MinInt(sdk.MaxInt(vestingAmt.Sub(delVestingAmt), sdk.ZeroInt()), coin.Amount) y := coin.Amount.Sub(x) if !x.IsZero() { xCoin := sdk.NewCoin(coin.Denom, x) bva.DelegatedVesting = bva.DelegatedVesting.Add(xCoin) } if !y.IsZero() { yCoin := sdk.NewCoin(coin.Denom, y) bva.DelegatedFree = bva.DelegatedFree.Add(yCoin) } } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (dva *DelayedVestingAccount) TrackDelegation(blockTime time.Time, balance, amount sdk.Coins) {\n\tdva.BaseVestingAccount.TrackDelegation(balance, dva.GetVestingCoins(blockTime), amount)\n}", "func (pva *PeriodicVestingAccount) TrackDelegation(blockTime time.Time, balance, amount sdk.Coins) {\n\tpva.BaseVestingAccount.TrackDelegation(balance, pva.GetVestingCoins(blockTime), amount)\n}", "func (cva *ContinuousVestingAccount) TrackDelegation(blockTime time.Time, balance, amount sdk.Coins) {\n\tcva.BaseVestingAccount.TrackDelegation(balance, cva.GetVestingCoins(blockTime), amount)\n}", "func (va *ClawbackVestingAccount) TrackDelegation(blockTime time.Time, balance, amount sdk.Coins) {\n\tva.BaseVestingAccount.TrackDelegation(balance, va.GetVestingCoins(blockTime), amount)\n}", "func (vva *ValidatorVestingAccount) TrackDelegation(blockTime time.Time, amount sdk.Coins) {\n\tvva.BaseVestingAccount.TrackDelegation(vva.GetVestingCoins(blockTime), amount)\n}", "func (plva *PermanentLockedAccount) TrackDelegation(blockTime time.Time, balance, amount sdk.Coins) {\n\tplva.BaseVestingAccount.TrackDelegation(balance, plva.OriginalVesting, amount)\n}", "func (bva *BaseVestingAccount) TrackUndelegation(amount sdk.Coins) {\n\tfor _, coin := range amount {\n\t\t// panic if the undelegation amount is zero\n\t\tif coin.Amount.IsZero() {\n\t\t\tpanic(\"undelegation attempt with zero coins\")\n\t\t}\n\t\tdelegatedFree := bva.DelegatedFree.AmountOf(coin.Denom)\n\t\tdelegatedVesting := bva.DelegatedVesting.AmountOf(coin.Denom)\n\n\t\t// compute x and y per the specification, where:\n\t\t// X := min(DF, D)\n\t\t// Y := min(DV, D - X)\n\t\tx := sdk.MinInt(delegatedFree, coin.Amount)\n\t\ty := sdk.MinInt(delegatedVesting, coin.Amount.Sub(x))\n\n\t\tif !x.IsZero() {\n\t\t\txCoin := sdk.NewCoin(coin.Denom, x)\n\t\t\tbva.DelegatedFree = bva.DelegatedFree.Sub(sdk.Coins{xCoin})\n\t\t}\n\n\t\tif !y.IsZero() {\n\t\t\tyCoin := sdk.NewCoin(coin.Denom, y)\n\t\t\tbva.DelegatedVesting = bva.DelegatedVesting.Sub(sdk.Coins{yCoin})\n\t\t}\n\t}\n}", "func (va *ClawbackVestingAccount) updateDelegation(encumbered, toClawBack, bonded, unbonding, unbonded sdk.Coins) sdk.Coins {\n\tdelegated := bonded.Add(unbonding...)\n\toldDelegated := va.DelegatedVesting.Add(va.DelegatedFree...)\n\tslashed := oldDelegated.Sub(coinsMin(delegated, oldDelegated))\n\ttotal := delegated.Add(unbonded...)\n\ttoClawBack = coinsMin(toClawBack, total) // might have been slashed\n\tnewDelegated := coinsMin(delegated, total.Sub(toClawBack)).Add(slashed...)\n\tva.DelegatedVesting = coinsMin(encumbered, newDelegated)\n\tva.DelegatedFree = newDelegated.Sub(va.DelegatedVesting)\n\treturn toClawBack\n}", "func (k msgServer) Delegate(goCtx context.Context, msg *types.MsgDelegate) (*types.MsgDelegateResponse, error) {\n\tctx := sdk.UnwrapSDKContext(goCtx)\n\tvalAddr, valErr := sdk.ValAddressFromBech32(msg.ValidatorAddress)\n\tif valErr != nil {\n\t\treturn nil, valErr\n\t}\n\n\tvalidator, found := k.GetValidator(ctx, valAddr)\n\tif !found {\n\t\treturn nil, types.ErrNoValidatorFound\n\t}\n\n\tdelegatorAddress, err := sdk.AccAddressFromBech32(msg.DelegatorAddress)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbondDenom := k.BondDenom(ctx)\n\tif msg.Amount.Denom != bondDenom {\n\t\treturn nil, sdkerrors.Wrapf(\n\t\t\tsdkerrors.ErrInvalidRequest, \"invalid coin denomination: got %s, expected %s\", msg.Amount.Denom, bondDenom,\n\t\t)\n\t}\n\n\ttokens := msg.Amount.Amount\n\n\t// if this delegation is from a liquid staking provider (identified if the delegator\n\t// is an ICA account), it cannot exceed the global or validator bond cap\n\tif k.DelegatorIsLiquidStaker(delegatorAddress) {\n\t\tshares, err := validator.SharesFromTokens(tokens)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif err := k.SafelyIncreaseTotalLiquidStakedTokens(ctx, tokens, false); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif err := k.SafelyIncreaseValidatorLiquidShares(ctx, &validator, shares); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// NOTE: source funds are always unbonded\n\tnewShares, err := k.Keeper.Delegate(ctx, delegatorAddress, tokens, types.Unbonded, validator, true)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif tokens.IsInt64() {\n\t\tdefer func() {\n\t\t\ttelemetry.IncrCounter(1, types.ModuleName, \"delegate\")\n\t\t\ttelemetry.SetGaugeWithLabels(\n\t\t\t\t[]string{\"tx\", \"msg\", msg.Type()},\n\t\t\t\tfloat32(tokens.Int64()),\n\t\t\t\t[]metrics.Label{telemetry.NewLabel(\"denom\", msg.Amount.Denom)},\n\t\t\t)\n\t\t}()\n\t}\n\n\tctx.EventManager().EmitEvents(sdk.Events{\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeDelegate,\n\t\t\tsdk.NewAttribute(types.AttributeKeyValidator, msg.ValidatorAddress),\n\t\t\tsdk.NewAttribute(sdk.AttributeKeyAmount, msg.Amount.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyNewShares, newShares.String()),\n\t\t),\n\t})\n\n\treturn &types.MsgDelegateResponse{}, nil\n}", "func (k Keeper) TransferDelegation(ctx sdk.Context, valAddr sdk.ValAddress, fromDelegator, toDelegator sdk.AccAddress, shares sdk.Dec) (sdk.Dec, error) {\n\t// Redelegations link a delegation to it's previous validator so slashes are propagated to the new validator.\n\t// If the delegation is transferred to a new owner, the redelegation object must be updated.\n\t// For expediency all transfers with redelegations are blocked.\n\tif k.stakingKeeper.HasReceivingRedelegation(ctx, fromDelegator, valAddr) {\n\t\treturn sdk.Dec{}, types.ErrRedelegationsNotCompleted\n\t}\n\n\tif shares.IsNil() || shares.LT(sdk.ZeroDec()) {\n\t\treturn sdk.Dec{}, errorsmod.Wrap(types.ErrUntransferableShares, \"nil or negative shares\")\n\t}\n\tif shares.Equal(sdk.ZeroDec()) {\n\t\t// Block 0 transfers to reduce edge cases.\n\t\treturn sdk.Dec{}, errorsmod.Wrap(types.ErrUntransferableShares, \"zero shares\")\n\t}\n\n\tfromDelegation, found := k.stakingKeeper.GetDelegation(ctx, fromDelegator, valAddr)\n\tif !found {\n\t\treturn sdk.Dec{}, types.ErrNoDelegatorForAddress\n\t}\n\tvalidator, found := k.stakingKeeper.GetValidator(ctx, valAddr)\n\tif !found {\n\t\treturn sdk.Dec{}, types.ErrNoValidatorFound\n\t}\n\t// Prevent validators from reducing their self delegation below the min.\n\tisValidatorOperator := fromDelegator.Equals(valAddr)\n\tif isValidatorOperator {\n\t\tif isBelowMinSelfDelegation(validator, fromDelegation.Shares.Sub(shares)) {\n\t\t\treturn sdk.Dec{}, types.ErrSelfDelegationBelowMinimum\n\t\t}\n\t}\n\n\treturnAmount, err := k.fastUndelegate(ctx, valAddr, fromDelegator, shares)\n\tif err != nil {\n\t\treturn sdk.Dec{}, err\n\t}\n\treturnCoins := sdk.NewCoins(sdk.NewCoin(k.stakingKeeper.BondDenom(ctx), returnAmount))\n\n\tif err := k.bankKeeper.SendCoins(ctx, fromDelegator, toDelegator, returnCoins); err != nil {\n\t\treturn sdk.Dec{}, err\n\t}\n\treceivedShares, err := k.delegateFromAccount(ctx, valAddr, toDelegator, returnAmount)\n\tif err != nil {\n\t\treturn sdk.Dec{}, err\n\t}\n\n\treturn receivedShares, nil\n}", "func (b *rpcVestingBalance) delegated() (sdk.Coins, sdk.Coins, error) {\n\tdelegatedCoins, err := b.totalDelegated()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tunbondingCoins, err := b.totalUnbondingDelegations()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tdelegated := delegatedCoins.AmountOf(stakingDenom)\n\tunbonding := unbondingCoins.AmountOf(stakingDenom)\n\ttotalStaked := delegated.Add(unbonding)\n\tdelegatedFree := b.vacc.GetDelegatedFree().AmountOf(stakingDenom)\n\n\t// total number of staked and unbonding tokens considered to be liquid\n\ttotalFree := sdk.MinInt(totalStaked, delegatedFree)\n\t// any coins that are not considered liquid, are vesting up to a maximum of delegated\n\tstakedVesting := sdk.MinInt(totalStaked.Sub(totalFree), delegated)\n\t// staked free coins are left over\n\tstakedFree := delegated.Sub(stakedVesting)\n\n\tliquidCoins := sdk.NewCoins(newKavaCoin(stakedFree))\n\tvestingCoins := sdk.NewCoins(newKavaCoin(stakedVesting))\n\treturn liquidCoins, vestingCoins, nil\n}", "func (_DelegationController *DelegationControllerTransactor) Delegate(opts *bind.TransactOpts, validatorId *big.Int, amount *big.Int, delegationPeriod *big.Int, info string) (*types.Transaction, error) {\n\treturn _DelegationController.contract.Transact(opts, \"delegate\", validatorId, amount, delegationPeriod, info)\n}", "func (a *account) managedTrackDeposit(amount types.Currency) {\n\ta.mu.Lock()\n\tdefer a.mu.Unlock()\n\ta.pendingDeposits = a.pendingDeposits.Add(amount)\n}", "func (_DelegationController *DelegationControllerSession) Delegate(validatorId *big.Int, amount *big.Int, delegationPeriod *big.Int, info string) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.Delegate(&_DelegationController.TransactOpts, validatorId, amount, delegationPeriod, info)\n}", "func (_DelegationController *DelegationControllerTransactorSession) Delegate(validatorId *big.Int, amount *big.Int, delegationPeriod *big.Int, info string) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.Delegate(&_DelegationController.TransactOpts, validatorId, amount, delegationPeriod, info)\n}", "func CalculateDelegateNetPayout(delegatedContracts []DelegatedContract) []DelegatedContract{\n var delegateIndex int\n\n for index, delegate := range delegatedContracts{\n if (delegate.Delegate){\n delegateIndex = index\n }\n }\n\n for _, delegate := range delegatedContracts{\n if (!delegate.Delegate){\n delegatedContracts[delegateIndex].TotalPayout = delegatedContracts[delegateIndex].TotalPayout + delegate.Fee\n }\n }\n return delegatedContracts\n}", "func (a *Account) Track() {\n\t// Request notifications for transactions sending to all wallet\n\t// addresses.\n\taddrs := a.ActiveAddresses()\n\taddrstrs := make([]string, len(addrs))\n\ti := 0\n\tfor addr := range addrs {\n\t\taddrstrs[i] = addr.EncodeAddress()\n\t\ti++\n\t}\n\n\terr := NotifyNewTXs(CurrentServerConn(), addrstrs)\n\tif err != nil {\n\t\tlog.Error(\"Unable to request transaction updates for address.\")\n\t}\n\n\tfor _, txout := range a.TxStore.UnspentOutputs() {\n\t\tReqSpentUtxoNtfn(txout)\n\t}\n}", "func (_TokensNetwork *TokensNetworkTransactor) UpdateBalanceProofDelegate(opts *bind.TransactOpts, token common.Address, partner common.Address, participant common.Address, transferred_amount *big.Int, locksroot [32]byte, nonce uint64, additional_hash [32]byte, partner_signature []byte, participant_signature []byte) (*types.Transaction, error) {\n\treturn _TokensNetwork.contract.Transact(opts, \"updateBalanceProofDelegate\", token, partner, participant, transferred_amount, locksroot, nonce, additional_hash, partner_signature, participant_signature)\n}", "func (a *Account) Track() {\n\trpcc, err := accessClient()\n\tif err != nil {\n\t\tlog.Errorf(\"No chain server client to track addresses.\")\n\t\treturn\n\t}\n\n\t// Request notifications for transactions sending to all wallet\n\t// addresses.\n\t//\n\t// TODO: return as slice? (doesn't have to be ordered, or\n\t// SortedActiveAddresses would be fine.)\n\taddrMap := a.KeyStore.ActiveAddresses()\n\taddrs := make([]btcutil.Address, 0, len(addrMap))\n\tfor addr := range addrMap {\n\t\taddrs = append(addrs, addr)\n\t}\n\n\tif err := rpcc.NotifyReceived(addrs); err != nil {\n\t\tlog.Error(\"Unable to request transaction updates for address.\")\n\t}\n\n\tunspent, err := a.TxStore.UnspentOutputs()\n\tif err != nil {\n\t\tlog.Errorf(\"Unable to access unspent outputs: %v\", err)\n\t\treturn\n\t}\n\tReqSpentUtxoNtfns(unspent)\n}", "func Delegate(stub shim.ChaincodeStubInterface, args []string) error {\n\tvar vote entities.Vote\n\terr := json.Unmarshal([]byte(args[0]), &vote)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tpoll, err := validateDelegate(stub, vote)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = addVoteToPoll(stub, poll, vote)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Println(\"saving delegate vote\")\n\tutil.UpdateObjectInChain(stub, vote.ID(), util.VotesIndexName, []byte(args[0]))\n\n\tfmt.Println(\"successfully delegated vote to \" + vote.Delegate + \"!\")\n\treturn nil\n}", "func (k Keeper) DelegateCoinsFromAccountToModule(\n\tctx sdk.Context, senderAddr sdk.AccAddress, recipientModule string, amt sdk.Coins,\n) error {\n\n\trecipientAcc := k.GetModuleAccount(ctx, recipientModule)\n\tif recipientAcc == nil {\n\t\tpanic(sdkerrors.Wrapf(sdkerrors.ErrUnknownAddress, \"module account %s does not exist\", recipientModule))\n\t}\n\n\tif !recipientAcc.HasPermission(types.Staking) {\n\t\tpanic(sdkerrors.Wrapf(sdkerrors.ErrUnauthorized, \"module account %s does not have permissions to receive delegated coins\", recipientModule))\n\t}\n\n\treturn k.bk.DelegateCoins(ctx, senderAddr, recipientAcc.GetAddress(), amt)\n}", "func (_TokensNetwork *TokensNetworkSession) UpdateBalanceProofDelegate(token common.Address, partner common.Address, participant common.Address, transferred_amount *big.Int, locksroot [32]byte, nonce uint64, additional_hash [32]byte, partner_signature []byte, participant_signature []byte) (*types.Transaction, error) {\n\treturn _TokensNetwork.Contract.UpdateBalanceProofDelegate(&_TokensNetwork.TransactOpts, token, partner, participant, transferred_amount, locksroot, nonce, additional_hash, partner_signature, participant_signature)\n}", "func (o OfflineNotaryRepository) AddDelegation(data.RoleName, []data.PublicKey, []string) error {\n\treturn nil\n}", "func CalculatePercentageSharesForCycle(delegatedContracts []DelegatedContract, cycle int, rate float64, spillage bool, delegateAddr string) ([]DelegatedContract, error){\n var stakingBalance float64\n //var balance float64\n var err error\n\n spillAlert := false\n\n stakingBalance, err = GetDelegateStakingBalance(delegateAddr, cycle)\n if (err != nil){\n return delegatedContracts, errors.New(\"func CalculateRollSpillage(delegatedContracts []DelegatedContract, delegateAddr string) failed: \" + err.Error())\n }\n\n mod := math.Mod(stakingBalance, 10000)\n sum := stakingBalance - mod\n balanceCheck := stakingBalance - mod\n\n for index, delegation := range delegatedContracts{\n counter := 0\n for i, _ := range delegation.Contracts {\n if (delegatedContracts[index].Contracts[i].Cycle == cycle){\n break\n }\n counter = counter + 1\n }\n balanceCheck = balanceCheck - delegatedContracts[index].Contracts[counter].Amount\n //fmt.Println(stakingBalance)\n if (spillAlert){\n delegatedContracts[index].Contracts[counter].SharePercentage = 0\n delegatedContracts[index].Contracts[counter].RollInclusion = 0\n } else if (balanceCheck < 0 && spillage){\n spillAlert = true\n delegatedContracts[index].Contracts[counter].SharePercentage = (delegatedContracts[index].Contracts[counter].Amount + stakingBalance) / sum\n delegatedContracts[index].Contracts[counter].RollInclusion = delegatedContracts[index].Contracts[counter].Amount + stakingBalance\n } else{\n delegatedContracts[index].Contracts[counter].SharePercentage = delegatedContracts[index].Contracts[counter].Amount / stakingBalance\n delegatedContracts[index].Contracts[counter].RollInclusion = delegatedContracts[index].Contracts[counter].Amount\n }\n delegatedContracts[index].Contracts[counter] = CalculatePayoutForContract(delegatedContracts[index].Contracts[counter], rate, delegatedContracts[index].Delegate)\n delegatedContracts[index].Fee = delegatedContracts[index].Fee + delegatedContracts[index].Contracts[counter].Fee\n }\n\n return delegatedContracts, nil\n}", "func (_TokensNetwork *TokensNetworkTransactorSession) UpdateBalanceProofDelegate(token common.Address, partner common.Address, participant common.Address, transferred_amount *big.Int, locksroot [32]byte, nonce uint64, additional_hash [32]byte, partner_signature []byte, participant_signature []byte) (*types.Transaction, error) {\n\treturn _TokensNetwork.Contract.UpdateBalanceProofDelegate(&_TokensNetwork.TransactOpts, token, partner, participant, transferred_amount, locksroot, nonce, additional_hash, partner_signature, participant_signature)\n}", "func (broadcast *Broadcast) Delegate(ctx context.Context, delegator, voter, amount,\n\tprivKeyHex string, seq int64) (*model.BroadcastResponse, error) {\n\tmsg := model.DelegateMsg{\n\t\tDelegator: delegator,\n\t\tVoter: voter,\n\t\tAmount: amount,\n\t}\n\treturn broadcast.broadcastTransaction(ctx, msg, privKeyHex, seq, \"\", false)\n}", "func (k Keeper) delegateFromAccount(ctx sdk.Context, valAddr sdk.ValAddress, delegator sdk.AccAddress, amount sdkmath.Int) (sdk.Dec, error) {\n\tvalidator, found := k.stakingKeeper.GetValidator(ctx, valAddr)\n\tif !found {\n\t\treturn sdk.Dec{}, types.ErrNoValidatorFound\n\t}\n\t// source tokens are from an account, so subtractAccount true and tokenSrc unbonded\n\tnewShares, err := k.stakingKeeper.Delegate(ctx, delegator, amount, stakingtypes.Unbonded, validator, true)\n\tif err != nil {\n\t\treturn sdk.Dec{}, err\n\t}\n\treturn newShares, nil\n}", "func (a *account) managedTrackWithdrawal(amount types.Currency) {\n\ta.mu.Lock()\n\tdefer a.mu.Unlock()\n\ta.pendingWithdrawals = a.pendingWithdrawals.Add(amount)\n}", "func Transfer(\n\tctx *vm.Context, db vm.StateDB, sender, recipient types.AddressHash, amount *big.Int,\n) {\n\t// NOTE: amount is a re-used pointer varaible\n\tdb.SubBalance(sender, amount)\n\tdb.AddBalance(recipient, amount)\n\tif db.IsContractAddr(sender) && amount.Uint64() > 0 {\n\t\ttransferInfo := vm.NewTransferInfo(sender, recipient, amount.Uint64())\n\t\tlogger.Debugf(\"new transfer info: sender: %x, recipient: %x, amount: %d\",\n\t\t\tsender[:], recipient[:], amount)\n\t\tif v, ok := ctx.Transfers[sender]; ok {\n\t\t\t// if sender and recipient already exists in Transfers, update it instead\n\t\t\t// of append to it\n\t\t\tfor _, w := range v {\n\t\t\t\tif w.To == recipient {\n\t\t\t\t\t// NOTE: cannot miss 'w.value = '\n\t\t\t\t\tw.Value += amount.Uint64()\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tctx.Transfers[sender] = append(ctx.Transfers[sender], transferInfo)\n\t}\n}", "func (pva *PeriodicVestingAccount) addGrant(ctx sdk.Context, sk StakingKeeper, grantStartTime int64, grantVestingPeriods []Period, grantCoins sdk.Coins) {\n\t// how much is really delegated?\n\tbondedAmt := sk.GetDelegatorBonded(ctx, pva.GetAddress())\n\tunbondingAmt := sk.GetDelegatorUnbonding(ctx, pva.GetAddress())\n\tdelegatedAmt := bondedAmt.Add(unbondingAmt)\n\tdelegated := sdk.NewCoins(sdk.NewCoin(sk.BondDenom(ctx), delegatedAmt))\n\n\t// discover what has been slashed\n\toldDelegated := pva.DelegatedVesting.Add(pva.DelegatedFree...)\n\tslashed := oldDelegated.Sub(coinsMin(oldDelegated, delegated))\n\n\t// rebase the DV+DF by capping slashed at the current unvested amount\n\tunvested := pva.GetVestingCoins(ctx.BlockTime())\n\tnewSlashed := coinsMin(unvested, slashed)\n\tnewTotalDelegated := delegated.Add(newSlashed...)\n\n\t// modify vesting schedule for the new grant\n\tnewStart, newEnd, newPeriods := DisjunctPeriods(pva.StartTime, grantStartTime,\n\t\tpva.GetVestingPeriods(), grantVestingPeriods)\n\tpva.StartTime = newStart\n\tpva.EndTime = newEnd\n\tpva.VestingPeriods = newPeriods\n\tpva.OriginalVesting = pva.OriginalVesting.Add(grantCoins...)\n\n\t// cap DV at the current unvested amount, DF rounds out to newTotalDelegated\n\tunvested2 := pva.GetVestingCoins(ctx.BlockTime())\n\tpva.DelegatedVesting = coinsMin(newTotalDelegated, unvested2)\n\tpva.DelegatedFree = newTotalDelegated.Sub(pva.DelegatedVesting)\n}", "func CalculateAllContractsForCycle(delegatedContracts []DelegatedContract, cycle int, rate float64, spillage bool, delegateAddr string) ([]DelegatedContract, error) {\n var err error\n var balance float64\n delegationsForCycle, _ := GetDelegatedContractsForCycle(cycle, delegateAddr)\n\n for index, delegation := range delegatedContracts{\n balance, err = GetAccountBalanceAtSnapshot(delegation.Address, cycle)\n if (err != nil){\n return delegatedContracts, errors.New(\"Could not calculate all commitments for cycle \" + strconv.Itoa(cycle) + \":GetAccountBalanceAtSnapshot(tezosAddr string, cycle int) failed: \" + err.Error())\n }\n if (isDelegationInGroup(delegatedContracts[index].Address, delegationsForCycle, delegatedContracts[index].Delegate)){\n delegatedContracts[index].Contracts = append(delegatedContracts[index].Contracts, Contract{Cycle:cycle, Amount:balance})\n } else{\n delegatedContracts[index].Contracts = append(delegatedContracts[index].Contracts, Contract{Cycle:cycle, Amount:0})\n }\n //fmt.Println(delegatedContracts[index].Contracts)\n }\n\n delegatedContracts, err = CalculatePercentageSharesForCycle(delegatedContracts, cycle, rate, spillage, delegateAddr)\n if (err != nil){\n return delegatedContracts, errors.New(\"func CalculateAllContractsForCycle(delegatedContracts []DelegatedContract, cycle int, rate float64, spillage bool, delegateAddr string) failed: \" + err.Error())\n }\n return delegatedContracts, nil\n}", "func (k Keeper) DelegateCoinsFromAccountToModule(\n\tctx sdk.Context, recipientModule string, amt Coins,\n) error {\n\trecipientAcc := k.GetModuleAccount(ctx, recipientModule)\n\tif recipientAcc == nil {\n\t\tpanic(sdkerrors.Wrapf(sdkerrors.ErrUnknownAddress, \"module account %s does not exist\", recipientModule))\n\t}\n\n\tif !recipientAcc.HasPermission(types.Staking) {\n\t\tpanic(sdkerrors.Wrapf(sdkerrors.ErrUnauthorized, \"module account %s does not have permissions to receive delegated coins\", recipientModule))\n\t}\n\n\t// Delegate will first send coins to ModuleAccountID\n\tif err := k.bk.CoinsToPower(ctx, stakingTypes.ModuleAccountID, recipientAcc.GetID(), amt); err != nil {\n\t\treturn sdkerrors.Wrapf(err,\n\t\t\t\"DelegateCoinsFromAccountToModule %s by %s\", recipientModule, amt.String())\n\t}\n\n\treturn nil\n}", "func (p *Ledger) RecordPayment(destination types.NodeAddress, amount int64, confirmed chan bool) {\n\tok := <-confirmed\n\tif ok {\n\t\tp.l.Lock()\n\t\tp.incoming_debt[p.id] -= amount\n\t\tp.outgoing_debt[destination] -= amount\n\t\tp.l.Unlock()\n\t}\n}", "func CalculatePayoutForContract(contract Contract, rate float64, delegate bool) Contract{\n ////-------------JUST FOR TESTING -------------////\n totalNodeRewards := 378 //Amount of rewards for my delegation in cycle 11\n ////--------------END TESTING ------------------////\n\n grossRewards := contract.SharePercentage * float64(totalNodeRewards)\n contract.GrossPayout = grossRewards\n fee := rate * grossRewards\n contract.Fee = fee\n var netRewards float64\n if (delegate){\n netRewards = grossRewards\n contract.NetPayout = netRewards\n contract.Fee = 0\n } else {\n netRewards = grossRewards - fee\n contract.NetPayout = contract.NetPayout + netRewards\n }\n\n return contract\n}", "func consolidateDelegations(ctx contract.Context, validator, delegator *types.Address) (*Delegation, []*Delegation, int, error) {\n\t// cycle through all delegations and delete those which are BONDED and\n\t// unlocked while accumulating their amounts\n\tdelegations, err := returnMatchingDelegations(ctx, validator, delegator)\n\tif err != nil {\n\t\treturn nil, nil, -1, err\n\t}\n\n\tunconsolidatedDelegationsCount := 0\n\ttotalDelegationAmount := common.BigZero()\n\tvar consolidatedDelegations []*Delegation\n\tfor _, delegation := range delegations {\n\t\tif delegation.LockTime > uint64(ctx.Now().Unix()) || delegation.State != BONDED {\n\t\t\tunconsolidatedDelegationsCount++\n\t\t\tcontinue\n\t\t}\n\n\t\ttotalDelegationAmount.Add(totalDelegationAmount, &delegation.Amount.Value)\n\t\tconsolidatedDelegations = append(consolidatedDelegations, delegation)\n\n\t\tif err = DeleteDelegation(ctx, delegation); err != nil {\n\t\t\treturn nil, nil, -1, err\n\t\t}\n\t}\n\n\tindex, err := GetNextDelegationIndex(ctx, *validator, *delegator)\n\tif err != nil {\n\t\treturn nil, nil, -1, err\n\t}\n\n\t// create new conolidated delegation\n\tdelegation := &Delegation{\n\t\tValidator: validator,\n\t\tDelegator: delegator,\n\t\tAmount: &types.BigUInt{Value: *totalDelegationAmount},\n\t\tUpdateAmount: loom.BigZeroPB(),\n\t\tLocktimeTier: 0,\n\t\tLockTime: 0,\n\t\tState: BONDED,\n\t\tIndex: index,\n\t}\n\tif err := SetDelegation(ctx, delegation); err != nil {\n\t\treturn nil, nil, -1, err\n\t}\n\treturn delegation, consolidatedDelegations, unconsolidatedDelegationsCount, nil\n}", "func SendPayments() {\n\tif !checkConfigSharingRatio() {\n\t\tlogger.Fatal(\"Unable to calculcate.\")\n\t}\n\n\tpubKey := viper.GetString(\"delegate.pubkey\")\n\tif core.EnvironmentParams.Network.Type == core.DEVNET {\n\t\tpubKey = viper.GetString(\"delegate.Dpubkey\")\n\t}\n\n\tparams := core.DelegateQueryParams{PublicKey: pubKey}\n\tvar payload core.TransactionPayload\n\n\tvotersEarnings := arkclient.CalculateVotersProfit(params, viper.GetFloat64(\"voters.shareratio\"))\n\n\tsumEarned := 0.0\n\tsumRatio := 0.0\n\tsumShareEarned := 0.0\n\n\tp1, p2 := \"\", \"\"\n\tif _, err := os.Stat(\"/path/to/whatever\"); err == nil {\n\t\t// path/to/whatever exists\n\t} else {\n\t\tp1, p2 = readAccountData()\n\t}\n\n\tclearScreen()\n\n\tfor _, element := range votersEarnings {\n\t\tsumEarned += element.EarnedAmount100\n\t\tsumShareEarned += element.EarnedAmountXX\n\t\tsumRatio += element.VoteWeightShare\n\n\t\t//transaction parameters\n\t\ttxAmount2Send := int64(element.EarnedAmountXX*core.SATOSHI) - core.EnvironmentParams.Fees.Send\n\t\ttx := core.CreateTransaction(element.Address, txAmount2Send, viper.GetString(\"voters.txdescription\"), p1, p2)\n\n\t\tpayload.Transactions = append(payload.Transactions, tx)\n\t}\n\n\t//Cost & reserve fund calculation\n\tcostAmount := sumEarned * viper.GetFloat64(\"costs.shareratio\")\n\treserveAmount := sumEarned * viper.GetFloat64(\"reserve.shareratio\")\n\n\t//summary and conversion checks\n\tif (costAmount + reserveAmount + sumShareEarned) != sumEarned {\n\t\tcolor.Set(color.FgHiRed)\n\t\tlog.Println(\"Calculation of ratios NOT OK - overall summary failing\")\n\t\tlogger.Println(\"Calculation of ratios NOT OK - overall summary failing\")\n\t}\n\n\tcostAmount2Send := int64(costAmount*core.SATOSHI) - core.EnvironmentParams.Fees.Send\n\tcostAddress := viper.GetString(\"costs.address\")\n\tif core.EnvironmentParams.Network.Type == core.DEVNET {\n\t\tcostAddress = viper.GetString(\"costs.Daddress\")\n\t}\n\ttxCosts := core.CreateTransaction(costAddress, costAmount2Send, viper.GetString(\"costs.txdescription\"), p1, p2)\n\tpayload.Transactions = append(payload.Transactions, txCosts)\n\n\treserveAddress := viper.GetString(\"reserve.address\")\n\tif core.EnvironmentParams.Network.Type == core.DEVNET {\n\t\treserveAddress = viper.GetString(\"reserve.Daddress\")\n\t}\n\treserveAmount2Send := int64(reserveAmount*core.SATOSHI) - core.EnvironmentParams.Fees.Send\n\n\ttxReserve := core.CreateTransaction(reserveAddress, reserveAmount2Send, viper.GetString(\"reserve.txdescription\"), p1, p2)\n\tpayload.Transactions = append(payload.Transactions, txReserve)\n\n\tcolor.Set(color.FgHiGreen)\n\tfmt.Println(\"--------------------------------------------------------------------------------------------------------------\")\n\tfmt.Println(\"Transactions to be sent:\")\n\tfmt.Println(\"--------------------------------------------------------------------------------------------------------------\")\n\tcolor.Set(color.FgHiCyan)\n\tfor _, el := range payload.Transactions {\n\t\ts := fmt.Sprintf(\"|%s|%15d| %-40s|\", el.RecipientID, el.Amount, el.VendorField)\n\t\tfmt.Println(s)\n\t\tlogger.Println(s)\n\t}\n\n\tcolor.Set(color.FgHiYellow)\n\tfmt.Println(\"\")\n\tfmt.Println(\"--------------------------------------------------------------------------------------------------------------\")\n\tfmt.Print(\"Send transactions and complete reward payments [Y/N]: \")\n\n\tc, _ := reader.ReadByte()\n\n\tif c == []byte(\"Y\")[0] || c == []byte(\"y\")[0] {\n\t\tfmt.Println(\"Sending rewards to voters and sharing accounts.............\")\n\n\t\tres, httpresponse, err := arkclient.PostTransaction(payload)\n\t\tif res.Success {\n\t\t\tcolor.Set(color.FgHiGreen)\n\t\t\tlogger.Println(\"Transactions sent with Success,\", httpresponse.Status, res.TransactionIDs)\n\t\t\tlog.Println(\"Transactions sent with Success,\", httpresponse.Status)\n\t\t\tlog.Println(\"Audit log of sent transactions is in file paymentLog.csv!\")\n\t\t\tlog2csv(payload, res.TransactionIDs, votersEarnings)\n\t\t} else {\n\t\t\tcolor.Set(color.FgHiRed)\n\t\t\tlogger.Println(res.Message, res.Error, httpresponse.Status, err.Error())\n\t\t\tfmt.Println()\n\t\t\tfmt.Println(\"Failed\", res.Error)\n\t\t}\n\t\treader.ReadString('\\n')\n\t\tpause()\n\t}\n}", "func (_DelegatableDai *DelegatableDaiCallerSession) BalanceOf(_owner common.Address) (*big.Int, error) {\n\treturn _DelegatableDai.Contract.BalanceOf(&_DelegatableDai.CallOpts, _owner)\n}", "func (_TokensNetwork *TokensNetworkTransactor) UnlockDelegate(opts *bind.TransactOpts, token common.Address, partner common.Address, participant common.Address, transferred_amount *big.Int, expiration *big.Int, amount *big.Int, secret_hash [32]byte, merkle_proof []byte, participant_signature []byte) (*types.Transaction, error) {\n\treturn _TokensNetwork.contract.Transact(opts, \"unlockDelegate\", token, partner, participant, transferred_amount, expiration, amount, secret_hash, merkle_proof, participant_signature)\n}", "func (del Delegation) Amount() (hexutil.Big, error) {\n\t// get the base amount delegated\n\tbase, err := repository.R().DelegationAmountStaked(&del.Address, del.Delegation.ToStakerId)\n\tif err != nil {\n\t\treturn hexutil.Big{}, err\n\t}\n\n\t// get the sum of all pending withdrawals\n\twd, err := del.pendingWithdrawalsValue()\n\tif err != nil {\n\t\treturn hexutil.Big{}, err\n\t}\n\tval := new(big.Int).Add(base, wd)\n\treturn (hexutil.Big)(*val), nil\n}", "func (va *ClawbackVestingAccount) addGrant(ctx sdk.Context, sk StakingKeeper, grantStartTime int64, grantLockupPeriods, grantVestingPeriods []Period, grantCoins sdk.Coins) {\n\t// how much is really delegated?\n\tbondedAmt := sk.GetDelegatorBonded(ctx, va.GetAddress())\n\tunbondingAmt := sk.GetDelegatorUnbonding(ctx, va.GetAddress())\n\tdelegatedAmt := bondedAmt.Add(unbondingAmt)\n\tdelegated := sdk.NewCoins(sdk.NewCoin(sk.BondDenom(ctx), delegatedAmt))\n\n\t// discover what has been slashed\n\toldDelegated := va.DelegatedVesting.Add(va.DelegatedFree...)\n\tslashed := oldDelegated.Sub(coinsMin(oldDelegated, delegated))\n\n\t// rebase the DV + DF by capping slashed at the current unvested amount\n\tunvested := va.OriginalVesting.Sub(va.GetVestedOnly(ctx.BlockTime()))\n\tnewSlashed := coinsMin(slashed, unvested)\n\tnewDelegated := delegated.Add(newSlashed...)\n\n\t// modify schedules for the new grant\n\tnewLockupStart, newLockupEnd, newLockupPeriods := DisjunctPeriods(va.StartTime, grantStartTime, va.LockupPeriods, grantLockupPeriods)\n\tnewVestingStart, newVestingEnd, newVestingPeriods := DisjunctPeriods(va.StartTime, grantStartTime,\n\t\tva.GetVestingPeriods(), grantVestingPeriods)\n\tif newLockupStart != newVestingStart {\n\t\tpanic(\"bad start time calculation\")\n\t}\n\tva.StartTime = newLockupStart\n\tva.EndTime = max64(newLockupEnd, newVestingEnd)\n\tva.LockupPeriods = newLockupPeriods\n\tva.VestingPeriods = newVestingPeriods\n\tva.OriginalVesting = va.OriginalVesting.Add(grantCoins...)\n\n\t// cap DV at the current unvested amount, DF rounds out to newDelegated\n\tunvested2 := va.GetVestingCoins(ctx.BlockTime())\n\tva.DelegatedVesting = coinsMin(newDelegated, unvested2)\n\tva.DelegatedFree = newDelegated.Sub(va.DelegatedVesting)\n}", "func CalculateRollSpillage(delegatedContracts []DelegatedContract, delegateAddr string, cycle int) ([]DelegatedContract, error) {\n stakingBalance, err := GetDelegateStakingBalance(delegateAddr, cycle)\n if (err != nil){\n return delegatedContracts, errors.New(\"func CalculateRollSpillage(delegatedContracts []DelegatedContract, delegateAddr string) failed: \" + err.Error())\n }\n\n mod := math.Mod(stakingBalance, 10000)\n sum := mod * 10000\n\n for index, delegatedContract := range delegatedContracts{\n for i, contract := range delegatedContract.Contracts{\n if (contract.Cycle == cycle){\n stakingBalance = stakingBalance - contract.Amount\n if (stakingBalance < 0){\n delegatedContracts[index].Contracts[i].SharePercentage = (contract.Amount - stakingBalance) / sum\n }\n }\n }\n }\n\n return delegatedContracts, nil\n}", "func CheckPercentageSumForCycle(cycle int, delegatedContracts []DelegatedContract) float64{\n var sum float64\n sum = 0\n for x := 0; x < len(delegatedContracts); x++{\n counter := 0\n for y := 0; y < len(delegatedContracts[x].Contracts); y++{\n if (delegatedContracts[x].Contracts[y].Cycle == cycle){\n break\n }\n counter = counter + 1\n }\n\n sum = sum + delegatedContracts[x].Contracts[counter].SharePercentage\n }\n return sum\n}", "func (bva BaseVestingAccount) GetDelegatedVesting() sdk.Coins {\n\treturn bva.DelegatedVesting\n}", "func trackMockBalances(bankKeeper *govtestutil.MockBankKeeper, distributionKeeper *govtestutil.MockDistributionKeeper) {\n\tbalances := make(map[string]sdk.Coins)\n\tbalances[distAcct.String()] = sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, math.NewInt(0)))\n\n\t// We don't track module account balances.\n\tbankKeeper.EXPECT().MintCoins(gomock.Any(), mintModuleName, gomock.Any()).AnyTimes()\n\tbankKeeper.EXPECT().BurnCoins(gomock.Any(), types.ModuleName, gomock.Any()).AnyTimes()\n\tbankKeeper.EXPECT().SendCoinsFromModuleToModule(gomock.Any(), mintModuleName, types.ModuleName, gomock.Any()).AnyTimes()\n\n\t// But we do track normal account balances.\n\tbankKeeper.EXPECT().SendCoinsFromAccountToModule(gomock.Any(), gomock.Any(), types.ModuleName, gomock.Any()).DoAndReturn(func(_ sdk.Context, sender sdk.AccAddress, _ string, coins sdk.Coins) error {\n\t\tnewBalance, negative := balances[sender.String()].SafeSub(coins...)\n\t\tif negative {\n\t\t\treturn fmt.Errorf(\"not enough balance\")\n\t\t}\n\t\tbalances[sender.String()] = newBalance\n\t\treturn nil\n\t}).AnyTimes()\n\tbankKeeper.EXPECT().SendCoinsFromModuleToAccount(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn(func(_ sdk.Context, module string, rcpt sdk.AccAddress, coins sdk.Coins) error {\n\t\tbalances[rcpt.String()] = balances[rcpt.String()].Add(coins...)\n\t\treturn nil\n\t}).AnyTimes()\n\tbankKeeper.EXPECT().GetAllBalances(gomock.Any(), gomock.Any()).DoAndReturn(func(_ sdk.Context, addr sdk.AccAddress) sdk.Coins {\n\t\treturn balances[addr.String()]\n\t}).AnyTimes()\n\tbankKeeper.EXPECT().GetBalance(gomock.Any(), gomock.Any(), sdk.DefaultBondDenom).DoAndReturn(func(_ sdk.Context, addr sdk.AccAddress, _ string) sdk.Coin {\n\t\tbalances := balances[addr.String()]\n\t\tfor _, balance := range balances {\n\t\t\tif balance.Denom == sdk.DefaultBondDenom {\n\t\t\t\treturn balance\n\t\t\t}\n\t\t}\n\t\treturn sdk.NewCoin(sdk.DefaultBondDenom, math.NewInt(0))\n\t}).AnyTimes()\n\n\tdistributionKeeper.EXPECT().FundCommunityPool(gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn(func(_ sdk.Context, coins sdk.Coins, sender sdk.AccAddress) error {\n\t\t// sender balance\n\t\tnewBalance, negative := balances[sender.String()].SafeSub(coins...)\n\t\tif negative {\n\t\t\treturn fmt.Errorf(\"not enough balance\")\n\t\t}\n\t\tbalances[sender.String()] = newBalance\n\t\t// receiver balance\n\t\tbalances[distAcct.String()] = balances[distAcct.String()].Add(coins...)\n\t\treturn nil\n\t}).AnyTimes()\n}", "func (tracker *PeerTracker) Track(ci *types.ChainInfo) {\n\ttracker.mu.Lock()\n\tdefer tracker.mu.Unlock()\n\n\t_, tracking := tracker.peers[ci.Peer]\n\t_, trusted := tracker.trusted[ci.Peer]\n\ttracker.peers[ci.Peer] = ci\n\tlogPeerTracker.Infof(\"Tracking %s, new=%t, count=%d trusted=%t\", ci, !tracking, len(tracker.peers), trusted)\n}", "func (this *MThrottle) Account(amount int64) {\n\tatomic.AddInt64(&this.used, amount)\n}", "func (_DelegatableDai *DelegatableDaiSession) BalanceOf(_owner common.Address) (*big.Int, error) {\n\treturn _DelegatableDai.Contract.BalanceOf(&_DelegatableDai.CallOpts, _owner)\n}", "func (_TokensNetwork *TokensNetworkSession) UnlockDelegate(token common.Address, partner common.Address, participant common.Address, transferred_amount *big.Int, expiration *big.Int, amount *big.Int, secret_hash [32]byte, merkle_proof []byte, participant_signature []byte) (*types.Transaction, error) {\n\treturn _TokensNetwork.Contract.UnlockDelegate(&_TokensNetwork.TransactOpts, token, partner, participant, transferred_amount, expiration, amount, secret_hash, merkle_proof, participant_signature)\n}", "func (acc *Account) delegationsTotal() (amount *big.Int, inWithdraw *big.Int, rewards *big.Int, err error) {\n\t// pull all the delegations of the account\n\tlist, err := repository.R().DelegationsByAddressAll(&acc.Address)\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\n\t// prep containers for calculation and loop all delegations found\n\tamount = new(big.Int)\n\trewards = new(big.Int)\n\tinWithdraw = new(big.Int)\n\tfor _, dlg := range list {\n\t\t// any active delegated amount?\n\t\tif 0 < dlg.AmountDelegated.ToInt().Uint64() {\n\t\t\tamount = new(big.Int).Add(amount, dlg.AmountDelegated.ToInt())\n\t\t}\n\n\t\t// get pending rewards for this delegation (can be stashed)\n\t\trw, err := repository.R().PendingRewards(&acc.Address, dlg.ToStakerId)\n\t\tif err != nil {\n\t\t\treturn nil, nil, nil, err\n\t\t}\n\n\t\t// any rewards?\n\t\tif 0 < rw.Amount.ToInt().Uint64() {\n\t\t\trewards = new(big.Int).Add(rewards, rw.Amount.ToInt())\n\t\t}\n\n\t\t// get pending withdrawals\n\t\twd, err := repository.R().WithdrawRequestsPendingTotal(&acc.Address, dlg.ToStakerId)\n\t\tif err != nil {\n\t\t\treturn nil, nil, nil, err\n\t\t}\n\n\t\t// add pending withdrawals value\n\t\tif 0 < wd.Uint64() {\n\t\t\tinWithdraw = new(big.Int).Add(inWithdraw, wd)\n\t\t}\n\t}\n\n\treturn amount, rewards, inWithdraw, nil\n}", "func (_TokensNetwork *TokensNetworkTransactorSession) UnlockDelegate(token common.Address, partner common.Address, participant common.Address, transferred_amount *big.Int, expiration *big.Int, amount *big.Int, secret_hash [32]byte, merkle_proof []byte, participant_signature []byte) (*types.Transaction, error) {\n\treturn _TokensNetwork.Contract.UnlockDelegate(&_TokensNetwork.TransactOpts, token, partner, participant, transferred_amount, expiration, amount, secret_hash, merkle_proof, participant_signature)\n}", "func (k msgServer) CancelUnbondingDelegation(goCtx context.Context, msg *types.MsgCancelUnbondingDelegation) (*types.MsgCancelUnbondingDelegationResponse, error) {\n\tctx := sdk.UnwrapSDKContext(goCtx)\n\n\tvalAddr, err := sdk.ValAddressFromBech32(msg.ValidatorAddress)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdelegatorAddress, err := sdk.AccAddressFromBech32(msg.DelegatorAddress)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbondDenom := k.BondDenom(ctx)\n\tif msg.Amount.Denom != bondDenom {\n\t\treturn nil, sdkerrors.Wrapf(\n\t\t\tsdkerrors.ErrInvalidRequest, \"invalid coin denomination: got %s, expected %s\", msg.Amount.Denom, bondDenom,\n\t\t)\n\t}\n\n\tvalidator, found := k.GetValidator(ctx, valAddr)\n\tif !found {\n\t\treturn nil, types.ErrNoValidatorFound\n\t}\n\n\t// In some situations, the exchange rate becomes invalid, e.g. if\n\t// Validator loses all tokens due to slashing. In this case,\n\t// make all future delegations invalid.\n\tif validator.InvalidExRate() {\n\t\treturn nil, types.ErrDelegatorShareExRateInvalid\n\t}\n\n\tif validator.IsJailed() {\n\t\treturn nil, types.ErrValidatorJailed\n\t}\n\n\tubd, found := k.GetUnbondingDelegation(ctx, delegatorAddress, valAddr)\n\tif !found {\n\t\treturn nil, status.Errorf(\n\t\t\tcodes.NotFound,\n\t\t\t\"unbonding delegation with delegator %s not found for validator %s\",\n\t\t\tmsg.DelegatorAddress, msg.ValidatorAddress,\n\t\t)\n\t}\n\n\t// if this undelegation was from a liquid staking provider (identified if the delegator\n\t// is an ICA account), the global and validator liquid totals should be incremented\n\ttokens := msg.Amount.Amount\n\tshares, err := validator.SharesFromTokens(tokens)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif k.DelegatorIsLiquidStaker(delegatorAddress) {\n\t\tif err := k.SafelyIncreaseTotalLiquidStakedTokens(ctx, tokens, false); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif err := k.SafelyIncreaseValidatorLiquidShares(ctx, &validator, shares); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tvar (\n\t\tunbondEntry types.UnbondingDelegationEntry\n\t\tunbondEntryIndex int64 = -1\n\t)\n\n\tfor i, entry := range ubd.Entries {\n\t\tif entry.CreationHeight == msg.CreationHeight {\n\t\t\tunbondEntry = entry\n\t\t\tunbondEntryIndex = int64(i)\n\t\t\tbreak\n\t\t}\n\t}\n\tif unbondEntryIndex == -1 {\n\t\treturn nil, sdkerrors.ErrNotFound.Wrapf(\"unbonding delegation entry is not found at block height %d\", msg.CreationHeight)\n\t}\n\n\tif unbondEntry.Balance.LT(msg.Amount.Amount) {\n\t\treturn nil, sdkerrors.ErrInvalidRequest.Wrap(\"amount is greater than the unbonding delegation entry balance\")\n\t}\n\n\tif unbondEntry.CompletionTime.Before(ctx.BlockTime()) {\n\t\treturn nil, sdkerrors.ErrInvalidRequest.Wrap(\"unbonding delegation is already processed\")\n\t}\n\n\t// delegate back the unbonding delegation amount to the validator\n\t_, err = k.Keeper.Delegate(ctx, delegatorAddress, msg.Amount.Amount, types.Unbonding, validator, false)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tamount := unbondEntry.Balance.Sub(msg.Amount.Amount)\n\tif amount.IsZero() {\n\t\tubd.RemoveEntry(unbondEntryIndex)\n\t} else {\n\t\t// update the unbondingDelegationEntryBalance and InitialBalance for ubd entry\n\t\tunbondEntry.Balance = amount\n\t\tunbondEntry.InitialBalance = unbondEntry.InitialBalance.Sub(msg.Amount.Amount)\n\t\tubd.Entries[unbondEntryIndex] = unbondEntry\n\t}\n\n\t// set the unbonding delegation or remove it if there are no more entries\n\tif len(ubd.Entries) == 0 {\n\t\tk.RemoveUnbondingDelegation(ctx, ubd)\n\t} else {\n\t\tk.SetUnbondingDelegation(ctx, ubd)\n\t}\n\n\tctx.EventManager().EmitEvent(\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeCancelUnbondingDelegation,\n\t\t\tsdk.NewAttribute(sdk.AttributeKeyAmount, msg.Amount.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyValidator, msg.ValidatorAddress),\n\t\t\tsdk.NewAttribute(types.AttributeKeyDelegator, msg.DelegatorAddress),\n\t\t\tsdk.NewAttribute(types.AttributeKeyCreationHeight, strconv.FormatInt(msg.CreationHeight, 10)),\n\t\t),\n\t)\n\n\treturn &types.MsgCancelUnbondingDelegationResponse{}, nil\n}", "func (del Delegation) AmountDelegated() hexutil.Big {\n\tif del.Delegation.AmountDelegated == nil {\n\t\treturn hexutil.Big{}\n\t}\n\treturn *del.Delegation.AmountDelegated\n}", "func (am *AccountManager) Track() {\n\tfor _, a := range am.AllAccounts() {\n\t\ta.Track()\n\t}\n}", "func Transfer(previousTxId merkle.Digest, transferTxId merkle.Digest, transferBlockNumber uint64, currentOwner *account.Account, newOwner *account.Account) {\n\n\t// ensure single threaded\n\ttoLock.Lock()\n\tdefer toLock.Unlock()\n\n\t// get count for current owner record\n\tdKey := append(currentOwner.Bytes(), previousTxId[:]...)\n\tdCount := storage.Pool.OwnerDigest.Get(dKey)\n\tif nil == dCount {\n\t\tlogger.Criticalf(\"ownership.Transfer: dKey: %x\", dKey)\n\t\tlogger.Criticalf(\"ownership.Transfer: block number: %d\", transferBlockNumber)\n\t\tlogger.Criticalf(\"ownership.Transfer: previous tx id: %#v\", previousTxId)\n\t\tlogger.Criticalf(\"ownership.Transfer: transfer tx id: %#v\", transferTxId)\n\t\tlogger.Criticalf(\"ownership.Transfer: current owner: %x %v\", currentOwner.Bytes(), currentOwner)\n\t\tif nil != newOwner {\n\t\t\tlogger.Criticalf(\"ownership.Transfer: new owner: %x %v\", newOwner.Bytes(), newOwner)\n\t\t}\n\n\t\t// ow, err := ListBitmarksFor(currentOwner, 0, 999)\n\t\t// if nil != err {\n\t\t// \tlogger.Criticalf(\"lbf: error: %s\", err)\n\t\t// } else {\n\t\t// \tlogger.Criticalf(\"lbf: %#v\", ow)\n\t\t// }\n\n\t\tlogger.Panic(\"ownership.Transfer: OwnerDigest database corrupt\")\n\t}\n\n\t// delete the current owners records\n\toKey := append(currentOwner.Bytes(), dCount...)\n\townerData := storage.Pool.Ownership.Get(oKey)\n\tif nil == ownerData {\n\t\tlogger.Criticalf(\"ownership.Transfer: no ownerData for key: %x\", oKey)\n\t\tlogger.Panic(\"ownership.Transfer: Ownership database corrupt\")\n\t}\n\tstorage.Pool.Ownership.Delete(oKey)\n\tstorage.Pool.OwnerDigest.Delete(dKey)\n\n\t// if no new owner only above delete was needed\n\tif nil == newOwner {\n\t\treturn\n\t}\n\n\tcopy(ownerData[TxIdStart:TxIdFinish], transferTxId[:])\n\tbinary.BigEndian.PutUint64(ownerData[TransferBlockNumberStart:TransferBlockNumberFinish], transferBlockNumber)\n\tcreate(transferTxId, ownerData, newOwner)\n}", "func (theAccount *Account) Deposit(amount int) {\n\ttheAccount.balance += amount\n}", "func (account *Account) Deposit(amount int) {\r\n\taccount.balance += amount\r\n}", "func CalculateTotalPayout(delegatedContract DelegatedContract) DelegatedContract{\n for _, contract := range delegatedContract.Contracts{\n delegatedContract.TotalPayout = delegatedContract.TotalPayout + contract.NetPayout\n }\n return delegatedContract\n}", "func (a *Account) Deposit(amount int) {\n\ta.Balance += amount\n}", "func transfer(\n\ttrx storage.Transaction,\n\tpreviousTxId merkle.Digest,\n\ttransferTxId merkle.Digest,\n\ttransferBlockNumber uint64,\n\n\tcurrentOwner *account.Account,\n\tnewOwner *account.Account,\n\tquantity uint64,\n) {\n\t// get count for current owner record\n\tdKey := append(currentOwner.Bytes(), previousTxId[:]...)\n\tdCount := trx.Get(storage.Pool.OwnerTxIndex, dKey)\n\tif nil == dCount {\n\t\tlogger.Criticalf(\"ownership.Transfer: dKey: %x\", dKey)\n\t\tlogger.Criticalf(\"ownership.Transfer: block number: %d\", transferBlockNumber)\n\t\tlogger.Criticalf(\"ownership.Transfer: previous tx id: %#v\", previousTxId)\n\t\tlogger.Criticalf(\"ownership.Transfer: transfer tx id: %#v\", transferTxId)\n\t\tlogger.Criticalf(\"ownership.Transfer: current owner: %x %v\", currentOwner.Bytes(), currentOwner)\n\t\tif nil != newOwner {\n\t\t\tlogger.Criticalf(\"ownership.Transfer: new owner: %x %v\", newOwner.Bytes(), newOwner)\n\t\t}\n\n\t\t// ow, err := listBitmarksFor(currentOwner, 0, 999)\n\t\t// if nil != err {\n\t\t// \tlogger.Criticalf(\"lbf: error: %s\", err)\n\t\t// } else {\n\t\t// \tlogger.Criticalf(\"lbf: %#v\", ow)\n\t\t// }\n\n\t\tlogger.Panic(\"ownership.Transfer: OwnerTxIndex database corrupt\")\n\t}\n\n\t// delete the current owners records\n\townerData, err := GetOwnerData(trx, previousTxId, storage.Pool.OwnerData)\n\tif nil != err {\n\t\tlogger.Criticalf(\"ownership.Transfer: invalid owner data for tx id: %s error: %s\", previousTxId, err)\n\t\tlogger.Panic(\"ownership.Transfer: Ownership database corrupt\")\n\t}\n\n\toKey := append(currentOwner.Bytes(), dCount...)\n\ttrx.Delete(storage.Pool.OwnerList, oKey)\n\ttrx.Delete(storage.Pool.OwnerTxIndex, dKey)\n\n\t// and the old owner data\n\ttrx.Delete(storage.Pool.OwnerData, previousTxId[:])\n\n\t// if no new owner only above delete was needed\n\tif nil == newOwner && 0 == quantity {\n\t\treturn\n\t}\n\n\tswitch ownerData := ownerData.(type) {\n\n\tcase *AssetOwnerData:\n\n\t\t// create a share - only from an asset\n\t\tif 0 != quantity {\n\n\t\t\t// convert initial quantity to 8 byte big endian\n\t\t\tquantityBytes := make([]byte, 8)\n\t\t\tbinary.BigEndian.PutUint64(quantityBytes, quantity)\n\n\t\t\t// the ID of the share is the issue id of the bitmark\n\t\t\tshareId := ownerData.issueTxId\n\n\t\t\t// the total quantity of this type of share\n\t\t\tshareData := append(quantityBytes, transferTxId[:]...)\n\t\t\ttrx.Put(storage.Pool.Shares, shareId[:], shareData, []byte{})\n\n\t\t\t// initially total quantity goes to the creator\n\t\t\tfKey := append(currentOwner.Bytes(), shareId[:]...)\n\t\t\ttrx.Put(storage.Pool.ShareQuantity, fKey, quantityBytes, []byte{})\n\n\t\t\t// convert to share and update\n\t\t\tnewOwnerData := ShareOwnerData{\n\t\t\t\ttransferBlockNumber: transferBlockNumber,\n\t\t\t\tissueTxId: ownerData.issueTxId,\n\t\t\t\tissueBlockNumber: ownerData.issueBlockNumber,\n\t\t\t\tassetId: ownerData.assetId,\n\t\t\t}\n\t\t\tcreate(trx, transferTxId, newOwnerData, currentOwner)\n\t\t\treturn\n\t\t}\n\n\t\t// otherwise create new ownership record\n\t\townerData.transferBlockNumber = transferBlockNumber\n\t\tcreate(trx, transferTxId, ownerData, newOwner)\n\n\tcase *BlockOwnerData:\n\t\t// create a share - only from an asset\n\t\tif 0 != quantity {\n\n\t\t\t// panic if not an asset (this should have been checked earlier)\n\t\t\tlogger.Criticalf(\"ownership.Transfer: ownerData for key: %x is not an asset\", oKey)\n\t\t\tlogger.Panic(\"ownership.Transfer: Ownership database corrupt\")\n\t\t}\n\n\t\t// otherwise create new ownership record\n\t\townerData.transferBlockNumber = transferBlockNumber\n\t\tcreate(trx, transferTxId, ownerData, newOwner)\n\n\tcase *ShareOwnerData:\n\n\t\t// create a share - only from an asset\n\t\tif 0 != quantity {\n\n\t\t\t// panic if not an asset (this should have been checked earlier)\n\t\t\tlogger.Criticalf(\"ownership.Transfer: ownerData for key: %x is not an asset\", oKey)\n\t\t\tlogger.Panic(\"ownership.Transfer: Ownership database corrupt\")\n\t\t}\n\n\t\t// Note: only called on delete (block/store.go prevents share back to asset)\n\n\t\t// convert to transfer and update\n\t\tnewOwnerData := AssetOwnerData{\n\t\t\ttransferBlockNumber: transferBlockNumber,\n\t\t\tissueTxId: ownerData.issueTxId,\n\t\t\tissueBlockNumber: ownerData.issueBlockNumber,\n\t\t\tassetId: ownerData.assetId,\n\t\t}\n\t\tcreate(trx, transferTxId, newOwnerData, currentOwner)\n\n\tdefault:\n\t\t// panic if not an asset (this should have been checked earlier)\n\t\tlogger.Criticalf(\"ownership.Transfer: unhandled owner data type: %+v\", ownerData)\n\t\tlogger.Panic(\"ownership.Transfer: missing owner data handler\")\n\t}\n}", "func (url *Url) TrackVisit(r *http.Request) {\n\tswitch acct := url.Owner.AcctID; {\n\tcase acct >= ACCTTYPE_PAID:\n\t\tvis := extractVisit(r)\n\t\tvis.InsertVisit()\n\tcase acct >= ACCTTYPE_FREE:\n\t\tIncrementVisits(url.Path)\n\t}\n}", "func (a *Account) Deposit (amount int) {\n\ta.balance += amount\n}", "func (_OwnerProxyRegistry *OwnerProxyRegistryCaller) CountDelegates(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _OwnerProxyRegistry.contract.Call(opts, &out, \"countDelegates\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (a *Account) Deposit(amount int) {\n\ta.balance += amount\n}", "func (t *SimpleChaincode) register_track(stub *shim.ChaincodeStub, args []string) ([]byte, error) {\n\n\t// Args\n\t// 0\t\t1\n\t// trackId\tplayed_by\n\n\t// 1. get track\n\ttrackBytes, err := stub.GetState(args[0])\n\tif err != nil {\n\t\treturn nil, errors.New(\"Could not fetch track \" + args[0])\n\t}\n\t// 1b. Unmarshal track\n\tvar tr Track\n\terr = json.Unmarshal(trackBytes, &tr)\n\tif err != nil {\n\t\treturn nil, errors.New(\"Could not unmarshal track \" )\n\t}\n\n\t// 2. get played by account\n\tplayedByBytes, err := stub.GetState(args[1])\n\tif err != nil {\n\t\treturn nil, errors.New(\"Could not fetch track \")\n\t}\n\t// 2b. unmarshal account\n\tvar account_sender Account\n\terr = json.Unmarshal(playedByBytes, &account_sender)\n\tif err != nil {\n\t\treturn nil, errors.New(\"Could not unmarshal account \" )\n\t}\n\n\t// Create array for payments by sender\n\tvar senderPayments []Payment\n\n\t// 3. loop through beneficiaries of track\n\tfor _, beneficiary := range tr.Beneficiaries {\n\n\t\t// 4. add a PendingPayment to their account\n\n\t\t// 4a. get beneficiary account\n\t\tbytes, err := stub.GetState(beneficiary.AccountId)\n\t\tif err != nil {\n\t\t\treturn nil, errors.New(\"Unable to get thing with ID \" )\n\t\t}\n\t\t// 4b. unmarshal account\n\t\tvar account_recipient Account\n\t\tjson.Unmarshal(bytes, &account_recipient)\n\n\t\t// 4c. calculate amount\n\t\tvar amount int64\n\t\tamount = (beneficiary.Percentage / 100 ) * tr.Price\n\n\t\t// 4d. create PendingPayment\n\t\tvar pendingPayment Payment\n\t\tpendingPayment.Amount \t\t= amount\n\t\tpendingPayment.Completed \t= false\n\t\tpendingPayment.RecipientId \t= account_recipient.Id\n\t\tpendingPayment.SenderId \t= account_sender.Id\n\n\t\t// 4e. append PendingPayment to recipient\n\t\taccount_recipient.PendingPayments = append(account_recipient.PendingPayments, pendingPayment)\n\n\t\t// 4f. push pendingpayment to senderpayments\n\t\tsenderPayments = append(senderPayments, pendingPayment)\n\n\t\t// 4g. Put beneficiary back in state\n\t\taccReciptientBytes, _ := json.Marshal(account_recipient)\n\t\terr = stub.PutState(account_recipient.Id, accReciptientBytes)\n\n\t\t// 4h. Append payment to payment index\n\n\n\t}\n\n\t// 5. append senderPayments to sender account\n\tfor _, payment := range senderPayments {\n\t\taccount_sender.PendingPayments = append(account_sender.PendingPayments, payment)\n\t}\n\treturn nil, nil\n}", "func (_DelegationController *DelegationControllerTransactor) GetAndUpdateDelegatedAmount(opts *bind.TransactOpts, holder common.Address) (*types.Transaction, error) {\n\treturn _DelegationController.contract.Transact(opts, \"getAndUpdateDelegatedAmount\", holder)\n}", "func PayoutDelegatedContracts(delegatedContracts []DelegatedContract, alias string) error{\n for _, delegatedContract := range delegatedContracts {\n err := SendTezos(delegatedContract.TotalPayout, delegatedContract.Address, alias)\n if (err != nil){\n return errors.New(\"Could not Payout Delegated Contracts: SendTezos(amount float64, toAddress string, alias string) failed: \" + err.Error())\n }\n }\n return nil\n}", "func (_Bep20 *Bep20Transactor) DelegateBySig(opts *bind.TransactOpts, delegatee common.Address, nonce *big.Int, expiry *big.Int, v uint8, r [32]byte, s [32]byte) (*types.Transaction, error) {\n\treturn _Bep20.contract.Transact(opts, \"delegateBySig\", delegatee, nonce, expiry, v, r, s)\n}", "func (k Keeper) BurnDerivative(ctx sdk.Context, delegatorAddr sdk.AccAddress, valAddr sdk.ValAddress, amount sdk.Coin) (sdk.Dec, error) {\n\n\tif amount.Denom != k.GetLiquidStakingTokenDenom(valAddr) {\n\t\treturn sdk.Dec{}, errorsmod.Wrap(types.ErrInvalidDenom, \"derivative denom does not match validator\")\n\t}\n\n\tif err := k.burnCoins(ctx, delegatorAddr, sdk.NewCoins(amount)); err != nil {\n\t\treturn sdk.Dec{}, err\n\t}\n\n\tmodAcc := k.accountKeeper.GetModuleAccount(ctx, types.ModuleAccountName)\n\tshares := sdk.NewDecFromInt(amount.Amount)\n\treceivedShares, err := k.TransferDelegation(ctx, valAddr, modAcc.GetAddress(), delegatorAddr, shares)\n\tif err != nil {\n\t\treturn sdk.Dec{}, err\n\t}\n\n\tctx.EventManager().EmitEvent(\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeBurnDerivative,\n\t\t\tsdk.NewAttribute(types.AttributeKeyDelegator, delegatorAddr.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyValidator, valAddr.String()),\n\t\t\tsdk.NewAttribute(sdk.AttributeKeyAmount, amount.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeySharesTransferred, shares.String()),\n\t\t),\n\t)\n\treturn receivedShares, nil\n}", "func (_TransferProxyRegistry *TransferProxyRegistryCaller) CountDelegates(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _TransferProxyRegistry.contract.Call(opts, &out, \"countDelegates\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (n *Node) BecomeDelegator(genesisAmount uint64, seedAmount uint64, delegatorAmount uint64, txFee uint64, stakerNodeID string) *Node {\n\n\t// exports AVAX from the X Chain\n\texportTxID, err := n.client.XChainAPI().ExportAVAX(\n\t\tn.UserPass,\n\t\tnil, // from addrs\n\t\t\"\", // change addr\n\t\tseedAmount+txFee,\n\t\tn.PAddress,\n\t)\n\tif err != nil {\n\t\tpanic(stacktrace.Propagate(err, \"Failed to export AVAX to pchainAddress %s\", n.PAddress))\n\t\treturn n\n\t}\n\n\t// waits Tx acceptance in the XChain\n\terr = chainhelper.XChain().AwaitTransactionAcceptance(n.client, exportTxID, constants.TimeoutDuration)\n\tif err != nil {\n\t\tpanic(err)\n\t\treturn n\n\t}\n\n\t// imports the amount to the P Chain\n\timportTxID, err := n.client.PChainAPI().ImportAVAX(\n\t\tn.UserPass,\n\t\tnil, // from addrs\n\t\t\"\", // change addr\n\t\tn.PAddress,\n\t\tconstants.XChainID.String(),\n\t)\n\tif err != nil {\n\t\tpanic(stacktrace.Propagate(err, \"Failed import AVAX to pchainAddress %s\", n.PAddress))\n\t\treturn n\n\t}\n\n\t// waits Tx acceptance in the PChain\n\terr = chainhelper.PChain().AwaitTransactionAcceptance(n.client, importTxID, constants.TimeoutDuration)\n\tif err != nil {\n\t\tpanic(err)\n\t\treturn n\n\t}\n\n\t// verify the PChain balance (seedAmount+txFee-txFee)\n\terr = chainhelper.PChain().CheckBalance(n.client, n.PAddress, seedAmount)\n\tif err != nil {\n\t\tpanic(stacktrace.Propagate(err, \"expected balance of seedAmount exists in the PChain\"))\n\t\treturn n\n\t}\n\n\t// verify the XChain balance of genesisAmount - seedAmount - txFee - txFee (import PChain)\n\terr = chainhelper.XChain().CheckBalance(n.client, n.XAddress, \"AVAX\", genesisAmount-seedAmount-2*txFee)\n\tif err != nil {\n\t\tpanic(stacktrace.Propagate(err, \"expected balance XChain balance of genesisAmount-seedAmount-txFee\"))\n\t\treturn n\n\t}\n\n\tdelegatorStartTime := time.Now().Add(20 * time.Second)\n\tstartTime := uint64(delegatorStartTime.Unix())\n\tendTime := uint64(delegatorStartTime.Add(36 * time.Hour).Unix())\n\taddDelegatorTxID, err := n.client.PChainAPI().AddDelegator(\n\t\tn.UserPass,\n\t\tnil, // from addrs\n\t\t\"\", // change addr\n\t\tn.PAddress,\n\t\tstakerNodeID,\n\t\tdelegatorAmount,\n\t\tstartTime,\n\t\tendTime,\n\t)\n\tif err != nil {\n\t\tpanic(stacktrace.Propagate(err, \"Failed to add delegator %s\", n.PAddress))\n\t\treturn n\n\t}\n\n\terr = chainhelper.PChain().AwaitTransactionAcceptance(n.client, addDelegatorTxID, constants.TimeoutDuration)\n\tif err != nil {\n\t\tpanic(stacktrace.Propagate(err, \"Failed to accept AddDelegator tx: %s\", addDelegatorTxID))\n\t\treturn n\n\t}\n\n\t// Sleep until delegator starts validating\n\ttime.Sleep(time.Until(delegatorStartTime) + 3*time.Second)\n\n\texpectedDelegatorBalance := seedAmount - delegatorAmount\n\terr = chainhelper.PChain().CheckBalance(n.client, n.PAddress, expectedDelegatorBalance)\n\tif err != nil {\n\t\tpanic(stacktrace.Propagate(err, \"Unexpected P Chain Balance after adding a new delegator to the network.\"))\n\t\treturn n\n\t}\n\tlogrus.Infof(\"Added delegator to subnet and verified the expected P Chain balance.\")\n\n\treturn n\n}", "func Transfer(db StateDB, sender, recipient common.Address, amount *big.Int) {\n\tdb.SubBalance(sender, amount)\n\tdb.AddBalance(recipient, amount)\n}", "func (a *Account) Deposit(amount int) {\n\n\ta.balance += amount\n\tfmt.Println(amount, \"원 입금완료 !\")\n}", "func (del Delegation) Amount() (hexutil.Big, error) {\n\t// lazy load data\n\tif del.extendedAmount == nil {\n\t\tvar err error\n\n\t\t// try to load the data\n\t\tdel.extendedAmount, del.extendedAmountInWithdraw, err = del.repo.DelegatedAmountExtended(&del.Delegation)\n\t\tif err != nil {\n\t\t\treturn hexutil.Big{}, err\n\t\t}\n\t}\n\n\treturn (hexutil.Big)(*del.extendedAmount), nil\n}", "func (k Keeper) SyncBorrowInterest(ctx sdk.Context, addr sdk.AccAddress) {\n\ttotalNewInterest := sdk.Coins{}\n\n\t// Update user's borrow interest factor list for each asset in the 'coins' array.\n\t// We use a list of BorrowInterestFactors here because Amino doesn't support marshaling maps.\n\tborrow, found := k.GetBorrow(ctx, addr)\n\tif !found {\n\t\treturn\n\t}\n\tfor _, coin := range borrow.Amount {\n\t\t// Locate the borrow interest factor item by coin denom in the user's list of borrow indexes\n\t\tfoundAtIndex := -1\n\t\tfor i := range borrow.Index {\n\t\t\tif borrow.Index[i].Denom == coin.Denom {\n\t\t\t\tfoundAtIndex = i\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tinterestFactorValue, _ := k.GetBorrowInterestFactor(ctx, coin.Denom)\n\t\tif foundAtIndex == -1 { // First time user has borrowed this denom\n\t\t\tborrow.Index = append(borrow.Index, types.NewBorrowInterestFactor(coin.Denom, interestFactorValue))\n\t\t} else { // User has an existing borrow index for this denom\n\t\t\t// Calculate interest owed by user since asset's last borrow index update\n\t\t\tstoredAmount := sdk.NewDecFromInt(borrow.Amount.AmountOf(coin.Denom))\n\t\t\tuserLastInterestFactor := borrow.Index[foundAtIndex].Value\n\t\t\tinterest := (storedAmount.Quo(userLastInterestFactor).Mul(interestFactorValue)).Sub(storedAmount)\n\t\t\ttotalNewInterest = totalNewInterest.Add(sdk.NewCoin(coin.Denom, interest.TruncateInt()))\n\t\t\t// We're synced up, so update user's borrow index value to match the current global borrow index value\n\t\t\tborrow.Index[foundAtIndex].Value = interestFactorValue\n\t\t}\n\t}\n\t// Add all pending interest to user's borrow\n\tborrow.Amount = borrow.Amount.Add(totalNewInterest...)\n\n\t// Update user's borrow in the store\n\tk.SetBorrow(ctx, borrow)\n}", "func (k Keeper) Delegation(ctx sdk.Context, addrDel sdk.AccAddress, addrVal sdk.ValAddress) exported.DelegationI {\n\treturn nil\n}", "func (k Keeper) Delegation(ctx context.Context, addrDel sdk.AccAddress, addrVal sdk.ValAddress) (types.DelegationI, error) {\n\tbond, err := k.Delegations.Get(ctx, collections.Join(addrDel, addrVal))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn bond, nil\n}", "func TestCallSimDelegate(t *testing.T) {\n\t// Roll up our sleeves and swear fealty to the witch-king\n\tctx, cancel := context.WithCancel(context.Background())\n\tdefer cancel()\n\tg, ctx := errgroup.WithContext(ctx)\n\n\tdb := dbm.NewMemDB()\n\tst, err := state.MakeGenesisState(db, genesisDoc)\n\trequire.NoError(t, err)\n\n\tfrom := crypto.PrivateKeyFromSecret(\"raaah\", crypto.CurveTypeEd25519)\n\tcontractAddress := crypto.Address{1, 2, 3, 4, 5}\n\tblockchain := &bcm.Blockchain{}\n\tsink := exec.NewNoopEventSink()\n\n\t// Function to set storage value for later\n\tsetDelegate := func(up state.Updatable, value crypto.Address) error {\n\t\tcall, _, err := abi.EncodeFunctionCall(string(solidity.Abi_DelegateProxy), \"setDelegate\", logger, value)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tcache := acmstate.NewCache(st)\n\t\t_, err = evm.Default().Execute(cache, blockchain, sink,\n\t\t\tengine.CallParams{\n\t\t\t\tCallType: exec.CallTypeCall,\n\t\t\t\tOrigin: from.GetAddress(),\n\t\t\t\tCaller: from.GetAddress(),\n\t\t\t\tCallee: contractAddress,\n\t\t\t\tInput: call,\n\t\t\t\tGas: big.NewInt(9999999),\n\t\t\t}, solidity.DeployedBytecode_DelegateProxy)\n\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn cache.Sync(up)\n\t}\n\n\t// Initialise sender smart contract state\n\t_, _, err = st.Update(func(up state.Updatable) error {\n\t\terr = up.UpdateAccount(&acm.Account{\n\t\t\tAddress: from.GetAddress(),\n\t\t\tPublicKey: from.GetPublicKey(),\n\t\t\tBalance: 9999999,\n\t\t\tPermissions: permission.DefaultAccountPermissions,\n\t\t})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn up.UpdateAccount(&acm.Account{\n\t\t\tAddress: contractAddress,\n\t\t\tEVMCode: solidity.DeployedBytecode_DelegateProxy,\n\t\t})\n\t})\n\trequire.NoError(t, err)\n\n\t// Set a series of values of storage slot so we get a deep version tree (which we need to trigger the bug)\n\tdelegate := crypto.Address{0xBE, 0xEF, 0, 0xFA, 0xCE, 0, 0xBA, 0}\n\tfor i := 0; i < 0xBF; i++ {\n\t\tdelegate[7] = byte(i)\n\t\t_, _, err = st.Update(func(up state.Updatable) error {\n\t\t\treturn setDelegate(up, delegate)\n\t\t})\n\t\trequire.NoError(t, err)\n\t}\n\n\t// This is important in order to illicit the former bug - we need a cold LRU tree cache in MutableForest\n\tst, err = state.LoadState(db, st.Version())\n\trequire.NoError(t, err)\n\n\tgetIntCall, _, err := abi.EncodeFunctionCall(string(solidity.Abi_DelegateProxy), \"getDelegate\", logger)\n\trequire.NoError(t, err)\n\tn := 1000\n\n\tfor i := 0; i < n; i++ {\n\t\tg.Go(func() error {\n\t\t\ttxe, err := CallSim(st, blockchain, from.GetAddress(), contractAddress, getIntCall, logger)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\terr = txe.GetException().AsError()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\taddress, err := crypto.AddressFromBytes(txe.GetResult().Return[12:])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif address != delegate {\n\t\t\t\t// The bug for which this test was written will return the zero address here since it is accessing\n\t\t\t\t// an uninitialised tree\n\t\t\t\treturn fmt.Errorf(\"getDelegate returned %v but expected %v\", address, delegate)\n\t\t\t}\n\t\t\treturn nil\n\t\t})\n\t}\n\n\trequire.NoError(t, g.Wait())\n}", "func (px *Paxos) send_decided(seq int, v interface{}) {\n\tfor idx, peer := range px.peers {\n\t\targs := &DecdidedArgs{}\n\t\treply := &DecidedReply{}\n\n\t\targs.Seq = seq\n\t\targs.V = v\n\n\t\tif idx == px.me {\n\t\t\tpx.Decided(args, reply)\n\t\t} else {\n\t\t\tcall(peer, \"Paxos.Decided\", args, reply)\n\t\t}\n\t}\n}", "func (w *Wallet) Deposit(amount Bitcoin) {\n\tfmt.Printf(\"address of balance in wallet is %v \\n\", &w.balance) // get the pointer\n\tw.balance += amount\n}", "func (_LvRecording *LvRecordingTransactor) TransferOwnership(opts *bind.TransactOpts, newOwner common.Address) (*types.Transaction, error) {\n\treturn _LvRecording.contract.Transact(opts, \"transferOwnership\", newOwner)\n}", "func (w *Wallet) Deposit(amount Bitcoin) {\n\t// fmt.Printf(\"address of balance in Deposit is %v \\n\", &w.balance)\n\tw.balance += amount\n}", "func (k msgServer) Undelegate(goCtx context.Context, msg *types.MsgUndelegate) (*types.MsgUndelegateResponse, error) {\n\tctx := sdk.UnwrapSDKContext(goCtx)\n\n\taddr, err := sdk.ValAddressFromBech32(msg.ValidatorAddress)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdelegatorAddress, err := sdk.AccAddressFromBech32(msg.DelegatorAddress)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttokens := msg.Amount.Amount\n\tshares, err := k.ValidateUnbondAmount(\n\t\tctx, delegatorAddress, addr, tokens,\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvalidator, found := k.GetValidator(ctx, addr)\n\tif !found {\n\t\treturn nil, types.ErrNoValidatorFound\n\t}\n\n\tdelegation, found := k.GetDelegation(ctx, delegatorAddress, addr)\n\tif !found {\n\t\treturn nil, status.Errorf(\n\t\t\tcodes.NotFound,\n\t\t\t\"delegation with delegator %s not found for validator %s\",\n\t\t\tmsg.DelegatorAddress, msg.ValidatorAddress,\n\t\t)\n\t}\n\n\t// if this is a validator self-bond, the new liquid delegation cannot fall below the self-bond * bond factor\n\tif delegation.ValidatorBond {\n\t\tif err := k.SafelyDecreaseValidatorBond(ctx, &validator, shares); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// if this delegation is from a liquid staking provider (identified if the delegator\n\t// is an ICA account), the global and validator liquid totals should be decremented\n\tif k.DelegatorIsLiquidStaker(delegatorAddress) {\n\t\tif err := k.DecreaseTotalLiquidStakedTokens(ctx, tokens); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif err := k.DecreaseValidatorLiquidShares(ctx, &validator, shares); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tbondDenom := k.BondDenom(ctx)\n\tif msg.Amount.Denom != bondDenom {\n\t\treturn nil, sdkerrors.Wrapf(\n\t\t\tsdkerrors.ErrInvalidRequest, \"invalid coin denomination: got %s, expected %s\", msg.Amount.Denom, bondDenom,\n\t\t)\n\t}\n\n\tcompletionTime, err := k.Keeper.Undelegate(ctx, delegatorAddress, addr, shares)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif tokens.IsInt64() {\n\t\tdefer func() {\n\t\t\ttelemetry.IncrCounter(1, types.ModuleName, \"undelegate\")\n\t\t\ttelemetry.SetGaugeWithLabels(\n\t\t\t\t[]string{\"tx\", \"msg\", msg.Type()},\n\t\t\t\tfloat32(tokens.Int64()),\n\t\t\t\t[]metrics.Label{telemetry.NewLabel(\"denom\", msg.Amount.Denom)},\n\t\t\t)\n\t\t}()\n\t}\n\n\tctx.EventManager().EmitEvents(sdk.Events{\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeUnbond,\n\t\t\tsdk.NewAttribute(types.AttributeKeyValidator, msg.ValidatorAddress),\n\t\t\tsdk.NewAttribute(sdk.AttributeKeyAmount, msg.Amount.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyCompletionTime, completionTime.Format(time.RFC3339)),\n\t\t),\n\t})\n\n\treturn &types.MsgUndelegateResponse{\n\t\tCompletionTime: completionTime,\n\t}, nil\n}", "func (s *ArkClient) GetDelegateVoteWeight(params DelegateQueryParams) (int, *http.Response, error) {\n\trespData := new(DelegateVoters)\n\trespError := new(ArkApiResponseError)\n\tresp, err := s.sling.New().Get(\"api/delegates/voters\").QueryStruct(&params).Receive(respData, respError)\n\tif err == nil {\n\t\terr = respError\n\t}\n\n\t//calculating vote weight\n\tbalance := 0\n\tif respData.Success {\n\t\tfor _, element := range respData.Accounts {\n\t\t\tintBalance, _ := strconv.Atoi(element.Balance)\n\t\t\tbalance += intBalance\n\t\t}\n\t}\n\n\treturn balance, resp, err\n}", "func (o OfflineNotaryRepository) AddDelegationPaths(data.RoleName, []string) error {\n\treturn nil\n}", "func (_DelegatableDai *DelegatableDaiCaller) BalanceOf(opts *bind.CallOpts, _owner common.Address) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _DelegatableDai.contract.Call(opts, out, \"balanceOf\", _owner)\n\treturn *ret0, err\n}", "func (_DelegationController *DelegationControllerSession) GetAndUpdateDelegatedAmount(holder common.Address) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.GetAndUpdateDelegatedAmount(&_DelegationController.TransactOpts, holder)\n}", "func (vi *votedInfo) CalculateReward(multiplier, divider *big.Int, period int) {\n\tif multiplier.Sign() == 0 || period == 0 {\n\t\treturn\n\t}\n\tif divider.Sign() == 0 || vi.totalBondedDelegation.Sign() == 0 {\n\t\treturn\n\t}\n\t// reward = multiplier * period * bondedDelegation / (divider * totalBondedDelegation)\n\tbase := new(big.Int).Mul(multiplier, big.NewInt(int64(period)))\n\treward := new(big.Int)\n\tfor i, addrKey := range vi.rank {\n\t\tif i == vi.maxRankForReward {\n\t\t\tbreak\n\t\t}\n\t\tprep := vi.preps[addrKey]\n\t\tif prep.Enable() == false {\n\t\t\tcontinue\n\t\t}\n\n\t\treward.Mul(base, prep.GetBondedDelegation())\n\t\treward.Div(reward, divider)\n\t\treward.Div(reward, vi.totalBondedDelegation)\n\n\t\tlog.Tracef(\"VOTED REWARD %d = %d * %d * %d / (%d * %d)\",\n\t\t\treward, multiplier, period, prep.GetBondedDelegation(), divider, vi.totalBondedDelegation)\n\n\t\tprep.SetIScore(new(big.Int).Add(prep.IScore(), reward))\n\t}\n}", "func (_OwnerProxyRegistry *OwnerProxyRegistryTransactor) AddDelegate(opts *bind.TransactOpts, from common.Address) (*types.Transaction, error) {\n\treturn _OwnerProxyRegistry.contract.Transact(opts, \"addDelegate\", from)\n}", "func (_DelegationController *DelegationControllerCaller) DelegationsByHolder(opts *bind.CallOpts, arg0 common.Address, arg1 *big.Int) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _DelegationController.contract.Call(opts, out, \"delegationsByHolder\", arg0, arg1)\n\treturn *ret0, err\n}", "func TestDelegatorProxyValidatorConstraints4Steps(t *testing.T) {\n\tcommon.InitConfig()\n\tparams := DefaultParams()\n\n\toriginVaSet := addrVals[1:]\n\tparams.MaxValidators = uint16(len(originVaSet))\n\tparams.Epoch = 2\n\tparams.UnbondingTime = time.Millisecond * 300\n\tstartUpValidator := NewValidator(StartUpValidatorAddr, StartUpValidatorPubkey, Description{}, types.DefaultMinSelfDelegation)\n\tstartUpStatus := baseValidatorStatus{startUpValidator}\n\torgValsLen := len(originVaSet)\n\tfullVaSet := make([]sdk.ValAddress, orgValsLen+1)\n\tcopy(fullVaSet, originVaSet)\n\tcopy(fullVaSet[orgValsLen:], []sdk.ValAddress{startUpStatus.getValidator().GetOperator()})\n\n\tbAction := baseAction{}\n\n\tstep1Actions := IActions{\n\t\tdelegatorRegProxyAction{bAction, ProxiedDelegator, true},\n\t\tdelegatorsAddSharesAction{bAction, false, true, 0, []sdk.AccAddress{ProxiedDelegator}},\n\t\tdelegatorWithdrawAction{bAction, ProxiedDelegator, sdk.OneDec(), sdk.DefaultBondDenom},\n\t\tproxyBindAction{bAction, ProxiedDelegator, ProxiedDelegator},\n\t\tproxyUnBindAction{bAction, ProxiedDelegator},\n\t}\n\n\tstep2Actions := IActions{\n\t\tdelegatorDepositAction{bAction, ValidDelegator1, DelegatedToken1, sdk.DefaultBondDenom},\n\t\tproxyBindAction{bAction, ValidDelegator1, ProxiedDelegator},\n\t\tdelegatorsAddSharesAction{bAction, false, true, 0, []sdk.AccAddress{ValidDelegator1}},\n\t\tproxyUnBindAction{bAction, ValidDelegator1},\n\t\tdelegatorWithdrawAction{bAction, ValidDelegator1, sdk.OneDec(), sdk.DefaultBondDenom},\n\t}\n\n\tstep3Actions := IActions{\n\t\tdelegatorDepositAction{bAction, ValidDelegator1, DelegatedToken1, sdk.DefaultBondDenom},\n\t\tproxyBindAction{bAction, ValidDelegator1, ProxiedDelegator},\n\t\tproxyUnBindAction{bAction, ValidDelegator1},\n\t\tdelegatorWithdrawAction{bAction, ValidDelegator1, sdk.OneDec(), sdk.DefaultBondDenom},\n\t}\n\n\tstep4Actions := IActions{\n\t\tdelegatorRegProxyAction{bAction, ProxiedDelegator, true},\n\t\tdelegatorsAddSharesAction{bAction, false, true, 0, []sdk.AccAddress{ProxiedDelegator}},\n\t\tproxyBindAction{bAction, ProxiedDelegator, ProxiedDelegator},\n\t\tproxyUnBindAction{bAction, ProxiedDelegator},\n\t\tdelegatorWithdrawAction{bAction, ProxiedDelegator, sdk.OneDec(), sdk.DefaultBondDenom},\n\t}\n\n\tfor s1 := 0; s1 < len(step1Actions); s1++ {\n\t\tfor s2 := 0; s2 < len(step2Actions); s2++ {\n\t\t\tfor s3 := 0; s3 < len(step3Actions); s3++ {\n\t\t\t\tfor s4 := 0; s4 < len(step4Actions); s4++ {\n\t\t\t\t\tinputActions := []IAction{\n\t\t\t\t\t\tcreateValidatorAction{bAction, nil},\n\t\t\t\t\t\tdelegatorsAddSharesAction{bAction, false, true, 0, []sdk.AccAddress{ValidDelegator2}},\n\t\t\t\t\t\tdelegatorDepositAction{bAction, ProxiedDelegator, MaxDelegatedToken, sdk.DefaultBondDenom},\n\t\t\t\t\t\tstep1Actions[s1],\n\t\t\t\t\t\tstep2Actions[s2],\n\t\t\t\t\t\tstep3Actions[s3],\n\t\t\t\t\t\tstep4Actions[s4],\n\t\t\t\t\t\tdelegatorRegProxyAction{bAction, ProxiedDelegator, false},\n\t\t\t\t\t\tdestroyValidatorAction{bAction},\n\t\t\t\t\t}\n\n\t\t\t\t\tactionsAndChecker, caseName := generateActionsAndCheckers(inputActions, 3)\n\n\t\t\t\t\tt.Logf(\"============================================== indexes:[%d,%d,%d,%d] %s ==============================================\", s1, s2, s3, s4, caseName)\n\t\t\t\t\t_, _, mk := CreateTestInput(t, false, SufficientInitPower)\n\t\t\t\t\tsmTestCase := newValidatorSMTestCase(mk, params, startUpStatus, inputActions, actionsAndChecker, t)\n\t\t\t\t\tsmTestCase.SetupValidatorSetAndDelegatorSet(int(params.MaxValidators))\n\t\t\t\t\tsmTestCase.printParticipantSnapshot(t)\n\t\t\t\t\tsmTestCase.Run(t)\n\t\t\t\t\tt.Log(\"============================================================================================\")\n\t\t\t\t}\n\n\t\t\t}\n\t\t}\n\t}\n}", "func TestDonationCase1(t *testing.T) {\n\tassert := assert.New(t)\n\tstore := newReputationStoreOnMock()\n\trep := NewTestReputationImpl(store)\n\tt1 := time.Date(1995, time.February, 5, 11, 11, 0, 0, time.UTC)\n\tt3 := time.Date(1995, time.February, 6, 12, 11, 0, 0, time.UTC)\n\tt4 := time.Date(1995, time.February, 7, 13, 11, 1, 0, time.UTC)\n\tuser1 := \"user1\"\n\tpost1 := \"post1\"\n\tpost2 := \"post2\"\n\n\t// round 2\n\trep.Update(t1.Unix())\n\trep.DonateAt(user1, post1, big.NewInt(100*OneLinoCoin))\n\tassert.Equal(big.NewInt(100*OneLinoCoin), rep.store.GetRoundPostSumStake(2, post1))\n\tassert.Equal(rep.GetReputation(user1), big.NewInt(InitialCustomerScore))\n\tassert.Equal(big.NewInt(OneLinoCoin), rep.store.GetRoundSumDp(2)) // bounded by this user's dp\n\n\t// round 3\n\trep.Update(t3.Unix())\n\t// (1 * 9 + 100) / 10\n\tassert.Equal(big.NewInt(1090000), rep.GetReputation(user1))\n\tassert.Equal(big.NewInt(OneLinoCoin), rep.GetSumRep(post1))\n\trep.DonateAt(user1, post1, big.NewInt(1*OneLinoCoin)) // does not count\n\trep.DonateAt(user1, post2, big.NewInt(900*OneLinoCoin))\n\trep.Update(t4.Unix())\n\t// (10.9 * 9 + 900) / 10\n\tassert.Equal(big.NewInt(9981000), rep.GetReputation(user1))\n\tassert.Equal([]Pid{post2}, rep.store.GetRoundResult(3))\n\t// round 4\n}", "func (_DelegationController *DelegationControllerTransactorSession) GetAndUpdateDelegatedAmount(holder common.Address) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.GetAndUpdateDelegatedAmount(&_DelegationController.TransactOpts, holder)\n}", "func (us *DelegationService) AddDelegation(delegation *models.Delegation) (*models.Delegation, error) {\n\t// TODO(tho) add CSR validation against template\n\treturn us.storeInterface.AddDelegation(delegation)\n}", "func (s *ArkClient) CalculateVotersProfit(params DelegateQueryParams, shareRatio float64, blocklist string, whitelist string, capBalance bool, balanceCapAmount float64, blockBalanceCap bool) []DelegateDataProfit {\n\tdelegateRes, _, _ := s.GetDelegate(params)\n\tvoters, _, _ := s.GetDelegateVoters(params)\n\taccountRes, _, _ := s.GetAccount(AccountQueryParams{Address: delegateRes.SingleDelegate.Address})\n\n\tdelegateBalance, _ := strconv.ParseFloat(accountRes.Account.Balance, 64)\n\tdelegateBalance = float64(delegateBalance) / SATOSHI\n\n\t//calculating vote weight\n\tvotersProfit := []DelegateDataProfit{}\n\tdelelgateVoteWeight := 0\n\n\t//computing summ of all votes\n\tfor _, element := range voters.Accounts {\n\t\t//skipping blocked ones\n\t\tif isBlockedAddress(blocklist, element.Address) {\n\t\t\tcontinue\n\t\t}\n\n\t\t//skip balanceCap unless whitelisted\n\t\tcurrentVoterBalance, _ := strconv.ParseFloat(element.Balance, 64)\n\t\tintBalance, _ := strconv.Atoi(element.Balance)\n\t\tif capBalance && currentVoterBalance > balanceCapAmount {\n\t\t\tif !isAllowedAddress(whitelist, element.Address) {\n\t\t\t\tif blockBalanceCap {\n\t\t\t\t\tintBalance = 0\n\t\t\t\t\tcontinue\n\t\t\t\t} else {\n\t\t\t\t\tintBalance = int(balanceCapAmount)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tdelelgateVoteWeight += intBalance\n\t}\n\n\t//calculating\n\tfor _, element := range voters.Accounts {\n\t\t//skipping blocked ones\n\t\tif isBlockedAddress(blocklist, element.Address) {\n\t\t\tcontinue\n\t\t}\n\n\t\t//skip balanceCap unless whitelisted\n\t\tcurrentVoterBalance, _ := strconv.ParseFloat(element.Balance, 64)\n\t\tif capBalance && currentVoterBalance > balanceCapAmount {\n\t\t\tif !isAllowedAddress(whitelist, element.Address) {\n\t\t\t\tif blockBalanceCap {\n\t\t\t\t\tcurrentVoterBalance = 0\n\t\t\t\t\tcontinue\n\t\t\t\t} else {\n\t\t\t\t\tcurrentVoterBalance = balanceCapAmount\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tdeleProfit := DelegateDataProfit{\n\t\t\tAddress: element.Address,\n\t\t}\n\t\tdeleProfit.VoteWeight = currentVoterBalance / SATOSHI\n\t\tdeleProfit.VoteWeightShare = float64(currentVoterBalance) / float64(delelgateVoteWeight)\n\t\tdeleProfit.EarnedAmount100 = float64(delegateBalance) * deleProfit.VoteWeightShare\n\t\tdeleProfit.EarnedAmountXX = float64(delegateBalance) * deleProfit.VoteWeightShare * shareRatio\n\t\tdeleProfit.VoteDuration = s.GetVoteDuration(element.Address)\n\t\tvotersProfit = append(votersProfit, deleProfit)\n\t}\n\n\treturn votersProfit\n}", "func (_FeeCurrencyWhitelist *FeeCurrencyWhitelistTransactor) TransferOwnership(opts *bind.TransactOpts, newOwner common.Address) (*types.Transaction, error) {\n\treturn _FeeCurrencyWhitelist.contract.Transact(opts, \"transferOwnership\", newOwner)\n}", "func (k Keeper) fastUndelegate(ctx sdk.Context, valAddr sdk.ValAddress, delegator sdk.AccAddress, shares sdk.Dec) (sdkmath.Int, error) {\n\tvalidator, found := k.stakingKeeper.GetValidator(ctx, valAddr)\n\tif !found {\n\t\treturn sdkmath.Int{}, types.ErrNoDelegatorForAddress\n\t}\n\n\treturnAmount, err := k.stakingKeeper.Unbond(ctx, delegator, valAddr, shares)\n\tif err != nil {\n\t\treturn sdkmath.Int{}, err\n\t}\n\treturnCoins := sdk.NewCoins(sdk.NewCoin(k.stakingKeeper.BondDenom(ctx), returnAmount))\n\n\t// transfer the validator tokens to the not bonded pool\n\tif validator.IsBonded() {\n\t\tif err := k.bankKeeper.SendCoinsFromModuleToModule(ctx, stakingtypes.BondedPoolName, stakingtypes.NotBondedPoolName, returnCoins); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\n\tif err := k.bankKeeper.UndelegateCoinsFromModuleToAccount(ctx, stakingtypes.NotBondedPoolName, delegator, returnCoins); err != nil {\n\t\treturn sdkmath.Int{}, err\n\t}\n\treturn returnAmount, nil\n}", "func DisplayCalculatedVoteRatio() {\n\tpubKey := viper.GetString(\"delegate.pubkey\")\n\tif core.EnvironmentParams.Network.Type == core.DEVNET {\n\t\tpubKey = viper.GetString(\"delegate.Dpubkey\")\n\t}\n\n\tparams := core.DelegateQueryParams{PublicKey: pubKey}\n\tdeleResp, _, _ := arkclient.GetDelegate(params)\n\tvotersEarnings := arkclient.CalculateVotersProfit(params, viper.GetFloat64(\"voters.shareratio\"))\n\tshareRatioStr := strconv.FormatFloat(viper.GetFloat64(\"voters.shareratio\")*100, 'f', -1, 64) + \"%\"\n\n\tsumEarned := 0.0\n\tsumRatio := 0.0\n\tsumShareEarned := 0.0\n\n\tcolor.Set(color.FgHiGreen)\n\tfmt.Println(\"--------------------------------------------------------------------------------------------------------------\")\n\tfmt.Println(\"Displaying voter information for delegate:\", deleResp.SingleDelegate.Username, deleResp.SingleDelegate.Address)\n\tfmt.Println(\"--------------------------------------------------------------------------------------------------------------\")\n\tfmt.Println(fmt.Sprintf(\"|%-34s|%18s|%8s|%17s|%17s|%6s|\", \"Voter address\", \"Balance\", \"Weight\", \"Reward-100%\", \"Reward-\"+shareRatioStr, \"Hours\"))\n\tcolor.Set(color.FgCyan)\n\tfor _, element := range votersEarnings {\n\t\ts := fmt.Sprintf(\"|%s|%18.8f|%8.4f|%15.8f A|%15.8f A|%6d|\", element.Address, element.VoteWeight, element.VoteWeightShare, element.EarnedAmount100, element.EarnedAmountXX, element.VoteDuration)\n\n\t\tfmt.Println(s)\n\t\tlogger.Println(s)\n\n\t\tsumEarned += element.EarnedAmount100\n\t\tsumShareEarned += element.EarnedAmountXX\n\t\tsumRatio += element.VoteWeightShare\n\t}\n\n\t//Cost calculation\n\tcostAmount := sumEarned * viper.GetFloat64(\"costs.shareratio\")\n\treserveAmount := sumEarned * viper.GetFloat64(\"reserve.shareratio\")\n\tfmt.Println(\"--------------------------------------------------------------------------------------------------------------\")\n\tfmt.Println(\"\")\n\tfmt.Println(\"Available amount:\", sumEarned)\n\tfmt.Println(\"Amount to voters:\", sumShareEarned, viper.GetFloat64(\"voters.shareratio\"))\n\tfmt.Println(\"Amount to costs:\", costAmount, viper.GetFloat64(\"costs.shareratio\"))\n\tfmt.Println(\"Amount to reserve:\", reserveAmount, viper.GetFloat64(\"reserve.shareratio\"))\n\n\tfmt.Println(\"Ratio calc check:\", sumRatio, \"(should be = 1)\")\n\tfmt.Println(\"Ratio share check:\", float64(sumShareEarned)/float64(sumEarned), \"should be=\", viper.GetFloat64(\"voters.shareratio\"))\n\n\tpause()\n}", "func (_Bindings *BindingsCallerSession) BalanceOf(owner common.Address) (*big.Int, error) {\n\treturn _Bindings.Contract.BalanceOf(&_Bindings.CallOpts, owner)\n}", "func (w *Wallet) Deposit(amount Bitcoin) {\n\tw.balance += amount\n\t// the language permits us to write w.balance, without an explicit dereference like (*w).balance\n\t// these are struct pointers and are automatically dereferenced\n}", "func (w *Wallet) Deposit(amount Bitcoin) {\n\tw.balance += amount\n}" ]
[ "0.7867072", "0.78303444", "0.78073776", "0.780251", "0.75030935", "0.74432373", "0.699153", "0.5845492", "0.53813183", "0.53045094", "0.51640373", "0.50583774", "0.5020244", "0.5015942", "0.49270812", "0.4878253", "0.4844824", "0.48211694", "0.47838807", "0.47838154", "0.47599217", "0.4758833", "0.47556818", "0.4749848", "0.47164202", "0.47110415", "0.4672311", "0.4637101", "0.46165854", "0.46052003", "0.45486128", "0.4545586", "0.45418587", "0.45072114", "0.45047978", "0.44973746", "0.44792435", "0.4471852", "0.44504377", "0.44501138", "0.44363105", "0.44217873", "0.44139975", "0.44137776", "0.4402222", "0.43824017", "0.4377815", "0.43594724", "0.43562368", "0.4307939", "0.42996725", "0.42801648", "0.4236818", "0.42316186", "0.41846398", "0.41723925", "0.41665915", "0.41640946", "0.41581213", "0.41533175", "0.41493884", "0.4148972", "0.4140926", "0.41213197", "0.41055018", "0.4102776", "0.4083533", "0.4083255", "0.40824875", "0.40785608", "0.4075577", "0.40751666", "0.407014", "0.4068983", "0.40686172", "0.40644214", "0.404685", "0.40369707", "0.40356362", "0.40248454", "0.4017359", "0.39997214", "0.3986815", "0.39788136", "0.3973045", "0.39671043", "0.39599237", "0.39467135", "0.39463183", "0.39373308", "0.39356163", "0.39328972", "0.39326757", "0.39301348", "0.39076164", "0.39069307", "0.38984543", "0.38926068", "0.38879532", "0.38833487" ]
0.8320274
0
TrackUndelegation tracks an undelegation amount by setting the necessary values by which delegated vesting and delegated vesting need to decrease and by which amount the base coins need to increase. NOTE: The undelegation (bond refund) amount may exceed the delegated vesting (bond) amount due to the way undelegation truncates the bond refund, which can increase the validator's exchange rate (tokens/shares) slightly if the undelegated tokens are nonintegral. CONTRACT: The account's coins and undelegation coins must be sorted.
func (bva *BaseVestingAccount) TrackUndelegation(amount sdk.Coins) { for _, coin := range amount { // panic if the undelegation amount is zero if coin.Amount.IsZero() { panic("undelegation attempt with zero coins") } delegatedFree := bva.DelegatedFree.AmountOf(coin.Denom) delegatedVesting := bva.DelegatedVesting.AmountOf(coin.Denom) // compute x and y per the specification, where: // X := min(DF, D) // Y := min(DV, D - X) x := sdk.MinInt(delegatedFree, coin.Amount) y := sdk.MinInt(delegatedVesting, coin.Amount.Sub(x)) if !x.IsZero() { xCoin := sdk.NewCoin(coin.Denom, x) bva.DelegatedFree = bva.DelegatedFree.Sub(sdk.Coins{xCoin}) } if !y.IsZero() { yCoin := sdk.NewCoin(coin.Denom, y) bva.DelegatedVesting = bva.DelegatedVesting.Sub(sdk.Coins{yCoin}) } } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (bva *BaseVestingAccount) TrackDelegation(balance, vestingCoins, amount sdk.Coins) {\n\tfor _, coin := range amount {\n\t\tbaseAmt := balance.AmountOf(coin.Denom)\n\t\tvestingAmt := vestingCoins.AmountOf(coin.Denom)\n\t\tdelVestingAmt := bva.DelegatedVesting.AmountOf(coin.Denom)\n\n\t\t// Panic if the delegation amount is zero or if the base coins does not\n\t\t// exceed the desired delegation amount.\n\t\tif coin.Amount.IsZero() || baseAmt.LT(coin.Amount) {\n\t\t\tpanic(\"delegation attempt with zero coins or insufficient funds\")\n\t\t}\n\n\t\t// compute x and y per the specification, where:\n\t\t// X := min(max(V - DV, 0), D)\n\t\t// Y := D - X\n\t\tx := sdk.MinInt(sdk.MaxInt(vestingAmt.Sub(delVestingAmt), sdk.ZeroInt()), coin.Amount)\n\t\ty := coin.Amount.Sub(x)\n\n\t\tif !x.IsZero() {\n\t\t\txCoin := sdk.NewCoin(coin.Denom, x)\n\t\t\tbva.DelegatedVesting = bva.DelegatedVesting.Add(xCoin)\n\t\t}\n\n\t\tif !y.IsZero() {\n\t\t\tyCoin := sdk.NewCoin(coin.Denom, y)\n\t\t\tbva.DelegatedFree = bva.DelegatedFree.Add(yCoin)\n\t\t}\n\t}\n}", "func (vva *ValidatorVestingAccount) TrackDelegation(blockTime time.Time, amount sdk.Coins) {\n\tvva.BaseVestingAccount.TrackDelegation(vva.GetVestingCoins(blockTime), amount)\n}", "func (k msgServer) Undelegate(goCtx context.Context, msg *types.MsgUndelegate) (*types.MsgUndelegateResponse, error) {\n\tctx := sdk.UnwrapSDKContext(goCtx)\n\n\taddr, err := sdk.ValAddressFromBech32(msg.ValidatorAddress)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdelegatorAddress, err := sdk.AccAddressFromBech32(msg.DelegatorAddress)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttokens := msg.Amount.Amount\n\tshares, err := k.ValidateUnbondAmount(\n\t\tctx, delegatorAddress, addr, tokens,\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvalidator, found := k.GetValidator(ctx, addr)\n\tif !found {\n\t\treturn nil, types.ErrNoValidatorFound\n\t}\n\n\tdelegation, found := k.GetDelegation(ctx, delegatorAddress, addr)\n\tif !found {\n\t\treturn nil, status.Errorf(\n\t\t\tcodes.NotFound,\n\t\t\t\"delegation with delegator %s not found for validator %s\",\n\t\t\tmsg.DelegatorAddress, msg.ValidatorAddress,\n\t\t)\n\t}\n\n\t// if this is a validator self-bond, the new liquid delegation cannot fall below the self-bond * bond factor\n\tif delegation.ValidatorBond {\n\t\tif err := k.SafelyDecreaseValidatorBond(ctx, &validator, shares); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// if this delegation is from a liquid staking provider (identified if the delegator\n\t// is an ICA account), the global and validator liquid totals should be decremented\n\tif k.DelegatorIsLiquidStaker(delegatorAddress) {\n\t\tif err := k.DecreaseTotalLiquidStakedTokens(ctx, tokens); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif err := k.DecreaseValidatorLiquidShares(ctx, &validator, shares); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tbondDenom := k.BondDenom(ctx)\n\tif msg.Amount.Denom != bondDenom {\n\t\treturn nil, sdkerrors.Wrapf(\n\t\t\tsdkerrors.ErrInvalidRequest, \"invalid coin denomination: got %s, expected %s\", msg.Amount.Denom, bondDenom,\n\t\t)\n\t}\n\n\tcompletionTime, err := k.Keeper.Undelegate(ctx, delegatorAddress, addr, shares)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif tokens.IsInt64() {\n\t\tdefer func() {\n\t\t\ttelemetry.IncrCounter(1, types.ModuleName, \"undelegate\")\n\t\t\ttelemetry.SetGaugeWithLabels(\n\t\t\t\t[]string{\"tx\", \"msg\", msg.Type()},\n\t\t\t\tfloat32(tokens.Int64()),\n\t\t\t\t[]metrics.Label{telemetry.NewLabel(\"denom\", msg.Amount.Denom)},\n\t\t\t)\n\t\t}()\n\t}\n\n\tctx.EventManager().EmitEvents(sdk.Events{\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeUnbond,\n\t\t\tsdk.NewAttribute(types.AttributeKeyValidator, msg.ValidatorAddress),\n\t\t\tsdk.NewAttribute(sdk.AttributeKeyAmount, msg.Amount.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyCompletionTime, completionTime.Format(time.RFC3339)),\n\t\t),\n\t})\n\n\treturn &types.MsgUndelegateResponse{\n\t\tCompletionTime: completionTime,\n\t}, nil\n}", "func (dva *DelayedVestingAccount) TrackDelegation(blockTime time.Time, balance, amount sdk.Coins) {\n\tdva.BaseVestingAccount.TrackDelegation(balance, dva.GetVestingCoins(blockTime), amount)\n}", "func (va *ClawbackVestingAccount) TrackDelegation(blockTime time.Time, balance, amount sdk.Coins) {\n\tva.BaseVestingAccount.TrackDelegation(balance, va.GetVestingCoins(blockTime), amount)\n}", "func (k msgServer) CancelUnbondingDelegation(goCtx context.Context, msg *types.MsgCancelUnbondingDelegation) (*types.MsgCancelUnbondingDelegationResponse, error) {\n\tctx := sdk.UnwrapSDKContext(goCtx)\n\n\tvalAddr, err := sdk.ValAddressFromBech32(msg.ValidatorAddress)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdelegatorAddress, err := sdk.AccAddressFromBech32(msg.DelegatorAddress)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbondDenom := k.BondDenom(ctx)\n\tif msg.Amount.Denom != bondDenom {\n\t\treturn nil, sdkerrors.Wrapf(\n\t\t\tsdkerrors.ErrInvalidRequest, \"invalid coin denomination: got %s, expected %s\", msg.Amount.Denom, bondDenom,\n\t\t)\n\t}\n\n\tvalidator, found := k.GetValidator(ctx, valAddr)\n\tif !found {\n\t\treturn nil, types.ErrNoValidatorFound\n\t}\n\n\t// In some situations, the exchange rate becomes invalid, e.g. if\n\t// Validator loses all tokens due to slashing. In this case,\n\t// make all future delegations invalid.\n\tif validator.InvalidExRate() {\n\t\treturn nil, types.ErrDelegatorShareExRateInvalid\n\t}\n\n\tif validator.IsJailed() {\n\t\treturn nil, types.ErrValidatorJailed\n\t}\n\n\tubd, found := k.GetUnbondingDelegation(ctx, delegatorAddress, valAddr)\n\tif !found {\n\t\treturn nil, status.Errorf(\n\t\t\tcodes.NotFound,\n\t\t\t\"unbonding delegation with delegator %s not found for validator %s\",\n\t\t\tmsg.DelegatorAddress, msg.ValidatorAddress,\n\t\t)\n\t}\n\n\t// if this undelegation was from a liquid staking provider (identified if the delegator\n\t// is an ICA account), the global and validator liquid totals should be incremented\n\ttokens := msg.Amount.Amount\n\tshares, err := validator.SharesFromTokens(tokens)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif k.DelegatorIsLiquidStaker(delegatorAddress) {\n\t\tif err := k.SafelyIncreaseTotalLiquidStakedTokens(ctx, tokens, false); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif err := k.SafelyIncreaseValidatorLiquidShares(ctx, &validator, shares); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tvar (\n\t\tunbondEntry types.UnbondingDelegationEntry\n\t\tunbondEntryIndex int64 = -1\n\t)\n\n\tfor i, entry := range ubd.Entries {\n\t\tif entry.CreationHeight == msg.CreationHeight {\n\t\t\tunbondEntry = entry\n\t\t\tunbondEntryIndex = int64(i)\n\t\t\tbreak\n\t\t}\n\t}\n\tif unbondEntryIndex == -1 {\n\t\treturn nil, sdkerrors.ErrNotFound.Wrapf(\"unbonding delegation entry is not found at block height %d\", msg.CreationHeight)\n\t}\n\n\tif unbondEntry.Balance.LT(msg.Amount.Amount) {\n\t\treturn nil, sdkerrors.ErrInvalidRequest.Wrap(\"amount is greater than the unbonding delegation entry balance\")\n\t}\n\n\tif unbondEntry.CompletionTime.Before(ctx.BlockTime()) {\n\t\treturn nil, sdkerrors.ErrInvalidRequest.Wrap(\"unbonding delegation is already processed\")\n\t}\n\n\t// delegate back the unbonding delegation amount to the validator\n\t_, err = k.Keeper.Delegate(ctx, delegatorAddress, msg.Amount.Amount, types.Unbonding, validator, false)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tamount := unbondEntry.Balance.Sub(msg.Amount.Amount)\n\tif amount.IsZero() {\n\t\tubd.RemoveEntry(unbondEntryIndex)\n\t} else {\n\t\t// update the unbondingDelegationEntryBalance and InitialBalance for ubd entry\n\t\tunbondEntry.Balance = amount\n\t\tunbondEntry.InitialBalance = unbondEntry.InitialBalance.Sub(msg.Amount.Amount)\n\t\tubd.Entries[unbondEntryIndex] = unbondEntry\n\t}\n\n\t// set the unbonding delegation or remove it if there are no more entries\n\tif len(ubd.Entries) == 0 {\n\t\tk.RemoveUnbondingDelegation(ctx, ubd)\n\t} else {\n\t\tk.SetUnbondingDelegation(ctx, ubd)\n\t}\n\n\tctx.EventManager().EmitEvent(\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeCancelUnbondingDelegation,\n\t\t\tsdk.NewAttribute(sdk.AttributeKeyAmount, msg.Amount.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyValidator, msg.ValidatorAddress),\n\t\t\tsdk.NewAttribute(types.AttributeKeyDelegator, msg.DelegatorAddress),\n\t\t\tsdk.NewAttribute(types.AttributeKeyCreationHeight, strconv.FormatInt(msg.CreationHeight, 10)),\n\t\t),\n\t)\n\n\treturn &types.MsgCancelUnbondingDelegationResponse{}, nil\n}", "func (pva *PeriodicVestingAccount) TrackDelegation(blockTime time.Time, balance, amount sdk.Coins) {\n\tpva.BaseVestingAccount.TrackDelegation(balance, pva.GetVestingCoins(blockTime), amount)\n}", "func (cva *ContinuousVestingAccount) TrackDelegation(blockTime time.Time, balance, amount sdk.Coins) {\n\tcva.BaseVestingAccount.TrackDelegation(balance, cva.GetVestingCoins(blockTime), amount)\n}", "func (plva *PermanentLockedAccount) TrackDelegation(blockTime time.Time, balance, amount sdk.Coins) {\n\tplva.BaseVestingAccount.TrackDelegation(balance, plva.OriginalVesting, amount)\n}", "func (va *ClawbackVestingAccount) updateDelegation(encumbered, toClawBack, bonded, unbonding, unbonded sdk.Coins) sdk.Coins {\n\tdelegated := bonded.Add(unbonding...)\n\toldDelegated := va.DelegatedVesting.Add(va.DelegatedFree...)\n\tslashed := oldDelegated.Sub(coinsMin(delegated, oldDelegated))\n\ttotal := delegated.Add(unbonded...)\n\ttoClawBack = coinsMin(toClawBack, total) // might have been slashed\n\tnewDelegated := coinsMin(delegated, total.Sub(toClawBack)).Add(slashed...)\n\tva.DelegatedVesting = coinsMin(encumbered, newDelegated)\n\tva.DelegatedFree = newDelegated.Sub(va.DelegatedVesting)\n\treturn toClawBack\n}", "func (k Querier) DelegatorUnbondingDelegations(ctx context.Context, req *types.QueryDelegatorUnbondingDelegationsRequest) (*types.QueryDelegatorUnbondingDelegationsResponse, error) {\n\tif req == nil {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"empty request\")\n\t}\n\n\tif req.DelegatorAddr == \"\" {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"delegator address cannot be empty\")\n\t}\n\tvar unbondingDelegations types.UnbondingDelegations\n\n\tdelAddr, err := k.authKeeper.AddressCodec().StringToBytes(req.DelegatorAddr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t_, pageRes, err := query.CollectionPaginate(\n\t\tctx,\n\t\tk.UnbondingDelegations,\n\t\treq.Pagination,\n\t\tfunc(key collections.Pair[[]byte, []byte], value types.UnbondingDelegation) (types.UnbondingDelegation, error) {\n\t\t\tunbondingDelegations = append(unbondingDelegations, value)\n\t\t\treturn value, nil\n\t\t},\n\t\tquery.WithCollectionPaginationPairPrefix[[]byte, []byte](delAddr),\n\t)\n\tif err != nil {\n\t\treturn nil, status.Error(codes.Internal, err.Error())\n\t}\n\n\treturn &types.QueryDelegatorUnbondingDelegationsResponse{\n\t\tUnbondingResponses: unbondingDelegations, Pagination: pageRes,\n\t}, nil\n}", "func (k Querier) ValidatorUnbondingDelegations(ctx context.Context, req *types.QueryValidatorUnbondingDelegationsRequest) (*types.QueryValidatorUnbondingDelegationsResponse, error) {\n\tif req == nil {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"empty request\")\n\t}\n\n\tif req.ValidatorAddr == \"\" {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"validator address cannot be empty\")\n\t}\n\n\tvalAddr, err := k.validatorAddressCodec.StringToBytes(req.ValidatorAddr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tstore := runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx))\n\tkeys, pageRes, err := query.CollectionPaginate(\n\t\tctx,\n\t\tk.UnbondingDelegationByValIndex,\n\t\treq.Pagination,\n\t\tfunc(key collections.Pair[[]byte, []byte], value []byte) (collections.Pair[[]byte, []byte], error) {\n\t\t\treturn key, nil\n\t\t},\n\t\tquery.WithCollectionPaginationPairPrefix[[]byte, []byte](valAddr),\n\t)\n\tif err != nil {\n\t\treturn nil, status.Error(codes.Internal, err.Error())\n\t}\n\n\t// loop over the collected keys and fetch unbonding delegations\n\tvar ubds []types.UnbondingDelegation\n\tfor _, key := range keys {\n\t\tvalAddr := key.K1()\n\t\tdelAddr := key.K2()\n\t\tubdKey := types.GetUBDKey(delAddr, valAddr)\n\t\tstoreValue := store.Get(ubdKey)\n\n\t\tubd, err := types.UnmarshalUBD(k.cdc, storeValue)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tubds = append(ubds, ubd)\n\t}\n\n\treturn &types.QueryValidatorUnbondingDelegationsResponse{\n\t\tUnbondingResponses: ubds,\n\t\tPagination: pageRes,\n\t}, nil\n}", "func (k Querier) UnbondingDelegation(ctx context.Context, req *types.QueryUnbondingDelegationRequest) (*types.QueryUnbondingDelegationResponse, error) {\n\tif req == nil {\n\t\treturn nil, status.Errorf(codes.InvalidArgument, \"empty request\")\n\t}\n\n\tif req.DelegatorAddr == \"\" {\n\t\treturn nil, status.Errorf(codes.InvalidArgument, \"delegator address cannot be empty\")\n\t}\n\tif req.ValidatorAddr == \"\" {\n\t\treturn nil, status.Errorf(codes.InvalidArgument, \"validator address cannot be empty\")\n\t}\n\n\tdelAddr, err := k.authKeeper.AddressCodec().StringToBytes(req.DelegatorAddr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvalAddr, err := k.validatorAddressCodec.StringToBytes(req.ValidatorAddr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tunbond, err := k.GetUnbondingDelegation(ctx, delAddr, valAddr)\n\tif err != nil {\n\t\treturn nil, status.Errorf(\n\t\t\tcodes.NotFound,\n\t\t\t\"unbonding delegation with delegator %s not found for validator %s\",\n\t\t\treq.DelegatorAddr, req.ValidatorAddr)\n\t}\n\n\treturn &types.QueryUnbondingDelegationResponse{Unbond: unbond}, nil\n}", "func (k Keeper) fastUndelegate(ctx sdk.Context, valAddr sdk.ValAddress, delegator sdk.AccAddress, shares sdk.Dec) (sdkmath.Int, error) {\n\tvalidator, found := k.stakingKeeper.GetValidator(ctx, valAddr)\n\tif !found {\n\t\treturn sdkmath.Int{}, types.ErrNoDelegatorForAddress\n\t}\n\n\treturnAmount, err := k.stakingKeeper.Unbond(ctx, delegator, valAddr, shares)\n\tif err != nil {\n\t\treturn sdkmath.Int{}, err\n\t}\n\treturnCoins := sdk.NewCoins(sdk.NewCoin(k.stakingKeeper.BondDenom(ctx), returnAmount))\n\n\t// transfer the validator tokens to the not bonded pool\n\tif validator.IsBonded() {\n\t\tif err := k.bankKeeper.SendCoinsFromModuleToModule(ctx, stakingtypes.BondedPoolName, stakingtypes.NotBondedPoolName, returnCoins); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\n\tif err := k.bankKeeper.UndelegateCoinsFromModuleToAccount(ctx, stakingtypes.NotBondedPoolName, delegator, returnCoins); err != nil {\n\t\treturn sdkmath.Int{}, err\n\t}\n\treturn returnAmount, nil\n}", "func (k msgServer) Delegate(goCtx context.Context, msg *types.MsgDelegate) (*types.MsgDelegateResponse, error) {\n\tctx := sdk.UnwrapSDKContext(goCtx)\n\tvalAddr, valErr := sdk.ValAddressFromBech32(msg.ValidatorAddress)\n\tif valErr != nil {\n\t\treturn nil, valErr\n\t}\n\n\tvalidator, found := k.GetValidator(ctx, valAddr)\n\tif !found {\n\t\treturn nil, types.ErrNoValidatorFound\n\t}\n\n\tdelegatorAddress, err := sdk.AccAddressFromBech32(msg.DelegatorAddress)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbondDenom := k.BondDenom(ctx)\n\tif msg.Amount.Denom != bondDenom {\n\t\treturn nil, sdkerrors.Wrapf(\n\t\t\tsdkerrors.ErrInvalidRequest, \"invalid coin denomination: got %s, expected %s\", msg.Amount.Denom, bondDenom,\n\t\t)\n\t}\n\n\ttokens := msg.Amount.Amount\n\n\t// if this delegation is from a liquid staking provider (identified if the delegator\n\t// is an ICA account), it cannot exceed the global or validator bond cap\n\tif k.DelegatorIsLiquidStaker(delegatorAddress) {\n\t\tshares, err := validator.SharesFromTokens(tokens)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif err := k.SafelyIncreaseTotalLiquidStakedTokens(ctx, tokens, false); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif err := k.SafelyIncreaseValidatorLiquidShares(ctx, &validator, shares); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// NOTE: source funds are always unbonded\n\tnewShares, err := k.Keeper.Delegate(ctx, delegatorAddress, tokens, types.Unbonded, validator, true)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif tokens.IsInt64() {\n\t\tdefer func() {\n\t\t\ttelemetry.IncrCounter(1, types.ModuleName, \"delegate\")\n\t\t\ttelemetry.SetGaugeWithLabels(\n\t\t\t\t[]string{\"tx\", \"msg\", msg.Type()},\n\t\t\t\tfloat32(tokens.Int64()),\n\t\t\t\t[]metrics.Label{telemetry.NewLabel(\"denom\", msg.Amount.Denom)},\n\t\t\t)\n\t\t}()\n\t}\n\n\tctx.EventManager().EmitEvents(sdk.Events{\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeDelegate,\n\t\t\tsdk.NewAttribute(types.AttributeKeyValidator, msg.ValidatorAddress),\n\t\t\tsdk.NewAttribute(sdk.AttributeKeyAmount, msg.Amount.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyNewShares, newShares.String()),\n\t\t),\n\t})\n\n\treturn &types.MsgDelegateResponse{}, nil\n}", "func (del Delegation) UnlockedAmount() (hexutil.Big, error) {\n\treturn repository.R().DelegationAmountUnlocked(&del.Address, (*big.Int)(del.Delegation.ToStakerId))\n}", "func CalculateDelegateNetPayout(delegatedContracts []DelegatedContract) []DelegatedContract{\n var delegateIndex int\n\n for index, delegate := range delegatedContracts{\n if (delegate.Delegate){\n delegateIndex = index\n }\n }\n\n for _, delegate := range delegatedContracts{\n if (!delegate.Delegate){\n delegatedContracts[delegateIndex].TotalPayout = delegatedContracts[delegateIndex].TotalPayout + delegate.Fee\n }\n }\n return delegatedContracts\n}", "func (_DelegationController *DelegationControllerTransactor) RequestUndelegation(opts *bind.TransactOpts, delegationId *big.Int) (*types.Transaction, error) {\n\treturn _DelegationController.contract.Transact(opts, \"requestUndelegation\", delegationId)\n}", "func (b *rpcVestingBalance) unbonding() (sdk.Coins, sdk.Coins, error) {\n\tunbondingCoins, err := b.totalUnbondingDelegations()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tunbonding := unbondingCoins.AmountOf(stakingDenom)\n\tdelegatedFree := b.vacc.GetDelegatedFree().AmountOf(stakingDenom)\n\n\tunbondingFree := sdk.MinInt(delegatedFree, unbonding)\n\tunbondingVesting := unbonding.Sub(unbondingFree)\n\n\tliquidCoins := sdk.NewCoins(newKavaCoin(unbondingFree))\n\tvestingCoins := sdk.NewCoins(newKavaCoin(unbondingVesting))\n\treturn liquidCoins, vestingCoins, nil\n}", "func (k Keeper) TransferDelegation(ctx sdk.Context, valAddr sdk.ValAddress, fromDelegator, toDelegator sdk.AccAddress, shares sdk.Dec) (sdk.Dec, error) {\n\t// Redelegations link a delegation to it's previous validator so slashes are propagated to the new validator.\n\t// If the delegation is transferred to a new owner, the redelegation object must be updated.\n\t// For expediency all transfers with redelegations are blocked.\n\tif k.stakingKeeper.HasReceivingRedelegation(ctx, fromDelegator, valAddr) {\n\t\treturn sdk.Dec{}, types.ErrRedelegationsNotCompleted\n\t}\n\n\tif shares.IsNil() || shares.LT(sdk.ZeroDec()) {\n\t\treturn sdk.Dec{}, errorsmod.Wrap(types.ErrUntransferableShares, \"nil or negative shares\")\n\t}\n\tif shares.Equal(sdk.ZeroDec()) {\n\t\t// Block 0 transfers to reduce edge cases.\n\t\treturn sdk.Dec{}, errorsmod.Wrap(types.ErrUntransferableShares, \"zero shares\")\n\t}\n\n\tfromDelegation, found := k.stakingKeeper.GetDelegation(ctx, fromDelegator, valAddr)\n\tif !found {\n\t\treturn sdk.Dec{}, types.ErrNoDelegatorForAddress\n\t}\n\tvalidator, found := k.stakingKeeper.GetValidator(ctx, valAddr)\n\tif !found {\n\t\treturn sdk.Dec{}, types.ErrNoValidatorFound\n\t}\n\t// Prevent validators from reducing their self delegation below the min.\n\tisValidatorOperator := fromDelegator.Equals(valAddr)\n\tif isValidatorOperator {\n\t\tif isBelowMinSelfDelegation(validator, fromDelegation.Shares.Sub(shares)) {\n\t\t\treturn sdk.Dec{}, types.ErrSelfDelegationBelowMinimum\n\t\t}\n\t}\n\n\treturnAmount, err := k.fastUndelegate(ctx, valAddr, fromDelegator, shares)\n\tif err != nil {\n\t\treturn sdk.Dec{}, err\n\t}\n\treturnCoins := sdk.NewCoins(sdk.NewCoin(k.stakingKeeper.BondDenom(ctx), returnAmount))\n\n\tif err := k.bankKeeper.SendCoins(ctx, fromDelegator, toDelegator, returnCoins); err != nil {\n\t\treturn sdk.Dec{}, err\n\t}\n\treceivedShares, err := k.delegateFromAccount(ctx, valAddr, toDelegator, returnAmount)\n\tif err != nil {\n\t\treturn sdk.Dec{}, err\n\t}\n\n\treturn receivedShares, nil\n}", "func (k Keeper) GetAllUnbondingDelegations(ctx sdk.Context, delegator sdk.AccAddress) []types.UnbondingDelegation {\n\tunbondingDelegations := make([]types.UnbondingDelegation, 0)\n\n\tstore := ctx.KVStore(k.storeKey)\n\tdelegatorPrefixKey := types.GetUBDsKey(delegator)\n\n\titerator := sdk.KVStorePrefixIterator(store, delegatorPrefixKey) // smallest to largest\n\tdefer iterator.Close()\n\n\tfor i := 0; iterator.Valid(); iterator.Next() {\n\t\tunbondingDelegation := types.MustUnmarshalUBD(k.cdc, iterator.Value())\n\t\tunbondingDelegations = append(unbondingDelegations, unbondingDelegation)\n\t\ti++\n\t}\n\n\treturn unbondingDelegations\n}", "func TestSlashWithUnbondingDelegation(t *testing.T) {\n\tapp, ctx, addrDels, addrVals := bootstrapSlashTest(t, 10)\n\n\tconsAddr := sdk.ConsAddress(PKs[0].Address())\n\tfraction := sdk.NewDecWithPrec(5, 1)\n\n\t// set an unbonding delegation with expiration timestamp beyond which the\n\t// unbonding delegation shouldn't be slashed\n\tubdTokens := app.StakingKeeper.TokensFromConsensusPower(ctx, 4)\n\tubd := types.NewUnbondingDelegation(addrDels[0], addrVals[0], 11, time.Unix(0, 0), ubdTokens)\n\tapp.StakingKeeper.SetUnbondingDelegation(ctx, ubd)\n\n\t// slash validator for the first time\n\tctx = ctx.WithBlockHeight(12)\n\tbondedPool := app.StakingKeeper.GetBondedPool(ctx)\n\toldBondedPoolBalances := app.BankKeeper.GetAllBalances(ctx, bondedPool.GetAddress())\n\n\tvalidator, found := app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)\n\trequire.True(t, found)\n\tapp.StakingKeeper.Slash(ctx, consAddr, 10, 10, fraction)\n\n\t// end block\n\tapplyValidatorSetUpdates(t, ctx, app.StakingKeeper, 1)\n\n\t// read updating unbonding delegation\n\tubd, found = app.StakingKeeper.GetUnbondingDelegation(ctx, addrDels[0], addrVals[0])\n\trequire.True(t, found)\n\trequire.Len(t, ubd.Entries, 1)\n\n\t// balance decreased\n\trequire.Equal(t, app.StakingKeeper.TokensFromConsensusPower(ctx, 2), ubd.Entries[0].Balance)\n\n\t// bonded tokens burned\n\tnewBondedPoolBalances := app.BankKeeper.GetAllBalances(ctx, bondedPool.GetAddress())\n\tdiffTokens := oldBondedPoolBalances.Sub(newBondedPoolBalances).AmountOf(app.StakingKeeper.BondDenom(ctx))\n\trequire.Equal(t, app.StakingKeeper.TokensFromConsensusPower(ctx, 3), diffTokens)\n\n\t// read updated validator\n\tvalidator, found = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)\n\trequire.True(t, found)\n\n\t// power decreased by 3 - 6 stake originally bonded at the time of infraction\n\t// was still bonded at the time of discovery and was slashed by half, 4 stake\n\t// bonded at the time of discovery hadn't been bonded at the time of infraction\n\t// and wasn't slashed\n\trequire.Equal(t, int64(7), validator.GetConsensusPower(app.StakingKeeper.PowerReduction(ctx)))\n\n\t// slash validator again\n\tctx = ctx.WithBlockHeight(13)\n\tapp.StakingKeeper.Slash(ctx, consAddr, 9, 10, fraction)\n\n\tubd, found = app.StakingKeeper.GetUnbondingDelegation(ctx, addrDels[0], addrVals[0])\n\trequire.True(t, found)\n\trequire.Len(t, ubd.Entries, 1)\n\n\t// balance decreased again\n\trequire.Equal(t, sdk.NewInt(0), ubd.Entries[0].Balance)\n\n\t// bonded tokens burned again\n\tnewBondedPoolBalances = app.BankKeeper.GetAllBalances(ctx, bondedPool.GetAddress())\n\tdiffTokens = oldBondedPoolBalances.Sub(newBondedPoolBalances).AmountOf(app.StakingKeeper.BondDenom(ctx))\n\trequire.Equal(t, app.StakingKeeper.TokensFromConsensusPower(ctx, 6), diffTokens)\n\n\t// read updated validator\n\tvalidator, found = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)\n\trequire.True(t, found)\n\n\t// power decreased by 3 again\n\trequire.Equal(t, int64(4), validator.GetConsensusPower(app.StakingKeeper.PowerReduction(ctx)))\n\n\t// slash validator again\n\t// all originally bonded stake has been slashed, so this will have no effect\n\t// on the unbonding delegation, but it will slash stake bonded since the infraction\n\t// this may not be the desirable behaviour, ref https://github.com/cosmos/cosmos-sdk/issues/1440\n\tctx = ctx.WithBlockHeight(13)\n\tapp.StakingKeeper.Slash(ctx, consAddr, 9, 10, fraction)\n\n\tubd, found = app.StakingKeeper.GetUnbondingDelegation(ctx, addrDels[0], addrVals[0])\n\trequire.True(t, found)\n\trequire.Len(t, ubd.Entries, 1)\n\n\t// balance unchanged\n\trequire.Equal(t, sdk.NewInt(0), ubd.Entries[0].Balance)\n\n\t// bonded tokens burned again\n\tnewBondedPoolBalances = app.BankKeeper.GetAllBalances(ctx, bondedPool.GetAddress())\n\tdiffTokens = oldBondedPoolBalances.Sub(newBondedPoolBalances).AmountOf(app.StakingKeeper.BondDenom(ctx))\n\trequire.Equal(t, app.StakingKeeper.TokensFromConsensusPower(ctx, 9), diffTokens)\n\n\t// read updated validator\n\tvalidator, found = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)\n\trequire.True(t, found)\n\n\t// power decreased by 3 again\n\trequire.Equal(t, int64(1), validator.GetConsensusPower(app.StakingKeeper.PowerReduction(ctx)))\n\n\t// slash validator again\n\t// all originally bonded stake has been slashed, so this will have no effect\n\t// on the unbonding delegation, but it will slash stake bonded since the infraction\n\t// this may not be the desirable behaviour, ref https://github.com/cosmos/cosmos-sdk/issues/1440\n\tctx = ctx.WithBlockHeight(13)\n\tapp.StakingKeeper.Slash(ctx, consAddr, 9, 10, fraction)\n\n\tubd, found = app.StakingKeeper.GetUnbondingDelegation(ctx, addrDels[0], addrVals[0])\n\trequire.True(t, found)\n\trequire.Len(t, ubd.Entries, 1)\n\n\t// balance unchanged\n\trequire.Equal(t, sdk.NewInt(0), ubd.Entries[0].Balance)\n\n\t// just 1 bonded token burned again since that's all the validator now has\n\tnewBondedPoolBalances = app.BankKeeper.GetAllBalances(ctx, bondedPool.GetAddress())\n\tdiffTokens = oldBondedPoolBalances.Sub(newBondedPoolBalances).AmountOf(app.StakingKeeper.BondDenom(ctx))\n\trequire.Equal(t, app.StakingKeeper.TokensFromConsensusPower(ctx, 10), diffTokens)\n\n\t// apply TM updates\n\tapplyValidatorSetUpdates(t, ctx, app.StakingKeeper, -1)\n\n\t// read updated validator\n\t// power decreased by 1 again, validator is out of stake\n\t// validator should be in unbonding period\n\tvalidator, _ = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)\n\trequire.Equal(t, validator.GetStatus(), types.Unbonding)\n}", "func (_TokensNetwork *TokensNetworkTransactor) UpdateBalanceProofDelegate(opts *bind.TransactOpts, token common.Address, partner common.Address, participant common.Address, transferred_amount *big.Int, locksroot [32]byte, nonce uint64, additional_hash [32]byte, partner_signature []byte, participant_signature []byte) (*types.Transaction, error) {\n\treturn _TokensNetwork.contract.Transact(opts, \"updateBalanceProofDelegate\", token, partner, participant, transferred_amount, locksroot, nonce, additional_hash, partner_signature, participant_signature)\n}", "func (_TokensNetwork *TokensNetworkTransactor) UnlockDelegate(opts *bind.TransactOpts, token common.Address, partner common.Address, participant common.Address, transferred_amount *big.Int, expiration *big.Int, amount *big.Int, secret_hash [32]byte, merkle_proof []byte, participant_signature []byte) (*types.Transaction, error) {\n\treturn _TokensNetwork.contract.Transact(opts, \"unlockDelegate\", token, partner, participant, transferred_amount, expiration, amount, secret_hash, merkle_proof, participant_signature)\n}", "func (o *GetStakingDelegatorsDelegatorAddrUnbondingDelegationsParams) WithDelegatorAddr(delegatorAddr string) *GetStakingDelegatorsDelegatorAddrUnbondingDelegationsParams {\n\to.SetDelegatorAddr(delegatorAddr)\n\treturn o\n}", "func CalculatePayoutForContract(contract Contract, rate float64, delegate bool) Contract{\n ////-------------JUST FOR TESTING -------------////\n totalNodeRewards := 378 //Amount of rewards for my delegation in cycle 11\n ////--------------END TESTING ------------------////\n\n grossRewards := contract.SharePercentage * float64(totalNodeRewards)\n contract.GrossPayout = grossRewards\n fee := rate * grossRewards\n contract.Fee = fee\n var netRewards float64\n if (delegate){\n netRewards = grossRewards\n contract.NetPayout = netRewards\n contract.Fee = 0\n } else {\n netRewards = grossRewards - fee\n contract.NetPayout = contract.NetPayout + netRewards\n }\n\n return contract\n}", "func (_DelegationController *DelegationControllerTransactorSession) RequestUndelegation(delegationId *big.Int) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.RequestUndelegation(&_DelegationController.TransactOpts, delegationId)\n}", "func (_DelegationController *DelegationControllerSession) RequestUndelegation(delegationId *big.Int) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.RequestUndelegation(&_DelegationController.TransactOpts, delegationId)\n}", "func (_TokensNetwork *TokensNetworkSession) UpdateBalanceProofDelegate(token common.Address, partner common.Address, participant common.Address, transferred_amount *big.Int, locksroot [32]byte, nonce uint64, additional_hash [32]byte, partner_signature []byte, participant_signature []byte) (*types.Transaction, error) {\n\treturn _TokensNetwork.Contract.UpdateBalanceProofDelegate(&_TokensNetwork.TransactOpts, token, partner, participant, transferred_amount, locksroot, nonce, additional_hash, partner_signature, participant_signature)\n}", "func (o *GetStakingDelegatorsDelegatorAddrUnbondingDelegationsParams) WithHTTPClient(client *http.Client) *GetStakingDelegatorsDelegatorAddrUnbondingDelegationsParams {\n\to.SetHTTPClient(client)\n\treturn o\n}", "func (_TokensNetwork *TokensNetworkTransactorSession) UpdateBalanceProofDelegate(token common.Address, partner common.Address, participant common.Address, transferred_amount *big.Int, locksroot [32]byte, nonce uint64, additional_hash [32]byte, partner_signature []byte, participant_signature []byte) (*types.Transaction, error) {\n\treturn _TokensNetwork.Contract.UpdateBalanceProofDelegate(&_TokensNetwork.TransactOpts, token, partner, participant, transferred_amount, locksroot, nonce, additional_hash, partner_signature, participant_signature)\n}", "func (a *account) managedTrackWithdrawal(amount types.Currency) {\n\ta.mu.Lock()\n\tdefer a.mu.Unlock()\n\ta.pendingWithdrawals = a.pendingWithdrawals.Add(amount)\n}", "func (_DelegationController *DelegationControllerTransactor) GetAndUpdateDelegatedAmount(opts *bind.TransactOpts, holder common.Address) (*types.Transaction, error) {\n\treturn _DelegationController.contract.Transact(opts, \"getAndUpdateDelegatedAmount\", holder)\n}", "func (_TokensNetwork *TokensNetworkSession) UnlockDelegate(token common.Address, partner common.Address, participant common.Address, transferred_amount *big.Int, expiration *big.Int, amount *big.Int, secret_hash [32]byte, merkle_proof []byte, participant_signature []byte) (*types.Transaction, error) {\n\treturn _TokensNetwork.Contract.UnlockDelegate(&_TokensNetwork.TransactOpts, token, partner, participant, transferred_amount, expiration, amount, secret_hash, merkle_proof, participant_signature)\n}", "func (_TokensNetwork *TokensNetworkTransactorSession) UnlockDelegate(token common.Address, partner common.Address, participant common.Address, transferred_amount *big.Int, expiration *big.Int, amount *big.Int, secret_hash [32]byte, merkle_proof []byte, participant_signature []byte) (*types.Transaction, error) {\n\treturn _TokensNetwork.Contract.UnlockDelegate(&_TokensNetwork.TransactOpts, token, partner, participant, transferred_amount, expiration, amount, secret_hash, merkle_proof, participant_signature)\n}", "func (o *GetStakingDelegatorsDelegatorAddrUnbondingDelegationsParams) WithContext(ctx context.Context) *GetStakingDelegatorsDelegatorAddrUnbondingDelegationsParams {\n\to.SetContext(ctx)\n\treturn o\n}", "func (b *rpcVestingBalance) delegated() (sdk.Coins, sdk.Coins, error) {\n\tdelegatedCoins, err := b.totalDelegated()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tunbondingCoins, err := b.totalUnbondingDelegations()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tdelegated := delegatedCoins.AmountOf(stakingDenom)\n\tunbonding := unbondingCoins.AmountOf(stakingDenom)\n\ttotalStaked := delegated.Add(unbonding)\n\tdelegatedFree := b.vacc.GetDelegatedFree().AmountOf(stakingDenom)\n\n\t// total number of staked and unbonding tokens considered to be liquid\n\ttotalFree := sdk.MinInt(totalStaked, delegatedFree)\n\t// any coins that are not considered liquid, are vesting up to a maximum of delegated\n\tstakedVesting := sdk.MinInt(totalStaked.Sub(totalFree), delegated)\n\t// staked free coins are left over\n\tstakedFree := delegated.Sub(stakedVesting)\n\n\tliquidCoins := sdk.NewCoins(newKavaCoin(stakedFree))\n\tvestingCoins := sdk.NewCoins(newKavaCoin(stakedVesting))\n\treturn liquidCoins, vestingCoins, nil\n}", "func Unfollow(pkt event.Packet) client.RegistryFunc {\n\treturn func(clients client.Registry) error {\n\t\tUIDs := pkt.UIDs()\n\t\tfrom, to := UIDs[0], UIDs[1]\n\n\t\tif _, ok := clients[to]; !ok {\n\t\t\treturn fmt.Errorf(\"for packet numbered %v client %#q is not connected\", pkt.Sequence(), to)\n\t\t}\n\n\t\ttargetClient := clients[to]\n\n\t\tif targetClient.Followers.Contains(from) {\n\t\t\tdelete(targetClient.Followers, from)\n\t\t}\n\n\t\treturn nil\n\t}\n}", "func CalcUnbindOng(balance uint64, startOffset, endOffset uint32) uint64 {\n\tvar amount uint64 = 0\n\tif startOffset >= endOffset {\n\t\treturn 0\n\t}\n\tif startOffset < constants.UNBOUND_DEADLINE {\n\t\tustart := startOffset / TIME_INTERVAL\n\t\tistart := startOffset % TIME_INTERVAL\n\t\tif endOffset >= constants.UNBOUND_DEADLINE {\n\t\t\tendOffset = constants.UNBOUND_DEADLINE\n\t\t}\n\t\tuend := endOffset / TIME_INTERVAL\n\t\tiend := endOffset % TIME_INTERVAL\n\t\tfor ustart < uend {\n\t\t\tamount += uint64(TIME_INTERVAL-istart) * GENERATION_AMOUNT[ustart]\n\t\t\tustart++\n\t\t\tistart = 0\n\t\t}\n\t\tamount += uint64(iend-istart) * GENERATION_AMOUNT[ustart]\n\t}\n\n\treturn uint64(amount) * balance\n}", "func (o *GetStakingDelegatorsDelegatorAddrUnbondingDelegationsParams) WithTimeout(timeout time.Duration) *GetStakingDelegatorsDelegatorAddrUnbondingDelegationsParams {\n\to.SetTimeout(timeout)\n\treturn o\n}", "func NewGetStakingDelegatorsDelegatorAddrUnbondingDelegationsParams() *GetStakingDelegatorsDelegatorAddrUnbondingDelegationsParams {\n\tvar ()\n\treturn &GetStakingDelegatorsDelegatorAddrUnbondingDelegationsParams{\n\n\t\ttimeout: cr.DefaultTimeout,\n\t}\n}", "func (del Delegation) AmountDelegated() hexutil.Big {\n\tif del.Delegation.AmountDelegated == nil {\n\t\treturn hexutil.Big{}\n\t}\n\treturn *del.Delegation.AmountDelegated\n}", "func consolidateDelegations(ctx contract.Context, validator, delegator *types.Address) (*Delegation, []*Delegation, int, error) {\n\t// cycle through all delegations and delete those which are BONDED and\n\t// unlocked while accumulating their amounts\n\tdelegations, err := returnMatchingDelegations(ctx, validator, delegator)\n\tif err != nil {\n\t\treturn nil, nil, -1, err\n\t}\n\n\tunconsolidatedDelegationsCount := 0\n\ttotalDelegationAmount := common.BigZero()\n\tvar consolidatedDelegations []*Delegation\n\tfor _, delegation := range delegations {\n\t\tif delegation.LockTime > uint64(ctx.Now().Unix()) || delegation.State != BONDED {\n\t\t\tunconsolidatedDelegationsCount++\n\t\t\tcontinue\n\t\t}\n\n\t\ttotalDelegationAmount.Add(totalDelegationAmount, &delegation.Amount.Value)\n\t\tconsolidatedDelegations = append(consolidatedDelegations, delegation)\n\n\t\tif err = DeleteDelegation(ctx, delegation); err != nil {\n\t\t\treturn nil, nil, -1, err\n\t\t}\n\t}\n\n\tindex, err := GetNextDelegationIndex(ctx, *validator, *delegator)\n\tif err != nil {\n\t\treturn nil, nil, -1, err\n\t}\n\n\t// create new conolidated delegation\n\tdelegation := &Delegation{\n\t\tValidator: validator,\n\t\tDelegator: delegator,\n\t\tAmount: &types.BigUInt{Value: *totalDelegationAmount},\n\t\tUpdateAmount: loom.BigZeroPB(),\n\t\tLocktimeTier: 0,\n\t\tLockTime: 0,\n\t\tState: BONDED,\n\t\tIndex: index,\n\t}\n\tif err := SetDelegation(ctx, delegation); err != nil {\n\t\treturn nil, nil, -1, err\n\t}\n\treturn delegation, consolidatedDelegations, unconsolidatedDelegationsCount, nil\n}", "func TestValidatorSMDestroyValidatorUnbonding2Removed(t *testing.T) {\n\n\t_, _, mk := CreateTestInput(t, false, SufficientInitPower)\n\tparams := DefaultParams()\n\n\toriginVaSet := addrVals[1:]\n\tparams.MaxValidators = uint16(len(originVaSet))\n\tparams.Epoch = 1\n\tparams.UnbondingTime = time.Millisecond * 300\n\n\tstartUpValidator := NewValidator(StartUpValidatorAddr, StartUpValidatorPubkey, Description{}, types.DefaultMinSelfDelegation)\n\n\tstartUpStatus := baseValidatorStatus{startUpValidator}\n\n\torgValsLen := len(originVaSet)\n\tfullVaSet := make([]sdk.ValAddress, orgValsLen+1)\n\tcopy(fullVaSet, originVaSet)\n\tcopy(fullVaSet[orgValsLen:], []sdk.ValAddress{startUpStatus.getValidator().GetOperator()})\n\n\tbAction := baseAction{mk}\n\tinputActions := []IAction{\n\t\tcreateValidatorAction{bAction, nil},\n\t\tendBlockAction{bAction},\n\t\tdelegatorsAddSharesAction{bAction, false, true, 0, nil},\n\t\tendBlockAction{bAction},\n\t\tdestroyValidatorAction{bAction},\n\t\tendBlockAction{bAction},\n\n\t\t// delegators unbond all tokens back, validator has no msd & delegator shares now, delegator removed\n\t\tdelegatorsWithdrawAction{bAction, true, true},\n\n\t\t// second unbonding time pass, no delegator shares left, unbonding --> validator removed\n\t\twaitUntilUnbondingTimeExpired{bAction},\n\t\tendBlockAction{bAction},\n\t}\n\n\t//expZeroInt := sdk.ZeroInt()\n\texpZeroDec := sdk.ZeroDec()\n\tdlgAddSharesCheck1 := andChecker{[]actResChecker{\n\t\tvalidatorDelegatorShareIncreased(true),\n\t\tvalidatorRemoved(false),\n\t\tvalidatorDelegatorShareLeft(true),\n\t\tvalidatorStatusChecker(sdk.Bonded.String()),\n\t}}\n\n\tdlgUnbondCheck2 := andChecker{[]actResChecker{\n\t\tnoErrorInHandlerResult(true),\n\t\tvalidatorStatusChecker(sdk.Unbonding.String()),\n\t\tvalidatorRemoved(false),\n\t\tqueryDelegatorCheck(ValidDelegator1, false, nil, nil, &expZeroDec, nil),\n\t}}\n\n\tafterUnbondingTimeExpiredCheck1 := andChecker{[]actResChecker{\n\t\tvalidatorRemoved(true),\n\t}}\n\n\tactionsAndChecker := []actResChecker{\n\t\tvalidatorStatusChecker(sdk.Unbonded.String()),\n\t\tqueryValidatorCheck(sdk.Bonded, false, &SharesFromDefaultMSD, &startUpValidator.MinSelfDelegation, nil),\n\t\tdlgAddSharesCheck1.GetChecker(),\n\t\tnil,\n\t\tqueryValidatorCheck(sdk.Bonded, true, nil, &expZeroDec, nil),\n\t\tvalidatorStatusChecker(sdk.Unbonding.String()),\n\t\tdlgUnbondCheck2.GetChecker(),\n\t\tqueryValidatorCheck(sdk.Unbonding, true, nil, &expZeroDec, nil),\n\t\tafterUnbondingTimeExpiredCheck1.GetChecker(),\n\t}\n\n\tsmTestCase := newValidatorSMTestCase(mk, params, startUpStatus, inputActions, actionsAndChecker, t)\n\tsmTestCase.SetupValidatorSetAndDelegatorSet(int(params.MaxValidators))\n\tsmTestCase.printParticipantSnapshot(t)\n\tsmTestCase.Run(t)\n}", "func (_DelegationController *DelegationControllerTransactorSession) GetAndUpdateDelegatedAmount(holder common.Address) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.GetAndUpdateDelegatedAmount(&_DelegationController.TransactOpts, holder)\n}", "func TestTransferNonMember(t *testing.T) {\n\tr := newTestRaft(1, []uint64{2, 3, 4}, 5, 1, NewMemoryStorage())\n\tdefer closeAndFreeRaft(r)\n\tr.Step(pb.Message{From: 2, To: 1, Type: pb.MsgTimeoutNow})\n\n\tr.Step(pb.Message{From: 2, To: 1, Type: pb.MsgVoteResp})\n\tr.Step(pb.Message{From: 3, To: 1, Type: pb.MsgVoteResp})\n\tif r.state != StateFollower {\n\t\tt.Fatalf(\"state is %s, want StateFollower\", r.state)\n\t}\n}", "func (_DelegationController *DelegationControllerSession) GetAndUpdateDelegatedAmount(holder common.Address) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.GetAndUpdateDelegatedAmount(&_DelegationController.TransactOpts, holder)\n}", "func CalculatePercentageSharesForCycle(delegatedContracts []DelegatedContract, cycle int, rate float64, spillage bool, delegateAddr string) ([]DelegatedContract, error){\n var stakingBalance float64\n //var balance float64\n var err error\n\n spillAlert := false\n\n stakingBalance, err = GetDelegateStakingBalance(delegateAddr, cycle)\n if (err != nil){\n return delegatedContracts, errors.New(\"func CalculateRollSpillage(delegatedContracts []DelegatedContract, delegateAddr string) failed: \" + err.Error())\n }\n\n mod := math.Mod(stakingBalance, 10000)\n sum := stakingBalance - mod\n balanceCheck := stakingBalance - mod\n\n for index, delegation := range delegatedContracts{\n counter := 0\n for i, _ := range delegation.Contracts {\n if (delegatedContracts[index].Contracts[i].Cycle == cycle){\n break\n }\n counter = counter + 1\n }\n balanceCheck = balanceCheck - delegatedContracts[index].Contracts[counter].Amount\n //fmt.Println(stakingBalance)\n if (spillAlert){\n delegatedContracts[index].Contracts[counter].SharePercentage = 0\n delegatedContracts[index].Contracts[counter].RollInclusion = 0\n } else if (balanceCheck < 0 && spillage){\n spillAlert = true\n delegatedContracts[index].Contracts[counter].SharePercentage = (delegatedContracts[index].Contracts[counter].Amount + stakingBalance) / sum\n delegatedContracts[index].Contracts[counter].RollInclusion = delegatedContracts[index].Contracts[counter].Amount + stakingBalance\n } else{\n delegatedContracts[index].Contracts[counter].SharePercentage = delegatedContracts[index].Contracts[counter].Amount / stakingBalance\n delegatedContracts[index].Contracts[counter].RollInclusion = delegatedContracts[index].Contracts[counter].Amount\n }\n delegatedContracts[index].Contracts[counter] = CalculatePayoutForContract(delegatedContracts[index].Contracts[counter], rate, delegatedContracts[index].Delegate)\n delegatedContracts[index].Fee = delegatedContracts[index].Fee + delegatedContracts[index].Contracts[counter].Fee\n }\n\n return delegatedContracts, nil\n}", "func (a *account) managedTrackDeposit(amount types.Currency) {\n\ta.mu.Lock()\n\tdefer a.mu.Unlock()\n\ta.pendingDeposits = a.pendingDeposits.Add(amount)\n}", "func (c *DPOS) UnbondAll(ctx contract.Context, req *UnbondAllRequest) error {\n\tif !ctx.FeatureEnabled(features.DPOSVersion3_7, false) {\n\t\treturn errors.New(\"DPOS v3.7 is not enabled\")\n\t}\n\n\tif req.ValidatorAddress == nil {\n\t\treturn errors.New(\"validator address must be specified\")\n\t}\n\n\tsender := ctx.Message().Sender\n\tstate, err := LoadState(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// ensure that function is only executed when called by oracle\n\tif state.Params.OracleAddress == nil || sender.Compare(loom.UnmarshalAddressPB(state.Params.OracleAddress)) != 0 {\n\t\treturn errOnlyOracle\n\t}\n\n\tdelegationIndexes, err := loadDelegationList(ctx)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to load delegations\")\n\t}\n\tvalidatorAddress := loom.UnmarshalAddressPB(req.ValidatorAddress)\n\tfor _, di := range delegationIndexes {\n\t\tif validatorAddress.Compare(loom.UnmarshalAddressPB(di.Validator)) != 0 {\n\t\t\tcontinue\n\t\t}\n\t\tdelegation, err := GetDelegation(ctx, di.Index, *di.Validator, *di.Delegator)\n\t\tif err == contract.ErrNotFound {\n\t\t\tvalidator := loom.UnmarshalAddressPB(di.Validator)\n\t\t\tdelegator := loom.UnmarshalAddressPB(di.Delegator)\n\t\t\treturn fmt.Errorf(\"delegation not found for validator %v / delegator %v\", validator, delegator)\n\t\t} else if err != nil {\n\t\t\treturn errors.Wrap(err, \"failed to load delegation\")\n\t\t}\n\n\t\tif delegation.State == BONDED {\n\t\t\tdelegation.State = UNBONDING\n\t\t\t// Unbond the full amount.\n\t\t\t// NOTE: If the delegation earns rewards during the election during which it's unbonded\n\t\t\t// then the amount that actually ends up being unbonded doesn't include the rewards\n\t\t\t// earned during that election, thus the delegation amount is going to be non-zero\n\t\t\t// after the election.\n\t\t\tdelegation.UpdateAmount = &types.BigUInt{Value: delegation.Amount.Value}\n\n\t\t\tif err := SetDelegation(ctx, delegation); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tif err = c.emitDelegatorUnbondsEvent(ctx, delegation); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func TestValidatorSMDestroyValidatorUnbonding2UnBonded2Removed(t *testing.T) {\n\n\t_, _, mk := CreateTestInput(t, false, SufficientInitPower)\n\tparams := DefaultParams()\n\n\toriginVaSet := addrVals[1:]\n\tparams.MaxValidators = uint16(len(originVaSet))\n\tparams.Epoch = 1\n\tparams.UnbondingTime = time.Millisecond * 300\n\n\tstartUpValidator := NewValidator(StartUpValidatorAddr, StartUpValidatorPubkey, Description{}, types.DefaultMinSelfDelegation)\n\n\tstartUpStatus := baseValidatorStatus{startUpValidator}\n\n\torgValsLen := len(originVaSet)\n\tfullVaSet := make([]sdk.ValAddress, orgValsLen+1)\n\tcopy(fullVaSet, originVaSet)\n\tcopy(fullVaSet[orgValsLen:], []sdk.ValAddress{startUpStatus.getValidator().GetOperator()})\n\n\tbAction := baseAction{mk}\n\tinputActions := []IAction{\n\t\tcreateValidatorAction{bAction, nil},\n\t\tendBlockAction{bAction},\n\t\tdelegatorsAddSharesAction{bAction, false, true, 0, nil},\n\t\tendBlockAction{bAction},\n\t\tdestroyValidatorAction{bAction},\n\t\tendBlockAction{bAction},\n\n\t\t// first unbonding time pass, delegator shares left, validator unbonding --> unbonded\n\t\twaitUntilUnbondingTimeExpired{bAction},\n\t\tendBlockAction{bAction},\n\n\t\t// delegators unbond all tokens back, validator has no msd & delegator shares now, delegator removed\n\t\tdelegatorsWithdrawAction{bAction, true, true},\n\t}\n\n\texpZeroDec := sdk.ZeroDec()\n\tdlgAddSharesCheck1 := andChecker{[]actResChecker{\n\t\tvalidatorDelegatorShareIncreased(true),\n\t\tvalidatorRemoved(false),\n\t\tvalidatorDelegatorShareLeft(true),\n\t\tvalidatorStatusChecker(sdk.Bonded.String()),\n\t}}\n\n\tafterUnbondingTimeExpiredCheck1 := andChecker{[]actResChecker{\n\t\tvalidatorRemoved(false),\n\t\tvalidatorStatusChecker(sdk.Unbonded.String()),\n\t}}\n\n\tdlgUnbondCheck2 := andChecker{[]actResChecker{\n\t\tnoErrorInHandlerResult(true),\n\t\tvalidatorStatusChecker(sdk.Unbonded.String()),\n\t\tvalidatorRemoved(true),\n\t\tqueryDelegatorCheck(ValidDelegator1, false, nil, nil, &expZeroDec, nil),\n\t}}\n\n\tactionsAndChecker := []actResChecker{\n\t\tvalidatorStatusChecker(sdk.Unbonded.String()),\n\t\tqueryValidatorCheck(sdk.Bonded, false, &SharesFromDefaultMSD, &startUpValidator.MinSelfDelegation, nil),\n\t\tdlgAddSharesCheck1.GetChecker(),\n\t\tnil,\n\t\tqueryValidatorCheck(sdk.Bonded, true, nil, &expZeroDec, nil),\n\t\tvalidatorStatusChecker(sdk.Unbonding.String()),\n\t\tvalidatorStatusChecker(sdk.Unbonding.String()),\n\t\tafterUnbondingTimeExpiredCheck1.GetChecker(),\n\t\tdlgUnbondCheck2.GetChecker(),\n\t}\n\n\tsmTestCase := newValidatorSMTestCase(mk, params, startUpStatus, inputActions, actionsAndChecker, t)\n\tsmTestCase.SetupValidatorSetAndDelegatorSet(int(params.MaxValidators))\n\tsmTestCase.printParticipantSnapshot(t)\n\tsmTestCase.Run(t)\n}", "func (serv *AppServer) Unfollow(user int, unfollowing int) {\n\tserv.ServerRequest([]string{\"Unfollow\", strconv.Itoa(user), strconv.Itoa(unfollowing)})\n}", "func TestDelegatorProxyValidatorConstraints4Steps(t *testing.T) {\n\tcommon.InitConfig()\n\tparams := DefaultParams()\n\n\toriginVaSet := addrVals[1:]\n\tparams.MaxValidators = uint16(len(originVaSet))\n\tparams.Epoch = 2\n\tparams.UnbondingTime = time.Millisecond * 300\n\tstartUpValidator := NewValidator(StartUpValidatorAddr, StartUpValidatorPubkey, Description{}, types.DefaultMinSelfDelegation)\n\tstartUpStatus := baseValidatorStatus{startUpValidator}\n\torgValsLen := len(originVaSet)\n\tfullVaSet := make([]sdk.ValAddress, orgValsLen+1)\n\tcopy(fullVaSet, originVaSet)\n\tcopy(fullVaSet[orgValsLen:], []sdk.ValAddress{startUpStatus.getValidator().GetOperator()})\n\n\tbAction := baseAction{}\n\n\tstep1Actions := IActions{\n\t\tdelegatorRegProxyAction{bAction, ProxiedDelegator, true},\n\t\tdelegatorsAddSharesAction{bAction, false, true, 0, []sdk.AccAddress{ProxiedDelegator}},\n\t\tdelegatorWithdrawAction{bAction, ProxiedDelegator, sdk.OneDec(), sdk.DefaultBondDenom},\n\t\tproxyBindAction{bAction, ProxiedDelegator, ProxiedDelegator},\n\t\tproxyUnBindAction{bAction, ProxiedDelegator},\n\t}\n\n\tstep2Actions := IActions{\n\t\tdelegatorDepositAction{bAction, ValidDelegator1, DelegatedToken1, sdk.DefaultBondDenom},\n\t\tproxyBindAction{bAction, ValidDelegator1, ProxiedDelegator},\n\t\tdelegatorsAddSharesAction{bAction, false, true, 0, []sdk.AccAddress{ValidDelegator1}},\n\t\tproxyUnBindAction{bAction, ValidDelegator1},\n\t\tdelegatorWithdrawAction{bAction, ValidDelegator1, sdk.OneDec(), sdk.DefaultBondDenom},\n\t}\n\n\tstep3Actions := IActions{\n\t\tdelegatorDepositAction{bAction, ValidDelegator1, DelegatedToken1, sdk.DefaultBondDenom},\n\t\tproxyBindAction{bAction, ValidDelegator1, ProxiedDelegator},\n\t\tproxyUnBindAction{bAction, ValidDelegator1},\n\t\tdelegatorWithdrawAction{bAction, ValidDelegator1, sdk.OneDec(), sdk.DefaultBondDenom},\n\t}\n\n\tstep4Actions := IActions{\n\t\tdelegatorRegProxyAction{bAction, ProxiedDelegator, true},\n\t\tdelegatorsAddSharesAction{bAction, false, true, 0, []sdk.AccAddress{ProxiedDelegator}},\n\t\tproxyBindAction{bAction, ProxiedDelegator, ProxiedDelegator},\n\t\tproxyUnBindAction{bAction, ProxiedDelegator},\n\t\tdelegatorWithdrawAction{bAction, ProxiedDelegator, sdk.OneDec(), sdk.DefaultBondDenom},\n\t}\n\n\tfor s1 := 0; s1 < len(step1Actions); s1++ {\n\t\tfor s2 := 0; s2 < len(step2Actions); s2++ {\n\t\t\tfor s3 := 0; s3 < len(step3Actions); s3++ {\n\t\t\t\tfor s4 := 0; s4 < len(step4Actions); s4++ {\n\t\t\t\t\tinputActions := []IAction{\n\t\t\t\t\t\tcreateValidatorAction{bAction, nil},\n\t\t\t\t\t\tdelegatorsAddSharesAction{bAction, false, true, 0, []sdk.AccAddress{ValidDelegator2}},\n\t\t\t\t\t\tdelegatorDepositAction{bAction, ProxiedDelegator, MaxDelegatedToken, sdk.DefaultBondDenom},\n\t\t\t\t\t\tstep1Actions[s1],\n\t\t\t\t\t\tstep2Actions[s2],\n\t\t\t\t\t\tstep3Actions[s3],\n\t\t\t\t\t\tstep4Actions[s4],\n\t\t\t\t\t\tdelegatorRegProxyAction{bAction, ProxiedDelegator, false},\n\t\t\t\t\t\tdestroyValidatorAction{bAction},\n\t\t\t\t\t}\n\n\t\t\t\t\tactionsAndChecker, caseName := generateActionsAndCheckers(inputActions, 3)\n\n\t\t\t\t\tt.Logf(\"============================================== indexes:[%d,%d,%d,%d] %s ==============================================\", s1, s2, s3, s4, caseName)\n\t\t\t\t\t_, _, mk := CreateTestInput(t, false, SufficientInitPower)\n\t\t\t\t\tsmTestCase := newValidatorSMTestCase(mk, params, startUpStatus, inputActions, actionsAndChecker, t)\n\t\t\t\t\tsmTestCase.SetupValidatorSetAndDelegatorSet(int(params.MaxValidators))\n\t\t\t\t\tsmTestCase.printParticipantSnapshot(t)\n\t\t\t\t\tsmTestCase.Run(t)\n\t\t\t\t\tt.Log(\"============================================================================================\")\n\t\t\t\t}\n\n\t\t\t}\n\t\t}\n\t}\n}", "func UnmarshalDelegation(cdc *codec.Codec, key, value []byte) (delegation Delegation, err error) {\n\tvar storeValue delegationValue\n\terr = cdc.UnmarshalBinaryLengthPrefixed(value, &storeValue)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"%v: %v\", ErrNoDelegation(DefaultCodespace).Data(), err)\n\t\treturn\n\t}\n\n\taddrs := key[1:] // remove prefix bytes\n\tif len(addrs) != 2*sdk.AddrLen {\n\t\terr = fmt.Errorf(\"%v\", ErrBadDelegationAddr(DefaultCodespace).Data())\n\t\treturn\n\t}\n\n\tdelAddr := sdk.AccAddress(addrs[:sdk.AddrLen])\n\tvalAddr := sdk.ValAddress(addrs[sdk.AddrLen:])\n\n\treturn Delegation{\n\t\tDelegatorAddr: delAddr,\n\t\tValidatorAddr: valAddr,\n\t\tShares: storeValue.Shares,\n\t}, nil\n}", "func (broadcast *Broadcast) Unfollow(ctx context.Context, follower, followee,\n\tprivKeyHex string, seq int64) (*model.BroadcastResponse, error) {\n\tmsg := model.UnfollowMsg{\n\t\tFollower: follower,\n\t\tFollowee: followee,\n\t}\n\treturn broadcast.broadcastTransaction(ctx, msg, privKeyHex, seq, \"\", false)\n}", "func (k Keeper) UpdateDelegatorsBeforeSlashing(ctx sdk.Context, valAddr sdk.ValAddress) {\n\tdelegations := k.stakingKeeper.GetValidatorDelegations(ctx, valAddr)\n\n\tdefaultCoin := coins.GetDefaultCoin()\n\n\tfor _, delegation := range delegations {\n\t\tk.SavePosmined(ctx, delegation.DelegatorAddress, defaultCoin)\n\t}\n}", "func (_FeeCurrencyWhitelist *FeeCurrencyWhitelistTransactor) RenounceOwnership(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _FeeCurrencyWhitelist.contract.Transact(opts, \"renounceOwnership\")\n}", "func NewGetStakingDelegatorsDelegatorAddrUnbondingDelegationsParamsWithHTTPClient(client *http.Client) *GetStakingDelegatorsDelegatorAddrUnbondingDelegationsParams {\n\tvar ()\n\treturn &GetStakingDelegatorsDelegatorAddrUnbondingDelegationsParams{\n\t\tHTTPClient: client,\n\t}\n}", "func (k Keeper) UndelegateCoinsFromModuleToAccount(\n\tctx sdk.Context, senderModule string, recipientAddr sdk.AccAddress, amt sdk.Coin,\n) error {\n\n\tacc := k.GetModuleAccount(ctx, senderModule)\n\tif acc == nil {\n\t\treturn sdk.ErrUnknownAddress(fmt.Sprintf(\"module account %s isn't able to be created\", recipientAddr))\n\t}\n\n\tif !acc.HasPermission(types2.Staking) {\n\t\treturn sdk.ErrNoPermission(fmt.Sprintf(\"module account %s has no expected permission\", recipientAddr))\n\t}\n\n\treturn k.ak.Transfer(ctx, acc.GetAddress(), recipientAddr, amt)\n}", "func (o OfflineNotaryRepository) RemoveDelegationPaths(data.RoleName, []string) error {\n\treturn nil\n}", "func (k Keeper) BurnDerivative(ctx sdk.Context, delegatorAddr sdk.AccAddress, valAddr sdk.ValAddress, amount sdk.Coin) (sdk.Dec, error) {\n\n\tif amount.Denom != k.GetLiquidStakingTokenDenom(valAddr) {\n\t\treturn sdk.Dec{}, errorsmod.Wrap(types.ErrInvalidDenom, \"derivative denom does not match validator\")\n\t}\n\n\tif err := k.burnCoins(ctx, delegatorAddr, sdk.NewCoins(amount)); err != nil {\n\t\treturn sdk.Dec{}, err\n\t}\n\n\tmodAcc := k.accountKeeper.GetModuleAccount(ctx, types.ModuleAccountName)\n\tshares := sdk.NewDecFromInt(amount.Amount)\n\treceivedShares, err := k.TransferDelegation(ctx, valAddr, modAcc.GetAddress(), delegatorAddr, shares)\n\tif err != nil {\n\t\treturn sdk.Dec{}, err\n\t}\n\n\tctx.EventManager().EmitEvent(\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeBurnDerivative,\n\t\t\tsdk.NewAttribute(types.AttributeKeyDelegator, delegatorAddr.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyValidator, valAddr.String()),\n\t\t\tsdk.NewAttribute(sdk.AttributeKeyAmount, amount.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeySharesTransferred, shares.String()),\n\t\t),\n\t)\n\treturn receivedShares, nil\n}", "func TestSlashWithRedelegation(t *testing.T) {\n\tapp, ctx, addrDels, addrVals := bootstrapSlashTest(t, 10)\n\tconsAddr := sdk.ConsAddress(PKs[0].Address())\n\tfraction := sdk.NewDecWithPrec(5, 1)\n\tbondDenom := app.StakingKeeper.BondDenom(ctx)\n\n\t// set a redelegation\n\trdTokens := app.StakingKeeper.TokensFromConsensusPower(ctx, 6)\n\trd := types.NewRedelegation(addrDels[0], addrVals[0], addrVals[1], 11,\n\t\ttime.Unix(0, 0), rdTokens, rdTokens.ToDec())\n\tapp.StakingKeeper.SetRedelegation(ctx, rd)\n\n\t// set the associated delegation\n\tdel := types.NewDelegation(addrDels[0], addrVals[1], rdTokens.ToDec())\n\tapp.StakingKeeper.SetDelegation(ctx, del)\n\n\t// update bonded tokens\n\tbondedPool := app.StakingKeeper.GetBondedPool(ctx)\n\tnotBondedPool := app.StakingKeeper.GetNotBondedPool(ctx)\n\trdCoins := sdk.NewCoins(sdk.NewCoin(bondDenom, rdTokens.MulRaw(2)))\n\n\trequire.NoError(t, simapp.FundModuleAccount(app.BankKeeper, ctx, bondedPool.GetName(), rdCoins))\n\n\tapp.AccountKeeper.SetModuleAccount(ctx, bondedPool)\n\n\toldBonded := app.BankKeeper.GetBalance(ctx, bondedPool.GetAddress(), bondDenom).Amount\n\toldNotBonded := app.BankKeeper.GetBalance(ctx, notBondedPool.GetAddress(), bondDenom).Amount\n\n\t// slash validator\n\tctx = ctx.WithBlockHeight(12)\n\tvalidator, found := app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)\n\trequire.True(t, found)\n\n\trequire.NotPanics(t, func() { app.StakingKeeper.Slash(ctx, consAddr, 10, 10, fraction) })\n\tburnAmount := app.StakingKeeper.TokensFromConsensusPower(ctx, 10).ToDec().Mul(fraction).TruncateInt()\n\n\tbondedPool = app.StakingKeeper.GetBondedPool(ctx)\n\tnotBondedPool = app.StakingKeeper.GetNotBondedPool(ctx)\n\n\t// burn bonded tokens from only from delegations\n\tbondedPoolBalance := app.BankKeeper.GetBalance(ctx, bondedPool.GetAddress(), bondDenom).Amount\n\trequire.True(sdk.IntEq(t, oldBonded.Sub(burnAmount), bondedPoolBalance))\n\n\tnotBondedPoolBalance := app.BankKeeper.GetBalance(ctx, notBondedPool.GetAddress(), bondDenom).Amount\n\trequire.True(sdk.IntEq(t, oldNotBonded, notBondedPoolBalance))\n\toldBonded = app.BankKeeper.GetBalance(ctx, bondedPool.GetAddress(), bondDenom).Amount\n\n\t// read updating redelegation\n\trd, found = app.StakingKeeper.GetRedelegation(ctx, addrDels[0], addrVals[0], addrVals[1])\n\trequire.True(t, found)\n\trequire.Len(t, rd.Entries, 1)\n\t// read updated validator\n\tvalidator, found = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)\n\trequire.True(t, found)\n\t// power decreased by 2 - 4 stake originally bonded at the time of infraction\n\t// was still bonded at the time of discovery and was slashed by half, 4 stake\n\t// bonded at the time of discovery hadn't been bonded at the time of infraction\n\t// and wasn't slashed\n\trequire.Equal(t, int64(8), validator.GetConsensusPower(app.StakingKeeper.PowerReduction(ctx)))\n\n\t// slash the validator again\n\tvalidator, found = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)\n\trequire.True(t, found)\n\n\trequire.NotPanics(t, func() { app.StakingKeeper.Slash(ctx, consAddr, 10, 10, sdk.OneDec()) })\n\tburnAmount = app.StakingKeeper.TokensFromConsensusPower(ctx, 7)\n\n\t// read updated pool\n\tbondedPool = app.StakingKeeper.GetBondedPool(ctx)\n\tnotBondedPool = app.StakingKeeper.GetNotBondedPool(ctx)\n\n\t// seven bonded tokens burned\n\tbondedPoolBalance = app.BankKeeper.GetBalance(ctx, bondedPool.GetAddress(), bondDenom).Amount\n\trequire.True(sdk.IntEq(t, oldBonded.Sub(burnAmount), bondedPoolBalance))\n\trequire.True(sdk.IntEq(t, oldNotBonded, notBondedPoolBalance))\n\n\tbondedPoolBalance = app.BankKeeper.GetBalance(ctx, bondedPool.GetAddress(), bondDenom).Amount\n\trequire.True(sdk.IntEq(t, oldBonded.Sub(burnAmount), bondedPoolBalance))\n\n\tnotBondedPoolBalance = app.BankKeeper.GetBalance(ctx, notBondedPool.GetAddress(), bondDenom).Amount\n\trequire.True(sdk.IntEq(t, oldNotBonded, notBondedPoolBalance))\n\toldBonded = app.BankKeeper.GetBalance(ctx, bondedPool.GetAddress(), bondDenom).Amount\n\n\t// read updating redelegation\n\trd, found = app.StakingKeeper.GetRedelegation(ctx, addrDels[0], addrVals[0], addrVals[1])\n\trequire.True(t, found)\n\trequire.Len(t, rd.Entries, 1)\n\t// read updated validator\n\tvalidator, found = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)\n\trequire.True(t, found)\n\t// power decreased by 4\n\trequire.Equal(t, int64(4), validator.GetConsensusPower(app.StakingKeeper.PowerReduction(ctx)))\n\n\t// slash the validator again, by 100%\n\tctx = ctx.WithBlockHeight(12)\n\tvalidator, found = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)\n\trequire.True(t, found)\n\n\trequire.NotPanics(t, func() { app.StakingKeeper.Slash(ctx, consAddr, 10, 10, sdk.OneDec()) })\n\n\tburnAmount = app.StakingKeeper.TokensFromConsensusPower(ctx, 10).ToDec().Mul(sdk.OneDec()).TruncateInt()\n\tburnAmount = burnAmount.Sub(sdk.OneDec().MulInt(rdTokens).TruncateInt())\n\n\t// read updated pool\n\tbondedPool = app.StakingKeeper.GetBondedPool(ctx)\n\tnotBondedPool = app.StakingKeeper.GetNotBondedPool(ctx)\n\n\tbondedPoolBalance = app.BankKeeper.GetBalance(ctx, bondedPool.GetAddress(), bondDenom).Amount\n\trequire.True(sdk.IntEq(t, oldBonded.Sub(burnAmount), bondedPoolBalance))\n\tnotBondedPoolBalance = app.BankKeeper.GetBalance(ctx, notBondedPool.GetAddress(), bondDenom).Amount\n\trequire.True(sdk.IntEq(t, oldNotBonded, notBondedPoolBalance))\n\toldBonded = app.BankKeeper.GetBalance(ctx, bondedPool.GetAddress(), bondDenom).Amount\n\n\t// read updating redelegation\n\trd, found = app.StakingKeeper.GetRedelegation(ctx, addrDels[0], addrVals[0], addrVals[1])\n\trequire.True(t, found)\n\trequire.Len(t, rd.Entries, 1)\n\t// apply TM updates\n\tapplyValidatorSetUpdates(t, ctx, app.StakingKeeper, -1)\n\t// read updated validator\n\t// validator decreased to zero power, should be in unbonding period\n\tvalidator, _ = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)\n\trequire.Equal(t, validator.GetStatus(), types.Unbonding)\n\n\t// slash the validator again, by 100%\n\t// no stake remains to be slashed\n\tctx = ctx.WithBlockHeight(12)\n\t// validator still in unbonding period\n\tvalidator, _ = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)\n\trequire.Equal(t, validator.GetStatus(), types.Unbonding)\n\n\trequire.NotPanics(t, func() { app.StakingKeeper.Slash(ctx, consAddr, 10, 10, sdk.OneDec()) })\n\n\t// read updated pool\n\tbondedPool = app.StakingKeeper.GetBondedPool(ctx)\n\tnotBondedPool = app.StakingKeeper.GetNotBondedPool(ctx)\n\n\tbondedPoolBalance = app.BankKeeper.GetBalance(ctx, bondedPool.GetAddress(), bondDenom).Amount\n\trequire.True(sdk.IntEq(t, oldBonded, bondedPoolBalance))\n\tnotBondedPoolBalance = app.BankKeeper.GetBalance(ctx, notBondedPool.GetAddress(), bondDenom).Amount\n\trequire.True(sdk.IntEq(t, oldNotBonded, notBondedPoolBalance))\n\n\t// read updating redelegation\n\trd, found = app.StakingKeeper.GetRedelegation(ctx, addrDels[0], addrVals[0], addrVals[1])\n\trequire.True(t, found)\n\trequire.Len(t, rd.Entries, 1)\n\t// read updated validator\n\t// power still zero, still in unbonding period\n\tvalidator, _ = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)\n\trequire.Equal(t, validator.GetStatus(), types.Unbonding)\n}", "func CalculateRollSpillage(delegatedContracts []DelegatedContract, delegateAddr string, cycle int) ([]DelegatedContract, error) {\n stakingBalance, err := GetDelegateStakingBalance(delegateAddr, cycle)\n if (err != nil){\n return delegatedContracts, errors.New(\"func CalculateRollSpillage(delegatedContracts []DelegatedContract, delegateAddr string) failed: \" + err.Error())\n }\n\n mod := math.Mod(stakingBalance, 10000)\n sum := mod * 10000\n\n for index, delegatedContract := range delegatedContracts{\n for i, contract := range delegatedContract.Contracts{\n if (contract.Cycle == cycle){\n stakingBalance = stakingBalance - contract.Amount\n if (stakingBalance < 0){\n delegatedContracts[index].Contracts[i].SharePercentage = (contract.Amount - stakingBalance) / sum\n }\n }\n }\n }\n\n return delegatedContracts, nil\n}", "func StoreUnbondingDelegationFromMessage(\n\ttx *juno.Tx, index int, msg *stakingtypes.MsgUndelegate, db *database.Db,\n) (*types.UnbondingDelegation, error) {\n\tevent, err := tx.FindEventByType(index, stakingtypes.EventTypeUnbond)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcompletionTimeStr, err := tx.FindAttributeByKey(event, stakingtypes.AttributeKeyCompletionTime)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcompletionTime, err := time.Parse(time.RFC3339, completionTimeStr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdelegation := types.NewUnbondingDelegation(\n\t\tmsg.DelegatorAddress,\n\t\tmsg.ValidatorAddress,\n\t\tmsg.Amount,\n\t\tcompletionTime,\n\t\ttx.Height,\n\t)\n\n\treturn &delegation, db.SaveUnbondingDelegations([]types.UnbondingDelegation{delegation})\n}", "func CalculateTotalPayout(delegatedContract DelegatedContract) DelegatedContract{\n for _, contract := range delegatedContract.Contracts{\n delegatedContract.TotalPayout = delegatedContract.TotalPayout + contract.NetPayout\n }\n return delegatedContract\n}", "func (_DelayedWithdrawal *DelayedWithdrawalTransactor) RenounceOwnership(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _DelayedWithdrawal.contract.Transact(opts, \"renounceOwnership\")\n}", "func (k msgServer) BeginRedelegate(goCtx context.Context, msg *types.MsgBeginRedelegate) (*types.MsgBeginRedelegateResponse, error) {\n\tctx := sdk.UnwrapSDKContext(goCtx)\n\n\tvalSrcAddr, err := sdk.ValAddressFromBech32(msg.ValidatorSrcAddress)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvalDstAddr, err := sdk.ValAddressFromBech32(msg.ValidatorDstAddress)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsrcValidator, found := k.GetValidator(ctx, valSrcAddr)\n\tif !found {\n\t\treturn nil, types.ErrNoValidatorFound\n\t}\n\tdstValidator, found := k.GetValidator(ctx, valDstAddr)\n\tif !found {\n\t\treturn nil, types.ErrBadRedelegationDst\n\t}\n\n\tdelegatorAddress, err := sdk.AccAddressFromBech32(msg.DelegatorAddress)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdelegation, found := k.GetDelegation(ctx, delegatorAddress, valSrcAddr)\n\tif !found {\n\t\treturn nil, status.Errorf(\n\t\t\tcodes.NotFound,\n\t\t\t\"delegation with delegator %s not found for validator %s\",\n\t\t\tmsg.DelegatorAddress, msg.ValidatorSrcAddress,\n\t\t)\n\t}\n\n\tsrcShares, err := k.ValidateUnbondAmount(ctx, delegatorAddress, valSrcAddr, msg.Amount.Amount)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdstShares, err := dstValidator.SharesFromTokensTruncated(msg.Amount.Amount)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// if this is a validator self-bond, the new liquid delegation cannot fall below the self-bond * bond factor\n\tif delegation.ValidatorBond {\n\t\tif err := k.SafelyDecreaseValidatorBond(ctx, &srcValidator, srcShares); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// If this delegation from a liquid staker, the delegation on the new validator\n\t// cannot exceed that validator's self-bond cap\n\t// The liquid shares from the source validator should get moved to the destination validator\n\tif k.DelegatorIsLiquidStaker(delegatorAddress) {\n\t\tif err := k.SafelyIncreaseValidatorLiquidShares(ctx, &dstValidator, dstShares); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif err := k.DecreaseValidatorLiquidShares(ctx, &srcValidator, srcShares); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tbondDenom := k.BondDenom(ctx)\n\tif msg.Amount.Denom != bondDenom {\n\t\treturn nil, sdkerrors.Wrapf(\n\t\t\tsdkerrors.ErrInvalidRequest, \"invalid coin denomination: got %s, expected %s\", msg.Amount.Denom, bondDenom,\n\t\t)\n\t}\n\n\tcompletionTime, err := k.BeginRedelegation(\n\t\tctx, delegatorAddress, valSrcAddr, valDstAddr, srcShares,\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif msg.Amount.Amount.IsInt64() {\n\t\tdefer func() {\n\t\t\ttelemetry.IncrCounter(1, types.ModuleName, \"redelegate\")\n\t\t\ttelemetry.SetGaugeWithLabels(\n\t\t\t\t[]string{\"tx\", \"msg\", msg.Type()},\n\t\t\t\tfloat32(msg.Amount.Amount.Int64()),\n\t\t\t\t[]metrics.Label{telemetry.NewLabel(\"denom\", msg.Amount.Denom)},\n\t\t\t)\n\t\t}()\n\t}\n\n\tctx.EventManager().EmitEvents(sdk.Events{\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeRedelegate,\n\t\t\tsdk.NewAttribute(types.AttributeKeySrcValidator, msg.ValidatorSrcAddress),\n\t\t\tsdk.NewAttribute(types.AttributeKeyDstValidator, msg.ValidatorDstAddress),\n\t\t\tsdk.NewAttribute(sdk.AttributeKeyAmount, msg.Amount.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyCompletionTime, completionTime.Format(time.RFC3339)),\n\t\t),\n\t})\n\n\treturn &types.MsgBeginRedelegateResponse{\n\t\tCompletionTime: completionTime,\n\t}, nil\n}", "func distributeDelegatorRewards(ctx contract.Context, cachedDelegations *CachedDposStorage, formerValidatorTotals map[string]loom.BigUInt, delegatorRewards map[string]*loom.BigUInt, distributedRewards *loom.BigUInt) (map[string]*loom.BigUInt, error) {\n\tnewDelegationTotals := make(map[string]*loom.BigUInt)\n\n\tcandidates, err := LoadCandidateList(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Initialize delegation totals with whitelist amounts\n\tfor _, candidate := range candidates {\n\t\tstatistic, _ := GetStatistic(ctx, loom.UnmarshalAddressPB(candidate.Address))\n\n\t\tif statistic != nil && statistic.WhitelistAmount != nil && !common.IsZero(statistic.WhitelistAmount.Value) {\n\t\t\tvalidatorKey := loom.UnmarshalAddressPB(statistic.Address).String()\n\t\t\tamount := calculateWeightedWhitelistAmount(*statistic)\n\t\t\tnewDelegationTotals[validatorKey] = &amount\n\t\t}\n\t}\n\n\tdelegations, err := cachedDelegations.loadDelegationList(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar currentDelegations = make(DelegationList, len(delegations))\n\tcopy(currentDelegations, delegations)\n\tfor _, d := range currentDelegations {\n\t\tdelegation, err := GetDelegation(ctx, d.Index, *d.Validator, *d.Delegator)\n\t\tif err == contract.ErrNotFound {\n\t\t\tcontinue\n\t\t} else if err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tvalidatorKey := loom.UnmarshalAddressPB(delegation.Validator).String()\n\n\t\t// Do not distribute rewards to delegators of the Limbo validator\n\t\t// NOTE: because all delegations are sorted in reverse index order, the\n\t\t// 0-index delegation (for rewards) is handled last. Therefore, all\n\t\t// increases to reward delegations will be reflected in newDelegation\n\t\t// totals that are computed at the end of this for loop. (We do this to\n\t\t// avoid looping over all delegations twice)\n\t\tif loom.UnmarshalAddressPB(delegation.Validator).Compare(LimboValidatorAddress(ctx)) != 0 {\n\t\t\t// allocating validator distributions to delegators\n\t\t\t// based on former validator delegation totals\n\t\t\tdelegationTotal := formerValidatorTotals[validatorKey]\n\t\t\trewardsTotal := delegatorRewards[validatorKey]\n\t\t\tif rewardsTotal != nil {\n\t\t\t\tweightedDelegation := calculateWeightedDelegationAmount(*delegation)\n\t\t\t\tdelegatorDistribution := calculateShare(weightedDelegation, delegationTotal, *rewardsTotal)\n\t\t\t\t// increase a delegator's distribution\n\t\t\t\tdistributedRewards.Add(distributedRewards, &delegatorDistribution)\n\t\t\t\tcachedDelegations.IncreaseRewardDelegation(ctx, delegation.Validator, delegation.Delegator, delegatorDistribution)\n\n\t\t\t\t// If the reward delegation is updated by the\n\t\t\t\t// IncreaseRewardDelegation command, we must be sure to use this\n\t\t\t\t// updated version in the rest of the loop. No other delegations\n\t\t\t\t// (non-rewards) have the possibility of being updated outside\n\t\t\t\t// of this loop.\n\t\t\t\tif ctx.FeatureEnabled(features.DPOSVersion3_1, false) && d.Index == REWARD_DELEGATION_INDEX {\n\t\t\t\t\tdelegation, err = GetDelegation(ctx, d.Index, *d.Validator, *d.Delegator)\n\t\t\t\t\tif err == contract.ErrNotFound {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t} else if err != nil {\n\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tupdatedAmount := common.BigZero()\n\t\tif delegation.State == BONDING {\n\t\t\tupdatedAmount.Add(&delegation.Amount.Value, &delegation.UpdateAmount.Value)\n\t\t\tdelegation.Amount = &types.BigUInt{Value: *updatedAmount}\n\t\t} else if delegation.State == UNBONDING {\n\t\t\tupdatedAmount.Sub(&delegation.Amount.Value, &delegation.UpdateAmount.Value)\n\t\t\tdelegation.Amount = &types.BigUInt{Value: *updatedAmount}\n\t\t\tcoin, err := loadCoin(ctx)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\terr = coin.Transfer(loom.UnmarshalAddressPB(delegation.Delegator), &delegation.UpdateAmount.Value)\n\t\t\tif err != nil {\n\t\t\t\ttransferFromErr := fmt.Sprintf(\"Failed coin Transfer - distributeDelegatorRewards, %v, %s\", delegation.Delegator.String(), delegation.UpdateAmount.Value.String())\n\t\t\t\treturn nil, logDposError(ctx, err, transferFromErr)\n\t\t\t}\n\t\t} else if delegation.State == REDELEGATING {\n\t\t\tif err = cachedDelegations.DeleteDelegation(ctx, delegation); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tdelegation.Validator = delegation.UpdateValidator\n\t\t\tdelegation.Amount = delegation.UpdateAmount\n\t\t\tdelegation.LocktimeTier = delegation.UpdateLocktimeTier\n\n\t\t\tindex, err := GetNextDelegationIndex(ctx, *delegation.Validator, *delegation.Delegator)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tdelegation.Index = index\n\n\t\t\tvalidatorKey = loom.UnmarshalAddressPB(delegation.Validator).String()\n\t\t}\n\n\t\t// Delete any delegation whose full amount has been unbonded. In all\n\t\t// other cases, update the delegation state to BONDED and reset its\n\t\t// UpdateAmount\n\t\tif common.IsZero(delegation.Amount.Value) && delegation.State == UNBONDING {\n\t\t\tif err := cachedDelegations.DeleteDelegation(ctx, delegation); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t} else {\n\t\t\t// After a delegation update, zero out UpdateAmount\n\t\t\tdelegation.UpdateAmount = loom.BigZeroPB()\n\t\t\tdelegation.State = BONDED\n\n\t\t\tresetDelegationIfExpired(ctx, delegation)\n\t\t\tif err := cachedDelegations.SetDelegation(ctx, delegation); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\n\t\t// Calculate delegation totals for all validators except the Limbo\n\t\t// validator\n\t\tif loom.UnmarshalAddressPB(delegation.Validator).Compare(LimboValidatorAddress(ctx)) != 0 {\n\t\t\tnewTotal := common.BigZero()\n\t\t\tweightedDelegation := calculateWeightedDelegationAmount(*delegation)\n\t\t\tnewTotal.Add(newTotal, &weightedDelegation)\n\t\t\tif newDelegationTotals[validatorKey] != nil {\n\t\t\t\tnewTotal.Add(newTotal, newDelegationTotals[validatorKey])\n\t\t\t}\n\t\t\tnewDelegationTotals[validatorKey] = newTotal\n\t\t}\n\t}\n\n\treturn newDelegationTotals, nil\n}", "func (fc *appendFlowControl) debit() {\n\tvar d = min64(fc.balance, fc.charge)\n\tfc.balance -= d\n\tfc.charge -= d\n\tfc.spent = min64(fc.spent+d, fc.minRate) // Add |d| bytes to |spent|, capping at |minRate|.\n\n\tif fc.maxRate == 0 {\n\t\t// |balance| is effectively infinite.\n\t\tfc.spent = min64(fc.spent+fc.charge, fc.minRate)\n\t\tfc.charge = 0\n\t}\n}", "func Transfer(previousTxId merkle.Digest, transferTxId merkle.Digest, transferBlockNumber uint64, currentOwner *account.Account, newOwner *account.Account) {\n\n\t// ensure single threaded\n\ttoLock.Lock()\n\tdefer toLock.Unlock()\n\n\t// get count for current owner record\n\tdKey := append(currentOwner.Bytes(), previousTxId[:]...)\n\tdCount := storage.Pool.OwnerDigest.Get(dKey)\n\tif nil == dCount {\n\t\tlogger.Criticalf(\"ownership.Transfer: dKey: %x\", dKey)\n\t\tlogger.Criticalf(\"ownership.Transfer: block number: %d\", transferBlockNumber)\n\t\tlogger.Criticalf(\"ownership.Transfer: previous tx id: %#v\", previousTxId)\n\t\tlogger.Criticalf(\"ownership.Transfer: transfer tx id: %#v\", transferTxId)\n\t\tlogger.Criticalf(\"ownership.Transfer: current owner: %x %v\", currentOwner.Bytes(), currentOwner)\n\t\tif nil != newOwner {\n\t\t\tlogger.Criticalf(\"ownership.Transfer: new owner: %x %v\", newOwner.Bytes(), newOwner)\n\t\t}\n\n\t\t// ow, err := ListBitmarksFor(currentOwner, 0, 999)\n\t\t// if nil != err {\n\t\t// \tlogger.Criticalf(\"lbf: error: %s\", err)\n\t\t// } else {\n\t\t// \tlogger.Criticalf(\"lbf: %#v\", ow)\n\t\t// }\n\n\t\tlogger.Panic(\"ownership.Transfer: OwnerDigest database corrupt\")\n\t}\n\n\t// delete the current owners records\n\toKey := append(currentOwner.Bytes(), dCount...)\n\townerData := storage.Pool.Ownership.Get(oKey)\n\tif nil == ownerData {\n\t\tlogger.Criticalf(\"ownership.Transfer: no ownerData for key: %x\", oKey)\n\t\tlogger.Panic(\"ownership.Transfer: Ownership database corrupt\")\n\t}\n\tstorage.Pool.Ownership.Delete(oKey)\n\tstorage.Pool.OwnerDigest.Delete(dKey)\n\n\t// if no new owner only above delete was needed\n\tif nil == newOwner {\n\t\treturn\n\t}\n\n\tcopy(ownerData[TxIdStart:TxIdFinish], transferTxId[:])\n\tbinary.BigEndian.PutUint64(ownerData[TransferBlockNumberStart:TransferBlockNumberFinish], transferBlockNumber)\n\tcreate(transferTxId, ownerData, newOwner)\n}", "func (_DelegationController *DelegationControllerFilterer) FilterUndelegationRequested(opts *bind.FilterOpts) (*DelegationControllerUndelegationRequestedIterator, error) {\n\n\tlogs, sub, err := _DelegationController.contract.FilterLogs(opts, \"UndelegationRequested\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &DelegationControllerUndelegationRequestedIterator{contract: _DelegationController.contract, event: \"UndelegationRequested\", logs: logs, sub: sub}, nil\n}", "func DelegatorSharesInvariant(k Keeper) sdk.Invariant {\n\treturn func(ctx sdk.Context) (string, bool) {\n\t\tvar (\n\t\t\tmsg string\n\t\t\tbroken bool\n\t\t)\n\n\t\tdefis := k.GetAllDefis(ctx)\n\t\tfor _, defi := range defis {\n\t\t\tdefiTotalDelShares := defi.GetDelegatorShares()\n\t\t\ttotalDelShares := sdk.ZeroDec()\n\n\t\t\tdelegations := k.GetDefiDelegations(ctx, defi.GetOperator())\n\t\t\tfor _, delegation := range delegations {\n\t\t\t\ttotalDelShares = totalDelShares.Add(delegation.Shares)\n\t\t\t}\n\n\t\t\tif !defiTotalDelShares.Equal(totalDelShares) {\n\t\t\t\tbroken = true\n\t\t\t\tmsg += fmt.Sprintf(\"broken delegator shares invariance:\\n\"+\n\t\t\t\t\t\"\\tdefi.DelegatorShares: %v\\n\"+\n\t\t\t\t\t\"\\tsum of Delegator.Shares: %v\\n\", defiTotalDelShares, totalDelShares)\n\t\t\t}\n\t\t}\n\n\t\treturn sdk.FormatInvariant(types.ModuleName, \"delegator shares\", msg), broken\n\t}\n}", "func (this *Twitter) Unfollow(followerId int, followeeId int) {\n \n}", "func (_L1Block *L1BlockCaller) DEPOSITORACCOUNT(opts *bind.CallOpts) (common.Address, error) {\n\tvar out []interface{}\n\terr := _L1Block.contract.Call(opts, &out, \"DEPOSITOR_ACCOUNT\")\n\n\tif err != nil {\n\t\treturn *new(common.Address), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address)\n\n\treturn out0, err\n\n}", "func (_DelegationController *DelegationControllerFilterer) WatchUndelegationRequested(opts *bind.WatchOpts, sink chan<- *DelegationControllerUndelegationRequested) (event.Subscription, error) {\n\n\tlogs, sub, err := _DelegationController.contract.WatchLogs(opts, \"UndelegationRequested\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn event.NewSubscription(func(quit <-chan struct{}) error {\n\t\tdefer sub.Unsubscribe()\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase log := <-logs:\n\t\t\t\t// New log arrived, parse the event and forward to the user\n\t\t\t\tevent := new(DelegationControllerUndelegationRequested)\n\t\t\t\tif err := _DelegationController.contract.UnpackLog(event, \"UndelegationRequested\", log); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tevent.Raw = log\n\n\t\t\t\tselect {\n\t\t\t\tcase sink <- event:\n\t\t\t\tcase err := <-sub.Err():\n\t\t\t\t\treturn err\n\t\t\t\tcase <-quit:\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\tcase err := <-sub.Err():\n\t\t\t\treturn err\n\t\t\tcase <-quit:\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t}), nil\n}", "func unFollow(e *event) {\n\tif fMap, ok := followers[e.to]; ok {\n\t\tdelete(fMap, e.from)\n\t}\n}", "func (_FeeCurrencyWhitelist *FeeCurrencyWhitelistSession) RenounceOwnership() (*types.Transaction, error) {\n\treturn _FeeCurrencyWhitelist.Contract.RenounceOwnership(&_FeeCurrencyWhitelist.TransactOpts)\n}", "func (w *xcWallet) RegisterUnspent(live uint64) {\n\tbonder, ok := w.Wallet.(asset.Bonder)\n\tif !ok {\n\t\treturn\n\t}\n\tbonder.RegisterUnspent(live)\n}", "func (sc stakingClient) UnbindProxy(fromInfo keys.Info, passWd, memo string, accNum, seqNum uint64) (\n\tresp sdk.TxResponse, err error) {\n\tif err = params.CheckKeyParams(fromInfo, passWd); err != nil {\n\t\treturn\n\t}\n\n\tmsg := types.NewMsgUnbindProxy(fromInfo.GetAddress())\n\n\treturn sc.BuildAndBroadcast(fromInfo.GetName(), passWd, memo, []sdk.Msg{msg}, accNum, seqNum)\n\n}", "func (_DelegationController *DelegationControllerSession) Delegate(validatorId *big.Int, amount *big.Int, delegationPeriod *big.Int, info string) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.Delegate(&_DelegationController.TransactOpts, validatorId, amount, delegationPeriod, info)\n}", "func (o *GetStakingDelegatorsDelegatorAddrUnbondingDelegationsParams) SetDelegatorAddr(delegatorAddr string) {\n\to.DelegatorAddr = delegatorAddr\n}", "func (_L1Block *L1BlockCallerSession) DEPOSITORACCOUNT() (common.Address, error) {\n\treturn _L1Block.Contract.DEPOSITORACCOUNT(&_L1Block.CallOpts)\n}", "func (_FeeCurrencyWhitelist *FeeCurrencyWhitelistTransactorSession) RenounceOwnership() (*types.Transaction, error) {\n\treturn _FeeCurrencyWhitelist.Contract.RenounceOwnership(&_FeeCurrencyWhitelist.TransactOpts)\n}", "func (k Keeper) UndelegateCoinsFromModuleToAccount(\n\tctx sdk.Context, senderModule string, recipientAcc types.AccountID, amt Coins,\n) error {\n\n\tacc := k.GetModuleAccount(ctx, senderModule)\n\tif acc == nil {\n\t\tpanic(sdkerrors.Wrapf(sdkerrors.ErrUnknownAddress, \"module account %s does not exist\", senderModule))\n\t}\n\n\tif !acc.HasPermission(types.Staking) {\n\t\tpanic(sdkerrors.Wrapf(sdkerrors.ErrUnauthorized, \"module account %s does not have permissions to undelegate coins\", senderModule))\n\t}\n\n\t// Delegate will first send coins to ModuleAccountID\n\tif err := k.bk.SendCoinPower(ctx, acc.GetID(), recipientAcc, amt); err != nil {\n\t\treturn sdkerrors.Wrapf(err,\n\t\t\t\"UndelegateCoinsFromModuleToAccount %s by %s\", recipientAcc, amt.String())\n\t}\n\n\treturn nil\n}", "func (acc *Account) delegationsTotal() (amount *big.Int, inWithdraw *big.Int, rewards *big.Int, err error) {\n\t// pull all the delegations of the account\n\tlist, err := repository.R().DelegationsByAddressAll(&acc.Address)\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\n\t// prep containers for calculation and loop all delegations found\n\tamount = new(big.Int)\n\trewards = new(big.Int)\n\tinWithdraw = new(big.Int)\n\tfor _, dlg := range list {\n\t\t// any active delegated amount?\n\t\tif 0 < dlg.AmountDelegated.ToInt().Uint64() {\n\t\t\tamount = new(big.Int).Add(amount, dlg.AmountDelegated.ToInt())\n\t\t}\n\n\t\t// get pending rewards for this delegation (can be stashed)\n\t\trw, err := repository.R().PendingRewards(&acc.Address, dlg.ToStakerId)\n\t\tif err != nil {\n\t\t\treturn nil, nil, nil, err\n\t\t}\n\n\t\t// any rewards?\n\t\tif 0 < rw.Amount.ToInt().Uint64() {\n\t\t\trewards = new(big.Int).Add(rewards, rw.Amount.ToInt())\n\t\t}\n\n\t\t// get pending withdrawals\n\t\twd, err := repository.R().WithdrawRequestsPendingTotal(&acc.Address, dlg.ToStakerId)\n\t\tif err != nil {\n\t\t\treturn nil, nil, nil, err\n\t\t}\n\n\t\t// add pending withdrawals value\n\t\tif 0 < wd.Uint64() {\n\t\t\tinWithdraw = new(big.Int).Add(inWithdraw, wd)\n\t\t}\n\t}\n\n\treturn amount, rewards, inWithdraw, nil\n}", "func (o OfflineNotaryRepository) RemoveDelegationKeys(data.RoleName, []string) error {\n\treturn nil\n}", "func (_DelegationController *DelegationControllerTransactorSession) Delegate(validatorId *big.Int, amount *big.Int, delegationPeriod *big.Int, info string) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.Delegate(&_DelegationController.TransactOpts, validatorId, amount, delegationPeriod, info)\n}", "func transfer(\n\ttrx storage.Transaction,\n\tpreviousTxId merkle.Digest,\n\ttransferTxId merkle.Digest,\n\ttransferBlockNumber uint64,\n\n\tcurrentOwner *account.Account,\n\tnewOwner *account.Account,\n\tquantity uint64,\n) {\n\t// get count for current owner record\n\tdKey := append(currentOwner.Bytes(), previousTxId[:]...)\n\tdCount := trx.Get(storage.Pool.OwnerTxIndex, dKey)\n\tif nil == dCount {\n\t\tlogger.Criticalf(\"ownership.Transfer: dKey: %x\", dKey)\n\t\tlogger.Criticalf(\"ownership.Transfer: block number: %d\", transferBlockNumber)\n\t\tlogger.Criticalf(\"ownership.Transfer: previous tx id: %#v\", previousTxId)\n\t\tlogger.Criticalf(\"ownership.Transfer: transfer tx id: %#v\", transferTxId)\n\t\tlogger.Criticalf(\"ownership.Transfer: current owner: %x %v\", currentOwner.Bytes(), currentOwner)\n\t\tif nil != newOwner {\n\t\t\tlogger.Criticalf(\"ownership.Transfer: new owner: %x %v\", newOwner.Bytes(), newOwner)\n\t\t}\n\n\t\t// ow, err := listBitmarksFor(currentOwner, 0, 999)\n\t\t// if nil != err {\n\t\t// \tlogger.Criticalf(\"lbf: error: %s\", err)\n\t\t// } else {\n\t\t// \tlogger.Criticalf(\"lbf: %#v\", ow)\n\t\t// }\n\n\t\tlogger.Panic(\"ownership.Transfer: OwnerTxIndex database corrupt\")\n\t}\n\n\t// delete the current owners records\n\townerData, err := GetOwnerData(trx, previousTxId, storage.Pool.OwnerData)\n\tif nil != err {\n\t\tlogger.Criticalf(\"ownership.Transfer: invalid owner data for tx id: %s error: %s\", previousTxId, err)\n\t\tlogger.Panic(\"ownership.Transfer: Ownership database corrupt\")\n\t}\n\n\toKey := append(currentOwner.Bytes(), dCount...)\n\ttrx.Delete(storage.Pool.OwnerList, oKey)\n\ttrx.Delete(storage.Pool.OwnerTxIndex, dKey)\n\n\t// and the old owner data\n\ttrx.Delete(storage.Pool.OwnerData, previousTxId[:])\n\n\t// if no new owner only above delete was needed\n\tif nil == newOwner && 0 == quantity {\n\t\treturn\n\t}\n\n\tswitch ownerData := ownerData.(type) {\n\n\tcase *AssetOwnerData:\n\n\t\t// create a share - only from an asset\n\t\tif 0 != quantity {\n\n\t\t\t// convert initial quantity to 8 byte big endian\n\t\t\tquantityBytes := make([]byte, 8)\n\t\t\tbinary.BigEndian.PutUint64(quantityBytes, quantity)\n\n\t\t\t// the ID of the share is the issue id of the bitmark\n\t\t\tshareId := ownerData.issueTxId\n\n\t\t\t// the total quantity of this type of share\n\t\t\tshareData := append(quantityBytes, transferTxId[:]...)\n\t\t\ttrx.Put(storage.Pool.Shares, shareId[:], shareData, []byte{})\n\n\t\t\t// initially total quantity goes to the creator\n\t\t\tfKey := append(currentOwner.Bytes(), shareId[:]...)\n\t\t\ttrx.Put(storage.Pool.ShareQuantity, fKey, quantityBytes, []byte{})\n\n\t\t\t// convert to share and update\n\t\t\tnewOwnerData := ShareOwnerData{\n\t\t\t\ttransferBlockNumber: transferBlockNumber,\n\t\t\t\tissueTxId: ownerData.issueTxId,\n\t\t\t\tissueBlockNumber: ownerData.issueBlockNumber,\n\t\t\t\tassetId: ownerData.assetId,\n\t\t\t}\n\t\t\tcreate(trx, transferTxId, newOwnerData, currentOwner)\n\t\t\treturn\n\t\t}\n\n\t\t// otherwise create new ownership record\n\t\townerData.transferBlockNumber = transferBlockNumber\n\t\tcreate(trx, transferTxId, ownerData, newOwner)\n\n\tcase *BlockOwnerData:\n\t\t// create a share - only from an asset\n\t\tif 0 != quantity {\n\n\t\t\t// panic if not an asset (this should have been checked earlier)\n\t\t\tlogger.Criticalf(\"ownership.Transfer: ownerData for key: %x is not an asset\", oKey)\n\t\t\tlogger.Panic(\"ownership.Transfer: Ownership database corrupt\")\n\t\t}\n\n\t\t// otherwise create new ownership record\n\t\townerData.transferBlockNumber = transferBlockNumber\n\t\tcreate(trx, transferTxId, ownerData, newOwner)\n\n\tcase *ShareOwnerData:\n\n\t\t// create a share - only from an asset\n\t\tif 0 != quantity {\n\n\t\t\t// panic if not an asset (this should have been checked earlier)\n\t\t\tlogger.Criticalf(\"ownership.Transfer: ownerData for key: %x is not an asset\", oKey)\n\t\t\tlogger.Panic(\"ownership.Transfer: Ownership database corrupt\")\n\t\t}\n\n\t\t// Note: only called on delete (block/store.go prevents share back to asset)\n\n\t\t// convert to transfer and update\n\t\tnewOwnerData := AssetOwnerData{\n\t\t\ttransferBlockNumber: transferBlockNumber,\n\t\t\tissueTxId: ownerData.issueTxId,\n\t\t\tissueBlockNumber: ownerData.issueBlockNumber,\n\t\t\tassetId: ownerData.assetId,\n\t\t}\n\t\tcreate(trx, transferTxId, newOwnerData, currentOwner)\n\n\tdefault:\n\t\t// panic if not an asset (this should have been checked earlier)\n\t\tlogger.Criticalf(\"ownership.Transfer: unhandled owner data type: %+v\", ownerData)\n\t\tlogger.Panic(\"ownership.Transfer: missing owner data handler\")\n\t}\n}", "func Unfollow(whoId, whomId int) int {\n\tif !misc.IsIdValid(whomId) {\n\t\tlog.Println(\"User id is not correct\", whomId)\n\t\treturn misc.NoElement\n\t}\n\n\tif whoId == whomId {\n\t\tlog.Println(\"can't follow yourself\")\n\t\treturn misc.FollowYourself\n\t}\n\n\tsqlResult, err := psql.Db.Exec(`\n\t\tDELETE FROM followers\n\t\tWHERE who_id = $1 AND whom_id = $2`, whoId, whomId)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn misc.NothingToReport\n\t}\n\n\tif err, code := psql.IsAffectedOneRow(sqlResult); err != nil {\n\t\treturn code\n\t}\n\n\tsqlResult, err = psql.Db.Exec(`\n\t\tUPDATE users\n\t\tSET followers_num = followers_num - 1\n\t\tWHERE id = $1`, whomId)\n\tif err, code := psql.CheckSpecificDriverErrors(err); err != nil {\n\t\tlog.Println(err)\n\t\treturn code\n\t}\n\n\tif err, code := psql.IsAffectedOneRow(sqlResult); err != nil {\n\t\treturn code\n\t}\n\n\tsqlResult, err = psql.Db.Exec(`\n\t\tUPDATE users\n\t\tSET following_num = following_num - 1\n\t\tWHERE id = $1`, whoId)\n\tif err, code := psql.CheckSpecificDriverErrors(err); err != nil {\n\t\tlog.Println(err)\n\t\treturn code\n\t}\n\n\tif err, code := psql.IsAffectedOneRow(sqlResult); err != nil {\n\t\treturn code\n\t}\n\n\treturn misc.NothingToReport\n}", "func (broadcast *Broadcast) DelegatorWithdraw(ctx context.Context, delegator, voter, amount,\n\tprivKeyHex string, seq int64) (*model.BroadcastResponse, error) {\n\tmsg := model.DelegatorWithdrawMsg{\n\t\tDelegator: delegator,\n\t\tVoter: voter,\n\t\tAmount: amount,\n\t}\n\treturn broadcast.broadcastTransaction(ctx, msg, privKeyHex, seq, \"\", false)\n}", "func (k Keeper) UndelegateCoinsFromModuleToAccount(\n\tctx sdk.Context, senderModule string, recipientAddr sdk.AccAddress, amt sdk.Coins,\n) error {\n\n\tacc := k.GetModuleAccount(ctx, senderModule)\n\tif acc == nil {\n\t\tpanic(sdkerrors.Wrapf(sdkerrors.ErrUnknownAddress, \"module account %s does not exist\", senderModule))\n\t}\n\n\tif !acc.HasPermission(types.Staking) {\n\t\tpanic(sdkerrors.Wrapf(sdkerrors.ErrUnauthorized, \"module account %s does not have permissions to undelegate coins\", senderModule))\n\t}\n\n\treturn k.bk.UndelegateCoins(ctx, acc.GetAddress(), recipientAddr, amt)\n}", "func unfollowDir (x, y *int, direction dirTable, lastDir int) {\n setCell(*x , *y , tried, update, 0, 0)\n setCell(*x + direction.x/2, *y + direction.y/2, tried, update, 0, 0)\n decInt(&pathLen)\n if (lastDir != direction.heading) {\n lastDir = direction.heading\n decInt(&turnCnt)\n }\n}", "func (_DelayedWithdrawal *DelayedWithdrawalSession) RenounceOwnership() (*types.Transaction, error) {\n\treturn _DelayedWithdrawal.Contract.RenounceOwnership(&_DelayedWithdrawal.TransactOpts)\n}", "func (mr *MockRepoSyncInfoKeeperMockRecorder) UnTrack(repos interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"UnTrack\", reflect.TypeOf((*MockRepoSyncInfoKeeper)(nil).UnTrack), repos)\n}", "func (_DelegationController *DelegationControllerTransactor) Delegate(opts *bind.TransactOpts, validatorId *big.Int, amount *big.Int, delegationPeriod *big.Int, info string) (*types.Transaction, error) {\n\treturn _DelegationController.contract.Transact(opts, \"delegate\", validatorId, amount, delegationPeriod, info)\n}", "func (rp RemovePeer) Influence(opInfluence OpInfluence, region *core.RegionInfo) {\n\tfrom := opInfluence.GetStoreInfluence(rp.FromStore)\n\n\tfrom.RegionSize -= region.ApproximateSize\n\tfrom.RegionCount--\n}", "func (_DelayedWithdrawal *DelayedWithdrawalTransactorSession) RenounceOwnership() (*types.Transaction, error) {\n\treturn _DelayedWithdrawal.Contract.RenounceOwnership(&_DelayedWithdrawal.TransactOpts)\n}", "func (_DelegationController *DelegationControllerTransactor) GetAndUpdateForbiddenForDelegationAmount(opts *bind.TransactOpts, wallet common.Address) (*types.Transaction, error) {\n\treturn _DelegationController.contract.Transact(opts, \"getAndUpdateForbiddenForDelegationAmount\", wallet)\n}", "func NewGetStakingDelegatorsDelegatorAddrUnbondingDelegationsParamsWithTimeout(timeout time.Duration) *GetStakingDelegatorsDelegatorAddrUnbondingDelegationsParams {\n\tvar ()\n\treturn &GetStakingDelegatorsDelegatorAddrUnbondingDelegationsParams{\n\n\t\ttimeout: timeout,\n\t}\n}", "func (broadcast *Broadcast) Delegate(ctx context.Context, delegator, voter, amount,\n\tprivKeyHex string, seq int64) (*model.BroadcastResponse, error) {\n\tmsg := model.DelegateMsg{\n\t\tDelegator: delegator,\n\t\tVoter: voter,\n\t\tAmount: amount,\n\t}\n\treturn broadcast.broadcastTransaction(ctx, msg, privKeyHex, seq, \"\", false)\n}" ]
[ "0.67113245", "0.59720033", "0.5943587", "0.59297115", "0.5854596", "0.5854328", "0.57884055", "0.5690635", "0.5682177", "0.5627405", "0.5558996", "0.534974", "0.5342968", "0.5292748", "0.52545184", "0.5147454", "0.5006151", "0.4952675", "0.4936225", "0.48720354", "0.4870784", "0.48670223", "0.47256628", "0.47146156", "0.47067925", "0.46748567", "0.46712703", "0.46707776", "0.46643007", "0.46359107", "0.46349537", "0.46253216", "0.45746884", "0.4565491", "0.4523303", "0.45191628", "0.45150453", "0.44600445", "0.44479662", "0.44478872", "0.4403414", "0.44007167", "0.43890938", "0.43839225", "0.4364061", "0.43613672", "0.43492237", "0.43406135", "0.43334723", "0.43220583", "0.43043453", "0.43019706", "0.42720184", "0.42690313", "0.42660734", "0.4265602", "0.42634234", "0.42522293", "0.42479384", "0.42413807", "0.4192106", "0.41876116", "0.4165924", "0.41625917", "0.4141422", "0.413056", "0.41188025", "0.4116411", "0.41112208", "0.4110812", "0.41069072", "0.41013372", "0.40991646", "0.40979236", "0.40938875", "0.40888253", "0.40772834", "0.40756813", "0.4067843", "0.4066682", "0.4065816", "0.40422675", "0.40378112", "0.4029262", "0.40289792", "0.40243962", "0.40233797", "0.4021465", "0.39924443", "0.39891014", "0.39760143", "0.3974541", "0.39710116", "0.39617026", "0.3958939", "0.39553958", "0.39551508", "0.3945829", "0.3935983", "0.3931791" ]
0.8533345
0
GetOriginalVesting returns a vesting account's original vesting amount
func (bva BaseVestingAccount) GetOriginalVesting() sdk.Coins { return bva.OriginalVesting }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (plva PermanentLockedAccount) GetVestingCoins(_ time.Time) sdk.Coins {\n\treturn plva.OriginalVesting\n}", "func (va ClawbackVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn va.OriginalVesting.Sub(va.GetVestedCoins(blockTime))\n}", "func (dva DelayedVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn dva.OriginalVesting.Sub(dva.GetVestedCoins(blockTime))\n}", "func (vva ValidatorVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn vva.OriginalVesting.Sub(vva.GetVestedCoins(blockTime))\n}", "func (pva PeriodicVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn pva.OriginalVesting.Sub(pva.GetVestedCoins(blockTime))\n}", "func (_TokenVesting *TokenVestingCaller) VestedAmount(opts *bind.CallOpts, _token common.Address) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _TokenVesting.contract.Call(opts, out, \"vestedAmount\", _token)\n\treturn *ret0, err\n}", "func (_TokenVesting *TokenVestingCallerSession) VestedAmount(_token common.Address) (*big.Int, error) {\n\treturn _TokenVesting.Contract.VestedAmount(&_TokenVesting.CallOpts, _token)\n}", "func (cva ContinuousVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn cva.OriginalVesting.Sub(cva.GetVestedCoins(blockTime))\n}", "func (bva BaseVestingAccount) GetDelegatedVesting() sdk.Coins {\n\treturn bva.DelegatedVesting\n}", "func (_TokenVesting *TokenVestingSession) VestedAmount(_token common.Address) (*big.Int, error) {\n\treturn _TokenVesting.Contract.VestedAmount(&_TokenVesting.CallOpts, _token)\n}", "func (o *GetRecipeInformation200ResponseExtendedIngredientsInner) GetOriginal() string {\n\tif o == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\n\treturn o.Original\n}", "func (dva DelayedVestingAccount) GetVestedCoins(blockTime time.Time) sdk.Coins {\n\tif blockTime.Unix() >= dva.EndTime {\n\t\treturn dva.OriginalVesting\n\t}\n\n\treturn nil\n}", "func (m *AgedAccountsPayable) GetCurrentAmount()(*float64) {\n val, err := m.GetBackingStore().Get(\"currentAmount\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*float64)\n }\n return nil\n}", "func (va ClawbackVestingAccount) GetVestedOnly(blockTime time.Time) sdk.Coins {\n\treturn ReadSchedule(va.StartTime, va.EndTime, va.VestingPeriods, va.OriginalVesting, blockTime.Unix())\n}", "func (ds *DepositToStake) Amount() *big.Int { return ds.amount }", "func (o GoogleCloudRetailV2alphaPriceInfoResponseOutput) OriginalPrice() pulumi.Float64Output {\n\treturn o.ApplyT(func(v GoogleCloudRetailV2alphaPriceInfoResponse) float64 { return v.OriginalPrice }).(pulumi.Float64Output)\n}", "func (bva BaseVestingAccount) LockedCoinsFromVesting(vestingCoins sdk.Coins) sdk.Coins {\n\tlockedCoins := vestingCoins.Sub(vestingCoins.Min(bva.DelegatedVesting))\n\tif lockedCoins == nil {\n\t\treturn sdk.Coins{}\n\t}\n\treturn lockedCoins\n}", "func (dtv *DailyTrxVolume) Amount() hexutil.Big {\n\tval := new(big.Int).Mul(new(big.Int).SetInt64(dtv.DailyTrxVolume.AmountAdjusted), types.TransactionDecimalsCorrection)\n\treturn hexutil.Big(*val)\n}", "func (ns *Namespace) GetOriginalObject(gvk schema.GroupVersionKind, nm string) *unstructured.Unstructured {\n\treturn ns.originalObjects[gvk][nm]\n}", "func (o *GetRecipeInformation200ResponseExtendedIngredientsInner) GetOriginalName() string {\n\tif o == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\n\treturn o.OriginalName\n}", "func (va ClawbackVestingAccount) GetVestingPeriods() Periods {\n\treturn va.VestingPeriods\n}", "func (o GoogleCloudRetailV2alphaPriceInfoOutput) OriginalPrice() pulumi.Float64PtrOutput {\n\treturn o.ApplyT(func(v GoogleCloudRetailV2alphaPriceInfo) *float64 { return v.OriginalPrice }).(pulumi.Float64PtrOutput)\n}", "func (m *EquipmentrentalMutation) OldRENTALAMOUNT(ctx context.Context) (v int, err error) {\n\tif !m.op.Is(OpUpdateOne) {\n\t\treturn v, fmt.Errorf(\"OldRENTALAMOUNT is allowed only on UpdateOne operations\")\n\t}\n\tif m.id == nil || m.oldValue == nil {\n\t\treturn v, fmt.Errorf(\"OldRENTALAMOUNT requires an ID field in the mutation\")\n\t}\n\toldValue, err := m.oldValue(ctx)\n\tif err != nil {\n\t\treturn v, fmt.Errorf(\"querying old value for OldRENTALAMOUNT: %w\", err)\n\t}\n\treturn oldValue.RENTALAMOUNT, nil\n}", "func (o *GetRecipeInformation200ResponseExtendedIngredientsInner) GetAmount() float32 {\n\tif o == nil {\n\t\tvar ret float32\n\t\treturn ret\n\t}\n\n\treturn o.Amount\n}", "func (cva ContinuousVestingAccount) GetVestedCoins(blockTime time.Time) sdk.Coins {\n\tvar vestedCoins sdk.Coins\n\n\t// We must handle the case where the start time for a vesting account has\n\t// been set into the future or when the start of the chain is not exactly\n\t// known.\n\tif blockTime.Unix() <= cva.StartTime {\n\t\treturn vestedCoins\n\t} else if blockTime.Unix() >= cva.EndTime {\n\t\treturn cva.OriginalVesting\n\t}\n\n\t// calculate the vesting scalar\n\tx := blockTime.Unix() - cva.StartTime\n\ty := cva.EndTime - cva.StartTime\n\ts := sdk.NewDec(x).Quo(sdk.NewDec(y))\n\n\tfor _, ovc := range cva.OriginalVesting {\n\t\tvestedAmt := ovc.Amount.ToDec().Mul(s).RoundInt()\n\t\tvestedCoins = append(vestedCoins, sdk.NewCoin(ovc.Denom, vestedAmt))\n\t}\n\n\treturn vestedCoins\n}", "func (service *StorageAccountsTableService) OriginalGVK() *schema.GroupVersionKind {\n\treturn &schema.GroupVersionKind{\n\t\tGroup: GroupVersion.Group,\n\t\tVersion: service.Spec.OriginalVersion,\n\t\tKind: \"StorageAccountsTableService\",\n\t}\n}", "func (o *GetRecipeInformation200ResponseExtendedIngredientsInner) SetOriginal(v string) {\n\to.Original = v\n}", "func (o GoogleCloudRetailV2alphaPriceInfoPtrOutput) OriginalPrice() pulumi.Float64PtrOutput {\n\treturn o.ApplyT(func(v *GoogleCloudRetailV2alphaPriceInfo) *float64 {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.OriginalPrice\n\t}).(pulumi.Float64PtrOutput)\n}", "func (_DelegationController *DelegationControllerTransactor) GetAndUpdateDelegatedAmount(opts *bind.TransactOpts, holder common.Address) (*types.Transaction, error) {\n\treturn _DelegationController.contract.Transact(opts, \"getAndUpdateDelegatedAmount\", holder)\n}", "func (_TokenStakingEscrow *TokenStakingEscrowCaller) DepositedAmount(opts *bind.CallOpts, operator common.Address) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _TokenStakingEscrow.contract.Call(opts, out, \"depositedAmount\", operator)\n\treturn *ret0, err\n}", "func (r Virtual_Guest) GetCurrentBillingTotal() (resp datatypes.Float64, err error) {\n\terr = r.Session.DoRequest(\"SoftLayer_Virtual_Guest\", \"getCurrentBillingTotal\", nil, &r.Options, &resp)\n\treturn\n}", "func (subnet *VirtualNetworksSubnet) OriginalGVK() *schema.GroupVersionKind {\n\treturn &schema.GroupVersionKind{\n\t\tGroup: GroupVersion.Group,\n\t\tVersion: subnet.Spec.OriginalVersion,\n\t\tKind: \"VirtualNetworksSubnet\",\n\t}\n}", "func (account *DatabaseAccount) OriginalGVK() *schema.GroupVersionKind {\n\treturn &schema.GroupVersionKind{\n\t\tGroup: GroupVersion.Group,\n\t\tVersion: account.Spec.OriginalVersion(),\n\t\tKind: \"DatabaseAccount\",\n\t}\n}", "func (account *DatabaseAccount_Spec) OriginalVersion() string {\n\treturn GroupVersion.Version\n}", "func (profile *Profile) OriginalGVK() *schema.GroupVersionKind {\n\treturn &schema.GroupVersionKind{\n\t\tGroup: GroupVersion.Group,\n\t\tVersion: profile.Spec.OriginalVersion,\n\t\tKind: \"Profile\",\n\t}\n}", "func (sm *StateManager) GetFilVested(ctx context.Context, height abi.ChainEpoch, st *state.StateTree) (abi.TokenAmount, error) {\n\tvf := big.Zero()\n\tif height <= build.UpgradeIgnitionHeight {\n\t\tfor _, v := range sm.preIgnitionGenInfos.genesisMsigs {\n\t\t\tau := big.Sub(v.InitialBalance, v.AmountLocked(height))\n\t\t\tvf = big.Add(vf, au)\n\t\t}\n\t} else {\n\t\tfor _, v := range sm.postIgnitionGenInfos.genesisMsigs {\n\t\t\t// In the pre-ignition logic, we simply called AmountLocked(height), assuming startEpoch was 0.\n\t\t\t// The start epoch changed in the Ignition upgrade.\n\t\t\tau := big.Sub(v.InitialBalance, v.AmountLocked(height-v.StartEpoch))\n\t\t\tvf = big.Add(vf, au)\n\t\t}\n\t}\n\n\t// there should not be any such accounts in testnet (and also none in mainnet?)\n\t// continue to use preIgnitionGenInfos, nothing changed at the Ignition epoch\n\tfor _, v := range sm.preIgnitionGenInfos.genesisActors {\n\t\tact, err := st.GetActor(v.addr)\n\t\tif err != nil {\n\t\t\treturn big.Zero(), xerrors.Errorf(\"failed to get actor: %w\", err)\n\t\t}\n\n\t\tdiff := big.Sub(v.initBal, act.Balance)\n\t\tif diff.GreaterThan(big.Zero()) {\n\t\t\tvf = big.Add(vf, diff)\n\t\t}\n\t}\n\n\t// continue to use preIgnitionGenInfos, nothing changed at the Ignition epoch\n\tvf = big.Add(vf, sm.preIgnitionGenInfos.genesisPledge)\n\t// continue to use preIgnitionGenInfos, nothing changed at the Ignition epoch\n\tvf = big.Add(vf, sm.preIgnitionGenInfos.genesisMarketFunds)\n\n\treturn vf, nil\n}", "func (o *GetRecipeInformation200ResponseExtendedIngredientsInner) GetOriginalOk() (*string, bool) {\n\tif o == nil {\n\t\treturn nil, false\n\t}\n\treturn &o.Original, true\n}", "func (machine *VirtualMachine) OriginalGVK() *schema.GroupVersionKind {\n\treturn &schema.GroupVersionKind{\n\t\tGroup: GroupVersion.Group,\n\t\tVersion: machine.Spec.OriginalVersion,\n\t\tKind: \"VirtualMachine\",\n\t}\n}", "func (peering *VirtualNetworksVirtualNetworkPeering) OriginalGVK() *schema.GroupVersionKind {\n\treturn &schema.GroupVersionKind{\n\t\tGroup: GroupVersion.Group,\n\t\tVersion: peering.Spec.OriginalVersion,\n\t\tKind: \"VirtualNetworksVirtualNetworkPeering\",\n\t}\n}", "func (o GoogleCloudRetailV2alphaPriceInfoPriceRangeResponseOutput) OriginalPrice() GoogleCloudRetailV2alphaIntervalResponseOutput {\n\treturn o.ApplyT(func(v GoogleCloudRetailV2alphaPriceInfoPriceRangeResponse) GoogleCloudRetailV2alphaIntervalResponse {\n\t\treturn v.OriginalPrice\n\t}).(GoogleCloudRetailV2alphaIntervalResponseOutput)\n}", "func (_DelegationController *DelegationControllerTransactor) GetAndUpdateLockedAmount(opts *bind.TransactOpts, wallet common.Address) (*types.Transaction, error) {\n\treturn _DelegationController.contract.Transact(opts, \"getAndUpdateLockedAmount\", wallet)\n}", "func (credential *FederatedIdentityCredential) OriginalGVK() *schema.GroupVersionKind {\n\treturn &schema.GroupVersionKind{\n\t\tGroup: GroupVersion.Group,\n\t\tVersion: credential.Spec.OriginalVersion(),\n\t\tKind: \"FederatedIdentityCredential\",\n\t}\n}", "func (_DelegationController *DelegationControllerTransactorSession) GetAndUpdateDelegatedAmount(holder common.Address) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.GetAndUpdateDelegatedAmount(&_DelegationController.TransactOpts, holder)\n}", "func (machine *VirtualMachine) OriginalGVK() *schema.GroupVersionKind {\n\treturn &schema.GroupVersionKind{\n\t\tGroup: GroupVersion.Group,\n\t\tVersion: machine.Spec.OriginalVersion(),\n\t\tKind: \"VirtualMachine\",\n\t}\n}", "func (t *Transaction) VATDollarAmount() string {\n\tp := 1 + float64(t.SubscriptionVATPercent)/100\n\tvat := t.TransactionAmount - int64(float64(t.TransactionAmount)/p)\n\treturn fmt.Sprintf(\"$%d.%02d\", vat/100, vat%100)\n}", "func (f Fixed) Original() uint64 {\n\treturn f.fp\n}", "func (c Cart) GetVoucherSavings() domain.Price {\n\tprice := domain.Price{}\n\tvar err error\n\n\tfor _, item := range c.Totalitems {\n\t\tif item.Type == TotalsTypeVoucher {\n\t\t\tprice, err = price.Add(item.Price)\n\t\t\tif err != nil {\n\t\t\t\treturn price\n\t\t\t}\n\t\t}\n\t}\n\n\tif price.IsNegative() {\n\t\treturn domain.Price{}\n\t}\n\n\treturn price\n}", "func RestoreMoneyTransfer(guid guid, store EventStore) *MoneyTransfer {\n\tt := NewMoneyTransfer()\n\tRestoreAggregate(guid, t, store)\n\treturn t\n}", "func (o *BaseReportTransaction) GetAmount() float64 {\n\tif o == nil {\n\t\tvar ret float64\n\t\treturn ret\n\t}\n\n\treturn o.Amount\n}", "func (o *ClientProvidedEnhancedTransaction) GetAmount() float64 {\n\tif o == nil {\n\t\tvar ret float64\n\t\treturn ret\n\t}\n\n\treturn o.Amount\n}", "func (o *Transaction) GetOriginalDescription() string {\n\tif o == nil || o.OriginalDescription.Get() == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.OriginalDescription.Get()\n}", "func (pva PeriodicVestingAccount) GetVestingPeriods() Periods {\n\treturn pva.VestingPeriods\n}", "func (o *BaseReportTransaction) GetOriginalDescription() string {\n\tif o == nil || o.OriginalDescription.Get() == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\n\treturn *o.OriginalDescription.Get()\n}", "func NewBaseVestingAccount(baseAccount *authtypes.BaseAccount, originalVesting sdk.Coins, endTime int64) *BaseVestingAccount {\n\treturn &BaseVestingAccount{\n\t\tBaseAccount: baseAccount,\n\t\tOriginalVesting: originalVesting,\n\t\tDelegatedFree: sdk.NewCoins(),\n\t\tDelegatedVesting: sdk.NewCoins(),\n\t\tEndTime: endTime,\n\t}\n}", "func (network *VirtualNetwork) OriginalGVK() *schema.GroupVersionKind {\n\treturn &schema.GroupVersionKind{\n\t\tGroup: GroupVersion.Group,\n\t\tVersion: network.Spec.OriginalVersion,\n\t\tKind: \"VirtualNetwork\",\n\t}\n}", "func (_DelegationController *DelegationControllerSession) GetAndUpdateDelegatedAmount(holder common.Address) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.GetAndUpdateDelegatedAmount(&_DelegationController.TransactOpts, holder)\n}", "func (o *CreditBankIncomeTransaction) GetOriginalDescription() string {\n\tif o == nil || o.OriginalDescription.Get() == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.OriginalDescription.Get()\n}", "func (setting *ServersAdvancedThreatProtectionSetting) OriginalGVK() *schema.GroupVersionKind {\n\treturn &schema.GroupVersionKind{\n\t\tGroup: GroupVersion.Group,\n\t\tVersion: setting.Spec.OriginalVersion,\n\t\tKind: \"ServersAdvancedThreatProtectionSetting\",\n\t}\n}", "func (s *stateObject) GetAmount() *big.Int {\n\treturn s.account.Amount\n}", "func getMoneyAmount(n int) int {\n \n}", "func (machine *VirtualMachine_Spec) OriginalVersion() string {\n\treturn GroupVersion.Version\n}", "func (b *rpcVestingBalance) delegated() (sdk.Coins, sdk.Coins, error) {\n\tdelegatedCoins, err := b.totalDelegated()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tunbondingCoins, err := b.totalUnbondingDelegations()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tdelegated := delegatedCoins.AmountOf(stakingDenom)\n\tunbonding := unbondingCoins.AmountOf(stakingDenom)\n\ttotalStaked := delegated.Add(unbonding)\n\tdelegatedFree := b.vacc.GetDelegatedFree().AmountOf(stakingDenom)\n\n\t// total number of staked and unbonding tokens considered to be liquid\n\ttotalFree := sdk.MinInt(totalStaked, delegatedFree)\n\t// any coins that are not considered liquid, are vesting up to a maximum of delegated\n\tstakedVesting := sdk.MinInt(totalStaked.Sub(totalFree), delegated)\n\t// staked free coins are left over\n\tstakedFree := delegated.Sub(stakedVesting)\n\n\tliquidCoins := sdk.NewCoins(newKavaCoin(stakedFree))\n\tvestingCoins := sdk.NewCoins(newKavaCoin(stakedVesting))\n\treturn liquidCoins, vestingCoins, nil\n}", "func (_DelegationController *DelegationControllerTransactorSession) GetAndUpdateLockedAmount(wallet common.Address) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.GetAndUpdateLockedAmount(&_DelegationController.TransactOpts, wallet)\n}", "func (pva PeriodicVestingAccount) GetVestedCoins(blockTime time.Time) sdk.Coins {\n\tcoins := ReadSchedule(pva.StartTime, pva.EndTime, pva.VestingPeriods, pva.OriginalVesting, blockTime.Unix())\n\tif coins.IsZero() {\n\t\treturn nil\n\t}\n\treturn coins\n}", "func (n Network) VestingAccounts(ctx context.Context, launchID uint64) (vestingAccs []networktypes.VestingAccount, err error) {\n\tn.ev.Send(events.New(events.StatusOngoing, \"Fetching genesis vesting accounts\"))\n\tres, err := n.launchQuery.\n\t\tVestingAccountAll(ctx,\n\t\t\t&launchtypes.QueryAllVestingAccountRequest{\n\t\t\t\tLaunchID: launchID,\n\t\t\t},\n\t\t)\n\tif err != nil {\n\t\treturn vestingAccs, err\n\t}\n\n\tfor i, acc := range res.VestingAccount {\n\t\tparsedAcc, err := networktypes.ToVestingAccount(acc)\n\t\tif err != nil {\n\t\t\treturn vestingAccs, errors.Wrapf(err, \"error parsing vesting account %d\", i)\n\t\t}\n\n\t\tvestingAccs = append(vestingAccs, parsedAcc)\n\t}\n\n\treturn vestingAccs, nil\n}", "func (record *PrivateDnsZonesSRVRecord) OriginalGVK() *schema.GroupVersionKind {\n\treturn &schema.GroupVersionKind{\n\t\tGroup: GroupVersion.Group,\n\t\tVersion: record.Spec.OriginalVersion(),\n\t\tKind: \"PrivateDnsZonesSRVRecord\",\n\t}\n}", "func (vva ValidatorVestingAccount) GetVestedCoins(blockTime time.Time) sdk.Coins {\n\tvar vestedCoins sdk.Coins\n\tif blockTime.Unix() <= vva.StartTime {\n\t\treturn vestedCoins\n\t}\n\tcurrentPeriodStartTime := vva.StartTime\n\tnumberPeriods := len(vva.VestingPeriods)\n\tfor i := 0; i < numberPeriods; i++ {\n\t\tx := blockTime.Unix() - currentPeriodStartTime\n\t\tif x >= vva.VestingPeriods[i].Length {\n\t\t\tif vva.VestingPeriodProgress[i].PeriodComplete {\n\t\t\t\tvestedCoins = vestedCoins.Add(vva.VestingPeriods[i].Amount)\n\t\t\t}\n\t\t\tcurrentPeriodStartTime += vva.VestingPeriods[i].Length\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn vestedCoins\n\n}", "func (m *Monzgo) WithdrawFromPot(potID string, destinationAccountID string, amount int64, dedupeID string) (*Pot, error) {\n\trequestData := make(map[string]string)\n\trequestData[\"destination_account_id\"] = destinationAccountID\n\trequestData[\"amount\"] = strconv.FormatInt(amount, 10)\n\trequestData[\"dedupe_id\"] = dedupeID\n\n\tpot := &Pot{}\n\tif err := m.request(\"PUT\", \"pots/\"+potID+\"/withdraw\", pot, requestData); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn pot, nil\n}", "func (_Crowdsale *CrowdsaleCaller) PctSold(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _Crowdsale.contract.Call(opts, out, \"pctSold\")\n\treturn *ret0, err\n}", "func (credential *UserAssignedIdentities_FederatedIdentityCredential_Spec) OriginalVersion() string {\n\treturn GroupVersion.Version\n}", "func (entry *UtxoEntry) Amount() int64 {\n\treturn entry.amount\n}", "func (_TokenStakingEscrow *TokenStakingEscrowCallerSession) DepositedAmount(operator common.Address) (*big.Int, error) {\n\treturn _TokenStakingEscrow.Contract.DepositedAmount(&_TokenStakingEscrow.CallOpts, operator)\n}", "func ExpectAttoFil(amount big.Int) *big.Int { return &amount }", "func (_DelegationController *DelegationControllerSession) GetAndUpdateLockedAmount(wallet common.Address) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.GetAndUpdateLockedAmount(&_DelegationController.TransactOpts, wallet)\n}", "func (policy *StorageAccountsManagementPolicy) OriginalGVK() *schema.GroupVersionKind {\n\treturn &schema.GroupVersionKind{\n\t\tGroup: GroupVersion.Group,\n\t\tVersion: policy.Spec.OriginalVersion,\n\t\tKind: \"StorageAccountsManagementPolicy\",\n\t}\n}", "func (vva ValidatorVestingAccount) GetFailedVestedCoins() sdk.Coins {\n\tvar failedVestedCoins sdk.Coins\n\tnumberPeriods := len(vva.VestingPeriods)\n\tfor i := 0; i < numberPeriods; i++ {\n\t\tif vva.VestingPeriodProgress[i].PeriodComplete {\n\t\t\tif !vva.VestingPeriodProgress[i].VestingSuccessful {\n\t\t\t\tfailedVestedCoins = failedVestedCoins.Add(vva.VestingPeriods[i].Amount)\n\t\t\t}\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn failedVestedCoins\n}", "func (v *VersionVector) Incr(actor string) LamportTime {\n\tv.l.Lock()\n\n\tt, exists := v.dots[actor]\n\tif !exists {\n\t\tt = LamportTime(1)\n\t\tv.dots[actor] = t\n\t} else {\n\t\tt++\n\t\tv.dots[actor] = t\n\t}\n\n\tv.l.Unlock()\n\treturn t\n}", "func (_TokenVesting *TokenVestingRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _TokenVesting.Contract.TokenVestingTransactor.contract.Transfer(opts)\n}", "func (o *RequestSepaMoneyTransferParams) GetAmount() float64 {\n\tif o == nil {\n\t\tvar ret float64\n\t\treturn ret\n\t}\n\n\treturn o.Amount\n}", "func (_Gatekeeper *GatekeeperCaller) GetCurrentTransactionAmountForBlock(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _Gatekeeper.contract.Call(opts, out, \"GetCurrentTransactionAmountForBlock\")\n\treturn *ret0, err\n}", "func (scaleSet *VirtualMachineScaleSet) OriginalGVK() *schema.GroupVersionKind {\n\treturn &schema.GroupVersionKind{\n\t\tGroup: GroupVersion.Group,\n\t\tVersion: scaleSet.Spec.OriginalVersion,\n\t\tKind: \"VirtualMachineScaleSet\",\n\t}\n}", "func (service *PrivateLinkService) OriginalGVK() *schema.GroupVersionKind {\n\treturn &schema.GroupVersionKind{\n\t\tGroup: GroupVersion.Group,\n\t\tVersion: service.Spec.OriginalVersion,\n\t\tKind: \"PrivateLinkService\",\n\t}\n}", "func (plva PermanentLockedAccount) GetVestedCoins(_ time.Time) sdk.Coins {\n\treturn nil\n}", "func (enterprise *RedisEnterprise) OriginalGVK() *schema.GroupVersionKind {\n\treturn &schema.GroupVersionKind{\n\t\tGroup: GroupVersion.Group,\n\t\tVersion: enterprise.Spec.OriginalVersion,\n\t\tKind: \"RedisEnterprise\",\n\t}\n}", "func (m *Money) Amount() int {\n\treturn m.amount\n}", "func (e *detailedError) Original() error {\n\tif e.original != nil {\n\t\treturn e.original\n\t}\n\treturn e\n}", "func (c *Channel) TransferAmount() *big.Int {\n\treturn c.OurState.TransferAmount()\n}", "func (c *Channel) TransferAmount() *big.Int {\n\treturn c.OurState.TransferAmount()\n}", "func (policy *StorageAccountsManagementPolicy) OriginalGVK() *schema.GroupVersionKind {\n\treturn &schema.GroupVersionKind{\n\t\tGroup: GroupVersion.Group,\n\t\tVersion: policy.Spec.OriginalVersion(),\n\t\tKind: \"StorageAccountsManagementPolicy\",\n\t}\n}", "func (o *TransactionSplit) GetOriginalSource() string {\n\tif o == nil || o.OriginalSource.Get() == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.OriginalSource.Get()\n}", "func getOriginalByID(originalID int) (*Original, error) {\n\tvar name, zone, ztname, tzdver string\n\tvar id, ztver, offset int64\n\n\tcolumns := getOriginalCols()\n\tquery := fmt.Sprintf(\"SELECT * FROM %s WHERE %s=%v\", originalTable, columns[0], originalID)\n\terr := db.QueryRow(query).Scan(&id, &name, &zone, &offset, &ztname, &ztver, &tzdver)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Original{ID: id, Name: name, DZone: zone, DOffset: offset, TabName: ztname, TabVer: ztver, TZDVer: tzdver}, nil\n}", "func (del Delegation) AmountInWithdraw() (hexutil.Big, error) {\n\t// lazy load data\n\tif del.extendedAmountInWithdraw == nil {\n\t\tvar err error\n\n\t\t// try to load the data\n\t\tdel.extendedAmount, del.extendedAmountInWithdraw, err = del.repo.DelegatedAmountExtended(&del.Delegation)\n\t\tif err != nil {\n\t\t\treturn hexutil.Big{}, err\n\t\t}\n\t}\n\n\treturn (hexutil.Big)(*del.extendedAmountInWithdraw), nil\n}", "func (o *Transfer) GetAmount() string {\n\tif o == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\n\treturn o.Amount\n}", "func (_ChpRegistry *ChpRegistryCaller) NODESTAKINGAMOUNT(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _ChpRegistry.contract.Call(opts, out, \"NODE_STAKING_AMOUNT\")\n\treturn *ret0, err\n}", "func (p Pinger) GetAmt() int {\r\n\treturn p.amt\r\n}", "func (del Delegation) Amount() (hexutil.Big, error) {\n\t// lazy load data\n\tif del.extendedAmount == nil {\n\t\tvar err error\n\n\t\t// try to load the data\n\t\tdel.extendedAmount, del.extendedAmountInWithdraw, err = del.repo.DelegatedAmountExtended(&del.Delegation)\n\t\tif err != nil {\n\t\t\treturn hexutil.Big{}, err\n\t\t}\n\t}\n\n\treturn (hexutil.Big)(*del.extendedAmount), nil\n}", "func (r *AssetRendering) Original() {\n\tv := \"original\"\n\tr.Value = &v\n}", "func (pool *WorkspacesBigDataPool) OriginalGVK() *schema.GroupVersionKind {\n\treturn &schema.GroupVersionKind{\n\t\tGroup: GroupVersion.Group,\n\t\tVersion: pool.Spec.OriginalVersion,\n\t\tKind: \"WorkspacesBigDataPool\",\n\t}\n}", "func (_ChpRegistry *ChpRegistryCallerSession) NODESTAKINGAMOUNT() (*big.Int, error) {\n\treturn _ChpRegistry.Contract.NODESTAKINGAMOUNT(&_ChpRegistry.CallOpts)\n}", "func (_ChpRegistry *ChpRegistryCaller) CORESTAKINGAMOUNT(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _ChpRegistry.contract.Call(opts, out, \"CORE_STAKING_AMOUNT\")\n\treturn *ret0, err\n}" ]
[ "0.5952986", "0.573784", "0.5716642", "0.56203747", "0.5533669", "0.54534984", "0.5265873", "0.52228105", "0.5221159", "0.521353", "0.5159928", "0.51219094", "0.51138663", "0.50696576", "0.502259", "0.496147", "0.49164215", "0.48761567", "0.4837371", "0.48261893", "0.4814075", "0.47619748", "0.4747914", "0.47214603", "0.46778437", "0.4671568", "0.46511054", "0.46290392", "0.4611493", "0.4605892", "0.458744", "0.458394", "0.45810792", "0.45632163", "0.45586377", "0.4542038", "0.45386615", "0.45385215", "0.45374814", "0.45359308", "0.45235464", "0.45059448", "0.45021504", "0.44914922", "0.44827646", "0.4476228", "0.4475878", "0.44708887", "0.44662935", "0.4465717", "0.44628403", "0.4454042", "0.44505158", "0.4449676", "0.44378456", "0.44277528", "0.44091144", "0.4405412", "0.43983763", "0.43813616", "0.4357735", "0.43536732", "0.43529522", "0.43465292", "0.43306765", "0.4330506", "0.4323709", "0.43225873", "0.4314342", "0.43140933", "0.43098992", "0.4306866", "0.43055096", "0.43035507", "0.4303256", "0.43012142", "0.43011218", "0.42756438", "0.42721313", "0.42691162", "0.42632952", "0.42620534", "0.42592248", "0.42572773", "0.42534518", "0.42530304", "0.4252269", "0.4252269", "0.4249081", "0.4243418", "0.4242883", "0.42283672", "0.42236423", "0.4214692", "0.42035466", "0.4203308", "0.41927865", "0.41922095", "0.41904837", "0.41848508" ]
0.8451787
0
GetDelegatedFree returns a vesting account's delegation amount that is not vesting.
func (bva BaseVestingAccount) GetDelegatedFree() sdk.Coins { return bva.DelegatedFree }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (del Delegation) AmountDelegated() hexutil.Big {\n\tif del.Delegation.AmountDelegated == nil {\n\t\treturn hexutil.Big{}\n\t}\n\treturn *del.Delegation.AmountDelegated\n}", "func (bva BaseVestingAccount) GetDelegatedVesting() sdk.Coins {\n\treturn bva.DelegatedVesting\n}", "func (b *rpcVestingBalance) delegated() (sdk.Coins, sdk.Coins, error) {\n\tdelegatedCoins, err := b.totalDelegated()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tunbondingCoins, err := b.totalUnbondingDelegations()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tdelegated := delegatedCoins.AmountOf(stakingDenom)\n\tunbonding := unbondingCoins.AmountOf(stakingDenom)\n\ttotalStaked := delegated.Add(unbonding)\n\tdelegatedFree := b.vacc.GetDelegatedFree().AmountOf(stakingDenom)\n\n\t// total number of staked and unbonding tokens considered to be liquid\n\ttotalFree := sdk.MinInt(totalStaked, delegatedFree)\n\t// any coins that are not considered liquid, are vesting up to a maximum of delegated\n\tstakedVesting := sdk.MinInt(totalStaked.Sub(totalFree), delegated)\n\t// staked free coins are left over\n\tstakedFree := delegated.Sub(stakedVesting)\n\n\tliquidCoins := sdk.NewCoins(newKavaCoin(stakedFree))\n\tvestingCoins := sdk.NewCoins(newKavaCoin(stakedVesting))\n\treturn liquidCoins, vestingCoins, nil\n}", "func (_DelegationController *DelegationControllerTransactor) GetAndUpdateDelegatedAmount(opts *bind.TransactOpts, holder common.Address) (*types.Transaction, error) {\n\treturn _DelegationController.contract.Transact(opts, \"getAndUpdateDelegatedAmount\", holder)\n}", "func (del Delegation) Amount() (hexutil.Big, error) {\n\t// lazy load data\n\tif del.extendedAmount == nil {\n\t\tvar err error\n\n\t\t// try to load the data\n\t\tdel.extendedAmount, del.extendedAmountInWithdraw, err = del.repo.DelegatedAmountExtended(&del.Delegation)\n\t\tif err != nil {\n\t\t\treturn hexutil.Big{}, err\n\t\t}\n\t}\n\n\treturn (hexutil.Big)(*del.extendedAmount), nil\n}", "func (_DelegationController *DelegationControllerTransactor) GetAndUpdateForbiddenForDelegationAmount(opts *bind.TransactOpts, wallet common.Address) (*types.Transaction, error) {\n\treturn _DelegationController.contract.Transact(opts, \"getAndUpdateForbiddenForDelegationAmount\", wallet)\n}", "func (del Delegation) Amount() (hexutil.Big, error) {\n\t// get the base amount delegated\n\tbase, err := repository.R().DelegationAmountStaked(&del.Address, del.Delegation.ToStakerId)\n\tif err != nil {\n\t\treturn hexutil.Big{}, err\n\t}\n\n\t// get the sum of all pending withdrawals\n\twd, err := del.pendingWithdrawalsValue()\n\tif err != nil {\n\t\treturn hexutil.Big{}, err\n\t}\n\tval := new(big.Int).Add(base, wd)\n\treturn (hexutil.Big)(*val), nil\n}", "func (_DelegationController *DelegationControllerSession) GetAndUpdateDelegatedAmount(holder common.Address) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.GetAndUpdateDelegatedAmount(&_DelegationController.TransactOpts, holder)\n}", "func (_DelegationController *DelegationControllerSession) GetAndUpdateForbiddenForDelegationAmount(wallet common.Address) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.GetAndUpdateForbiddenForDelegationAmount(&_DelegationController.TransactOpts, wallet)\n}", "func (_DelegationController *DelegationControllerTransactorSession) GetAndUpdateDelegatedAmount(holder common.Address) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.GetAndUpdateDelegatedAmount(&_DelegationController.TransactOpts, holder)\n}", "func (_DelegationController *DelegationControllerTransactorSession) GetAndUpdateForbiddenForDelegationAmount(wallet common.Address) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.GetAndUpdateForbiddenForDelegationAmount(&_DelegationController.TransactOpts, wallet)\n}", "func (acc *Account) delegationsTotal() (amount *big.Int, inWithdraw *big.Int, rewards *big.Int, err error) {\n\t// pull all the delegations of the account\n\tlist, err := repository.R().DelegationsByAddressAll(&acc.Address)\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\n\t// prep containers for calculation and loop all delegations found\n\tamount = new(big.Int)\n\trewards = new(big.Int)\n\tinWithdraw = new(big.Int)\n\tfor _, dlg := range list {\n\t\t// any active delegated amount?\n\t\tif 0 < dlg.AmountDelegated.ToInt().Uint64() {\n\t\t\tamount = new(big.Int).Add(amount, dlg.AmountDelegated.ToInt())\n\t\t}\n\n\t\t// get pending rewards for this delegation (can be stashed)\n\t\trw, err := repository.R().PendingRewards(&acc.Address, dlg.ToStakerId)\n\t\tif err != nil {\n\t\t\treturn nil, nil, nil, err\n\t\t}\n\n\t\t// any rewards?\n\t\tif 0 < rw.Amount.ToInt().Uint64() {\n\t\t\trewards = new(big.Int).Add(rewards, rw.Amount.ToInt())\n\t\t}\n\n\t\t// get pending withdrawals\n\t\twd, err := repository.R().WithdrawRequestsPendingTotal(&acc.Address, dlg.ToStakerId)\n\t\tif err != nil {\n\t\t\treturn nil, nil, nil, err\n\t\t}\n\n\t\t// add pending withdrawals value\n\t\tif 0 < wd.Uint64() {\n\t\t\tinWithdraw = new(big.Int).Add(inWithdraw, wd)\n\t\t}\n\t}\n\n\treturn amount, rewards, inWithdraw, nil\n}", "func (pr *ProvenAccountResource) GetDelegatedWithdrawalCapability() bool {\n\tif !pr.proven {\n\t\tpanic(\"not valid proven account resource\")\n\t}\n\treturn pr.accountResource.DelegatedWithdrawalCapability\n}", "func (del Delegation) UnlockedAmount() (hexutil.Big, error) {\n\treturn repository.R().DelegationAmountUnlocked(&del.Address, (*big.Int)(del.Delegation.ToStakerId))\n}", "func (del Delegation) LockedAmount() (hexutil.Big, error) {\n\tlock, err := del.DelegationLock()\n\tif err != nil {\n\t\treturn hexutil.Big{}, err\n\t}\n\treturn lock.LockedAmount, nil\n}", "func (bva *BaseVestingAccount) TrackUndelegation(amount sdk.Coins) {\n\tfor _, coin := range amount {\n\t\t// panic if the undelegation amount is zero\n\t\tif coin.Amount.IsZero() {\n\t\t\tpanic(\"undelegation attempt with zero coins\")\n\t\t}\n\t\tdelegatedFree := bva.DelegatedFree.AmountOf(coin.Denom)\n\t\tdelegatedVesting := bva.DelegatedVesting.AmountOf(coin.Denom)\n\n\t\t// compute x and y per the specification, where:\n\t\t// X := min(DF, D)\n\t\t// Y := min(DV, D - X)\n\t\tx := sdk.MinInt(delegatedFree, coin.Amount)\n\t\ty := sdk.MinInt(delegatedVesting, coin.Amount.Sub(x))\n\n\t\tif !x.IsZero() {\n\t\t\txCoin := sdk.NewCoin(coin.Denom, x)\n\t\t\tbva.DelegatedFree = bva.DelegatedFree.Sub(sdk.Coins{xCoin})\n\t\t}\n\n\t\tif !y.IsZero() {\n\t\t\tyCoin := sdk.NewCoin(coin.Denom, y)\n\t\t\tbva.DelegatedVesting = bva.DelegatedVesting.Sub(sdk.Coins{yCoin})\n\t\t}\n\t}\n}", "func (k Keeper) Delegation(ctx context.Context, addrDel sdk.AccAddress, addrVal sdk.ValAddress) (types.DelegationI, error) {\n\tbond, err := k.Delegations.Get(ctx, collections.Join(addrDel, addrVal))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn bond, nil\n}", "func (s *PublicSfcAPI) GetDelegator(ctx context.Context, addr common.Address, verbosity hexutil.Uint64) (map[string]interface{}, error) {\n\tdelegator, err := s.b.GetDelegator(ctx, addr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif delegator == nil {\n\t\treturn nil, nil\n\t}\n\tit := sfctype.SfcDelegatorAndAddr{\n\t\tAddr: addr,\n\t\tDelegator: delegator,\n\t}\n\tdelegatorRPC := RPCMarshalDelegator(it)\n\tif verbosity <= 1 {\n\t\treturn delegatorRPC, nil\n\t}\n\treturn s.addDelegatorMetricFields(ctx, delegatorRPC, addr)\n}", "func (_TokenStakingEscrow *TokenStakingEscrowCaller) DepositRedelegatedAmount(opts *bind.CallOpts, operator common.Address) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _TokenStakingEscrow.contract.Call(opts, out, \"depositRedelegatedAmount\", operator)\n\treturn *ret0, err\n}", "func (del Delegation) AmountInWithdraw() (hexutil.Big, error) {\n\t// lazy load data\n\tif del.extendedAmountInWithdraw == nil {\n\t\tvar err error\n\n\t\t// try to load the data\n\t\tdel.extendedAmount, del.extendedAmountInWithdraw, err = del.repo.DelegatedAmountExtended(&del.Delegation)\n\t\tif err != nil {\n\t\t\treturn hexutil.Big{}, err\n\t\t}\n\t}\n\n\treturn (hexutil.Big)(*del.extendedAmountInWithdraw), nil\n}", "func (_TokenStakingEscrow *TokenStakingEscrowCallerSession) DepositRedelegatedAmount(operator common.Address) (*big.Int, error) {\n\treturn _TokenStakingEscrow.Contract.DepositRedelegatedAmount(&_TokenStakingEscrow.CallOpts, operator)\n}", "func (va *ClawbackVestingAccount) updateDelegation(encumbered, toClawBack, bonded, unbonding, unbonded sdk.Coins) sdk.Coins {\n\tdelegated := bonded.Add(unbonding...)\n\toldDelegated := va.DelegatedVesting.Add(va.DelegatedFree...)\n\tslashed := oldDelegated.Sub(coinsMin(delegated, oldDelegated))\n\ttotal := delegated.Add(unbonded...)\n\ttoClawBack = coinsMin(toClawBack, total) // might have been slashed\n\tnewDelegated := coinsMin(delegated, total.Sub(toClawBack)).Add(slashed...)\n\tva.DelegatedVesting = coinsMin(encumbered, newDelegated)\n\tva.DelegatedFree = newDelegated.Sub(va.DelegatedVesting)\n\treturn toClawBack\n}", "func (_TokenStakingEscrow *TokenStakingEscrowSession) DepositRedelegatedAmount(operator common.Address) (*big.Int, error) {\n\treturn _TokenStakingEscrow.Contract.DepositRedelegatedAmount(&_TokenStakingEscrow.CallOpts, operator)\n}", "func (k Keeper) Delegation(ctx sdk.Context, addrDel sdk.AccAddress, addrVal sdk.ValAddress) exported.DelegationI {\n\treturn nil\n}", "func (k Keeper) Delegator(ctx sdk.Context, delAddr sdk.AccAddress) exported.DelegatorI {\n\tdelegator, found := k.GetDelegator(ctx, delAddr)\n\tif !found {\n\t\treturn nil\n\t}\n\n\treturn delegator\n}", "func (a *Account) Deposit(amt int64) (newBal int64, ok bool) {\n\tif a.defunct == 1 {\n\t\treturn 0, false\n\t}\n\n\t// deposits are safe; just add them atomically\n\tif amt >= 0 {\n\t\treturn atomic.AddInt64(&a.amt, amt), true\n\t}\n\n\t// withdrawal; make sure decision is based on fresh value\n\tconclusive := false\n\tvar bal int64\n\tfor !conclusive {\n\t\tbal = a.amt // work on a copy, not the hot original\n\t\tif -amt > bal {\n\t\t\treturn a.amt, false\n\t\t}\n\t\tconclusive = atomic.CompareAndSwapInt64(&a.amt, bal, amt+bal)\n\t}\n\treturn (bal + amt), true\n}", "func (_DelegationController *DelegationControllerCaller) GetDelegation(opts *bind.CallOpts, delegationId *big.Int) (DelegationControllerDelegation, error) {\n\tvar (\n\t\tret0 = new(DelegationControllerDelegation)\n\t)\n\tout := ret0\n\terr := _DelegationController.contract.Call(opts, out, \"getDelegation\", delegationId)\n\treturn *ret0, err\n}", "func CalculateDelegateNetPayout(delegatedContracts []DelegatedContract) []DelegatedContract{\n var delegateIndex int\n\n for index, delegate := range delegatedContracts{\n if (delegate.Delegate){\n delegateIndex = index\n }\n }\n\n for _, delegate := range delegatedContracts{\n if (!delegate.Delegate){\n delegatedContracts[delegateIndex].TotalPayout = delegatedContracts[delegateIndex].TotalPayout + delegate.Fee\n }\n }\n return delegatedContracts\n}", "func (del Delegation) pendingWithdrawalsValue() (*big.Int, error) {\n\t// call for it only once\n\tval, err, _ := del.cg.Do(\"withdraw-total\", func() (interface{}, error) {\n\t\treturn repository.R().WithdrawRequestsPendingTotal(&del.Address, del.Delegation.ToStakerId)\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn val.(*big.Int), nil\n}", "func (_DelegationController *DelegationControllerTransactor) AcceptPendingDelegation(opts *bind.TransactOpts, delegationId *big.Int) (*types.Transaction, error) {\n\treturn _DelegationController.contract.Transact(opts, \"acceptPendingDelegation\", delegationId)\n}", "func (broadcast *Broadcast) DelegatorWithdraw(ctx context.Context, delegator, voter, amount,\n\tprivKeyHex string, seq int64) (*model.BroadcastResponse, error) {\n\tmsg := model.DelegatorWithdrawMsg{\n\t\tDelegator: delegator,\n\t\tVoter: voter,\n\t\tAmount: amount,\n\t}\n\treturn broadcast.broadcastTransaction(ctx, msg, privKeyHex, seq, \"\", false)\n}", "func (o *StorageBaseCapacity) GetFree() int64 {\n\tif o == nil || o.Free == nil {\n\t\tvar ret int64\n\t\treturn ret\n\t}\n\treturn *o.Free\n}", "func (o *AssetReportFreddieGetResponse) GetDEAL() AssetReportFreddie {\n\tif o == nil {\n\t\tvar ret AssetReportFreddie\n\t\treturn ret\n\t}\n\n\treturn o.DEAL\n}", "func (del Delegation) AmountInWithdraw() (hexutil.Big, error) {\n\tval, err := del.pendingWithdrawalsValue()\n\tif err != nil {\n\t\treturn hexutil.Big{}, err\n\t}\n\treturn (hexutil.Big)(*val), nil\n}", "func (k msgServer) Delegate(goCtx context.Context, msg *types.MsgDelegate) (*types.MsgDelegateResponse, error) {\n\tctx := sdk.UnwrapSDKContext(goCtx)\n\tvalAddr, valErr := sdk.ValAddressFromBech32(msg.ValidatorAddress)\n\tif valErr != nil {\n\t\treturn nil, valErr\n\t}\n\n\tvalidator, found := k.GetValidator(ctx, valAddr)\n\tif !found {\n\t\treturn nil, types.ErrNoValidatorFound\n\t}\n\n\tdelegatorAddress, err := sdk.AccAddressFromBech32(msg.DelegatorAddress)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbondDenom := k.BondDenom(ctx)\n\tif msg.Amount.Denom != bondDenom {\n\t\treturn nil, sdkerrors.Wrapf(\n\t\t\tsdkerrors.ErrInvalidRequest, \"invalid coin denomination: got %s, expected %s\", msg.Amount.Denom, bondDenom,\n\t\t)\n\t}\n\n\ttokens := msg.Amount.Amount\n\n\t// if this delegation is from a liquid staking provider (identified if the delegator\n\t// is an ICA account), it cannot exceed the global or validator bond cap\n\tif k.DelegatorIsLiquidStaker(delegatorAddress) {\n\t\tshares, err := validator.SharesFromTokens(tokens)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif err := k.SafelyIncreaseTotalLiquidStakedTokens(ctx, tokens, false); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif err := k.SafelyIncreaseValidatorLiquidShares(ctx, &validator, shares); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// NOTE: source funds are always unbonded\n\tnewShares, err := k.Keeper.Delegate(ctx, delegatorAddress, tokens, types.Unbonded, validator, true)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif tokens.IsInt64() {\n\t\tdefer func() {\n\t\t\ttelemetry.IncrCounter(1, types.ModuleName, \"delegate\")\n\t\t\ttelemetry.SetGaugeWithLabels(\n\t\t\t\t[]string{\"tx\", \"msg\", msg.Type()},\n\t\t\t\tfloat32(tokens.Int64()),\n\t\t\t\t[]metrics.Label{telemetry.NewLabel(\"denom\", msg.Amount.Denom)},\n\t\t\t)\n\t\t}()\n\t}\n\n\tctx.EventManager().EmitEvents(sdk.Events{\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeDelegate,\n\t\t\tsdk.NewAttribute(types.AttributeKeyValidator, msg.ValidatorAddress),\n\t\t\tsdk.NewAttribute(sdk.AttributeKeyAmount, msg.Amount.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyNewShares, newShares.String()),\n\t\t),\n\t})\n\n\treturn &types.MsgDelegateResponse{}, nil\n}", "func (k Keeper) TransferDelegation(ctx sdk.Context, valAddr sdk.ValAddress, fromDelegator, toDelegator sdk.AccAddress, shares sdk.Dec) (sdk.Dec, error) {\n\t// Redelegations link a delegation to it's previous validator so slashes are propagated to the new validator.\n\t// If the delegation is transferred to a new owner, the redelegation object must be updated.\n\t// For expediency all transfers with redelegations are blocked.\n\tif k.stakingKeeper.HasReceivingRedelegation(ctx, fromDelegator, valAddr) {\n\t\treturn sdk.Dec{}, types.ErrRedelegationsNotCompleted\n\t}\n\n\tif shares.IsNil() || shares.LT(sdk.ZeroDec()) {\n\t\treturn sdk.Dec{}, errorsmod.Wrap(types.ErrUntransferableShares, \"nil or negative shares\")\n\t}\n\tif shares.Equal(sdk.ZeroDec()) {\n\t\t// Block 0 transfers to reduce edge cases.\n\t\treturn sdk.Dec{}, errorsmod.Wrap(types.ErrUntransferableShares, \"zero shares\")\n\t}\n\n\tfromDelegation, found := k.stakingKeeper.GetDelegation(ctx, fromDelegator, valAddr)\n\tif !found {\n\t\treturn sdk.Dec{}, types.ErrNoDelegatorForAddress\n\t}\n\tvalidator, found := k.stakingKeeper.GetValidator(ctx, valAddr)\n\tif !found {\n\t\treturn sdk.Dec{}, types.ErrNoValidatorFound\n\t}\n\t// Prevent validators from reducing their self delegation below the min.\n\tisValidatorOperator := fromDelegator.Equals(valAddr)\n\tif isValidatorOperator {\n\t\tif isBelowMinSelfDelegation(validator, fromDelegation.Shares.Sub(shares)) {\n\t\t\treturn sdk.Dec{}, types.ErrSelfDelegationBelowMinimum\n\t\t}\n\t}\n\n\treturnAmount, err := k.fastUndelegate(ctx, valAddr, fromDelegator, shares)\n\tif err != nil {\n\t\treturn sdk.Dec{}, err\n\t}\n\treturnCoins := sdk.NewCoins(sdk.NewCoin(k.stakingKeeper.BondDenom(ctx), returnAmount))\n\n\tif err := k.bankKeeper.SendCoins(ctx, fromDelegator, toDelegator, returnCoins); err != nil {\n\t\treturn sdk.Dec{}, err\n\t}\n\treceivedShares, err := k.delegateFromAccount(ctx, valAddr, toDelegator, returnAmount)\n\tif err != nil {\n\t\treturn sdk.Dec{}, err\n\t}\n\n\treturn receivedShares, nil\n}", "func (m *AgedAccountsPayable) GetCurrentAmount()(*float64) {\n val, err := m.GetBackingStore().Get(\"currentAmount\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*float64)\n }\n return nil\n}", "func (bva *BaseVestingAccount) TrackDelegation(balance, vestingCoins, amount sdk.Coins) {\n\tfor _, coin := range amount {\n\t\tbaseAmt := balance.AmountOf(coin.Denom)\n\t\tvestingAmt := vestingCoins.AmountOf(coin.Denom)\n\t\tdelVestingAmt := bva.DelegatedVesting.AmountOf(coin.Denom)\n\n\t\t// Panic if the delegation amount is zero or if the base coins does not\n\t\t// exceed the desired delegation amount.\n\t\tif coin.Amount.IsZero() || baseAmt.LT(coin.Amount) {\n\t\t\tpanic(\"delegation attempt with zero coins or insufficient funds\")\n\t\t}\n\n\t\t// compute x and y per the specification, where:\n\t\t// X := min(max(V - DV, 0), D)\n\t\t// Y := D - X\n\t\tx := sdk.MinInt(sdk.MaxInt(vestingAmt.Sub(delVestingAmt), sdk.ZeroInt()), coin.Amount)\n\t\ty := coin.Amount.Sub(x)\n\n\t\tif !x.IsZero() {\n\t\t\txCoin := sdk.NewCoin(coin.Denom, x)\n\t\t\tbva.DelegatedVesting = bva.DelegatedVesting.Add(xCoin)\n\t\t}\n\n\t\tif !y.IsZero() {\n\t\t\tyCoin := sdk.NewCoin(coin.Denom, y)\n\t\t\tbva.DelegatedFree = bva.DelegatedFree.Add(yCoin)\n\t\t}\n\t}\n}", "func (ftm *FtmBridge) PendingWithdrawalsAmount(addr *common.Address, staker *big.Int) (*big.Int, error) {\n\t// get withdraw requests list\n\tlist, err := ftm.withdrawRequestsList(addr, staker)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// start with an empty value\n\tvalue := big.NewInt(0)\n\n\t// loop over the list of requests and add non-finished\n\tfor _, req := range list {\n\t\t// is this request doesn't have a finalization block number\n\t\t// it's still pending and it's amount will be added\n\t\t// to the pending total\n\t\tif req.WithdrawBlockNumber == nil {\n\t\t\tvalue = new(big.Int).Add(value, req.Amount.ToInt())\n\t\t}\n\t}\n\n\treturn value, nil\n}", "func (k Keeper) fastUndelegate(ctx sdk.Context, valAddr sdk.ValAddress, delegator sdk.AccAddress, shares sdk.Dec) (sdkmath.Int, error) {\n\tvalidator, found := k.stakingKeeper.GetValidator(ctx, valAddr)\n\tif !found {\n\t\treturn sdkmath.Int{}, types.ErrNoDelegatorForAddress\n\t}\n\n\treturnAmount, err := k.stakingKeeper.Unbond(ctx, delegator, valAddr, shares)\n\tif err != nil {\n\t\treturn sdkmath.Int{}, err\n\t}\n\treturnCoins := sdk.NewCoins(sdk.NewCoin(k.stakingKeeper.BondDenom(ctx), returnAmount))\n\n\t// transfer the validator tokens to the not bonded pool\n\tif validator.IsBonded() {\n\t\tif err := k.bankKeeper.SendCoinsFromModuleToModule(ctx, stakingtypes.BondedPoolName, stakingtypes.NotBondedPoolName, returnCoins); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\n\tif err := k.bankKeeper.UndelegateCoinsFromModuleToAccount(ctx, stakingtypes.NotBondedPoolName, delegator, returnCoins); err != nil {\n\t\treturn sdkmath.Int{}, err\n\t}\n\treturn returnAmount, nil\n}", "func (k Querier) DelegatorUnbondingDelegations(ctx context.Context, req *types.QueryDelegatorUnbondingDelegationsRequest) (*types.QueryDelegatorUnbondingDelegationsResponse, error) {\n\tif req == nil {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"empty request\")\n\t}\n\n\tif req.DelegatorAddr == \"\" {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"delegator address cannot be empty\")\n\t}\n\tvar unbondingDelegations types.UnbondingDelegations\n\n\tdelAddr, err := k.authKeeper.AddressCodec().StringToBytes(req.DelegatorAddr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t_, pageRes, err := query.CollectionPaginate(\n\t\tctx,\n\t\tk.UnbondingDelegations,\n\t\treq.Pagination,\n\t\tfunc(key collections.Pair[[]byte, []byte], value types.UnbondingDelegation) (types.UnbondingDelegation, error) {\n\t\t\tunbondingDelegations = append(unbondingDelegations, value)\n\t\t\treturn value, nil\n\t\t},\n\t\tquery.WithCollectionPaginationPairPrefix[[]byte, []byte](delAddr),\n\t)\n\tif err != nil {\n\t\treturn nil, status.Error(codes.Internal, err.Error())\n\t}\n\n\treturn &types.QueryDelegatorUnbondingDelegationsResponse{\n\t\tUnbondingResponses: unbondingDelegations, Pagination: pageRes,\n\t}, nil\n}", "func (_DelegationController *DelegationControllerTransactorSession) AcceptPendingDelegation(delegationId *big.Int) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.AcceptPendingDelegation(&_DelegationController.TransactOpts, delegationId)\n}", "func (o QuotaLimitOutput) FreeTier() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v QuotaLimit) *string { return v.FreeTier }).(pulumi.StringPtrOutput)\n}", "func (_DelegationController *DelegationControllerSession) AcceptPendingDelegation(delegationId *big.Int) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.AcceptPendingDelegation(&_DelegationController.TransactOpts, delegationId)\n}", "func (k msgServer) Undelegate(goCtx context.Context, msg *types.MsgUndelegate) (*types.MsgUndelegateResponse, error) {\n\tctx := sdk.UnwrapSDKContext(goCtx)\n\n\taddr, err := sdk.ValAddressFromBech32(msg.ValidatorAddress)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdelegatorAddress, err := sdk.AccAddressFromBech32(msg.DelegatorAddress)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttokens := msg.Amount.Amount\n\tshares, err := k.ValidateUnbondAmount(\n\t\tctx, delegatorAddress, addr, tokens,\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvalidator, found := k.GetValidator(ctx, addr)\n\tif !found {\n\t\treturn nil, types.ErrNoValidatorFound\n\t}\n\n\tdelegation, found := k.GetDelegation(ctx, delegatorAddress, addr)\n\tif !found {\n\t\treturn nil, status.Errorf(\n\t\t\tcodes.NotFound,\n\t\t\t\"delegation with delegator %s not found for validator %s\",\n\t\t\tmsg.DelegatorAddress, msg.ValidatorAddress,\n\t\t)\n\t}\n\n\t// if this is a validator self-bond, the new liquid delegation cannot fall below the self-bond * bond factor\n\tif delegation.ValidatorBond {\n\t\tif err := k.SafelyDecreaseValidatorBond(ctx, &validator, shares); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// if this delegation is from a liquid staking provider (identified if the delegator\n\t// is an ICA account), the global and validator liquid totals should be decremented\n\tif k.DelegatorIsLiquidStaker(delegatorAddress) {\n\t\tif err := k.DecreaseTotalLiquidStakedTokens(ctx, tokens); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif err := k.DecreaseValidatorLiquidShares(ctx, &validator, shares); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tbondDenom := k.BondDenom(ctx)\n\tif msg.Amount.Denom != bondDenom {\n\t\treturn nil, sdkerrors.Wrapf(\n\t\t\tsdkerrors.ErrInvalidRequest, \"invalid coin denomination: got %s, expected %s\", msg.Amount.Denom, bondDenom,\n\t\t)\n\t}\n\n\tcompletionTime, err := k.Keeper.Undelegate(ctx, delegatorAddress, addr, shares)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif tokens.IsInt64() {\n\t\tdefer func() {\n\t\t\ttelemetry.IncrCounter(1, types.ModuleName, \"undelegate\")\n\t\t\ttelemetry.SetGaugeWithLabels(\n\t\t\t\t[]string{\"tx\", \"msg\", msg.Type()},\n\t\t\t\tfloat32(tokens.Int64()),\n\t\t\t\t[]metrics.Label{telemetry.NewLabel(\"denom\", msg.Amount.Denom)},\n\t\t\t)\n\t\t}()\n\t}\n\n\tctx.EventManager().EmitEvents(sdk.Events{\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeUnbond,\n\t\t\tsdk.NewAttribute(types.AttributeKeyValidator, msg.ValidatorAddress),\n\t\t\tsdk.NewAttribute(sdk.AttributeKeyAmount, msg.Amount.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyCompletionTime, completionTime.Format(time.RFC3339)),\n\t\t),\n\t})\n\n\treturn &types.MsgUndelegateResponse{\n\t\tCompletionTime: completionTime,\n\t}, nil\n}", "func (_DelegationController *DelegationControllerCaller) GetLockedInPendingDelegations(opts *bind.CallOpts, holder common.Address) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _DelegationController.contract.Call(opts, out, \"getLockedInPendingDelegations\", holder)\n\treturn *ret0, err\n}", "func (_Dospayment *DospaymentSession) DefaultGuardianFee() (*big.Int, error) {\n\treturn _Dospayment.Contract.DefaultGuardianFee(&_Dospayment.CallOpts)\n}", "func (o *APIServiceAddressParams) SetDelegated(delegated *bool) {\n\to.Delegated = delegated\n}", "func (_Dospayment *DospaymentCaller) DefaultGuardianFee(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _Dospayment.contract.Call(opts, out, \"defaultGuardianFee\")\n\treturn *ret0, err\n}", "func (_DelegationController *DelegationControllerCallerSession) GetLockedInPendingDelegations(holder common.Address) (*big.Int, error) {\n\treturn _DelegationController.Contract.GetLockedInPendingDelegations(&_DelegationController.CallOpts, holder)\n}", "func (_DelegationController *DelegationControllerSession) GetLockedInPendingDelegations(holder common.Address) (*big.Int, error) {\n\treturn _DelegationController.Contract.GetLockedInPendingDelegations(&_DelegationController.CallOpts, holder)\n}", "func (_Dospayment *DospaymentCallerSession) DefaultGuardianFee() (*big.Int, error) {\n\treturn _Dospayment.Contract.DefaultGuardianFee(&_Dospayment.CallOpts)\n}", "func (o *AssetReportFreddieGetResponse) GetDEALOk() (*AssetReportFreddie, bool) {\n\tif o == nil {\n\t\treturn nil, false\n\t}\n\treturn &o.DEAL, true\n}", "func CalculatePayoutForContract(contract Contract, rate float64, delegate bool) Contract{\n ////-------------JUST FOR TESTING -------------////\n totalNodeRewards := 378 //Amount of rewards for my delegation in cycle 11\n ////--------------END TESTING ------------------////\n\n grossRewards := contract.SharePercentage * float64(totalNodeRewards)\n contract.GrossPayout = grossRewards\n fee := rate * grossRewards\n contract.Fee = fee\n var netRewards float64\n if (delegate){\n netRewards = grossRewards\n contract.NetPayout = netRewards\n contract.Fee = 0\n } else {\n netRewards = grossRewards - fee\n contract.NetPayout = contract.NetPayout + netRewards\n }\n\n return contract\n}", "func (g *Group) GetFreePort() uint16 {\n\n\tvar ports []uint16\n\t/*\n\t\tfor _, s := range g.Services {\n\t\t\tports = append(ports, s.Ports...)\n\t\t}\n\t*/\n\tfor i := g.MinPort; i < g.MaxPort; i++ {\n\t\tif !findPort(i, ports) {\n\t\t\treturn i\n\t\t}\n\t}\n\n\treturn 0\n}", "func (_DelegationController *DelegationControllerCallerSession) GetDelegation(delegationId *big.Int) (DelegationControllerDelegation, error) {\n\treturn _DelegationController.Contract.GetDelegation(&_DelegationController.CallOpts, delegationId)\n}", "func (dcr *ExchangeWallet) feeRateWithFallback(feeSuggestion uint64) uint64 {\n\tif feeSuggestion > 0 && feeSuggestion < dcr.feeRateLimit {\n\t\tdcr.log.Tracef(\"Using caller's suggestion for fee rate, %d\", feeSuggestion)\n\t\treturn feeSuggestion\n\t}\n\tdcr.log.Warnf(\"No usable fee rate suggestion. Using fallback of %d\", dcr.fallbackFeeRate)\n\treturn dcr.fallbackFeeRate\n}", "func (_ChpRegistry *ChpRegistryCallerSession) NODESTAKINGAMOUNT() (*big.Int, error) {\n\treturn _ChpRegistry.Contract.NODESTAKINGAMOUNT(&_ChpRegistry.CallOpts)\n}", "func (m *ParcelMock) DelegationToken() (r insolar.DelegationToken) {\n\tcounter := atomic.AddUint64(&m.DelegationTokenPreCounter, 1)\n\tdefer atomic.AddUint64(&m.DelegationTokenCounter, 1)\n\n\tif len(m.DelegationTokenMock.expectationSeries) > 0 {\n\t\tif counter > uint64(len(m.DelegationTokenMock.expectationSeries)) {\n\t\t\tm.t.Fatalf(\"Unexpected call to ParcelMock.DelegationToken.\")\n\t\t\treturn\n\t\t}\n\n\t\tresult := m.DelegationTokenMock.expectationSeries[counter-1].result\n\t\tif result == nil {\n\t\t\tm.t.Fatal(\"No results are set for the ParcelMock.DelegationToken\")\n\t\t\treturn\n\t\t}\n\n\t\tr = result.r\n\n\t\treturn\n\t}\n\n\tif m.DelegationTokenMock.mainExpectation != nil {\n\n\t\tresult := m.DelegationTokenMock.mainExpectation.result\n\t\tif result == nil {\n\t\t\tm.t.Fatal(\"No results are set for the ParcelMock.DelegationToken\")\n\t\t}\n\n\t\tr = result.r\n\n\t\treturn\n\t}\n\n\tif m.DelegationTokenFunc == nil {\n\t\tm.t.Fatalf(\"Unexpected call to ParcelMock.DelegationToken.\")\n\t\treturn\n\t}\n\n\treturn m.DelegationTokenFunc()\n}", "func (x *fastReflection_DelegatorWithdrawInfo) Get(descriptor protoreflect.FieldDescriptor) protoreflect.Value {\n\tswitch descriptor.FullName() {\n\tcase \"cosmos.distribution.v1beta1.DelegatorWithdrawInfo.delegator_address\":\n\t\tvalue := x.DelegatorAddress\n\t\treturn protoreflect.ValueOfString(value)\n\tcase \"cosmos.distribution.v1beta1.DelegatorWithdrawInfo.withdraw_address\":\n\t\tvalue := x.WithdrawAddress\n\t\treturn protoreflect.ValueOfString(value)\n\tdefault:\n\t\tif descriptor.IsExtension() {\n\t\t\tpanic(fmt.Errorf(\"proto3 declared messages do not support extensions: cosmos.distribution.v1beta1.DelegatorWithdrawInfo\"))\n\t\t}\n\t\tpanic(fmt.Errorf(\"message cosmos.distribution.v1beta1.DelegatorWithdrawInfo does not contain field %s\", descriptor.FullName()))\n\t}\n}", "func (_ElvTradableLocal *ElvTradableLocalCaller) GetTransferFee(opts *bind.CallOpts, _tokenId *big.Int) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _ElvTradableLocal.contract.Call(opts, &out, \"getTransferFee\", _tokenId)\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (acc *Account) Deposit(amount int64) (newBalance int64, ok bool) {\n\tacc.mu.Lock()\n\tdefer acc.mu.Unlock()\n\tif acc.closed {\n\t\treturn 0, false\n\t}\n\tnewBalance = acc.balance + amount\n\tif newBalance < 0 {\n\t\treturn acc.balance, false\n\t}\n\tacc.balance = newBalance\n\treturn acc.balance, true\n}", "func (m *AgedAccountsPayable) GetBalanceDue()(*float64) {\n val, err := m.GetBackingStore().Get(\"balanceDue\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*float64)\n }\n return nil\n}", "func (_DelegationController *DelegationControllerTransactor) GetAndUpdateLockedAmount(opts *bind.TransactOpts, wallet common.Address) (*types.Transaction, error) {\n\treturn _DelegationController.contract.Transact(opts, \"getAndUpdateLockedAmount\", wallet)\n}", "func consolidateDelegations(ctx contract.Context, validator, delegator *types.Address) (*Delegation, []*Delegation, int, error) {\n\t// cycle through all delegations and delete those which are BONDED and\n\t// unlocked while accumulating their amounts\n\tdelegations, err := returnMatchingDelegations(ctx, validator, delegator)\n\tif err != nil {\n\t\treturn nil, nil, -1, err\n\t}\n\n\tunconsolidatedDelegationsCount := 0\n\ttotalDelegationAmount := common.BigZero()\n\tvar consolidatedDelegations []*Delegation\n\tfor _, delegation := range delegations {\n\t\tif delegation.LockTime > uint64(ctx.Now().Unix()) || delegation.State != BONDED {\n\t\t\tunconsolidatedDelegationsCount++\n\t\t\tcontinue\n\t\t}\n\n\t\ttotalDelegationAmount.Add(totalDelegationAmount, &delegation.Amount.Value)\n\t\tconsolidatedDelegations = append(consolidatedDelegations, delegation)\n\n\t\tif err = DeleteDelegation(ctx, delegation); err != nil {\n\t\t\treturn nil, nil, -1, err\n\t\t}\n\t}\n\n\tindex, err := GetNextDelegationIndex(ctx, *validator, *delegator)\n\tif err != nil {\n\t\treturn nil, nil, -1, err\n\t}\n\n\t// create new conolidated delegation\n\tdelegation := &Delegation{\n\t\tValidator: validator,\n\t\tDelegator: delegator,\n\t\tAmount: &types.BigUInt{Value: *totalDelegationAmount},\n\t\tUpdateAmount: loom.BigZeroPB(),\n\t\tLocktimeTier: 0,\n\t\tLockTime: 0,\n\t\tState: BONDED,\n\t\tIndex: index,\n\t}\n\tif err := SetDelegation(ctx, delegation); err != nil {\n\t\treturn nil, nil, -1, err\n\t}\n\treturn delegation, consolidatedDelegations, unconsolidatedDelegationsCount, nil\n}", "func (k Querier) Delegation(ctx context.Context, req *types.QueryDelegationRequest) (*types.QueryDelegationResponse, error) {\n\tif req == nil {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"empty request\")\n\t}\n\n\tif req.DelegatorAddr == \"\" {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"delegator address cannot be empty\")\n\t}\n\tif req.ValidatorAddr == \"\" {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"validator address cannot be empty\")\n\t}\n\n\tdelAddr, err := k.authKeeper.AddressCodec().StringToBytes(req.DelegatorAddr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvalAddr, err := k.validatorAddressCodec.StringToBytes(req.ValidatorAddr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdelegation, err := k.Delegations.Get(ctx, collections.Join(sdk.AccAddress(delAddr), sdk.ValAddress(valAddr)))\n\tif err != nil {\n\t\tif errors.Is(err, collections.ErrNotFound) {\n\t\t\treturn nil, status.Errorf(\n\t\t\t\tcodes.NotFound,\n\t\t\t\t\"delegation with delegator %s not found for validator %s\",\n\t\t\t\treq.DelegatorAddr, req.ValidatorAddr)\n\t\t}\n\t\treturn nil, status.Error(codes.Internal, err.Error())\n\t}\n\n\tdelResponse, err := delegationToDelegationResponse(ctx, k.Keeper, delegation)\n\tif err != nil {\n\t\treturn nil, status.Error(codes.Internal, err.Error())\n\t}\n\n\treturn &types.QueryDelegationResponse{DelegationResponse: &delResponse}, nil\n}", "func (f *Fortune) Withdrawal(amount decimal.Decimal) {\n\tf.active = f.active.Sub(amount)\n}", "func GetDelegatorWithdrawInfoAddress(key []byte) (delAddr sdk.AccAddress) {\n\taddr := key[1:]\n\tif len(addr) != sdk.AddrLen {\n\t\tpanic(\"unexpected key length\")\n\t}\n\treturn sdk.AccAddress(addr)\n}", "func (o *GetStakingDelegatorsDelegatorAddrUnbondingDelegationsParams) WithDelegatorAddr(delegatorAddr string) *GetStakingDelegatorsDelegatorAddrUnbondingDelegationsParams {\n\to.SetDelegatorAddr(delegatorAddr)\n\treturn o\n}", "func (acc Account) Debit(amount uint) uint {\n\t// convert incoming amount into cents and subtract to account balance\n\treturn acc.AvailableBalance - (amount * 100)\n}", "func (_EtherDelta *EtherDeltaCaller) AmountFilled(opts *bind.CallOpts, tokenGet common.Address, amountGet *big.Int, tokenGive common.Address, amountGive *big.Int, expires *big.Int, nonce *big.Int, user common.Address, v uint8, r [32]byte, s [32]byte) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _EtherDelta.contract.Call(opts, out, \"amountFilled\", tokenGet, amountGet, tokenGive, amountGive, expires, nonce, user, v, r, s)\n\treturn *ret0, err\n}", "func (_DelegationController *DelegationControllerSession) GetDelegation(delegationId *big.Int) (DelegationControllerDelegation, error) {\n\treturn _DelegationController.Contract.GetDelegation(&_DelegationController.CallOpts, delegationId)\n}", "func (_Withdrawable *WithdrawableCaller) GetDepositedBalance(opts *bind.CallOpts, arg0 common.Address, arg1 common.Address) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _Withdrawable.contract.Call(opts, out, \"getDepositedBalance\", arg0, arg1)\n\treturn *ret0, err\n}", "func (o QuotaLimitResponseOutput) FreeTier() pulumi.StringOutput {\n\treturn o.ApplyT(func(v QuotaLimitResponse) string { return v.FreeTier }).(pulumi.StringOutput)\n}", "func (sc SfcConfig) MaxDelegatedRatio() (hexutil.Big, error) {\n\tc, err := sc.getConfig()\n\tif err != nil {\n\t\treturn hexutil.Big{}, err\n\t}\n\treturn c.MaxDelegatedRatio, nil\n}", "func (f Fortune) Active() decimal.Decimal { return f.active }", "func CalculateTotalPayout(delegatedContract DelegatedContract) DelegatedContract{\n for _, contract := range delegatedContract.Contracts{\n delegatedContract.TotalPayout = delegatedContract.TotalPayout + contract.NetPayout\n }\n return delegatedContract\n}", "func (k msgServer) CancelUnbondingDelegation(goCtx context.Context, msg *types.MsgCancelUnbondingDelegation) (*types.MsgCancelUnbondingDelegationResponse, error) {\n\tctx := sdk.UnwrapSDKContext(goCtx)\n\n\tvalAddr, err := sdk.ValAddressFromBech32(msg.ValidatorAddress)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdelegatorAddress, err := sdk.AccAddressFromBech32(msg.DelegatorAddress)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbondDenom := k.BondDenom(ctx)\n\tif msg.Amount.Denom != bondDenom {\n\t\treturn nil, sdkerrors.Wrapf(\n\t\t\tsdkerrors.ErrInvalidRequest, \"invalid coin denomination: got %s, expected %s\", msg.Amount.Denom, bondDenom,\n\t\t)\n\t}\n\n\tvalidator, found := k.GetValidator(ctx, valAddr)\n\tif !found {\n\t\treturn nil, types.ErrNoValidatorFound\n\t}\n\n\t// In some situations, the exchange rate becomes invalid, e.g. if\n\t// Validator loses all tokens due to slashing. In this case,\n\t// make all future delegations invalid.\n\tif validator.InvalidExRate() {\n\t\treturn nil, types.ErrDelegatorShareExRateInvalid\n\t}\n\n\tif validator.IsJailed() {\n\t\treturn nil, types.ErrValidatorJailed\n\t}\n\n\tubd, found := k.GetUnbondingDelegation(ctx, delegatorAddress, valAddr)\n\tif !found {\n\t\treturn nil, status.Errorf(\n\t\t\tcodes.NotFound,\n\t\t\t\"unbonding delegation with delegator %s not found for validator %s\",\n\t\t\tmsg.DelegatorAddress, msg.ValidatorAddress,\n\t\t)\n\t}\n\n\t// if this undelegation was from a liquid staking provider (identified if the delegator\n\t// is an ICA account), the global and validator liquid totals should be incremented\n\ttokens := msg.Amount.Amount\n\tshares, err := validator.SharesFromTokens(tokens)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif k.DelegatorIsLiquidStaker(delegatorAddress) {\n\t\tif err := k.SafelyIncreaseTotalLiquidStakedTokens(ctx, tokens, false); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif err := k.SafelyIncreaseValidatorLiquidShares(ctx, &validator, shares); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tvar (\n\t\tunbondEntry types.UnbondingDelegationEntry\n\t\tunbondEntryIndex int64 = -1\n\t)\n\n\tfor i, entry := range ubd.Entries {\n\t\tif entry.CreationHeight == msg.CreationHeight {\n\t\t\tunbondEntry = entry\n\t\t\tunbondEntryIndex = int64(i)\n\t\t\tbreak\n\t\t}\n\t}\n\tif unbondEntryIndex == -1 {\n\t\treturn nil, sdkerrors.ErrNotFound.Wrapf(\"unbonding delegation entry is not found at block height %d\", msg.CreationHeight)\n\t}\n\n\tif unbondEntry.Balance.LT(msg.Amount.Amount) {\n\t\treturn nil, sdkerrors.ErrInvalidRequest.Wrap(\"amount is greater than the unbonding delegation entry balance\")\n\t}\n\n\tif unbondEntry.CompletionTime.Before(ctx.BlockTime()) {\n\t\treturn nil, sdkerrors.ErrInvalidRequest.Wrap(\"unbonding delegation is already processed\")\n\t}\n\n\t// delegate back the unbonding delegation amount to the validator\n\t_, err = k.Keeper.Delegate(ctx, delegatorAddress, msg.Amount.Amount, types.Unbonding, validator, false)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tamount := unbondEntry.Balance.Sub(msg.Amount.Amount)\n\tif amount.IsZero() {\n\t\tubd.RemoveEntry(unbondEntryIndex)\n\t} else {\n\t\t// update the unbondingDelegationEntryBalance and InitialBalance for ubd entry\n\t\tunbondEntry.Balance = amount\n\t\tunbondEntry.InitialBalance = unbondEntry.InitialBalance.Sub(msg.Amount.Amount)\n\t\tubd.Entries[unbondEntryIndex] = unbondEntry\n\t}\n\n\t// set the unbonding delegation or remove it if there are no more entries\n\tif len(ubd.Entries) == 0 {\n\t\tk.RemoveUnbondingDelegation(ctx, ubd)\n\t} else {\n\t\tk.SetUnbondingDelegation(ctx, ubd)\n\t}\n\n\tctx.EventManager().EmitEvent(\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeCancelUnbondingDelegation,\n\t\t\tsdk.NewAttribute(sdk.AttributeKeyAmount, msg.Amount.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyValidator, msg.ValidatorAddress),\n\t\t\tsdk.NewAttribute(types.AttributeKeyDelegator, msg.DelegatorAddress),\n\t\t\tsdk.NewAttribute(types.AttributeKeyCreationHeight, strconv.FormatInt(msg.CreationHeight, 10)),\n\t\t),\n\t)\n\n\treturn &types.MsgCancelUnbondingDelegationResponse{}, nil\n}", "func (_Cakevault *CakevaultCallerSession) MAXWITHDRAWFEE() (*big.Int, error) {\n\treturn _Cakevault.Contract.MAXWITHDRAWFEE(&_Cakevault.CallOpts)\n}", "func (_ChpRegistry *ChpRegistrySession) NODESTAKINGAMOUNT() (*big.Int, error) {\n\treturn _ChpRegistry.Contract.NODESTAKINGAMOUNT(&_ChpRegistry.CallOpts)\n}", "func (_Vault *VaultCaller) GetDepositedBalance(opts *bind.CallOpts, token common.Address, owner common.Address) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _Vault.contract.Call(opts, out, \"getDepositedBalance\", token, owner)\n\treturn *ret0, err\n}", "func (_TokenStakingEscrow *TokenStakingEscrowCaller) DepositedAmount(opts *bind.CallOpts, operator common.Address) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _TokenStakingEscrow.contract.Call(opts, out, \"depositedAmount\", operator)\n\treturn *ret0, err\n}", "func (_L1Block *L1BlockCallerSession) DEPOSITORACCOUNT() (common.Address, error) {\n\treturn _L1Block.Contract.DEPOSITORACCOUNT(&_L1Block.CallOpts)\n}", "func (a *Account) Deposit(depAmt int) (int, bool) {\n\tcMutex.Lock()\n\tdefer cMutex.Unlock()\n\n\tif a.isOpen && (a.balance+depAmt >= 0) {\n\t\ta.balance += depAmt\n\t\treturn a.balance, true\n\t}\n\n\treturn a.balance, false\n}", "func (_TokensNetwork *TokensNetworkTransactor) UnlockDelegate(opts *bind.TransactOpts, token common.Address, partner common.Address, participant common.Address, transferred_amount *big.Int, expiration *big.Int, amount *big.Int, secret_hash [32]byte, merkle_proof []byte, participant_signature []byte) (*types.Transaction, error) {\n\treturn _TokensNetwork.contract.Transact(opts, \"unlockDelegate\", token, partner, participant, transferred_amount, expiration, amount, secret_hash, merkle_proof, participant_signature)\n}", "func (_PlasmaFramework *PlasmaFrameworkCaller) NextDeposit(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _PlasmaFramework.contract.Call(opts, out, \"nextDeposit\")\n\treturn *ret0, err\n}", "func (f GatewayFilter) WithFreeToUse(freeToUse bool) GatewayFilter {\n\treturn append(f, bson.E{Key: \"free_to_use\", Value: freeToUse})\n}", "func (o *StorageBaseCapacity) GetFreeOk() (*int64, bool) {\n\tif o == nil || o.Free == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Free, true\n}", "func (_Token *TokenCallerSession) PendingBurner() (common.Address, error) {\n\treturn _Token.Contract.PendingBurner(&_Token.CallOpts)\n}", "func (x *fastReflection_DelegatorWithdrawInfo) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) {\n\tif x.DelegatorAddress != \"\" {\n\t\tvalue := protoreflect.ValueOfString(x.DelegatorAddress)\n\t\tif !f(fd_DelegatorWithdrawInfo_delegator_address, value) {\n\t\t\treturn\n\t\t}\n\t}\n\tif x.WithdrawAddress != \"\" {\n\t\tvalue := protoreflect.ValueOfString(x.WithdrawAddress)\n\t\tif !f(fd_DelegatorWithdrawInfo_withdraw_address, value) {\n\t\t\treturn\n\t\t}\n\t}\n}", "func (_ElvTradable *ElvTradableCaller) GetTransferFee(opts *bind.CallOpts, _tokenId *big.Int) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _ElvTradable.contract.Call(opts, &out, \"getTransferFee\", _tokenId)\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (_DelegationController *DelegationControllerTransactor) Delegate(opts *bind.TransactOpts, validatorId *big.Int, amount *big.Int, delegationPeriod *big.Int, info string) (*types.Transaction, error) {\n\treturn _DelegationController.contract.Transact(opts, \"delegate\", validatorId, amount, delegationPeriod, info)\n}", "func (_DelegationController *DelegationControllerCaller) GetAndUpdateDelegatedByHolderToValidatorNowReadOnly(opts *bind.CallOpts, holder common.Address, validatorId *big.Int) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\t//params := [1]Bytes{wallet.Bytes()}\n\terr := _DelegationController.contract.Call(opts, ret0, \"getAndUpdateDelegatedByHolderToValidatorNow\", holder, validatorId)\n\treturn *ret0, err\n}", "func (_EtherDelta *EtherDeltaCallerSession) AmountFilled(tokenGet common.Address, amountGet *big.Int, tokenGive common.Address, amountGive *big.Int, expires *big.Int, nonce *big.Int, user common.Address, v uint8, r [32]byte, s [32]byte) (*big.Int, error) {\n\treturn _EtherDelta.Contract.AmountFilled(&_EtherDelta.CallOpts, tokenGet, amountGet, tokenGive, amountGive, expires, nonce, user, v, r, s)\n}", "func (f *Fortune) Deposit(amount decimal.Decimal) {\n\tf.active = f.active.Add(amount)\n}", "func (_ChpRegistry *ChpRegistryCaller) NODESTAKINGAMOUNT(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _ChpRegistry.contract.Call(opts, out, \"NODE_STAKING_AMOUNT\")\n\treturn *ret0, err\n}", "func (_DelegationController *DelegationControllerSession) Delegate(validatorId *big.Int, amount *big.Int, delegationPeriod *big.Int, info string) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.Delegate(&_DelegationController.TransactOpts, validatorId, amount, delegationPeriod, info)\n}", "func GetDelegatorBondKey(delegator crypto.Address, candidate crypto.PubKey) []byte {\n\treturn append(GetDelegatorBondKeyPrefix(delegator), candidate.Bytes()...)\n}", "func GetDelegatorWithdrawAddrKey(delAddr sdk.AccAddress) []byte {\n\treturn append(DelegatorWithdrawAddrPrefix, delAddr.Bytes()...)\n}", "func (_TokenStakingEscrow *TokenStakingEscrowCallerSession) DepositedAmount(operator common.Address) (*big.Int, error) {\n\treturn _TokenStakingEscrow.Contract.DepositedAmount(&_TokenStakingEscrow.CallOpts, operator)\n}" ]
[ "0.6416068", "0.6220628", "0.61514586", "0.5716628", "0.57010835", "0.5647869", "0.55818397", "0.55180794", "0.55074596", "0.5507106", "0.5489881", "0.53663415", "0.5286763", "0.5263716", "0.52178216", "0.506366", "0.505962", "0.5042922", "0.49995175", "0.49780974", "0.49774384", "0.4927477", "0.49093345", "0.48935023", "0.48577845", "0.4832844", "0.48271775", "0.47762653", "0.4741573", "0.4676783", "0.4675203", "0.46646553", "0.46563205", "0.46559483", "0.46518984", "0.46513766", "0.46500406", "0.46484238", "0.4647513", "0.46403238", "0.46170837", "0.46143523", "0.46075767", "0.4597845", "0.4588091", "0.458412", "0.45720032", "0.4571057", "0.45606253", "0.45600483", "0.4557461", "0.4549218", "0.4544041", "0.4503434", "0.4479428", "0.44770113", "0.44718906", "0.445475", "0.4449063", "0.44362918", "0.44246227", "0.4418969", "0.44120154", "0.4410577", "0.44072127", "0.4406723", "0.44030917", "0.44008502", "0.43964764", "0.4396358", "0.43870872", "0.4385226", "0.43770072", "0.4370892", "0.4360077", "0.43590224", "0.435523", "0.43545303", "0.4353183", "0.43523216", "0.4352181", "0.43440396", "0.43383268", "0.43328816", "0.43239713", "0.431307", "0.43109158", "0.43095857", "0.43039688", "0.43032855", "0.42972234", "0.42954546", "0.42914626", "0.4287348", "0.42852828", "0.42837164", "0.4283616", "0.42788914", "0.42735666", "0.426648" ]
0.8334656
0
GetDelegatedVesting returns a vesting account's delegation amount that is still vesting.
func (bva BaseVestingAccount) GetDelegatedVesting() sdk.Coins { return bva.DelegatedVesting }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (b *rpcVestingBalance) delegated() (sdk.Coins, sdk.Coins, error) {\n\tdelegatedCoins, err := b.totalDelegated()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tunbondingCoins, err := b.totalUnbondingDelegations()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tdelegated := delegatedCoins.AmountOf(stakingDenom)\n\tunbonding := unbondingCoins.AmountOf(stakingDenom)\n\ttotalStaked := delegated.Add(unbonding)\n\tdelegatedFree := b.vacc.GetDelegatedFree().AmountOf(stakingDenom)\n\n\t// total number of staked and unbonding tokens considered to be liquid\n\ttotalFree := sdk.MinInt(totalStaked, delegatedFree)\n\t// any coins that are not considered liquid, are vesting up to a maximum of delegated\n\tstakedVesting := sdk.MinInt(totalStaked.Sub(totalFree), delegated)\n\t// staked free coins are left over\n\tstakedFree := delegated.Sub(stakedVesting)\n\n\tliquidCoins := sdk.NewCoins(newKavaCoin(stakedFree))\n\tvestingCoins := sdk.NewCoins(newKavaCoin(stakedVesting))\n\treturn liquidCoins, vestingCoins, nil\n}", "func (bva BaseVestingAccount) GetDelegatedFree() sdk.Coins {\n\treturn bva.DelegatedFree\n}", "func (del Delegation) AmountDelegated() hexutil.Big {\n\tif del.Delegation.AmountDelegated == nil {\n\t\treturn hexutil.Big{}\n\t}\n\treturn *del.Delegation.AmountDelegated\n}", "func (_DelegationController *DelegationControllerTransactor) GetAndUpdateDelegatedAmount(opts *bind.TransactOpts, holder common.Address) (*types.Transaction, error) {\n\treturn _DelegationController.contract.Transact(opts, \"getAndUpdateDelegatedAmount\", holder)\n}", "func (_DelegationController *DelegationControllerSession) GetAndUpdateDelegatedAmount(holder common.Address) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.GetAndUpdateDelegatedAmount(&_DelegationController.TransactOpts, holder)\n}", "func (_DelegationController *DelegationControllerTransactorSession) GetAndUpdateDelegatedAmount(holder common.Address) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.GetAndUpdateDelegatedAmount(&_DelegationController.TransactOpts, holder)\n}", "func (bva *BaseVestingAccount) TrackDelegation(balance, vestingCoins, amount sdk.Coins) {\n\tfor _, coin := range amount {\n\t\tbaseAmt := balance.AmountOf(coin.Denom)\n\t\tvestingAmt := vestingCoins.AmountOf(coin.Denom)\n\t\tdelVestingAmt := bva.DelegatedVesting.AmountOf(coin.Denom)\n\n\t\t// Panic if the delegation amount is zero or if the base coins does not\n\t\t// exceed the desired delegation amount.\n\t\tif coin.Amount.IsZero() || baseAmt.LT(coin.Amount) {\n\t\t\tpanic(\"delegation attempt with zero coins or insufficient funds\")\n\t\t}\n\n\t\t// compute x and y per the specification, where:\n\t\t// X := min(max(V - DV, 0), D)\n\t\t// Y := D - X\n\t\tx := sdk.MinInt(sdk.MaxInt(vestingAmt.Sub(delVestingAmt), sdk.ZeroInt()), coin.Amount)\n\t\ty := coin.Amount.Sub(x)\n\n\t\tif !x.IsZero() {\n\t\t\txCoin := sdk.NewCoin(coin.Denom, x)\n\t\t\tbva.DelegatedVesting = bva.DelegatedVesting.Add(xCoin)\n\t\t}\n\n\t\tif !y.IsZero() {\n\t\t\tyCoin := sdk.NewCoin(coin.Denom, y)\n\t\t\tbva.DelegatedFree = bva.DelegatedFree.Add(yCoin)\n\t\t}\n\t}\n}", "func (del Delegation) Amount() (hexutil.Big, error) {\n\t// lazy load data\n\tif del.extendedAmount == nil {\n\t\tvar err error\n\n\t\t// try to load the data\n\t\tdel.extendedAmount, del.extendedAmountInWithdraw, err = del.repo.DelegatedAmountExtended(&del.Delegation)\n\t\tif err != nil {\n\t\t\treturn hexutil.Big{}, err\n\t\t}\n\t}\n\n\treturn (hexutil.Big)(*del.extendedAmount), nil\n}", "func (del Delegation) Amount() (hexutil.Big, error) {\n\t// get the base amount delegated\n\tbase, err := repository.R().DelegationAmountStaked(&del.Address, del.Delegation.ToStakerId)\n\tif err != nil {\n\t\treturn hexutil.Big{}, err\n\t}\n\n\t// get the sum of all pending withdrawals\n\twd, err := del.pendingWithdrawalsValue()\n\tif err != nil {\n\t\treturn hexutil.Big{}, err\n\t}\n\tval := new(big.Int).Add(base, wd)\n\treturn (hexutil.Big)(*val), nil\n}", "func (del Delegation) LockedAmount() (hexutil.Big, error) {\n\tlock, err := del.DelegationLock()\n\tif err != nil {\n\t\treturn hexutil.Big{}, err\n\t}\n\treturn lock.LockedAmount, nil\n}", "func (_TokenStakingEscrow *TokenStakingEscrowCallerSession) DepositRedelegatedAmount(operator common.Address) (*big.Int, error) {\n\treturn _TokenStakingEscrow.Contract.DepositRedelegatedAmount(&_TokenStakingEscrow.CallOpts, operator)\n}", "func (_TokenStakingEscrow *TokenStakingEscrowSession) DepositRedelegatedAmount(operator common.Address) (*big.Int, error) {\n\treturn _TokenStakingEscrow.Contract.DepositRedelegatedAmount(&_TokenStakingEscrow.CallOpts, operator)\n}", "func (del Delegation) AmountInWithdraw() (hexutil.Big, error) {\n\t// lazy load data\n\tif del.extendedAmountInWithdraw == nil {\n\t\tvar err error\n\n\t\t// try to load the data\n\t\tdel.extendedAmount, del.extendedAmountInWithdraw, err = del.repo.DelegatedAmountExtended(&del.Delegation)\n\t\tif err != nil {\n\t\t\treturn hexutil.Big{}, err\n\t\t}\n\t}\n\n\treturn (hexutil.Big)(*del.extendedAmountInWithdraw), nil\n}", "func (_TokenStakingEscrow *TokenStakingEscrowCaller) DepositRedelegatedAmount(opts *bind.CallOpts, operator common.Address) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _TokenStakingEscrow.contract.Call(opts, out, \"depositRedelegatedAmount\", operator)\n\treturn *ret0, err\n}", "func (_DelegationController *DelegationControllerTransactor) GetAndUpdateForbiddenForDelegationAmount(opts *bind.TransactOpts, wallet common.Address) (*types.Transaction, error) {\n\treturn _DelegationController.contract.Transact(opts, \"getAndUpdateForbiddenForDelegationAmount\", wallet)\n}", "func (_DelegationController *DelegationControllerSession) GetAndUpdateForbiddenForDelegationAmount(wallet common.Address) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.GetAndUpdateForbiddenForDelegationAmount(&_DelegationController.TransactOpts, wallet)\n}", "func (acc *Account) delegationsTotal() (amount *big.Int, inWithdraw *big.Int, rewards *big.Int, err error) {\n\t// pull all the delegations of the account\n\tlist, err := repository.R().DelegationsByAddressAll(&acc.Address)\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\n\t// prep containers for calculation and loop all delegations found\n\tamount = new(big.Int)\n\trewards = new(big.Int)\n\tinWithdraw = new(big.Int)\n\tfor _, dlg := range list {\n\t\t// any active delegated amount?\n\t\tif 0 < dlg.AmountDelegated.ToInt().Uint64() {\n\t\t\tamount = new(big.Int).Add(amount, dlg.AmountDelegated.ToInt())\n\t\t}\n\n\t\t// get pending rewards for this delegation (can be stashed)\n\t\trw, err := repository.R().PendingRewards(&acc.Address, dlg.ToStakerId)\n\t\tif err != nil {\n\t\t\treturn nil, nil, nil, err\n\t\t}\n\n\t\t// any rewards?\n\t\tif 0 < rw.Amount.ToInt().Uint64() {\n\t\t\trewards = new(big.Int).Add(rewards, rw.Amount.ToInt())\n\t\t}\n\n\t\t// get pending withdrawals\n\t\twd, err := repository.R().WithdrawRequestsPendingTotal(&acc.Address, dlg.ToStakerId)\n\t\tif err != nil {\n\t\t\treturn nil, nil, nil, err\n\t\t}\n\n\t\t// add pending withdrawals value\n\t\tif 0 < wd.Uint64() {\n\t\t\tinWithdraw = new(big.Int).Add(inWithdraw, wd)\n\t\t}\n\t}\n\n\treturn amount, rewards, inWithdraw, nil\n}", "func (_TokenVesting *TokenVestingCallerSession) VestedAmount(_token common.Address) (*big.Int, error) {\n\treturn _TokenVesting.Contract.VestedAmount(&_TokenVesting.CallOpts, _token)\n}", "func (_DelegationController *DelegationControllerTransactorSession) GetAndUpdateForbiddenForDelegationAmount(wallet common.Address) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.GetAndUpdateForbiddenForDelegationAmount(&_DelegationController.TransactOpts, wallet)\n}", "func (s *ArkClient) GetDelegateVoteWeight(params DelegateQueryParams) (int, *http.Response, error) {\n\trespData := new(DelegateVoters)\n\trespError := new(ArkApiResponseError)\n\tresp, err := s.sling.New().Get(\"api/delegates/voters\").QueryStruct(&params).Receive(respData, respError)\n\tif err == nil {\n\t\terr = respError\n\t}\n\n\t//calculating vote weight\n\tbalance := 0\n\tif respData.Success {\n\t\tfor _, element := range respData.Accounts {\n\t\t\tintBalance, _ := strconv.Atoi(element.Balance)\n\t\t\tbalance += intBalance\n\t\t}\n\t}\n\n\treturn balance, resp, err\n}", "func (bva BaseVestingAccount) GetOriginalVesting() sdk.Coins {\n\treturn bva.OriginalVesting\n}", "func (k Keeper) Delegation(ctx context.Context, addrDel sdk.AccAddress, addrVal sdk.ValAddress) (types.DelegationI, error) {\n\tbond, err := k.Delegations.Get(ctx, collections.Join(addrDel, addrVal))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn bond, nil\n}", "func (_TokenVesting *TokenVestingSession) VestedAmount(_token common.Address) (*big.Int, error) {\n\treturn _TokenVesting.Contract.VestedAmount(&_TokenVesting.CallOpts, _token)\n}", "func (_TokenVesting *TokenVestingCaller) VestedAmount(opts *bind.CallOpts, _token common.Address) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _TokenVesting.contract.Call(opts, out, \"vestedAmount\", _token)\n\treturn *ret0, err\n}", "func (dva *DelayedVestingAccount) TrackDelegation(blockTime time.Time, balance, amount sdk.Coins) {\n\tdva.BaseVestingAccount.TrackDelegation(balance, dva.GetVestingCoins(blockTime), amount)\n}", "func (_DelegationController *DelegationControllerCaller) GetDelegation(opts *bind.CallOpts, delegationId *big.Int) (DelegationControllerDelegation, error) {\n\tvar (\n\t\tret0 = new(DelegationControllerDelegation)\n\t)\n\tout := ret0\n\terr := _DelegationController.contract.Call(opts, out, \"getDelegation\", delegationId)\n\treturn *ret0, err\n}", "func (bva *BaseVestingAccount) TrackUndelegation(amount sdk.Coins) {\n\tfor _, coin := range amount {\n\t\t// panic if the undelegation amount is zero\n\t\tif coin.Amount.IsZero() {\n\t\t\tpanic(\"undelegation attempt with zero coins\")\n\t\t}\n\t\tdelegatedFree := bva.DelegatedFree.AmountOf(coin.Denom)\n\t\tdelegatedVesting := bva.DelegatedVesting.AmountOf(coin.Denom)\n\n\t\t// compute x and y per the specification, where:\n\t\t// X := min(DF, D)\n\t\t// Y := min(DV, D - X)\n\t\tx := sdk.MinInt(delegatedFree, coin.Amount)\n\t\ty := sdk.MinInt(delegatedVesting, coin.Amount.Sub(x))\n\n\t\tif !x.IsZero() {\n\t\t\txCoin := sdk.NewCoin(coin.Denom, x)\n\t\t\tbva.DelegatedFree = bva.DelegatedFree.Sub(sdk.Coins{xCoin})\n\t\t}\n\n\t\tif !y.IsZero() {\n\t\t\tyCoin := sdk.NewCoin(coin.Denom, y)\n\t\t\tbva.DelegatedVesting = bva.DelegatedVesting.Sub(sdk.Coins{yCoin})\n\t\t}\n\t}\n}", "func (pr *ProvenAccountResource) GetDelegatedWithdrawalCapability() bool {\n\tif !pr.proven {\n\t\tpanic(\"not valid proven account resource\")\n\t}\n\treturn pr.accountResource.DelegatedWithdrawalCapability\n}", "func (k Keeper) TransferDelegation(ctx sdk.Context, valAddr sdk.ValAddress, fromDelegator, toDelegator sdk.AccAddress, shares sdk.Dec) (sdk.Dec, error) {\n\t// Redelegations link a delegation to it's previous validator so slashes are propagated to the new validator.\n\t// If the delegation is transferred to a new owner, the redelegation object must be updated.\n\t// For expediency all transfers with redelegations are blocked.\n\tif k.stakingKeeper.HasReceivingRedelegation(ctx, fromDelegator, valAddr) {\n\t\treturn sdk.Dec{}, types.ErrRedelegationsNotCompleted\n\t}\n\n\tif shares.IsNil() || shares.LT(sdk.ZeroDec()) {\n\t\treturn sdk.Dec{}, errorsmod.Wrap(types.ErrUntransferableShares, \"nil or negative shares\")\n\t}\n\tif shares.Equal(sdk.ZeroDec()) {\n\t\t// Block 0 transfers to reduce edge cases.\n\t\treturn sdk.Dec{}, errorsmod.Wrap(types.ErrUntransferableShares, \"zero shares\")\n\t}\n\n\tfromDelegation, found := k.stakingKeeper.GetDelegation(ctx, fromDelegator, valAddr)\n\tif !found {\n\t\treturn sdk.Dec{}, types.ErrNoDelegatorForAddress\n\t}\n\tvalidator, found := k.stakingKeeper.GetValidator(ctx, valAddr)\n\tif !found {\n\t\treturn sdk.Dec{}, types.ErrNoValidatorFound\n\t}\n\t// Prevent validators from reducing their self delegation below the min.\n\tisValidatorOperator := fromDelegator.Equals(valAddr)\n\tif isValidatorOperator {\n\t\tif isBelowMinSelfDelegation(validator, fromDelegation.Shares.Sub(shares)) {\n\t\t\treturn sdk.Dec{}, types.ErrSelfDelegationBelowMinimum\n\t\t}\n\t}\n\n\treturnAmount, err := k.fastUndelegate(ctx, valAddr, fromDelegator, shares)\n\tif err != nil {\n\t\treturn sdk.Dec{}, err\n\t}\n\treturnCoins := sdk.NewCoins(sdk.NewCoin(k.stakingKeeper.BondDenom(ctx), returnAmount))\n\n\tif err := k.bankKeeper.SendCoins(ctx, fromDelegator, toDelegator, returnCoins); err != nil {\n\t\treturn sdk.Dec{}, err\n\t}\n\treceivedShares, err := k.delegateFromAccount(ctx, valAddr, toDelegator, returnAmount)\n\tif err != nil {\n\t\treturn sdk.Dec{}, err\n\t}\n\n\treturn receivedShares, nil\n}", "func (_DelegationController *DelegationControllerCallerSession) GetDelegation(delegationId *big.Int) (DelegationControllerDelegation, error) {\n\treturn _DelegationController.Contract.GetDelegation(&_DelegationController.CallOpts, delegationId)\n}", "func (va *ClawbackVestingAccount) updateDelegation(encumbered, toClawBack, bonded, unbonding, unbonded sdk.Coins) sdk.Coins {\n\tdelegated := bonded.Add(unbonding...)\n\toldDelegated := va.DelegatedVesting.Add(va.DelegatedFree...)\n\tslashed := oldDelegated.Sub(coinsMin(delegated, oldDelegated))\n\ttotal := delegated.Add(unbonded...)\n\ttoClawBack = coinsMin(toClawBack, total) // might have been slashed\n\tnewDelegated := coinsMin(delegated, total.Sub(toClawBack)).Add(slashed...)\n\tva.DelegatedVesting = coinsMin(encumbered, newDelegated)\n\tva.DelegatedFree = newDelegated.Sub(va.DelegatedVesting)\n\treturn toClawBack\n}", "func (_TokenStakingEscrow *TokenStakingEscrowCallerSession) DepositedAmount(operator common.Address) (*big.Int, error) {\n\treturn _TokenStakingEscrow.Contract.DepositedAmount(&_TokenStakingEscrow.CallOpts, operator)\n}", "func (k Keeper) Delegation(ctx sdk.Context, addrDel sdk.AccAddress, addrVal sdk.ValAddress) exported.DelegationI {\n\treturn nil\n}", "func (_DelegationController *DelegationControllerSession) GetDelegation(delegationId *big.Int) (DelegationControllerDelegation, error) {\n\treturn _DelegationController.Contract.GetDelegation(&_DelegationController.CallOpts, delegationId)\n}", "func (_DelegationController *DelegationControllerTransactorSession) GetAndUpdateLockedAmount(wallet common.Address) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.GetAndUpdateLockedAmount(&_DelegationController.TransactOpts, wallet)\n}", "func (_DelegationController *DelegationControllerSession) Delegate(validatorId *big.Int, amount *big.Int, delegationPeriod *big.Int, info string) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.Delegate(&_DelegationController.TransactOpts, validatorId, amount, delegationPeriod, info)\n}", "func (_DelegationController *DelegationControllerSession) GetAndUpdateLockedAmount(wallet common.Address) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.GetAndUpdateLockedAmount(&_DelegationController.TransactOpts, wallet)\n}", "func (_DelegationController *DelegationControllerTransactorSession) Delegate(validatorId *big.Int, amount *big.Int, delegationPeriod *big.Int, info string) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.Delegate(&_DelegationController.TransactOpts, validatorId, amount, delegationPeriod, info)\n}", "func (del Delegation) AmountInWithdraw() (hexutil.Big, error) {\n\tval, err := del.pendingWithdrawalsValue()\n\tif err != nil {\n\t\treturn hexutil.Big{}, err\n\t}\n\treturn (hexutil.Big)(*val), nil\n}", "func (va *ClawbackVestingAccount) TrackDelegation(blockTime time.Time, balance, amount sdk.Coins) {\n\tva.BaseVestingAccount.TrackDelegation(balance, va.GetVestingCoins(blockTime), amount)\n}", "func (_DelegationController *DelegationControllerTransactor) GetAndUpdateLockedAmount(opts *bind.TransactOpts, wallet common.Address) (*types.Transaction, error) {\n\treturn _DelegationController.contract.Transact(opts, \"getAndUpdateLockedAmount\", wallet)\n}", "func (pva *PeriodicVestingAccount) TrackDelegation(blockTime time.Time, balance, amount sdk.Coins) {\n\tpva.BaseVestingAccount.TrackDelegation(balance, pva.GetVestingCoins(blockTime), amount)\n}", "func (vva *ValidatorVestingAccount) TrackDelegation(blockTime time.Time, amount sdk.Coins) {\n\tvva.BaseVestingAccount.TrackDelegation(vva.GetVestingCoins(blockTime), amount)\n}", "func (va ClawbackVestingAccount) GetVestedOnly(blockTime time.Time) sdk.Coins {\n\treturn ReadSchedule(va.StartTime, va.EndTime, va.VestingPeriods, va.OriginalVesting, blockTime.Unix())\n}", "func (_DelegationController *DelegationControllerTransactorSession) AcceptPendingDelegation(delegationId *big.Int) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.AcceptPendingDelegation(&_DelegationController.TransactOpts, delegationId)\n}", "func (group *networkGroup) getDelegatedInfo(c *gin.Context) {\n\tdelegatedInfo, err := group.facade.GetDelegatedInfo()\n\tif err != nil {\n\t\tshared.RespondWith(c, http.StatusInternalServerError, nil, err.Error(), data.ReturnCodeInternalError)\n\t\treturn\n\t}\n\n\tc.JSON(http.StatusOK, delegatedInfo)\n}", "func (_DelegationController *DelegationControllerSession) AcceptPendingDelegation(delegationId *big.Int) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.AcceptPendingDelegation(&_DelegationController.TransactOpts, delegationId)\n}", "func (_TokenStakingEscrow *TokenStakingEscrowSession) DepositedAmount(operator common.Address) (*big.Int, error) {\n\treturn _TokenStakingEscrow.Contract.DepositedAmount(&_TokenStakingEscrow.CallOpts, operator)\n}", "func (s *PublicSfcAPI) GetDelegator(ctx context.Context, addr common.Address, verbosity hexutil.Uint64) (map[string]interface{}, error) {\n\tdelegator, err := s.b.GetDelegator(ctx, addr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif delegator == nil {\n\t\treturn nil, nil\n\t}\n\tit := sfctype.SfcDelegatorAndAddr{\n\t\tAddr: addr,\n\t\tDelegator: delegator,\n\t}\n\tdelegatorRPC := RPCMarshalDelegator(it)\n\tif verbosity <= 1 {\n\t\treturn delegatorRPC, nil\n\t}\n\treturn s.addDelegatorMetricFields(ctx, delegatorRPC, addr)\n}", "func (_TokenStakingEscrow *TokenStakingEscrowCaller) DepositedAmount(opts *bind.CallOpts, operator common.Address) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _TokenStakingEscrow.contract.Call(opts, out, \"depositedAmount\", operator)\n\treturn *ret0, err\n}", "func (_DelegationController *DelegationControllerTransactor) GetAndUpdateDelegatedToValidatorNow(opts *bind.TransactOpts, validatorId *big.Int) (*types.Transaction, error) {\n\treturn _DelegationController.contract.Transact(opts, \"getAndUpdateDelegatedToValidatorNow\", validatorId)\n}", "func (m *ParcelMock) DelegationToken() (r insolar.DelegationToken) {\n\tcounter := atomic.AddUint64(&m.DelegationTokenPreCounter, 1)\n\tdefer atomic.AddUint64(&m.DelegationTokenCounter, 1)\n\n\tif len(m.DelegationTokenMock.expectationSeries) > 0 {\n\t\tif counter > uint64(len(m.DelegationTokenMock.expectationSeries)) {\n\t\t\tm.t.Fatalf(\"Unexpected call to ParcelMock.DelegationToken.\")\n\t\t\treturn\n\t\t}\n\n\t\tresult := m.DelegationTokenMock.expectationSeries[counter-1].result\n\t\tif result == nil {\n\t\t\tm.t.Fatal(\"No results are set for the ParcelMock.DelegationToken\")\n\t\t\treturn\n\t\t}\n\n\t\tr = result.r\n\n\t\treturn\n\t}\n\n\tif m.DelegationTokenMock.mainExpectation != nil {\n\n\t\tresult := m.DelegationTokenMock.mainExpectation.result\n\t\tif result == nil {\n\t\t\tm.t.Fatal(\"No results are set for the ParcelMock.DelegationToken\")\n\t\t}\n\n\t\tr = result.r\n\n\t\treturn\n\t}\n\n\tif m.DelegationTokenFunc == nil {\n\t\tm.t.Fatalf(\"Unexpected call to ParcelMock.DelegationToken.\")\n\t\treturn\n\t}\n\n\treturn m.DelegationTokenFunc()\n}", "func (_DelegationController *DelegationControllerTransactor) Delegate(opts *bind.TransactOpts, validatorId *big.Int, amount *big.Int, delegationPeriod *big.Int, info string) (*types.Transaction, error) {\n\treturn _DelegationController.contract.Transact(opts, \"delegate\", validatorId, amount, delegationPeriod, info)\n}", "func (cva *ContinuousVestingAccount) TrackDelegation(blockTime time.Time, balance, amount sdk.Coins) {\n\tcva.BaseVestingAccount.TrackDelegation(balance, cva.GetVestingCoins(blockTime), amount)\n}", "func (k Keeper) Delegator(ctx sdk.Context, delAddr sdk.AccAddress) exported.DelegatorI {\n\tdelegator, found := k.GetDelegator(ctx, delAddr)\n\tif !found {\n\t\treturn nil\n\t}\n\n\treturn delegator\n}", "func CalculateDelegateNetPayout(delegatedContracts []DelegatedContract) []DelegatedContract{\n var delegateIndex int\n\n for index, delegate := range delegatedContracts{\n if (delegate.Delegate){\n delegateIndex = index\n }\n }\n\n for _, delegate := range delegatedContracts{\n if (!delegate.Delegate){\n delegatedContracts[delegateIndex].TotalPayout = delegatedContracts[delegateIndex].TotalPayout + delegate.Fee\n }\n }\n return delegatedContracts\n}", "func (plva PermanentLockedAccount) GetVestingCoins(_ time.Time) sdk.Coins {\n\treturn plva.OriginalVesting\n}", "func (plva *PermanentLockedAccount) TrackDelegation(blockTime time.Time, balance, amount sdk.Coins) {\n\tplva.BaseVestingAccount.TrackDelegation(balance, plva.OriginalVesting, amount)\n}", "func (_DelegationController *DelegationControllerTransactor) AcceptPendingDelegation(opts *bind.TransactOpts, delegationId *big.Int) (*types.Transaction, error) {\n\treturn _DelegationController.contract.Transact(opts, \"acceptPendingDelegation\", delegationId)\n}", "func (m *AgedAccountsPayable) GetCurrentAmount()(*float64) {\n val, err := m.GetBackingStore().Get(\"currentAmount\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*float64)\n }\n return nil\n}", "func (_DelegationController *DelegationControllerTransactorSession) GetAndUpdateDelegatedToValidatorNow(validatorId *big.Int) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.GetAndUpdateDelegatedToValidatorNow(&_DelegationController.TransactOpts, validatorId)\n}", "func (_DelegatableDai *DelegatableDaiCallerSession) BalanceOf(_owner common.Address) (*big.Int, error) {\n\treturn _DelegatableDai.Contract.BalanceOf(&_DelegatableDai.CallOpts, _owner)\n}", "func (_DelegationController *DelegationControllerSession) GetAndUpdateDelegatedToValidatorNow(validatorId *big.Int) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.GetAndUpdateDelegatedToValidatorNow(&_DelegationController.TransactOpts, validatorId)\n}", "func (dva DelayedVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn dva.OriginalVesting.Sub(dva.GetVestedCoins(blockTime))\n}", "func (del Delegation) pendingWithdrawalsValue() (*big.Int, error) {\n\t// call for it only once\n\tval, err, _ := del.cg.Do(\"withdraw-total\", func() (interface{}, error) {\n\t\treturn repository.R().WithdrawRequestsPendingTotal(&del.Address, del.Delegation.ToStakerId)\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn val.(*big.Int), nil\n}", "func (_DelegationController *DelegationControllerCallerSession) GetLockedInPendingDelegations(holder common.Address) (*big.Int, error) {\n\treturn _DelegationController.Contract.GetLockedInPendingDelegations(&_DelegationController.CallOpts, holder)\n}", "func consolidateDelegations(ctx contract.Context, validator, delegator *types.Address) (*Delegation, []*Delegation, int, error) {\n\t// cycle through all delegations and delete those which are BONDED and\n\t// unlocked while accumulating their amounts\n\tdelegations, err := returnMatchingDelegations(ctx, validator, delegator)\n\tif err != nil {\n\t\treturn nil, nil, -1, err\n\t}\n\n\tunconsolidatedDelegationsCount := 0\n\ttotalDelegationAmount := common.BigZero()\n\tvar consolidatedDelegations []*Delegation\n\tfor _, delegation := range delegations {\n\t\tif delegation.LockTime > uint64(ctx.Now().Unix()) || delegation.State != BONDED {\n\t\t\tunconsolidatedDelegationsCount++\n\t\t\tcontinue\n\t\t}\n\n\t\ttotalDelegationAmount.Add(totalDelegationAmount, &delegation.Amount.Value)\n\t\tconsolidatedDelegations = append(consolidatedDelegations, delegation)\n\n\t\tif err = DeleteDelegation(ctx, delegation); err != nil {\n\t\t\treturn nil, nil, -1, err\n\t\t}\n\t}\n\n\tindex, err := GetNextDelegationIndex(ctx, *validator, *delegator)\n\tif err != nil {\n\t\treturn nil, nil, -1, err\n\t}\n\n\t// create new conolidated delegation\n\tdelegation := &Delegation{\n\t\tValidator: validator,\n\t\tDelegator: delegator,\n\t\tAmount: &types.BigUInt{Value: *totalDelegationAmount},\n\t\tUpdateAmount: loom.BigZeroPB(),\n\t\tLocktimeTier: 0,\n\t\tLockTime: 0,\n\t\tState: BONDED,\n\t\tIndex: index,\n\t}\n\tif err := SetDelegation(ctx, delegation); err != nil {\n\t\treturn nil, nil, -1, err\n\t}\n\treturn delegation, consolidatedDelegations, unconsolidatedDelegationsCount, nil\n}", "func (_DelegationController *DelegationControllerTransactor) GetAndUpdateEffectiveDelegatedToValidator(opts *bind.TransactOpts, validatorId *big.Int, month *big.Int) (*types.Transaction, error) {\n\treturn _DelegationController.contract.Transact(opts, \"getAndUpdateEffectiveDelegatedToValidator\", validatorId, month)\n}", "func (_DelegationController *DelegationControllerSession) GetLockedInPendingDelegations(holder common.Address) (*big.Int, error) {\n\treturn _DelegationController.Contract.GetLockedInPendingDelegations(&_DelegationController.CallOpts, holder)\n}", "func CalculateTotalPayout(delegatedContract DelegatedContract) DelegatedContract{\n for _, contract := range delegatedContract.Contracts{\n delegatedContract.TotalPayout = delegatedContract.TotalPayout + contract.NetPayout\n }\n return delegatedContract\n}", "func (dva DelayedVestingAccount) GetVestedCoins(blockTime time.Time) sdk.Coins {\n\tif blockTime.Unix() >= dva.EndTime {\n\t\treturn dva.OriginalVesting\n\t}\n\n\treturn nil\n}", "func (_DelegationController *DelegationControllerSession) GetAndUpdateEffectiveDelegatedToValidator(validatorId *big.Int, month *big.Int) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.GetAndUpdateEffectiveDelegatedToValidator(&_DelegationController.TransactOpts, validatorId, month)\n}", "func (k Querier) Delegation(ctx context.Context, req *types.QueryDelegationRequest) (*types.QueryDelegationResponse, error) {\n\tif req == nil {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"empty request\")\n\t}\n\n\tif req.DelegatorAddr == \"\" {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"delegator address cannot be empty\")\n\t}\n\tif req.ValidatorAddr == \"\" {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"validator address cannot be empty\")\n\t}\n\n\tdelAddr, err := k.authKeeper.AddressCodec().StringToBytes(req.DelegatorAddr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvalAddr, err := k.validatorAddressCodec.StringToBytes(req.ValidatorAddr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdelegation, err := k.Delegations.Get(ctx, collections.Join(sdk.AccAddress(delAddr), sdk.ValAddress(valAddr)))\n\tif err != nil {\n\t\tif errors.Is(err, collections.ErrNotFound) {\n\t\t\treturn nil, status.Errorf(\n\t\t\t\tcodes.NotFound,\n\t\t\t\t\"delegation with delegator %s not found for validator %s\",\n\t\t\t\treq.DelegatorAddr, req.ValidatorAddr)\n\t\t}\n\t\treturn nil, status.Error(codes.Internal, err.Error())\n\t}\n\n\tdelResponse, err := delegationToDelegationResponse(ctx, k.Keeper, delegation)\n\tif err != nil {\n\t\treturn nil, status.Error(codes.Internal, err.Error())\n\t}\n\n\treturn &types.QueryDelegationResponse{DelegationResponse: &delResponse}, nil\n}", "func (broadcast *Broadcast) DelegatorWithdraw(ctx context.Context, delegator, voter, amount,\n\tprivKeyHex string, seq int64) (*model.BroadcastResponse, error) {\n\tmsg := model.DelegatorWithdrawMsg{\n\t\tDelegator: delegator,\n\t\tVoter: voter,\n\t\tAmount: amount,\n\t}\n\treturn broadcast.broadcastTransaction(ctx, msg, privKeyHex, seq, \"\", false)\n}", "func (_DelegatableDai *DelegatableDaiSession) BalanceOf(_owner common.Address) (*big.Int, error) {\n\treturn _DelegatableDai.Contract.BalanceOf(&_DelegatableDai.CallOpts, _owner)\n}", "func (bva BaseVestingAccount) LockedCoinsFromVesting(vestingCoins sdk.Coins) sdk.Coins {\n\tlockedCoins := vestingCoins.Sub(vestingCoins.Min(bva.DelegatedVesting))\n\tif lockedCoins == nil {\n\t\treturn sdk.Coins{}\n\t}\n\treturn lockedCoins\n}", "func (_DelegationController *DelegationControllerCaller) GetLockedInPendingDelegations(opts *bind.CallOpts, holder common.Address) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _DelegationController.contract.Call(opts, out, \"getLockedInPendingDelegations\", holder)\n\treturn *ret0, err\n}", "func (_DelegationController *DelegationControllerTransactor) GetAndUpdateDelegatedToValidator(opts *bind.TransactOpts, validatorId *big.Int, month *big.Int) (*types.Transaction, error) {\n\treturn _DelegationController.contract.Transact(opts, \"getAndUpdateDelegatedToValidator\", validatorId, month)\n}", "func (_DelegationController *DelegationControllerTransactorSession) GetAndUpdateEffectiveDelegatedToValidator(validatorId *big.Int, month *big.Int) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.GetAndUpdateEffectiveDelegatedToValidator(&_DelegationController.TransactOpts, validatorId, month)\n}", "func (k msgServer) Delegate(goCtx context.Context, msg *types.MsgDelegate) (*types.MsgDelegateResponse, error) {\n\tctx := sdk.UnwrapSDKContext(goCtx)\n\tvalAddr, valErr := sdk.ValAddressFromBech32(msg.ValidatorAddress)\n\tif valErr != nil {\n\t\treturn nil, valErr\n\t}\n\n\tvalidator, found := k.GetValidator(ctx, valAddr)\n\tif !found {\n\t\treturn nil, types.ErrNoValidatorFound\n\t}\n\n\tdelegatorAddress, err := sdk.AccAddressFromBech32(msg.DelegatorAddress)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbondDenom := k.BondDenom(ctx)\n\tif msg.Amount.Denom != bondDenom {\n\t\treturn nil, sdkerrors.Wrapf(\n\t\t\tsdkerrors.ErrInvalidRequest, \"invalid coin denomination: got %s, expected %s\", msg.Amount.Denom, bondDenom,\n\t\t)\n\t}\n\n\ttokens := msg.Amount.Amount\n\n\t// if this delegation is from a liquid staking provider (identified if the delegator\n\t// is an ICA account), it cannot exceed the global or validator bond cap\n\tif k.DelegatorIsLiquidStaker(delegatorAddress) {\n\t\tshares, err := validator.SharesFromTokens(tokens)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif err := k.SafelyIncreaseTotalLiquidStakedTokens(ctx, tokens, false); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif err := k.SafelyIncreaseValidatorLiquidShares(ctx, &validator, shares); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// NOTE: source funds are always unbonded\n\tnewShares, err := k.Keeper.Delegate(ctx, delegatorAddress, tokens, types.Unbonded, validator, true)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif tokens.IsInt64() {\n\t\tdefer func() {\n\t\t\ttelemetry.IncrCounter(1, types.ModuleName, \"delegate\")\n\t\t\ttelemetry.SetGaugeWithLabels(\n\t\t\t\t[]string{\"tx\", \"msg\", msg.Type()},\n\t\t\t\tfloat32(tokens.Int64()),\n\t\t\t\t[]metrics.Label{telemetry.NewLabel(\"denom\", msg.Amount.Denom)},\n\t\t\t)\n\t\t}()\n\t}\n\n\tctx.EventManager().EmitEvents(sdk.Events{\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeDelegate,\n\t\t\tsdk.NewAttribute(types.AttributeKeyValidator, msg.ValidatorAddress),\n\t\t\tsdk.NewAttribute(sdk.AttributeKeyAmount, msg.Amount.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyNewShares, newShares.String()),\n\t\t),\n\t})\n\n\treturn &types.MsgDelegateResponse{}, nil\n}", "func (o *APIServiceAddressParams) SetDelegated(delegated *bool) {\n\to.Delegated = delegated\n}", "func (va ClawbackVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn va.OriginalVesting.Sub(va.GetVestedCoins(blockTime))\n}", "func (_ChpRegistry *ChpRegistryCallerSession) NODESTAKINGAMOUNT() (*big.Int, error) {\n\treturn _ChpRegistry.Contract.NODESTAKINGAMOUNT(&_ChpRegistry.CallOpts)\n}", "func (del Delegation) DelegationLock() *types.DelegationLock {\n\tif nil == del.lock {\n\t\tvar err error\n\t\tdel.lock, err = del.repo.DelegationLock(&del.Delegation)\n\t\tif err != nil {\n\t\t\treturn nil\n\t\t}\n\t}\n\n\treturn del.lock\n}", "func (_DelegationController *DelegationControllerSession) GetAndUpdateDelegatedToValidator(validatorId *big.Int, month *big.Int) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.GetAndUpdateDelegatedToValidator(&_DelegationController.TransactOpts, validatorId, month)\n}", "func CalculatePayoutForContract(contract Contract, rate float64, delegate bool) Contract{\n ////-------------JUST FOR TESTING -------------////\n totalNodeRewards := 378 //Amount of rewards for my delegation in cycle 11\n ////--------------END TESTING ------------------////\n\n grossRewards := contract.SharePercentage * float64(totalNodeRewards)\n contract.GrossPayout = grossRewards\n fee := rate * grossRewards\n contract.Fee = fee\n var netRewards float64\n if (delegate){\n netRewards = grossRewards\n contract.NetPayout = netRewards\n contract.Fee = 0\n } else {\n netRewards = grossRewards - fee\n contract.NetPayout = contract.NetPayout + netRewards\n }\n\n return contract\n}", "func (_DelegationController *DelegationControllerSession) GetAndUpdateEffectiveDelegatedByHolderToValidator(holder common.Address, validatorId *big.Int, month *big.Int) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.GetAndUpdateEffectiveDelegatedByHolderToValidator(&_DelegationController.TransactOpts, holder, validatorId, month)\n}", "func (_DelegationController *DelegationControllerTransactorSession) GetAndUpdateDelegatedToValidator(validatorId *big.Int, month *big.Int) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.GetAndUpdateDelegatedToValidator(&_DelegationController.TransactOpts, validatorId, month)\n}", "func (_DelegationController *DelegationControllerTransactorSession) GetAndUpdateEffectiveDelegatedByHolderToValidator(holder common.Address, validatorId *big.Int, month *big.Int) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.GetAndUpdateEffectiveDelegatedByHolderToValidator(&_DelegationController.TransactOpts, holder, validatorId, month)\n}", "func (rs *rootResolver) Delegation(args *struct {\n\tAddress common.Address\n\tStaker hexutil.Big\n}) (*Delegation, error) {\n\t// get the delegator detail from backend\n\td, err := repository.R().Delegation(&args.Address, &args.Staker)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn NewDelegation(d), nil\n}", "func (p Pinger) GetAmt() int {\r\n\treturn p.amt\r\n}", "func (_TrialRulesAbstract *TrialRulesAbstractTransactorSession) GetStatus(witnessStatus uint8, trialStatus uint8) (*types.Transaction, error) {\n\treturn _TrialRulesAbstract.Contract.GetStatus(&_TrialRulesAbstract.TransactOpts, witnessStatus, trialStatus)\n}", "func (_DelegationController *DelegationControllerCallerSession) Delegations(arg0 *big.Int) (struct {\n\tHolder common.Address\n\tValidatorId *big.Int\n\tAmount *big.Int\n\tDelegationPeriod *big.Int\n\tCreated *big.Int\n\tStarted *big.Int\n\tFinished *big.Int\n\tInfo string\n}, error) {\n\treturn _DelegationController.Contract.Delegations(&_DelegationController.CallOpts, arg0)\n}", "func (n *Node) BecomeDelegator(genesisAmount uint64, seedAmount uint64, delegatorAmount uint64, txFee uint64, stakerNodeID string) *Node {\n\n\t// exports AVAX from the X Chain\n\texportTxID, err := n.client.XChainAPI().ExportAVAX(\n\t\tn.UserPass,\n\t\tnil, // from addrs\n\t\t\"\", // change addr\n\t\tseedAmount+txFee,\n\t\tn.PAddress,\n\t)\n\tif err != nil {\n\t\tpanic(stacktrace.Propagate(err, \"Failed to export AVAX to pchainAddress %s\", n.PAddress))\n\t\treturn n\n\t}\n\n\t// waits Tx acceptance in the XChain\n\terr = chainhelper.XChain().AwaitTransactionAcceptance(n.client, exportTxID, constants.TimeoutDuration)\n\tif err != nil {\n\t\tpanic(err)\n\t\treturn n\n\t}\n\n\t// imports the amount to the P Chain\n\timportTxID, err := n.client.PChainAPI().ImportAVAX(\n\t\tn.UserPass,\n\t\tnil, // from addrs\n\t\t\"\", // change addr\n\t\tn.PAddress,\n\t\tconstants.XChainID.String(),\n\t)\n\tif err != nil {\n\t\tpanic(stacktrace.Propagate(err, \"Failed import AVAX to pchainAddress %s\", n.PAddress))\n\t\treturn n\n\t}\n\n\t// waits Tx acceptance in the PChain\n\terr = chainhelper.PChain().AwaitTransactionAcceptance(n.client, importTxID, constants.TimeoutDuration)\n\tif err != nil {\n\t\tpanic(err)\n\t\treturn n\n\t}\n\n\t// verify the PChain balance (seedAmount+txFee-txFee)\n\terr = chainhelper.PChain().CheckBalance(n.client, n.PAddress, seedAmount)\n\tif err != nil {\n\t\tpanic(stacktrace.Propagate(err, \"expected balance of seedAmount exists in the PChain\"))\n\t\treturn n\n\t}\n\n\t// verify the XChain balance of genesisAmount - seedAmount - txFee - txFee (import PChain)\n\terr = chainhelper.XChain().CheckBalance(n.client, n.XAddress, \"AVAX\", genesisAmount-seedAmount-2*txFee)\n\tif err != nil {\n\t\tpanic(stacktrace.Propagate(err, \"expected balance XChain balance of genesisAmount-seedAmount-txFee\"))\n\t\treturn n\n\t}\n\n\tdelegatorStartTime := time.Now().Add(20 * time.Second)\n\tstartTime := uint64(delegatorStartTime.Unix())\n\tendTime := uint64(delegatorStartTime.Add(36 * time.Hour).Unix())\n\taddDelegatorTxID, err := n.client.PChainAPI().AddDelegator(\n\t\tn.UserPass,\n\t\tnil, // from addrs\n\t\t\"\", // change addr\n\t\tn.PAddress,\n\t\tstakerNodeID,\n\t\tdelegatorAmount,\n\t\tstartTime,\n\t\tendTime,\n\t)\n\tif err != nil {\n\t\tpanic(stacktrace.Propagate(err, \"Failed to add delegator %s\", n.PAddress))\n\t\treturn n\n\t}\n\n\terr = chainhelper.PChain().AwaitTransactionAcceptance(n.client, addDelegatorTxID, constants.TimeoutDuration)\n\tif err != nil {\n\t\tpanic(stacktrace.Propagate(err, \"Failed to accept AddDelegator tx: %s\", addDelegatorTxID))\n\t\treturn n\n\t}\n\n\t// Sleep until delegator starts validating\n\ttime.Sleep(time.Until(delegatorStartTime) + 3*time.Second)\n\n\texpectedDelegatorBalance := seedAmount - delegatorAmount\n\terr = chainhelper.PChain().CheckBalance(n.client, n.PAddress, expectedDelegatorBalance)\n\tif err != nil {\n\t\tpanic(stacktrace.Propagate(err, \"Unexpected P Chain Balance after adding a new delegator to the network.\"))\n\t\treturn n\n\t}\n\tlogrus.Infof(\"Added delegator to subnet and verified the expected P Chain balance.\")\n\n\treturn n\n}", "func GetDelegatedAdminAccount(ctx *pulumi.Context,\n\tname string, id pulumi.IDInput, state *DelegatedAdminAccountState, opts ...pulumi.ResourceOption) (*DelegatedAdminAccount, error) {\n\tvar resource DelegatedAdminAccount\n\terr := ctx.ReadResource(\"aws:inspector2/delegatedAdminAccount:DelegatedAdminAccount\", name, id, state, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func (pva PeriodicVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn pva.OriginalVesting.Sub(pva.GetVestedCoins(blockTime))\n}", "func (t *Transaction) VATDollarAmount() string {\n\tp := 1 + float64(t.SubscriptionVATPercent)/100\n\tvat := t.TransactionAmount - int64(float64(t.TransactionAmount)/p)\n\treturn fmt.Sprintf(\"$%d.%02d\", vat/100, vat%100)\n}", "func (pva *PeriodicVestingAccount) addGrant(ctx sdk.Context, sk StakingKeeper, grantStartTime int64, grantVestingPeriods []Period, grantCoins sdk.Coins) {\n\t// how much is really delegated?\n\tbondedAmt := sk.GetDelegatorBonded(ctx, pva.GetAddress())\n\tunbondingAmt := sk.GetDelegatorUnbonding(ctx, pva.GetAddress())\n\tdelegatedAmt := bondedAmt.Add(unbondingAmt)\n\tdelegated := sdk.NewCoins(sdk.NewCoin(sk.BondDenom(ctx), delegatedAmt))\n\n\t// discover what has been slashed\n\toldDelegated := pva.DelegatedVesting.Add(pva.DelegatedFree...)\n\tslashed := oldDelegated.Sub(coinsMin(oldDelegated, delegated))\n\n\t// rebase the DV+DF by capping slashed at the current unvested amount\n\tunvested := pva.GetVestingCoins(ctx.BlockTime())\n\tnewSlashed := coinsMin(unvested, slashed)\n\tnewTotalDelegated := delegated.Add(newSlashed...)\n\n\t// modify vesting schedule for the new grant\n\tnewStart, newEnd, newPeriods := DisjunctPeriods(pva.StartTime, grantStartTime,\n\t\tpva.GetVestingPeriods(), grantVestingPeriods)\n\tpva.StartTime = newStart\n\tpva.EndTime = newEnd\n\tpva.VestingPeriods = newPeriods\n\tpva.OriginalVesting = pva.OriginalVesting.Add(grantCoins...)\n\n\t// cap DV at the current unvested amount, DF rounds out to newTotalDelegated\n\tunvested2 := pva.GetVestingCoins(ctx.BlockTime())\n\tpva.DelegatedVesting = coinsMin(newTotalDelegated, unvested2)\n\tpva.DelegatedFree = newTotalDelegated.Sub(pva.DelegatedVesting)\n}", "func (del Delegation) UnlockedAmount() (hexutil.Big, error) {\n\treturn repository.R().DelegationAmountUnlocked(&del.Address, (*big.Int)(del.Delegation.ToStakerId))\n}", "func (ds *DepositToStake) Amount() *big.Int { return ds.amount }" ]
[ "0.6808024", "0.6490734", "0.6425168", "0.626219", "0.62174875", "0.61955094", "0.58210653", "0.58202344", "0.57796836", "0.5438589", "0.54209054", "0.53295773", "0.53165835", "0.5281906", "0.5265446", "0.52373785", "0.5235998", "0.52340764", "0.52320075", "0.5212645", "0.5169682", "0.5168632", "0.511625", "0.50889724", "0.5023153", "0.5016559", "0.49889177", "0.49777207", "0.49682355", "0.4966987", "0.49299845", "0.4924162", "0.4880946", "0.48697677", "0.48545033", "0.48529866", "0.48479193", "0.4807962", "0.48025924", "0.47867483", "0.47861755", "0.47775576", "0.47624192", "0.47586733", "0.4752832", "0.47373295", "0.4712842", "0.47033507", "0.47008824", "0.46877086", "0.46804667", "0.46786028", "0.46775153", "0.46594846", "0.46452567", "0.4642076", "0.46401346", "0.46363488", "0.46135455", "0.45925125", "0.45798704", "0.4568625", "0.45629698", "0.45476705", "0.45354307", "0.45285845", "0.45103458", "0.4508565", "0.44977474", "0.4495867", "0.447977", "0.44687447", "0.4468701", "0.44674814", "0.44435427", "0.44419882", "0.44403616", "0.4438636", "0.44234914", "0.44152346", "0.43600646", "0.4343488", "0.43323618", "0.43287122", "0.4285977", "0.42854974", "0.4264218", "0.42530668", "0.424948", "0.42491555", "0.4242937", "0.4235145", "0.42331687", "0.4229914", "0.42293176", "0.42080674", "0.41972953", "0.4196245", "0.41897964", "0.41869402" ]
0.82544625
0
GetEndTime returns a vesting account's end time
func (bva BaseVestingAccount) GetEndTime() int64 { return bva.EndTime }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (plva PermanentLockedAccount) GetEndTime() int64 {\n\treturn 0\n}", "func (o *ApplianceSetupInfoAllOf) GetEndTime() time.Time {\n\tif o == nil || o.EndTime == nil {\n\t\tvar ret time.Time\n\t\treturn ret\n\t}\n\treturn *o.EndTime\n}", "func (o *WorkflowCatalogServiceRequest) GetEndTime() time.Time {\n\tif o == nil || o.EndTime == nil {\n\t\tvar ret time.Time\n\t\treturn ret\n\t}\n\treturn *o.EndTime\n}", "func (o *AvailableBudget) GetEnd() time.Time {\n\tif o == nil {\n\t\tvar ret time.Time\n\t\treturn ret\n\t}\n\n\treturn o.End\n}", "func (m *GetSchedulePostRequestBody) GetEndTime()(iadcd81124412c61e647227ecfc4449d8bba17de0380ddda76f641a29edf2b242.DateTimeTimeZoneable) {\n return m.endTime\n}", "func (o *WorkflowServiceItemActionInstance) GetEndTime() time.Time {\n\tif o == nil || o.EndTime == nil {\n\t\tvar ret time.Time\n\t\treturn ret\n\t}\n\treturn *o.EndTime\n}", "func (o *ApplianceClusterInstallPhase) GetEndTime() time.Time {\n\tif o == nil || o.EndTime == nil {\n\t\tvar ret time.Time\n\t\treturn ret\n\t}\n\treturn *o.EndTime\n}", "func (_Casper *CasperSession) EndTime() (*big.Int, error) {\n\treturn _Casper.Contract.EndTime(&_Casper.CallOpts)\n}", "func (c *Container) GetEndTime() time.Time {\n\treturn c.end\n}", "func (req *StartWFSRequest) GetEndTime() time.Time {\n\treturn req.EndTime\n}", "func (v *Validator) EndTime() time.Time {\n\treturn time.Unix(int64(v.End), 0)\n}", "func (r Reservation) EndTime() string {\n\thr := r.End / 60\n\tmin := r.End % 60\n\tvar ampm string\n\tif ampm = \"AM\"; hr >= 12 {\n\t\tampm = \"PM\"\n\t}\n\tif hr > 12 {\n\t\thr = hr - 12\n\t}\n\tif hr == 0 {\n\t\thr = 12\n\t}\n\treturn fmt.Sprintf(\"%02d:%02d %s\", hr, min, ampm)\n}", "func (m *SimulationAutomationRun) GetEndDateTime()(*i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time) {\n val, err := m.GetBackingStore().Get(\"endDateTime\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time)\n }\n return nil\n}", "func (t *TimeDuration) GetEnd() time.Time {\n\tend := t.Start.Add(time.Duration(t.Duration) * time.Minute)\n\treturn end\n}", "func (m *DateDrivenRolloutSettings) GetEndDateTime()(*i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time) {\n val, err := m.GetBackingStore().Get(\"endDateTime\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time)\n }\n return nil\n}", "func (_Casper *CasperCallerSession) EndTime() (*big.Int, error) {\n\treturn _Casper.Contract.EndTime(&_Casper.CallOpts)\n}", "func (o *OnpremUpgradePhase) GetEndTime() time.Time {\n\tif o == nil || o.EndTime == nil {\n\t\tvar ret time.Time\n\t\treturn ret\n\t}\n\treturn *o.EndTime\n}", "func (m *BookingWorkTimeSlot) GetEnd()(*i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.TimeOnly) {\n val, err := m.GetBackingStore().Get(\"end\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.TimeOnly)\n }\n return nil\n}", "func (m *ScheduleItem) GetEnd()(DateTimeTimeZoneable) {\n val, err := m.GetBackingStore().Get(\"end\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(DateTimeTimeZoneable)\n }\n return nil\n}", "func (m *SharePostRequestBody) GetEndDateTime()(*i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time) {\n return m.endDateTime\n}", "func (o GoogleCloudRetailV2alphaConditionTimeRangeResponseOutput) EndTime() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GoogleCloudRetailV2alphaConditionTimeRangeResponse) string { return v.EndTime }).(pulumi.StringOutput)\n}", "func (o *Job) GetExpectedEndTime(ctx context.Context) (expectedEndTime uint64, err error) {\n\terr = o.object.CallWithContext(ctx, \"org.freedesktop.DBus.Properties.Get\", 0, InterfaceJob, \"ExpectedEndTime\").Store(&expectedEndTime)\n\treturn\n}", "func (o RestoreResponseOutput) EndTime() pulumi.StringOutput {\n\treturn o.ApplyT(func(v RestoreResponse) string { return v.EndTime }).(pulumi.StringOutput)\n}", "func (o *Giveaway) GetEndDate() time.Time {\n\tif o == nil || o.EndDate == nil {\n\t\tvar ret time.Time\n\t\treturn ret\n\t}\n\treturn *o.EndDate\n}", "func (_Casper *CasperCaller) EndTime(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _Casper.contract.Call(opts, out, \"endTime\")\n\treturn *ret0, err\n}", "func (m *Reminder) GetEventEndTime()(DateTimeTimeZoneable) {\n val, err := m.GetBackingStore().Get(\"eventEndTime\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(DateTimeTimeZoneable)\n }\n return nil\n}", "func (o BaselineStrategyOutput) EndTime() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *BaselineStrategy) pulumi.StringOutput { return v.EndTime }).(pulumi.StringOutput)\n}", "func (o ScanRunResponseOutput) EndTime() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ScanRunResponse) string { return v.EndTime }).(pulumi.StringOutput)\n}", "func (o ScanRunResponseOutput) EndTime() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ScanRunResponse) string { return v.EndTime }).(pulumi.StringOutput)\n}", "func (o GoogleCloudRetailV2alphaConditionTimeRangeOutput) EndTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v GoogleCloudRetailV2alphaConditionTimeRange) *string { return v.EndTime }).(pulumi.StringPtrOutput)\n}", "func (r *ScheduledAction) EndTime() pulumi.StringOutput {\n\treturn (pulumi.StringOutput)(r.s.State[\"endTime\"])\n}", "func (o DataTransferConfigScheduleOptionsOutput) EndTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v DataTransferConfigScheduleOptions) *string { return v.EndTime }).(pulumi.StringPtrOutput)\n}", "func (o *HealthIncident) GetEndDate() time.Time {\n\tif o == nil || o.EndDate.Get() == nil {\n\t\tvar ret time.Time\n\t\treturn ret\n\t}\n\treturn *o.EndDate.Get()\n}", "func (o MetadataExportResponseOutput) EndTime() pulumi.StringOutput {\n\treturn o.ApplyT(func(v MetadataExportResponse) string { return v.EndTime }).(pulumi.StringOutput)\n}", "func (o LookupJobResultOutput) EndTime() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupJobResult) string { return v.EndTime }).(pulumi.StringOutput)\n}", "func (o DataTransferConfigScheduleOptionsPtrOutput) EndTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *DataTransferConfigScheduleOptions) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.EndTime\n\t}).(pulumi.StringPtrOutput)\n}", "func (o InstanceMaintenanceScheduleOutput) EndTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v InstanceMaintenanceSchedule) *string { return v.EndTime }).(pulumi.StringPtrOutput)\n}", "func (o InstanceMaintenanceScheduleOutput) EndTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v InstanceMaintenanceSchedule) *string { return v.EndTime }).(pulumi.StringPtrOutput)\n}", "func (c *PurchasesVoidedpurchasesListCall) EndTime(endTime int64) *PurchasesVoidedpurchasesListCall {\n\tc.urlParams_.Set(\"endTime\", fmt.Sprint(endTime))\n\treturn c\n}", "func EndDate() time.Time {\n\treturn viper.GetTime(\"end_date\")\n}", "func (_LvRecording *LvRecordingCaller) EndTime(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _LvRecording.contract.Call(opts, &out, \"endTime\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (c deploymentChecker) EndTime() uint64 {\n\treturn c.deployment.ExpireTime\n}", "func (object Object) EndTime(value time.Time) Object {\n\treturn object.Property(as.PropertyEndTime, value)\n}", "func (o TimelineOutput) EndTime() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v *Timeline) pulumi.IntPtrOutput { return v.EndTime }).(pulumi.IntPtrOutput)\n}", "func (o LookupGlossaryResultOutput) EndTime() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupGlossaryResult) string { return v.EndTime }).(pulumi.StringOutput)\n}", "func (m *IosUpdateConfiguration) GetActiveHoursEnd()(*i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.TimeOnly) {\n val, err := m.GetBackingStore().Get(\"activeHoursEnd\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.TimeOnly)\n }\n return nil\n}", "func (o InterconnectOutageNotificationResponseOutput) EndTime() pulumi.StringOutput {\n\treturn o.ApplyT(func(v InterconnectOutageNotificationResponse) string { return v.EndTime }).(pulumi.StringOutput)\n}", "func (m TradingSessionStatus) GetTradSesEndTime() (v time.Time, err quickfix.MessageRejectError) {\n\tvar f field.TradSesEndTimeField\n\tif err = m.Get(&f); err == nil {\n\t\tv = f.Value()\n\t}\n\treturn\n}", "func (o *ViewProjectBudget) GetEndDateTime() string {\n\tif o == nil || o.EndDateTime == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.EndDateTime\n}", "func (o TriggerBuildArtifactsObjectsTimingOutput) EndTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v TriggerBuildArtifactsObjectsTiming) *string { return v.EndTime }).(pulumi.StringPtrOutput)\n}", "func (o ScanRunResponsePtrOutput) EndTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ScanRunResponse) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.EndTime\n\t}).(pulumi.StringPtrOutput)\n}", "func (r *ReportTaskRequest) SetEndTime(endTime string) {\n r.EndTime = &endTime\n}", "func (_Crowdsale *CrowdsaleSession) EndDate() (*big.Int, error) {\n\treturn _Crowdsale.Contract.EndDate(&_Crowdsale.CallOpts)\n}", "func (o ScanRunOutput) EndTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ScanRun) *string { return v.EndTime }).(pulumi.StringPtrOutput)\n}", "func (o ScanRunOutput) EndTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ScanRun) *string { return v.EndTime }).(pulumi.StringPtrOutput)\n}", "func (c *ProjectsTracesListCall) EndTime(endTime string) *ProjectsTracesListCall {\n\tc.urlParams_.Set(\"endTime\", endTime)\n\treturn c\n}", "func (o InstanceMaintenanceSchedulePtrOutput) EndTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *InstanceMaintenanceSchedule) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.EndTime\n\t}).(pulumi.StringPtrOutput)\n}", "func (o *ApplianceSetupInfoAllOf) SetEndTime(v time.Time) {\n\to.EndTime = &v\n}", "func (o *WorkflowServiceItemActionInstance) GetEndTimeOk() (*time.Time, bool) {\n\tif o == nil || o.EndTime == nil {\n\t\treturn nil, false\n\t}\n\treturn o.EndTime, true\n}", "func (tcr *TestCaseReporter) SetEndTime(t time.Time) {\n\ttcr.endTime = t\n\n\tif tcr.testCase == nil {\n\t\treturn\n\t}\n\ttcr.testCase.TimeInSeconds = tcr.Duration().Seconds()\n}", "func (m *sdt) EndDateTime() int64 {\n\treturn m.endDateTimeField\n}", "func (o *WorkflowCatalogServiceRequest) GetEndTimeOk() (*time.Time, bool) {\n\tif o == nil || o.EndTime == nil {\n\t\treturn nil, false\n\t}\n\treturn o.EndTime, true\n}", "func (r *ModifyTaskRequest) SetEndTime(endTime string) {\n r.EndTime = &endTime\n}", "func (o *ApplianceSetupInfoAllOf) GetEndTimeOk() (*time.Time, bool) {\n\tif o == nil || o.EndTime == nil {\n\t\treturn nil, false\n\t}\n\treturn o.EndTime, true\n}", "func (o TriggerBuildArtifactsObjectsTimingPtrOutput) EndTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *TriggerBuildArtifactsObjectsTiming) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.EndTime\n\t}).(pulumi.StringPtrOutput)\n}", "func CurrentTaskEndTime() time.Time {\n\tif !IsTaskRunning() {\n\t\treturn time.Unix(0, 0)\n\t}\n\treturn time.Unix(persist.GetValueInt(taskEndTimeKey), 0)\n}", "func (m *MarketHoursMutation) EndTime() (r time.Time, exists bool) {\n\tv := m.end_time\n\tif v == nil {\n\t\treturn\n\t}\n\treturn *v, true\n}", "func (o AccessReviewInstanceOutput) EndDateTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v AccessReviewInstance) *string { return v.EndDateTime }).(pulumi.StringPtrOutput)\n}", "func (o GetClustersClusterOutput) EndTime() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetClustersCluster) string { return v.EndTime }).(pulumi.StringOutput)\n}", "func (s *GetProfileInput) SetEndTime(v time.Time) *GetProfileInput {\n\ts.EndTime = &v\n\treturn s\n}", "func (o *WorkflowCatalogServiceRequest) SetEndTime(v time.Time) {\n\to.EndTime = &v\n}", "func (o *AvailableBudget) GetEndOk() (*time.Time, bool) {\n\tif o == nil {\n\t\treturn nil, false\n\t}\n\treturn &o.End, true\n}", "func (m *SequentialActivationRenewalsAlertIncident) GetSequenceEndDateTime()(*i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time) {\n val, err := m.GetBackingStore().Get(\"sequenceEndDateTime\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time)\n }\n return nil\n}", "func (o *AvailableBudgetUpdate) GetEnd() string {\n\tif o == nil || o.End == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.End\n}", "func (o AccessReviewInstanceResponseOutput) EndDateTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v AccessReviewInstanceResponse) *string { return v.EndDateTime }).(pulumi.StringPtrOutput)\n}", "func (m *sdt) EndHour() int32 {\n\treturn m.endHourField\n}", "func (ir Range) End() time.Time {\n\treturn cabiriaTime.FromFrameAndFPS(ir.EndFrame, ir.FPS)\n}", "func (m *VulnEvidence) SetEndTime(in *google_protobuf.Timestamp) {\n\tm.EndTime = in\n}", "func (o ScanRunPtrOutput) EndTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ScanRun) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.EndTime\n\t}).(pulumi.StringPtrOutput)\n}", "func (o ScanRunPtrOutput) EndTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ScanRun) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.EndTime\n\t}).(pulumi.StringPtrOutput)\n}", "func (c WebCredential) GetEnd() string {\n\treturn c.End\n}", "func (o *ApplianceClusterInstallPhase) SetEndTime(v time.Time) {\n\to.EndTime = &v\n}", "func (tr *Trail) GetTime() time.Time {\n\treturn tr.EndTime\n}", "func (dao *Dao) GetTermEnd() time.Time {\n\n\tyear, month, _ := time.Now().Date()\n\tthisMonth := time.Date(year, month, 1, 0, 0, 0, 0, time.Local)\n\tsecond, _ := time.ParseDuration(\"-1s\")\n\treturn thisMonth.Add(second)\n}", "func (o *CreditBankStatementUploadBankAccountPeriod) GetEndDate() string {\n\tif o == nil || o.EndDate.Get() == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\n\treturn *o.EndDate.Get()\n}", "func (o *ApplianceImageBundleAllOf) GetUpgradeEndTime() time.Time {\n\tif o == nil || o.UpgradeEndTime == nil {\n\t\tvar ret time.Time\n\t\treturn ret\n\t}\n\treturn *o.UpgradeEndTime\n}", "func (o *WorkflowServiceItemActionInstance) SetEndTime(v time.Time) {\n\to.EndTime = &v\n}", "func (_LvRecordableStream *LvRecordableStreamCaller) EndTime(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _LvRecordableStream.contract.Call(opts, &out, \"endTime\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (o *ApplianceClusterInstallPhase) GetEndTimeOk() (*time.Time, bool) {\n\tif o == nil || o.EndTime == nil {\n\t\treturn nil, false\n\t}\n\treturn o.EndTime, true\n}", "func (_Crowdsale *CrowdsaleCallerSession) EndDate() (*big.Int, error) {\n\treturn _Crowdsale.Contract.EndDate(&_Crowdsale.CallOpts)\n}", "func (c *Calendar) End(t time.Time) string {\n\tyear := NewTime().Year(t)\n\tmonth := NewTime().Month(t)\n\tday := c.Day(year, month)\n\treturn fmt.Sprintf(\"%d-%02d-%02d\", year, month, day)\n}", "func (o *OnpremUpgradePhase) SetEndTime(v time.Time) {\n\to.EndTime = &v\n}", "func (m *GetSchedulePostRequestBody) SetEndTime(value iadcd81124412c61e647227ecfc4449d8bba17de0380ddda76f641a29edf2b242.DateTimeTimeZoneable)() {\n m.endTime = value\n}", "func EndTime() {\n\telapsed := time.Since(start)\n\tlog.Printf(EndText, elapsed)\n}", "func (s *GetMetricDataInput) SetEndTime(v time.Time) *GetMetricDataInput {\n\ts.EndTime = &v\n\treturn s\n}", "func (s *GetRecommendationsInput) SetEndTime(v time.Time) *GetRecommendationsInput {\n\ts.EndTime = &v\n\treturn s\n}", "func (s *PrefetchRetrieval) SetEndTime(v time.Time) *PrefetchRetrieval {\n\ts.EndTime = &v\n\treturn s\n}", "func (s *ListProfileTimesInput) SetEndTime(v time.Time) *ListProfileTimesInput {\n\ts.EndTime = &v\n\treturn s\n}", "func (s *Recommendation) SetEndTime(v time.Time) *Recommendation {\n\ts.EndTime = &v\n\treturn s\n}", "func (o CapacityCommitmentOutput) CommitmentEndTime() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *CapacityCommitment) pulumi.StringOutput { return v.CommitmentEndTime }).(pulumi.StringOutput)\n}" ]
[ "0.7872648", "0.74200815", "0.7327126", "0.7283611", "0.72377", "0.71718276", "0.7111663", "0.7106381", "0.70978665", "0.709069", "0.70450336", "0.7016598", "0.70135844", "0.70091736", "0.70076275", "0.6910157", "0.6902684", "0.6840315", "0.6741191", "0.6707876", "0.66914344", "0.66911834", "0.6681538", "0.66788095", "0.6643845", "0.6635152", "0.66066486", "0.6606515", "0.6606515", "0.6570785", "0.6562812", "0.6554779", "0.6550839", "0.6521244", "0.650624", "0.6504174", "0.6487666", "0.6487666", "0.64848393", "0.64729244", "0.64713097", "0.64456457", "0.6439239", "0.64324325", "0.6410791", "0.6369616", "0.6329899", "0.63113785", "0.62935764", "0.6286987", "0.62764066", "0.62610155", "0.6247007", "0.6231133", "0.6231133", "0.6220913", "0.62127686", "0.6189297", "0.6180234", "0.61801493", "0.61723995", "0.6160977", "0.6149615", "0.61442745", "0.61419576", "0.61372805", "0.61285526", "0.6121095", "0.6117887", "0.61129004", "0.61057836", "0.61019623", "0.60942525", "0.60934436", "0.60713875", "0.6070805", "0.6058668", "0.6056768", "0.60539156", "0.60539156", "0.6026453", "0.6022873", "0.60225177", "0.60098994", "0.5980603", "0.5975191", "0.59695774", "0.59683", "0.5959025", "0.5957766", "0.5956747", "0.59532696", "0.5923749", "0.59231484", "0.58954203", "0.5889231", "0.5885844", "0.58837074", "0.587288", "0.58694273" ]
0.86487454
0
Validate checks for errors on the account fields
func (bva BaseVestingAccount) Validate() error { if !(bva.DelegatedVesting.IsAllLTE(bva.OriginalVesting)) { return errors.New("delegated vesting amount cannot be greater than original vesting amount") } return bva.BaseAccount.Validate() }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (account *Account) Validate() (map[string]interface{}, bool) {\n\n\tif !strings.Contains(account.Phone, \"+\") {\n\t\treturn u.Message(false, \"Phone Number address is required\"), false\n\t}\n\n\tif len(account.UserName) < 3 {\n\t\treturn u.Message(false, \"Username is required\"), false\n\t}\n\n\t//PhoneNumber must be unique\n\ttemp := &Account{}\n\n\t//check for errors and duplicate phones\n\terr := GetDB().Table(\"accounts\").Where(\"phone = ?\", account.Phone).First(temp).Error\n\tif err != nil && err != gorm.ErrRecordNotFound {\n\t\treturn u.Message(false, \"Connection error. Please retry\"+err.Error()), false\n\t}\n\tif temp.Phone != \"\" {\n\t\treturn u.Message(false, \"Phone Number address already in use by another user.\"), false\n\t}\n\n\t//check for errors and duplicate username\n\terr = GetDB().Table(\"accounts\").Where(\"user_name = ?\", account.UserName).First(temp).Error\n\tif err != nil && err != gorm.ErrRecordNotFound {\n\t\treturn u.Message(false, \"Connection error. Please retry\"+err.Error()), false\n\t}\n\tif temp.UserName != \"\" {\n\t\tresponse := fmt.Sprintf(\"Username: %d is already in use by another user.\", account.UserName)\n\t\treturn u.Message(false, response), false\n\t}\n\n\treturn u.Message(false, \"Requirement passed\"), true\n}", "func (account Account) Validate() (map[string]interface{}, bool) {\n\n\tif !strings.Contains(account.Email, \"@\") {\n\t\treturn u.Message(false, ERROR_EMAIL), false\n\t}\n\n\tif len(account.Password) < 6 {\n\t\treturn u.Message(false, ERROR_PASSWORD_LENTH), false\n\t}\n\n\t// Email must be unique\n\ttemp := &Account{}\n\n\t// 数据类型合法时,查询数据表,GetDB return the configed db\n\terr := GetDB().Table(\"accounts\").Where(\"email = ?\", account.Email).First(temp).Error\n\tif err != nil && err != gorm.ErrRecordNotFound {\n\t\treturn u.Message(false, ERROR_CONNECTION), false\n\t}\n\t// 存在该email\n\tif temp.Email != \"\" {\n\t\treturn u.Message(false, ERROR_EMAIL_USED), false\n\t}\n\n\treturn u.Message(false, GET_SUCCESS), true\n}", "func (a Account) Validate() error {\n\treturn validation.ValidateStruct(&a,\n\t\tvalidation.Field(&a.Name, validation.Required, validation.Length(3, 75)),\n\t)\n}", "func (m *Account) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateAccountID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateAuditLogs(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateCurrency(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateParentAccountID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validatePaymentMethodID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateReferenceTime(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (account *Account) Validate() (map[string]interface{}, bool) {\n\n\tif !strings.Contains(account.Email, \"@\") {\n\t\treturn u.Message(false, \"Email address is required\"), false\n\t}\n\n\tif len(account.Password) < 6 {\n\t\treturn u.Message(false, \"Password is required\"), false\n\t}\n\n\t//Email must be unique\n\ttemp := &Account{}\n\t//check for errors and duplicate emails\n\terr := GetDB().Table(\"accounts\").Where(\"email = ?\", account.Email).First(temp).Error\n\tif err != nil && err != gorm.ErrRecordNotFound {\n\t\treturn u.Message(false, \"Connection error. Please retry\"), false\n\t}\n\tif temp.Email != \"\" {\n\t\treturn u.Message(false, \"Email address already in use by another user.\"), false\n\t}\n\treturn u.Message(false, \"Requirement passed\"), true\n}", "func (a *Account) Validate() error {\n\treturn nil\n}", "func (mt *Account) Validate() (err error) {\n\tif mt.ID == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`response`, \"id\"))\n\t}\n\tif mt.Password == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`response`, \"password\"))\n\t}\n\n\treturn\n}", "func (accountInfo *AccountInfo) Validate() error {\n\taccountSchema, _ := GetAccountSchema(accountInfo.Domain)\n\tif accountSchema == nil {\n\t\treturn errors.New(\"schema undefined for domain \" + accountInfo.Domain)\n\t}\n\n\t// Group\n\tif !accountSchema.IsGroupExist(accountInfo.Group) {\n\t\treturn errors.New(\"unknown group \" + accountInfo.Group)\n\t}\n\n\t// UserID\n\tif accountInfo.Uid == \"\" {\n\t\treturn errors.New(\"uid can not be empty\")\n\t}\n\n\t// LoginIDs\n\tif len(accountInfo.LoginIDs) == 0 {\n\t\treturn errors.New(\"should have at least one login id\")\n\t}\n\trequiredIDs := accountSchema.getRequiredLogIDs()\n\tfor _, requiredID := range requiredIDs {\n\t\tif _, ok := accountInfo.LoginIDs[requiredID]; !ok {\n\t\t\treturn errors.New(\"login id:\" + requiredID + \" is required but not specified\")\n\t\t}\n\t}\n\tfor k, v := range accountInfo.LoginIDs {\n\t\tloginIDSchema, _ := accountSchema.GetLoginIDSchema(k)\n\t\tif loginIDSchema == nil {\n\t\t\treturn errors.New(\"login id schema for \" + k + \" is not defined\")\n\t\t} else {\n\t\t\tif !loginIDSchema.NeedVerified {\n\t\t\t\tv.Verified = true\n\t\t\t\t// accountInfo.LoginIDs[k] = v\n\t\t\t}\n\t\t\tif !loginIDSchema.Validator.Validate(v.ID) {\n\t\t\t\treturn errors.New(\"invalid format of login id \" + k + \":\" + v.ID)\n\t\t\t}\n\t\t}\n\t}\n\n\t// options\n\toptionsMap := mergeMaps(accountInfo.Profiles, accountInfo.Others)\n\trequiredOptions := accountSchema.getRequiredOptions()\n\tfor _, requiredOption := range requiredOptions {\n\t\tif _, ok := optionsMap[requiredOption]; !ok {\n\t\t\treturn errors.New(\"option:\" + requiredOption + \" is required but not specified\")\n\t\t}\n\t}\n\n\tfor k, v := range optionsMap {\n\t\toptionSchema, _ := accountSchema.GetOptionSchema(k)\n\t\tif optionSchema == nil {\n\t\t\treturn errors.New(\"option schema for \" + k + \" is not defined\")\n\t\t} else {\n\t\t\tif !optionSchema.Validator.Validate(v) {\n\t\t\t\treturn errors.New(\"invalid format of option \" + k)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func (mt *Account) Validate() (err error) {\n\n\tif mt.Href == \"\" {\n\t\terr = goa.MissingAttributeError(`response`, \"href\", err)\n\t}\n\tif mt.Name == \"\" {\n\t\terr = goa.MissingAttributeError(`response`, \"name\", err)\n\t}\n\n\tif mt.CreatedAt != nil {\n\t\tif err2 := goa.ValidateFormat(goa.FormatDateTime, *mt.CreatedAt); err2 != nil {\n\t\t\terr = goa.InvalidFormatError(`response.created_at`, *mt.CreatedAt, goa.FormatDateTime, err2, err)\n\t\t}\n\t}\n\tif mt.CreatedBy != nil {\n\t\tif err2 := goa.ValidateFormat(goa.FormatEmail, *mt.CreatedBy); err2 != nil {\n\t\t\terr = goa.InvalidFormatError(`response.created_by`, *mt.CreatedBy, goa.FormatEmail, err2, err)\n\t\t}\n\t}\n\treturn\n}", "func (c *modAccountRun) validate(args []string) error {\n\tif len(args) < 2 {\n\t\treturn errors.New(\"not enough arguments\")\n\t}\n\n\tif len(args) > 2 {\n\t\treturn errors.New(\"too many arguments\")\n\t}\n\n\treturn nil\n}", "func (m *LedgerAccount) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateAccount(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateCurrency(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validatePostings(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (b *OGame) ValidateAccount(code string) error {\n\treturn b.validateAccount(code)\n}", "func (ut *accountInputPayload) Validate() (err error) {\n\tif ut.Email != nil {\n\t\tif err2 := goa.ValidateFormat(goa.FormatEmail, *ut.Email); err2 != nil {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidFormatError(`response.email`, *ut.Email, goa.FormatEmail, err2))\n\t\t}\n\t}\n\tif ut.Name != nil {\n\t\tif utf8.RuneCountInString(*ut.Name) < 1 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`response.name`, *ut.Name, utf8.RuneCountInString(*ut.Name), 1, true))\n\t\t}\n\t}\n\tif ut.Name != nil {\n\t\tif utf8.RuneCountInString(*ut.Name) > 30 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`response.name`, *ut.Name, utf8.RuneCountInString(*ut.Name), 30, false))\n\t\t}\n\t}\n\tif ut.Surname != nil {\n\t\tif utf8.RuneCountInString(*ut.Surname) < 1 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`response.surname`, *ut.Surname, utf8.RuneCountInString(*ut.Surname), 1, true))\n\t\t}\n\t}\n\tif ut.Surname != nil {\n\t\tif utf8.RuneCountInString(*ut.Surname) > 30 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`response.surname`, *ut.Surname, utf8.RuneCountInString(*ut.Surname), 30, false))\n\t\t}\n\t}\n\treturn\n}", "func (account *Account) ValidateUpdate() (map[string]interface{}, bool) {\n\n\tif !strings.Contains(account.Email, \"@\") {\n\t\treturn u.Message(false, \"Email address is required\"), false\n\t}\n\n\tif len(account.Password) < 6 {\n\t\treturn u.Message(false, \"Password is required\"), false\n\t}\n\n\t//Email must be unique\n\ttemp := &Account{}\n\t//check for errors and duplicate emails\n\terr := GetDB().Table(\"accounts\").Where(\"email = ?\", account.Email).First(temp).Error\n\tif err != nil && err != gorm.ErrRecordNotFound {\n\t\treturn u.Message(false, \"Connection error. Please retry\"), false\n\t}\n\tif temp.Email == \"\" {\n\t\treturn u.Message(false, \"Email address not found in database.\"), false\n\t}\n\treturn u.Message(true, \"Requirement passed\"), true\n}", "func (ut *AccountInputPayload) Validate() (err error) {\n\tif ut.Email != nil {\n\t\tif err2 := goa.ValidateFormat(goa.FormatEmail, *ut.Email); err2 != nil {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidFormatError(`response.email`, *ut.Email, goa.FormatEmail, err2))\n\t\t}\n\t}\n\tif ut.Name != nil {\n\t\tif utf8.RuneCountInString(*ut.Name) < 1 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`response.name`, *ut.Name, utf8.RuneCountInString(*ut.Name), 1, true))\n\t\t}\n\t}\n\tif ut.Name != nil {\n\t\tif utf8.RuneCountInString(*ut.Name) > 30 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`response.name`, *ut.Name, utf8.RuneCountInString(*ut.Name), 30, false))\n\t\t}\n\t}\n\tif ut.Surname != nil {\n\t\tif utf8.RuneCountInString(*ut.Surname) < 1 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`response.surname`, *ut.Surname, utf8.RuneCountInString(*ut.Surname), 1, true))\n\t\t}\n\t}\n\tif ut.Surname != nil {\n\t\tif utf8.RuneCountInString(*ut.Surname) > 30 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`response.surname`, *ut.Surname, utf8.RuneCountInString(*ut.Surname), 30, false))\n\t\t}\n\t}\n\treturn\n}", "func ValidateAccount(client httpclient.IHttpClient, ctx context.Context, lobby, code string) error {\n\tif len(code) != 36 {\n\t\treturn errors.New(\"invalid validation code\")\n\t}\n\treq, err := http.NewRequest(http.MethodPut, \"https://\"+lobby+\".ogame.gameforge.com/api/users/validate/\"+code, strings.NewReader(`{\"language\":\"en\"}`))\n\tif err != nil {\n\t\treturn err\n\t}\n\treq.WithContext(ctx)\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\treturn nil\n}", "func (b *Builder) Validate() (*Account, error) {\n\tb.validate.SetTagName(b.essential.Country)\n\tif err := validateStruct(b.validate, b.essential); err != nil {\n\t\treturn nil, err\n\t}\n\tb.validate.SetTagName(\"validate\")\n\tif err := validateStruct(b.validate, b.essential); err != nil {\n\t\treturn nil, err\n\t}\n\tif err := validateStruct(b.validate, b.optional); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Account{\n\t\tid: b.essential.ID,\n\t\torganizationID: b.essential.OrganizationID,\n\t\tversionIndex: b.optional.VersionIndex,\n\t\tcountry: b.essential.Country,\n\t\tbankIDCode: b.essential.BankIDCode,\n\t\tbankID: b.essential.BankID,\n\t\tbic: b.essential.Bic,\n\t\tiban: b.essential.Iban,\n\t\tbaseCurrency: b.optional.BaseCurrency,\n\t\taccountNumber: b.optional.AccountNumber,\n\t\tcustomerID: b.optional.CustomerID,\n\t\ttitle: b.optional.Title,\n\t\tfirstName: b.optional.FirstName,\n\t\tbankAccountName: b.optional.BankAccountName,\n\t\taltBankAccountNames: b.optional.AltBankAccountNames,\n\t\taccountClassification: b.optional.AccountClassification,\n\t\tjointAccount: b.optional.JointAccount,\n\t\taccountMatchingOptOut: b.optional.AccountMatchingOptOut,\n\t\tsecondaryIdentification: b.optional.SecondaryIdentification,\n\t}, nil\n}", "func (a *Account) Validate() error {\n\tvalidate := validator.New()\n\treturn validate.Struct(a)\n}", "func (ga GenesisAccount) Validate() error {\n\tif ethermint.IsZeroAddress(ga.Address) {\n\t\treturn fmt.Errorf(\"address cannot be the zero address %s\", ga.Address)\n\t}\n\tif len(ethcmn.Hex2Bytes(ga.Code)) == 0 {\n\t\treturn errors.New(\"code cannot be empty\")\n\t}\n\n\treturn ga.Storage.Validate()\n}", "func validate(user *customer_api.DbUser, allowEmpty bool) error {\n\tconst minNameLength, maxNameLength = 3, 20\n\tconst emailRegexString = \"^[a-zA-Z0-9+_.-]+@[a-zA-Z0-9.-]+$\"\n\tvar emailRegex = regexp.MustCompile(emailRegexString)\n\n\tif !(allowEmpty && user.Email == \"\") {\n\t\tif len(user.Email) < 5 || !emailRegex.MatchString(user.Email) {\n\t\t\treturn errors.New(\"invalid email\")\n\t\t}\n\t}\n\n\tif !(allowEmpty && user.FirstName == \"\") {\n\t\tif len(user.FirstName) < minNameLength || len(user.FirstName) > maxNameLength {\n\t\t\treturn errors.New(\"first_name should be between 3 and 20 characters\")\n\t\t}\n\t}\n\n\tif !(allowEmpty && user.LastName == \"\") {\n\t\tif len(user.LastName) < minNameLength || len(user.LastName) > maxNameLength {\n\t\t\treturn errors.New(\"last_name should be between 3 and 20 characters\")\n\t\t}\n\t}\n\n\tif !(allowEmpty && user.Phone == 0) {\n\t\tif user.Phone < 1000000000 || user.Phone > 9999999999 {\n\t\t\treturn errors.New(\"invalid phone no\")\n\t\t}\n\t}\n\n\tif !(allowEmpty && user.Id == \"\") {\n\t\tif user.Id == \"\" {\n\t\t\treturn errors.New(\"id cannot be empty\")\n\t\t}\n\t}\n\treturn nil\n}", "func (server *Server) checkValidAccount(ctx *gin.Context, id int64, curr string) (bool, db.Account) {\n\tacc, err := server.repository.GetAccount(ctx, id)\n\tif err != nil {\n\t\tctx.JSON(http.StatusNotFound, errorResponse(err))\n\t\treturn false, db.Account{}\n\t}\n\tif acc.Currency != curr {\n\t\terr = fmt.Errorf(\"invalid currency for account [%d]: expected %s received %s\", acc.ID, acc.Currency, curr)\n\t\tctx.JSON(http.StatusBadRequest, errorResponse(err))\n\t\treturn false, db.Account{}\n\t}\n\n\treturn true, acc\n}", "func (mt *EasypostCarrierAccounts) Validate() (err error) {\n\tif mt.ID == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`response`, \"id\"))\n\t}\n\tif mt.Object == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`response`, \"object\"))\n\t}\n\n\tif ok := goa.ValidatePattern(`^CarrierAccount$`, mt.Object); !ok {\n\t\terr = goa.MergeErrors(err, goa.InvalidPatternError(`response.object`, mt.Object, `^CarrierAccount$`))\n\t}\n\treturn\n}", "func (m *InfrastructureAccount) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateCostCenter(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateCriticalityLevel(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateEnvironment(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateExternalID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateLifecycleStatus(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateName(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateOwner(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateType(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (m *CloudAccountExtended) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\t// validation for a type composition with CloudAccount\n\tif err := m.CloudAccount.Validate(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateState(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateType(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (a *Account) Validate() error {\n\terr := validation.ValidateStruct(a,\n\t\tvalidation.Field(&a.AdminRoleArn, validateAdminRoleArn...),\n\t\tvalidation.Field(&a.ID, validateID...),\n\t\tvalidation.Field(&a.LastModifiedOn, validateInt64...),\n\t\tvalidation.Field(&a.Status, validateStatus...),\n\t\tvalidation.Field(&a.CreatedOn, validateInt64...),\n\t\tvalidation.Field(&a.PrincipalRoleArn, validatePrincipalRoleArn...),\n\t\tvalidation.Field(&a.PrincipalPolicyHash, validatePrincipalPolicyHash...),\n\t)\n\tif err != nil {\n\t\treturn errors.NewValidation(\"account\", err)\n\t}\n\treturn nil\n}", "func validRawAccount(accountName string) error {\n\t// param absence check\n\tif accountName == \"\" {\n\t\treturn fmt.Errorf(\"invoke NewAccount failed, account name is empty\")\n\t}\n\n\t// account naming rule check\n\tif len(accountName) != accountSize {\n\t\treturn fmt.Errorf(\"invoke NewAccount failed, account name length expect %d, actual: %d\", accountSize, len(accountName))\n\t}\n\n\tfor i := 0; i < accountSize; i++ {\n\t\tif accountName[i] >= '0' && accountName[i] <= '9' {\n\t\t\tcontinue\n\t\t} else {\n\t\t\treturn fmt.Errorf(\"invoke NewAccount failed, account name expect continuous %d number\", accountSize)\n\t\t}\n\t}\n\n\treturn nil\n}", "func (o *CloudSnapshotAccount) Validate() error {\n\n\terrors := elemental.Errors{}\n\trequiredErrors := elemental.Errors{}\n\n\tif err := ValidateTagsWithoutReservedPrefixes(\"associatedTags\", o.AssociatedTags); err != nil {\n\t\terrors = errors.Append(err)\n\t}\n\n\tif err := elemental.ValidateStringInList(\"cloudType\", string(o.CloudType), []string{\"AWS\", \"GCP\"}, false); err != nil {\n\t\terrors = errors.Append(err)\n\t}\n\n\tif len(requiredErrors) > 0 {\n\t\treturn requiredErrors\n\t}\n\n\tif len(errors) > 0 {\n\t\treturn errors\n\t}\n\n\treturn nil\n}", "func (m *ProviderAccountRequest) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateDataset(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateDatasetName(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateField(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validatePreferences(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (uu *UserUpdate) check() error {\n\tif v, ok := uu.mutation.AccountName(); ok {\n\t\tif err := user.AccountNameValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"account_name\", err: fmt.Errorf(\"ent: validator failed for field \\\"account_name\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.StaffType(); ok {\n\t\tif err := user.StaffTypeValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"staff_type\", err: fmt.Errorf(\"ent: validator failed for field \\\"staff_type\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.FamilyName(); ok {\n\t\tif err := user.FamilyNameValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"family_name\", err: fmt.Errorf(\"ent: validator failed for field \\\"family_name\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.GivenName(); ok {\n\t\tif err := user.GivenNameValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"given_name\", err: fmt.Errorf(\"ent: validator failed for field \\\"given_name\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.DisplayName(); ok {\n\t\tif err := user.DisplayNameValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"display_name\", err: fmt.Errorf(\"ent: validator failed for field \\\"display_name\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.IDNumber(); ok {\n\t\tif err := user.IDNumberValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"id_number\", err: fmt.Errorf(\"ent: validator failed for field \\\"id_number\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.Sex(); ok {\n\t\tif err := user.SexValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"sex\", err: fmt.Errorf(\"ent: validator failed for field \\\"sex\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.PhoneNumber(); ok {\n\t\tif err := user.PhoneNumberValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"phone_number\", err: fmt.Errorf(\"ent: validator failed for field \\\"phone_number\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.Address(); ok {\n\t\tif err := user.AddressValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"address\", err: fmt.Errorf(\"ent: validator failed for field \\\"address\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.StaffID(); ok {\n\t\tif err := user.StaffIDValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"staff_id\", err: fmt.Errorf(\"ent: validator failed for field \\\"staff_id\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.PersonalEmail(); ok {\n\t\tif err := user.PersonalEmailValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"personal_email\", err: fmt.Errorf(\"ent: validator failed for field \\\"personal_email\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.IntranetWorkEmail(); ok {\n\t\tif err := user.IntranetWorkEmailValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"intranet_work_email\", err: fmt.Errorf(\"ent: validator failed for field \\\"intranet_work_email\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.ExtranetWorkEmail(); ok {\n\t\tif err := user.ExtranetWorkEmailValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"extranet_work_email\", err: fmt.Errorf(\"ent: validator failed for field \\\"extranet_work_email\\\": %w\", err)}\n\t\t}\n\t}\n\treturn nil\n}", "func (profileImport *ProfileImportRequest) Validate(tx *sql.Tx) error {\n\n\tprofile := profileImport.Profile\n\n\t// Profile fields are valid\n\terrs := tovalidate.ToErrors(validation.Errors{\n\t\t\"name\": validation.Validate(profile.Name, validation.By(\n\t\t\tfunc(value interface{}) error {\n\t\t\t\tname, ok := value.(*string)\n\t\t\t\tif !ok {\n\t\t\t\t\treturn fmt.Errorf(\"wrong type, need: string, got: %T\", value)\n\t\t\t\t}\n\t\t\t\tif name == nil || *name == \"\" {\n\t\t\t\t\treturn errors.New(\"required and cannot be blank\")\n\t\t\t\t}\n\t\t\t\tif strings.Contains(*name, \" \") {\n\t\t\t\t\treturn errors.New(\"cannot contain spaces\")\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t},\n\t\t)),\n\t\t\"description\": validation.Validate(profile.Description, validation.Required),\n\t\t\"cdnName\": validation.Validate(profile.CDNName, validation.Required),\n\t\t\"type\": validation.Validate(profile.Type, validation.Required),\n\t})\n\n\t// Validate CDN exist\n\tif profile.CDNName != nil {\n\t\tif ok, err := CDNExistsByName(*profile.CDNName, tx); err != nil {\n\t\t\terrString := fmt.Sprintf(\"checking cdn name %v existence\", *profile.CDNName)\n\t\t\tlog.Errorf(\"%v: %v\", errString, err.Error())\n\t\t\terrs = append(errs, errors.New(errString))\n\t\t} else if !ok {\n\t\t\terrs = append(errs, fmt.Errorf(\"%v CDN does not exist\", *profile.CDNName))\n\t\t}\n\t}\n\n\t// Validate profile does not already exist\n\tif profile.Name != nil {\n\t\tif ok, err := ProfileExistsByName(*profile.Name, tx); err != nil {\n\t\t\terrString := fmt.Sprintf(\"checking profile name %v existence\", *profile.Name)\n\t\t\tlog.Errorf(\"%v: %v\", errString, err.Error())\n\t\t\terrs = append(errs, errors.New(errString))\n\t\t} else if ok {\n\t\t\terrs = append(errs, fmt.Errorf(\"a profile with the name \\\"%s\\\" already exists\", *profile.Name))\n\t\t}\n\t}\n\n\t// Validate all parameters\n\t// export/import does not include secure flag\n\t// default value to not flag on validation\n\tsecure := 1\n\tfor i, pp := range profileImport.Parameters {\n\t\tif ppErrs := validateProfileParamPostFields(pp.ConfigFile, pp.Name, pp.Value, &secure); len(ppErrs) > 0 {\n\t\t\tfor _, err := range ppErrs {\n\t\t\t\terrs = append(errs, errors.New(\"parameter \"+strconv.Itoa(i)+\": \"+err.Error()))\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(errs) > 0 {\n\t\treturn util.JoinErrs(errs)\n\t}\n\n\treturn nil\n}", "func (u *Usecase) validFields(d *Device) error {\n\tif d.Name == \"\" {\n\t\treturn &InvalidError{\"attribute `Name` must not be empty\"}\n\t}\n\n\tif d.User == 0 {\n\t\treturn &InvalidError{\"invalid user\"}\n\t}\n\n\treturn nil\n}", "func (t *TokenAccount) Validate() error {\n\tv := validator.New()\n\terr := v.RegisterValidation(\"notblank\", validators.NotBlank)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = v.RegisterValidation(\"notall\", validation.NotAll)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn v.Struct(t)\n}", "func (v *Reg) Validate(ctx context.Context, f *reg.Form) error {\n\tvar es Errors\n\n\tif err := validation.Validate(f.Email, validation.Required, is.Email); err != nil {\n\t\tes = append(es, Error{\n\t\t\tField: \"email\",\n\t\t\tMessage: err.Error(),\n\t\t})\n\t}\n\n\tif err := validation.Validate(f.AccountID, validation.Required); err != nil {\n\t\tes = append(es, Error{\n\t\t\tField: \"account_id\",\n\t\t\tMessage: err.Error(),\n\t\t})\n\t}\n\n\tif err := v.Uniquer.Unique(ctx, f.Email); err != nil {\n\t\tswitch errors.Cause(err) {\n\t\tcase reg.ErrEmailExists:\n\t\t\tes = append(es, Error{\n\t\t\t\tField: \"email\",\n\t\t\t\tMessage: err.Error(),\n\t\t\t})\n\t\tdefault:\n\t\t\treturn errors.Wrap(err, \"unique\")\n\t\t}\n\t}\n\n\tfmt.Println(f.Password, f.PasswordConfirmation)\n\n\tif err := validation.Validate(f.Password, validation.Required, validation.Length(6, 32)); err != nil {\n\t\tes = append(es, Error{\n\t\t\tField: \"password\",\n\t\t\tMessage: err.Error(),\n\t\t})\n\t}\n\n\tif err := validation.Validate(f.PasswordConfirmation, validation.Required, validation.Length(6, 32)); err != nil {\n\t\tes = append(es, Error{\n\t\t\tField: \"password_confirmation\",\n\t\t\tMessage: err.Error(),\n\t\t})\n\t}\n\n\tif f.Password != f.PasswordConfirmation {\n\t\tes = append(es, Error{\n\t\t\tField: \"password_confirmation\",\n\t\t\tMessage: \"mismatch\",\n\t\t}, Error{\n\t\t\tField: \"password\",\n\t\t\tMessage: \"mismatch\",\n\t\t})\n\t}\n\n\tif len(es) > 0 {\n\t\treturn es\n\t}\n\n\treturn nil\n}", "func validateAccountName(accountName string) (string, error) {\n\treturn accountName, nil\n}", "func (rcv *controller) validate() error {\n\n\tif err := rcv.read(); err != nil {\n\t\treturn err\n\t}\n\n\t// If account does not exists\n\tif rcv.store.Email == \"\" {\n\t\treturn errors.New(rcv.Translate(\"text11\"))\n\t}\n\n\t// If time for activating account is expired\n\tif time.Now().Unix() > rcv.store.Expired {\n\t\t// Delete registered user from neo4j\n\t\tmaccount.Delete(rcv.store.Email, rcv.Local)\n\t\treturn &expiredError{rcv.Controller}\n\t}\n\n\treturn nil\n}", "func (acc *AccessControlCreate) check() error {\n\tif _, ok := acc.mutation.ServiceID(); !ok {\n\t\treturn &ValidationError{Name: \"service_id\", err: errors.New(\"ent: missing required field \\\"service_id\\\"\")}\n\t}\n\tif _, ok := acc.mutation.OpenAuth(); !ok {\n\t\treturn &ValidationError{Name: \"open_auth\", err: errors.New(\"ent: missing required field \\\"open_auth\\\"\")}\n\t}\n\tif _, ok := acc.mutation.BlackList(); !ok {\n\t\treturn &ValidationError{Name: \"black_list\", err: errors.New(\"ent: missing required field \\\"black_list\\\"\")}\n\t}\n\tif _, ok := acc.mutation.WhiteList(); !ok {\n\t\treturn &ValidationError{Name: \"white_list\", err: errors.New(\"ent: missing required field \\\"white_list\\\"\")}\n\t}\n\tif _, ok := acc.mutation.WhiteHostName(); !ok {\n\t\treturn &ValidationError{Name: \"white_host_name\", err: errors.New(\"ent: missing required field \\\"white_host_name\\\"\")}\n\t}\n\tif _, ok := acc.mutation.ClientipFlowLimit(); !ok {\n\t\treturn &ValidationError{Name: \"clientip_flow_limit\", err: errors.New(\"ent: missing required field \\\"clientip_flow_limit\\\"\")}\n\t}\n\tif _, ok := acc.mutation.ServiceFlowLimit(); !ok {\n\t\treturn &ValidationError{Name: \"service_flow_limit\", err: errors.New(\"ent: missing required field \\\"service_flow_limit\\\"\")}\n\t}\n\treturn nil\n}", "func (u *User) Validate(tx *pop.Connection) (*validate.Errors, error) {\n\tvar err error\n\t//validate based on is agent\n\tif !u.IsAgent { //is not an agent\n\t\treturn validate.Validate(\n\t\t\t&validators.StringIsPresent{Field: u.Email, Name: \"Email\"},\n\t\t\t&validators.StringIsPresent{Field: u.PasswordHash, Name: \"PasswordHash\"},\n\t\t\t&validators.StringIsPresent{Field: u.LastName, Name: \"LastName\"},\n\t\t\t&validators.StringIsPresent{Field: u.FirstName, Name: \"FirstName\"},\n\t\t\t&validators.StringIsPresent{Field: u.Phone, Name: \"Phone\"},\n\t\t\t// check to see if the email address is already taken:\n\t\t\t&validators.FuncValidator{\n\t\t\t\tField: u.Email,\n\t\t\t\tName: \"Email\",\n\t\t\t\tMessage: \"%s is already taken\",\n\t\t\t\tFn: func() bool {\n\t\t\t\t\tvar b bool\n\t\t\t\t\tq := tx.Where(\"email = ?\", u.Email)\n\t\t\t\t\tif u.ID != uuid.Nil {\n\t\t\t\t\t\tq = q.Where(\"id != ?\", u.ID)\n\t\t\t\t\t}\n\t\t\t\t\tb, err = q.Exists(u)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn false\n\t\t\t\t\t}\n\t\t\t\t\treturn !b\n\t\t\t\t},\n\t\t\t},\n\t\t), err\n\n\t} else { // trying to save agent\n\t\treturn validate.Validate(\n\t\t\t&validators.StringIsPresent{Field: u.Email, Name: \"Email\"},\n\t\t\t&validators.StringIsPresent{Field: u.PasswordHash, Name: \"PasswordHash\"},\n\t\t\t&validators.StringIsPresent{Field: u.LastName, Name: \"LastName\"},\n\t\t\t&validators.StringIsPresent{Field: u.FirstName, Name: \"FirstName\"},\n\t\t\t&validators.StringIsPresent{Field: u.Phone, Name: \"Phone\"},\n\t\t\t&validators.StringIsPresent{Field: u.PublicEmail.String, Name: \"PublicEmail\"},\n\t\t\t&validators.StringIsPresent{Field: u.Company.String, Name: \"Company\"},\n\t\t\t&validators.StringIsPresent{Field: u.Address1.String, Name: \"Address1\"},\n\t\t\t&validators.StringIsPresent{Field: u.City.String, Name: \"City\"},\n\t\t\t&validators.StringIsPresent{Field: u.State.String, Name: \"State\"},\n\t\t\t&validators.StringIsPresent{Field: u.Zipcode.String, Name: \"Zipcode\"},\n\t\t\t// check to see if the email address is already taken:\n\t\t\t&validators.FuncValidator{\n\t\t\t\tField: u.Email,\n\t\t\t\tName: \"Email\",\n\t\t\t\tMessage: \"%s is already taken\",\n\t\t\t\tFn: func() bool {\n\t\t\t\t\tvar b bool\n\t\t\t\t\tq := tx.Where(\"email = ?\", u.Email)\n\t\t\t\t\tif u.ID != uuid.Nil {\n\t\t\t\t\t\tq = q.Where(\"id != ?\", u.ID)\n\t\t\t\t\t}\n\t\t\t\t\tb, err = q.Exists(u)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn false\n\t\t\t\t\t}\n\t\t\t\t\treturn !b\n\t\t\t\t},\n\t\t\t},\n\t\t), err\n\n\t}\n}", "func IsValidAccount(a string) bool {\n\t_, err := NewAccount(a)\n\treturn err == nil\n}", "func (u User) IsValid() []error{\n\tvar errs []error\n\tfirstname := strings.Trim(u.FirstName, \" \")\n\tlastname := strings.Trim(u.LastName, \" \")\n\n\tif firstname != \"\" {\n\t\tif strings.Contains(firstname, \" \"){\n\t\t\terrs = append(errs, errors.New(\"FirstName can't have spaces\"))\n\t\t}\n\t\tif len(firstname) < 2 {\n\t\t\terrs = append(errs, errors.New(\"FirstName must be at least 2 characters\"))\n\t\t}\n\t\tif !helper.IsLetter(firstname) {\n\t\t\terrs = append(errs, errors.New(\"Firstname contains a number\"))\n\t\t}\n\t}\n\n\tif lastname != \"\"{\n\t\tif strings.Contains(lastname, \" \"){\n\t\t\terrs = append(errs, errors.New(\"LastName can't have spaces\"))\n\t\t}\n\n\t\tif len(lastname) < 2 {\n\t\t\terrs = append(errs, errors.New(\"LastName must be at least 2 characters\"))\n\t\t}\n\n\t\tif !helper.IsLetter(lastname) {\n\t\t\terrs = append(errs, errors.New(\"Lastname contains a number\"))\n\t\t}\n\t}\n\n\tif u.Email != \"\" {\n\t\tre := regexp.MustCompile(\"^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$\")\n\n\t\tif !re.MatchString(u.Email) {\n\t\t\terrs = append(errs, errors.New(\"Email address is not valid\"))\n\t\t}\n\t}\n\n\n\tyear, _, _, _, _, _ := helper.DateDiff(u.DateOfBirth, time.Now())\n\tif year < 18 {\n\t\terrs = append(errs, errors.New(\"You must be 18 or more\"))\n\t}\n\tif len(errs) > 0 {\n\t\treturn errs\n\t}\n\treturn nil\n}", "func (m *BillingProfiles2) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateAdviceOfCharge(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateCurrency(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateFraudDailyLimit(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateFraudDailyLock(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateFraudDailyNotify(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateFraudIntervalLimit(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateFraudIntervalLock(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateFraudIntervalNotify(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateFraudUseResellerRates(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateHandle(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateIntervalCharge(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateIntervalFreeCash(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateIntervalFreeTime(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateName(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validatePeaktimeSpecial(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validatePeaktimeWeekdays(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validatePrepaid(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validatePrepaidLibrary(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateResellerID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (o *conversionOptions) validate() error {\r\n\tif o.goalID == 0 && len(o.goalName) == 0 {\r\n\t\treturn fmt.Errorf(\"missing required attribute(s): %s or %s\", fieldID, fieldName)\r\n\t} else if o.goalID == 0 && o.tonicPowUserID > 0 {\r\n\t\treturn fmt.Errorf(\"missing required attribute: %s\", fieldID)\r\n\t} else if o.tonicPowUserID == 0 && len(o.tncpwSession) == 0 {\r\n\t\treturn fmt.Errorf(\"missing required attribute(s): %s or %s\", fieldVisitorSessionGUID, fieldUserID)\r\n\t}\r\n\treturn nil\r\n}", "func (m *CustomerTripletexAccount2) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateAccountType(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateAdministrator(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateChartOfAccountsType(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateModules(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateType(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateVatStatusType(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (uuo *UserUpdateOne) check() error {\n\tif v, ok := uuo.mutation.AccountName(); ok {\n\t\tif err := user.AccountNameValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"account_name\", err: fmt.Errorf(\"ent: validator failed for field \\\"account_name\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.StaffType(); ok {\n\t\tif err := user.StaffTypeValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"staff_type\", err: fmt.Errorf(\"ent: validator failed for field \\\"staff_type\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.FamilyName(); ok {\n\t\tif err := user.FamilyNameValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"family_name\", err: fmt.Errorf(\"ent: validator failed for field \\\"family_name\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.GivenName(); ok {\n\t\tif err := user.GivenNameValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"given_name\", err: fmt.Errorf(\"ent: validator failed for field \\\"given_name\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.DisplayName(); ok {\n\t\tif err := user.DisplayNameValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"display_name\", err: fmt.Errorf(\"ent: validator failed for field \\\"display_name\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.IDNumber(); ok {\n\t\tif err := user.IDNumberValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"id_number\", err: fmt.Errorf(\"ent: validator failed for field \\\"id_number\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.Sex(); ok {\n\t\tif err := user.SexValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"sex\", err: fmt.Errorf(\"ent: validator failed for field \\\"sex\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.PhoneNumber(); ok {\n\t\tif err := user.PhoneNumberValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"phone_number\", err: fmt.Errorf(\"ent: validator failed for field \\\"phone_number\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.Address(); ok {\n\t\tif err := user.AddressValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"address\", err: fmt.Errorf(\"ent: validator failed for field \\\"address\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.StaffID(); ok {\n\t\tif err := user.StaffIDValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"staff_id\", err: fmt.Errorf(\"ent: validator failed for field \\\"staff_id\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.PersonalEmail(); ok {\n\t\tif err := user.PersonalEmailValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"personal_email\", err: fmt.Errorf(\"ent: validator failed for field \\\"personal_email\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.IntranetWorkEmail(); ok {\n\t\tif err := user.IntranetWorkEmailValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"intranet_work_email\", err: fmt.Errorf(\"ent: validator failed for field \\\"intranet_work_email\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.ExtranetWorkEmail(); ok {\n\t\tif err := user.ExtranetWorkEmailValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"extranet_work_email\", err: fmt.Errorf(\"ent: validator failed for field \\\"extranet_work_email\\\": %w\", err)}\n\t\t}\n\t}\n\treturn nil\n}", "func (m *DomainDiscoverAPIAccount) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateCid(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (msg MsgAddAdminAccount) ValidateBasic() sdk.Error {\n if msg.AdminAddress.Empty() {\n return sdk.ErrInvalidAddress(msg.AdminAddress.String())\n }\n if msg.Owner.Empty() {\n return sdk.ErrInvalidAddress(msg.Owner.String())\n }\n return nil\n}", "func init() {\n\taccountFields := schema.Account{}.Fields()\n\t_ = accountFields\n\t// accountDescProvider is the schema descriptor for provider field.\n\taccountDescProvider := accountFields[1].Descriptor()\n\t// account.ProviderValidator is a validator for the \"provider\" field. It is called by the builders before save.\n\taccount.ProviderValidator = accountDescProvider.Validators[0].(func(string) error)\n\t// accountDescEmail is the schema descriptor for email field.\n\taccountDescEmail := accountFields[2].Descriptor()\n\t// account.EmailValidator is a validator for the \"email\" field. It is called by the builders before save.\n\taccount.EmailValidator = accountDescEmail.Validators[0].(func(string) error)\n\t// accountDescPassword is the schema descriptor for password field.\n\taccountDescPassword := accountFields[3].Descriptor()\n\t// account.PasswordValidator is a validator for the \"password\" field. It is called by the builders before save.\n\taccount.PasswordValidator = func() func(string) error {\n\t\tvalidators := accountDescPassword.Validators\n\t\tfns := [...]func(string) error{\n\t\t\tvalidators[0].(func(string) error),\n\t\t\tvalidators[1].(func(string) error),\n\t\t}\n\t\treturn func(password string) error {\n\t\t\tfor _, fn := range fns {\n\t\t\t\tif err := fn(password); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\t}()\n\t// accountDescLocked is the schema descriptor for locked field.\n\taccountDescLocked := accountFields[4].Descriptor()\n\t// account.DefaultLocked holds the default value on creation for the locked field.\n\taccount.DefaultLocked = accountDescLocked.Default.(bool)\n\t// accountDescConfirmed is the schema descriptor for confirmed field.\n\taccountDescConfirmed := accountFields[5].Descriptor()\n\t// account.DefaultConfirmed holds the default value on creation for the confirmed field.\n\taccount.DefaultConfirmed = accountDescConfirmed.Default.(bool)\n\t// accountDescConfirmationToken is the schema descriptor for confirmation_token field.\n\taccountDescConfirmationToken := accountFields[7].Descriptor()\n\t// account.ConfirmationTokenValidator is a validator for the \"confirmation_token\" field. It is called by the builders before save.\n\taccount.ConfirmationTokenValidator = accountDescConfirmationToken.Validators[0].(func(string) error)\n\t// accountDescRecoveryToken is the schema descriptor for recovery_token field.\n\taccountDescRecoveryToken := accountFields[9].Descriptor()\n\t// account.RecoveryTokenValidator is a validator for the \"recovery_token\" field. It is called by the builders before save.\n\taccount.RecoveryTokenValidator = accountDescRecoveryToken.Validators[0].(func(string) error)\n\t// accountDescOtp is the schema descriptor for otp field.\n\taccountDescOtp := accountFields[11].Descriptor()\n\t// account.OtpValidator is a validator for the \"otp\" field. It is called by the builders before save.\n\taccount.OtpValidator = accountDescOtp.Validators[0].(func(string) error)\n\t// accountDescEmailChange is the schema descriptor for email_change field.\n\taccountDescEmailChange := accountFields[12].Descriptor()\n\t// account.EmailChangeValidator is a validator for the \"email_change\" field. It is called by the builders before save.\n\taccount.EmailChangeValidator = accountDescEmailChange.Validators[0].(func(string) error)\n\t// accountDescEmailChangeToken is the schema descriptor for email_change_token field.\n\taccountDescEmailChangeToken := accountFields[14].Descriptor()\n\t// account.EmailChangeTokenValidator is a validator for the \"email_change_token\" field. It is called by the builders before save.\n\taccount.EmailChangeTokenValidator = accountDescEmailChangeToken.Validators[0].(func(string) error)\n\t// accountDescCreatedAt is the schema descriptor for created_at field.\n\taccountDescCreatedAt := accountFields[18].Descriptor()\n\t// account.DefaultCreatedAt holds the default value on creation for the created_at field.\n\taccount.DefaultCreatedAt = accountDescCreatedAt.Default.(func() time.Time)\n\t// accountDescUpdatedAt is the schema descriptor for updated_at field.\n\taccountDescUpdatedAt := accountFields[19].Descriptor()\n\t// account.DefaultUpdatedAt holds the default value on creation for the updated_at field.\n\taccount.DefaultUpdatedAt = accountDescUpdatedAt.Default.(func() time.Time)\n\t// account.UpdateDefaultUpdatedAt holds the default value on update for the updated_at field.\n\taccount.UpdateDefaultUpdatedAt = accountDescUpdatedAt.UpdateDefault.(func() time.Time)\n\t// accountDescID is the schema descriptor for id field.\n\taccountDescID := accountFields[0].Descriptor()\n\t// account.DefaultID holds the default value on creation for the id field.\n\taccount.DefaultID = accountDescID.Default.(func() uuid.UUID)\n\tsessionFields := schema.Session{}.Fields()\n\t_ = sessionFields\n\t// sessionDescCreatedAt is the schema descriptor for created_at field.\n\tsessionDescCreatedAt := sessionFields[2].Descriptor()\n\t// session.DefaultCreatedAt holds the default value on creation for the created_at field.\n\tsession.DefaultCreatedAt = sessionDescCreatedAt.Default.(func() time.Time)\n\t// sessionDescUpdatedAt is the schema descriptor for updated_at field.\n\tsessionDescUpdatedAt := sessionFields[3].Descriptor()\n\t// session.DefaultUpdatedAt holds the default value on creation for the updated_at field.\n\tsession.DefaultUpdatedAt = sessionDescUpdatedAt.Default.(func() time.Time)\n\t// session.UpdateDefaultUpdatedAt holds the default value on update for the updated_at field.\n\tsession.UpdateDefaultUpdatedAt = sessionDescUpdatedAt.UpdateDefault.(func() time.Time)\n}", "func (mt AccountCollection) Validate() (err error) {\n\tfor _, e := range mt {\n\t\tif e != nil {\n\t\t\tif err2 := e.Validate(); err2 != nil {\n\t\t\t\terr = goa.MergeErrors(err, err2)\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}", "func (frm entryForm) Validate() (map[string]string, bool) {\n\terrs := map[string]string{}\n\tg1 := frm.Department != \"\"\n\tif !g1 {\n\t\terrs[\"department\"] = \"Missing department\"\n\t}\n\tg2 := frm.CheckThis\n\tif !g2 {\n\t\terrs[\"check_this\"] = \"You need to comply\"\n\t}\n\tg3 := frm.Items != \"\"\n\tif !g3 {\n\t\terrs[\"items\"] = \"No items\"\n\t}\n\treturn errs, g1 && g2 && g3\n}", "func (vva ValidatorVestingAccount) Validate() error {\n\tif vva.SigningThreshold > 100 || vva.SigningThreshold < 0 {\n\t\treturn errors.New(\"signing threshold must be between 0 and 100\")\n\t}\n\tif vva.ReturnAddress.Equals(vva.Address) {\n\t\treturn errors.New(\"return address cannot be the same as the account address\")\n\t}\n\treturn vva.PeriodicVestingAccount.Validate()\n}", "func (dva DelayedVestingAccount) Validate() error {\n\treturn dva.BaseVestingAccount.Validate()\n}", "func validate(msgs []*LogMsg) {\n\tif !validatePRAMRegistration(msgs) {\n\t\tlog.Fatalf(\"validatePRAMRegistration\\n\")\n\t}\n}", "func (_PermInterface *PermInterfaceCaller) ValidateAccount(opts *bind.CallOpts, _account common.Address, _orgId string) (bool, error) {\n\tvar out []interface{}\n\terr := _PermInterface.contract.Call(opts, &out, \"validateAccount\", _account, _orgId)\n\n\tif err != nil {\n\t\treturn *new(bool), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(bool)).(*bool)\n\n\treturn out0, err\n\n}", "func (ut *RegisterPayload) Validate() (err error) {\n\tif ut.Email == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`type`, \"email\"))\n\t}\n\tif ut.Password == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`type`, \"password\"))\n\t}\n\tif ut.FirstName == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`type`, \"first_name\"))\n\t}\n\tif ut.LastName == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`type`, \"last_name\"))\n\t}\n\tif err2 := goa.ValidateFormat(goa.FormatEmail, ut.Email); err2 != nil {\n\t\terr = goa.MergeErrors(err, goa.InvalidFormatError(`type.email`, ut.Email, goa.FormatEmail, err2))\n\t}\n\tif utf8.RuneCountInString(ut.Email) < 6 {\n\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`type.email`, ut.Email, utf8.RuneCountInString(ut.Email), 6, true))\n\t}\n\tif utf8.RuneCountInString(ut.Email) > 150 {\n\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`type.email`, ut.Email, utf8.RuneCountInString(ut.Email), 150, false))\n\t}\n\tif utf8.RuneCountInString(ut.FirstName) < 1 {\n\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`type.first_name`, ut.FirstName, utf8.RuneCountInString(ut.FirstName), 1, true))\n\t}\n\tif utf8.RuneCountInString(ut.FirstName) > 200 {\n\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`type.first_name`, ut.FirstName, utf8.RuneCountInString(ut.FirstName), 200, false))\n\t}\n\tif utf8.RuneCountInString(ut.LastName) < 1 {\n\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`type.last_name`, ut.LastName, utf8.RuneCountInString(ut.LastName), 1, true))\n\t}\n\tif utf8.RuneCountInString(ut.LastName) > 200 {\n\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`type.last_name`, ut.LastName, utf8.RuneCountInString(ut.LastName), 200, false))\n\t}\n\tif utf8.RuneCountInString(ut.Password) < 5 {\n\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`type.password`, ut.Password, utf8.RuneCountInString(ut.Password), 5, true))\n\t}\n\tif utf8.RuneCountInString(ut.Password) > 100 {\n\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`type.password`, ut.Password, utf8.RuneCountInString(ut.Password), 100, false))\n\t}\n\treturn\n}", "func (a *Api) validateError() (err error) {\n\tif a.UserID == 0 {\n\t\treturn a.Errors(ErrorMissingValue, \"user_id\")\n\t}\n\n\tif a.Token == \"\" {\n\t\treturn a.Errors(ErrorMissingValue, \"token\")\n\t}\n\n\treturn\n}", "func (uc *UserCreate) check() error {\n\tif _, ok := uc.mutation.Firstname(); !ok {\n\t\treturn &ValidationError{Name: \"firstname\", err: errors.New(\"ent: missing required field \\\"firstname\\\"\")}\n\t}\n\tif _, ok := uc.mutation.Lastname(); !ok {\n\t\treturn &ValidationError{Name: \"lastname\", err: errors.New(\"ent: missing required field \\\"lastname\\\"\")}\n\t}\n\tif _, ok := uc.mutation.Username(); !ok {\n\t\treturn &ValidationError{Name: \"username\", err: errors.New(\"ent: missing required field \\\"username\\\"\")}\n\t}\n\tif _, ok := uc.mutation.Password(); !ok {\n\t\treturn &ValidationError{Name: \"password\", err: errors.New(\"ent: missing required field \\\"password\\\"\")}\n\t}\n\treturn nil\n}", "func (ac *AreahistoryCreate) check() error {\n\tif _, ok := ac.mutation.WalletID(); !ok {\n\t\treturn &ValidationError{Name: \"WalletID\", err: errors.New(\"ent: missing required field \\\"WalletID\\\"\")}\n\t}\n\tif v, ok := ac.mutation.WalletID(); ok {\n\t\tif err := areahistory.WalletIDValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"WalletID\", err: fmt.Errorf(\"ent: validator failed for field \\\"WalletID\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := ac.mutation.ProvinceNameTH(); ok {\n\t\tif err := areahistory.ProvinceNameTHValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"ProvinceNameTH\", err: fmt.Errorf(\"ent: validator failed for field \\\"ProvinceNameTH\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := ac.mutation.DistrictNameTH(); ok {\n\t\tif err := areahistory.DistrictNameTHValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"DistrictNameTH\", err: fmt.Errorf(\"ent: validator failed for field \\\"DistrictNameTH\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := ac.mutation.SubDistrict(); ok {\n\t\tif err := areahistory.SubDistrictValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"SubDistrict\", err: fmt.Errorf(\"ent: validator failed for field \\\"SubDistrict\\\": %w\", err)}\n\t\t}\n\t}\n\treturn nil\n}", "func (_PermInterface *PermInterfaceSession) ValidateAccount(_account common.Address, _orgId string) (bool, error) {\n\treturn _PermInterface.Contract.ValidateAccount(&_PermInterface.CallOpts, _account, _orgId)\n}", "func (uu *UserUpdate) check() error {\n\tif v, ok := uu.mutation.Username(); ok {\n\t\tif err := user.UsernameValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"username\", err: fmt.Errorf(\"ent: validator failed for field \\\"username\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.Fullname(); ok {\n\t\tif err := user.FullnameValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"fullname\", err: fmt.Errorf(\"ent: validator failed for field \\\"fullname\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.Password(); ok {\n\t\tif err := user.PasswordValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"password\", err: fmt.Errorf(\"ent: validator failed for field \\\"password\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.Email(); ok {\n\t\tif err := user.EmailValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"email\", err: fmt.Errorf(\"ent: validator failed for field \\\"email\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.Phone(); ok {\n\t\tif err := user.PhoneValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"phone\", err: fmt.Errorf(\"ent: validator failed for field \\\"phone\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.Bio(); ok {\n\t\tif err := user.BioValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"bio\", err: fmt.Errorf(\"ent: validator failed for field \\\"bio\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.Intro(); ok {\n\t\tif err := user.IntroValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"intro\", err: fmt.Errorf(\"ent: validator failed for field \\\"intro\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.GithubProfile(); ok {\n\t\tif err := user.GithubProfileValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"github_profile\", err: fmt.Errorf(\"ent: validator failed for field \\\"github_profile\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.ProfilePictureURL(); ok {\n\t\tif err := user.ProfilePictureURLValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"profile_picture_url\", err: fmt.Errorf(\"ent: validator failed for field \\\"profile_picture_url\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.Status(); ok {\n\t\tif err := user.StatusValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"status\", err: fmt.Errorf(\"ent: validator failed for field \\\"status\\\": %w\", err)}\n\t\t}\n\t}\n\treturn nil\n}", "func (uc *UserCreate) check() error {\n\tif _, ok := uc.mutation.Age(); !ok {\n\t\treturn &ValidationError{Name: \"age\", err: errors.New(\"ent: missing required field \\\"age\\\"\")}\n\t}\n\tif v, ok := uc.mutation.Age(); ok {\n\t\tif err := user.AgeValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"age\", err: fmt.Errorf(\"ent: validator failed for field \\\"age\\\": %w\", err)}\n\t\t}\n\t}\n\tif _, ok := uc.mutation.Name(); !ok {\n\t\treturn &ValidationError{Name: \"name\", err: errors.New(\"ent: missing required field \\\"name\\\"\")}\n\t}\n\tif v, ok := uc.mutation.ID(); ok {\n\t\tif err := user.IDValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"id\", err: fmt.Errorf(\"ent: validator failed for field \\\"id\\\": %w\", err)}\n\t\t}\n\t}\n\treturn nil\n}", "func (p *PaymentNeed) validate() error {\n\tif p.BeneficiaryID == 0 {\n\t\treturn fmt.Errorf(\"beneficiary ID nul\")\n\t}\n\tif p.Value == 0 {\n\t\treturn fmt.Errorf(\"value nul\")\n\t}\n\treturn nil\n}", "func (r *Result) validate(errMsg *[]string, parentField string) {\n\tjn := resultJsonMap\n\taddErrMessage(errMsg, len(r.Key) > 0 && hasNonEmptyKV(r.Key), \"field '%s' must be non-empty and must not have empty keys or values\", parentField+\".\"+jn[\"Key\"])\n\taddErrMessage(errMsg, hasNonEmptyKV(r.Options), \"field '%s' must not have empty keys or values\", parentField+\".\"+jn[\"Options\"])\n\taddErrMessage(errMsg, regExHexadecimal.MatchString(string(r.Digest)), \"field '%s' must be hexadecimal\", parentField+\".\"+jn[\"Digest\"])\n}", "func CheckAccountResponse(t *testing.T, resp *models.Account, expectedAccount *models.Account) {\n\tif resp.ID != expectedAccount.ID {\n\t\tt.Errorf(\"Response contains wrong ID, got %v expected %v\", resp.ID, expectedAccount.ID)\n\t}\n\tif resp.Type != expectedAccount.Type {\n\t\tt.Errorf(\"Response contains wrong Type, got %v expected %v\", resp.Type, expectedAccount.Type)\n\t}\n\tif resp.OrganisationID != expectedAccount.OrganisationID {\n\t\tt.Errorf(\"Response contains wrong OrganisationID, got %v expected %v\", resp.OrganisationID, expectedAccount.OrganisationID)\n\t}\n\tif resp.Version != expectedAccount.Version {\n\t\tt.Errorf(\"Response contains wrong Version, got %v expected %v\", resp.Version, expectedAccount.Version)\n\t}\n\tif resp.Attributes.Country != expectedAccount.Attributes.Country {\n\t\tt.Errorf(\"Response contains wrong Country, got %v expected %v\", resp.Attributes.Country, expectedAccount.Attributes.Country)\n\t}\n\tif resp.Attributes.BaseCurrency != expectedAccount.Attributes.BaseCurrency {\n\t\tt.Errorf(\"Response contains wrong BaseCurrency, got %v expected %v\", resp.Attributes.BaseCurrency, expectedAccount.Attributes.BaseCurrency)\n\t}\n\tif resp.Attributes.BankID != expectedAccount.Attributes.BankID {\n\t\tt.Errorf(\"Response contains wrong BankID, got %v expected %v\", resp.Attributes.BankID, expectedAccount.Attributes.BankID)\n\t}\n\tif resp.Attributes.BankIDCode != expectedAccount.Attributes.BankIDCode {\n\t\tt.Errorf(\"Response contains wrong BankIDCode, got %v expected %v\", resp.Attributes.BankIDCode, expectedAccount.Attributes.BankIDCode)\n\t}\n\tif resp.Attributes.Bic != expectedAccount.Attributes.Bic {\n\t\tt.Errorf(\"Response contains wrong Bic, got %v expected %v\", resp.Attributes.Bic, expectedAccount.Attributes.Bic)\n\t}\n\tif resp.Attributes.AccountNumber != expectedAccount.Attributes.AccountNumber {\n\t\tt.Errorf(\"Response contains wrong AccountNumber, got %v expected %v\", resp.Attributes.AccountNumber, expectedAccount.Attributes.AccountNumber)\n\t}\n\tif resp.Attributes.CustomerID != expectedAccount.Attributes.CustomerID {\n\t\tt.Errorf(\"Response contains wrong CustomerID, got %v expected %v\", resp.Attributes.CustomerID, expectedAccount.Attributes.CustomerID)\n\t}\n\tif resp.Attributes.FirstName != expectedAccount.Attributes.FirstName {\n\t\tt.Errorf(\"Response contains wrong FirstName, got %v expected %v\", resp.Attributes.FirstName, expectedAccount.Attributes.FirstName)\n\t}\n\tif resp.Attributes.BankAccountName != expectedAccount.Attributes.BankAccountName {\n\t\tt.Errorf(\"Response contains wrong BankAccountName, got %v expected %v\", resp.Attributes.BankAccountName, expectedAccount.Attributes.BankAccountName)\n\t}\n\n\tresponseLength := len(resp.Attributes.AlternativeBankAccountNames)\n\texpectedLength := len(expectedAccount.Attributes.AlternativeBankAccountNames)\n\n\tif responseLength != expectedLength {\n\t\tt.Errorf(\"AlternativeBankAccountNames array is wrong, got %v expected %v\", responseLength, expectedLength)\n\t} else {\n\t\ti := 0\n\t\tfor i < responseLength {\n\t\t\tif resp.Attributes.AlternativeBankAccountNames[i] != expectedAccount.Attributes.AlternativeBankAccountNames[i] {\n\t\t\t\tt.Errorf(\"Response contains wrong AlternativeBankAccountNames, got %v expected %v\", resp.Attributes.AlternativeBankAccountNames[i], expectedAccount.Attributes.AlternativeBankAccountNames[i])\n\t\t\t}\n\t\t\ti = i + 1\n\t\t}\n\t}\n\n\tif resp.Attributes.AlternativeBankAccountNames[0] != expectedAccount.Attributes.AlternativeBankAccountNames[0] {\n\t\tt.Errorf(\"Response contains wrong AlternativeBankAccountNames, got %v expected %v\", resp.Attributes.AlternativeBankAccountNames[0], expectedAccount.Attributes.AlternativeBankAccountNames[0])\n\t}\n\tif resp.Attributes.AccountClassification != expectedAccount.Attributes.AccountClassification {\n\t\tt.Errorf(\"Response contains wrong AccountClassification, got %v expected %v\", resp.Attributes.AccountClassification, expectedAccount.Attributes.AccountClassification)\n\t}\n\tif resp.Attributes.JointAccount != expectedAccount.Attributes.JointAccount {\n\t\tt.Errorf(\"Response contains wrong JointAccount, got %v expected %v\", resp.Attributes.JointAccount, expectedAccount.Attributes.JointAccount)\n\t}\n\tif resp.Attributes.Switched != expectedAccount.Attributes.Switched {\n\t\tt.Errorf(\"Response contains wrong Switched, got %v expected %v\", resp.Attributes.Switched, expectedAccount.Attributes.Switched)\n\t}\n\tif resp.Attributes.AccountMatchingOptOut != expectedAccount.Attributes.AccountMatchingOptOut {\n\t\tt.Errorf(\"Response contains wrong AccountMatchingOptOut, got %v expected %v\", resp.Attributes.AccountMatchingOptOut, expectedAccount.Attributes.AccountMatchingOptOut)\n\t}\n\tif resp.Attributes.Status != expectedAccount.Attributes.Status {\n\t\tt.Errorf(\"Response contains wrong Status, got %v expected %v\", resp.Attributes.Status, expectedAccount.Attributes.Status)\n\t}\n\tif resp.Attributes.SecondaryIdentification != expectedAccount.Attributes.SecondaryIdentification {\n\t\tt.Errorf(\"Response contains wrong SecondaryIdentification, got %v expected %v\", resp.Attributes.SecondaryIdentification, expectedAccount.Attributes.SecondaryIdentification)\n\t}\n}", "func (_PermInterface *PermInterfaceCallerSession) ValidateAccount(_account common.Address, _orgId string) (bool, error) {\n\treturn _PermInterface.Contract.ValidateAccount(&_PermInterface.CallOpts, _account, _orgId)\n}", "func (cfg fromCFN) validate() error {\n\tif cfg.isEmpty() {\n\t\treturn nil\n\t}\n\tif len(aws.StringValue(cfg.Name)) == 0 {\n\t\treturn errors.New(\"name cannot be an empty string\")\n\t}\n\treturn nil\n}", "func isAccountFlagsValid(accountId string) bool {\n\taccount := GetStellarAccount(accountId)\n\treturn account.Flags.AuthRequired && account.Flags.AuthRevocable\n}", "func validate(name, gender string) error {\n\tif name == \"\" {\n\t\treturn &inputError{message: \"name is missing\", missingField: \"name\"}\n\t}\n\tif gender == \"\" {\n\t\treturn &inputError{message: \"gender is missing\", missingField: \"gender\"}\n\t}\n\treturn nil\n}", "func (user *User) Validate() *errors.RestErr {\n\t// Delete spaces at first_name, last_name and email before saving\n\tuser.FirstName = strings.TrimSpace(user.FirstName)\n\tuser.LastName = strings.TrimSpace(user.LastName)\n\tuser.Email = strings.TrimSpace(strings.ToLower(user.Email))\n\n\tif user.Email == \"\"{\n\t\treturn errors.NewBadRequestError(\"Email addres is required\")\n\t}\n\tif !ValidateEmail(user.Email){\n\t\treturn errors.NewBadRequestError(\"Wrong email format\")\n\t}\n\tif strings.TrimSpace(user.Password)== \"\" || len(strings.TrimSpace(user.Password)) < 8{\n\t\treturn errors.NewBadRequestError(\"Password is required and password length must be higher than 8 characters\")\n\t}\n\n\n\treturn nil\n}", "func checkAccount(t *testing.T, tree *avl.Tree, id AccountID, expectedBalance, expectedReward, expectedStake *uint64) {\n\tvar balance, reward, stake uint64\n\tvar exist bool\n\n\tbalance, exist = ReadAccountBalance(tree, id)\n\tassert.Equal(t, expectedBalance != nil, exist, \"account ID: %x\", id)\n\treward, exist = ReadAccountReward(tree, id)\n\tassert.Equal(t, expectedReward != nil, exist, \"account ID: %x\", id)\n\tstake, exist = ReadAccountStake(tree, id)\n\tassert.Equal(t, expectedStake != nil, exist, \"account ID: %x\", id)\n\n\tif expectedBalance != nil {\n\t\tassert.Equal(t, balance, *expectedBalance, \"account ID: %x\", id)\n\t}\n\n\tif expectedReward != nil {\n\t\tassert.Equal(t, reward, *expectedReward, \"account ID: %x\", id)\n\t}\n\n\tif expectedStake != nil {\n\t\tassert.Equal(t, stake, *expectedStake, \"account ID: %x\", id)\n\t}\n}", "func ValidBaseInfo(ctx *gin.Context) {\n\tres := helper.Res{}\n\n\tvar baseInfo BaseInfo\n\tif err := ctx.Bind(&baseInfo); err != nil {\n\t\tres.Status(http.StatusBadRequest).Error(err).Send(ctx)\n\t\treturn\n\t}\n\n\t// user does exist\n\tif _, err := models.FindOneByUsername(baseInfo.Username); err != nil {\n\t\tres.Status(http.StatusBadRequest).Error(err).Send(ctx)\n\t\treturn\n\t}\n\n\t// the email of user does exist\n\tif _, err := models.FindOneByEmail(baseInfo.Email); err != nil {\n\t\tres.Status(http.StatusBadRequest).Error(err).Send(ctx)\n\t\treturn\n\t}\n\n\tres.Success(gin.H{\n\t\t\"isValid\": true,\n\t}).Send(ctx)\n}", "func (w Warrant) Validate() error {\n\tif len(w.FirstName) == 0 {\n\t\treturn errors.New(\"missing first name element\")\n\t}\n\tif len(w.LastName) == 0 {\n\t\treturn errors.New(\"missing last name element\")\n\t}\n\tif len(w.Civility) == 0 {\n\t\treturn errors.New(\"missing civility element\")\n\t}\n\treturn nil\n}", "func (va ClawbackVestingAccount) Validate() error {\n\tif va.GetStartTime() >= va.GetEndTime() {\n\t\treturn errors.New(\"vesting start-time must be before end-time\")\n\t}\n\n\tlockupEnd := va.StartTime\n\tlockupCoins := sdk.NewCoins()\n\tfor _, p := range va.LockupPeriods {\n\t\tlockupEnd += p.Length\n\t\tlockupCoins = lockupCoins.Add(p.Amount...)\n\t}\n\tif lockupEnd > va.EndTime {\n\t\treturn errors.New(\"lockup schedule extends beyond account end time\")\n\t}\n\tif !coinEq(lockupCoins, va.OriginalVesting) {\n\t\treturn errors.New(\"original vesting coins does not match the sum of all coins in lockup periods\")\n\t}\n\n\tvestingEnd := va.StartTime\n\tvestingCoins := sdk.NewCoins()\n\tfor _, p := range va.VestingPeriods {\n\t\tvestingEnd += p.Length\n\t\tvestingCoins = vestingCoins.Add(p.Amount...)\n\t}\n\tif vestingEnd > va.EndTime {\n\t\treturn errors.New(\"vesting schedule exteds beyond account end time\")\n\t}\n\tif !coinEq(vestingCoins, va.OriginalVesting) {\n\t\treturn errors.New(\"original vesting coins does not match the sum of all coins in vesting periods\")\n\t}\n\n\treturn va.BaseVestingAccount.Validate()\n}", "func (ut *registerPayload) Validate() (err error) {\n\tif ut.Email == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`request`, \"email\"))\n\t}\n\tif ut.Password == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`request`, \"password\"))\n\t}\n\tif ut.FirstName == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`request`, \"first_name\"))\n\t}\n\tif ut.LastName == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`request`, \"last_name\"))\n\t}\n\tif ut.Email != nil {\n\t\tif err2 := goa.ValidateFormat(goa.FormatEmail, *ut.Email); err2 != nil {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidFormatError(`request.email`, *ut.Email, goa.FormatEmail, err2))\n\t\t}\n\t}\n\tif ut.Email != nil {\n\t\tif utf8.RuneCountInString(*ut.Email) < 6 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`request.email`, *ut.Email, utf8.RuneCountInString(*ut.Email), 6, true))\n\t\t}\n\t}\n\tif ut.Email != nil {\n\t\tif utf8.RuneCountInString(*ut.Email) > 150 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`request.email`, *ut.Email, utf8.RuneCountInString(*ut.Email), 150, false))\n\t\t}\n\t}\n\tif ut.FirstName != nil {\n\t\tif utf8.RuneCountInString(*ut.FirstName) < 1 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`request.first_name`, *ut.FirstName, utf8.RuneCountInString(*ut.FirstName), 1, true))\n\t\t}\n\t}\n\tif ut.FirstName != nil {\n\t\tif utf8.RuneCountInString(*ut.FirstName) > 200 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`request.first_name`, *ut.FirstName, utf8.RuneCountInString(*ut.FirstName), 200, false))\n\t\t}\n\t}\n\tif ut.LastName != nil {\n\t\tif utf8.RuneCountInString(*ut.LastName) < 1 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`request.last_name`, *ut.LastName, utf8.RuneCountInString(*ut.LastName), 1, true))\n\t\t}\n\t}\n\tif ut.LastName != nil {\n\t\tif utf8.RuneCountInString(*ut.LastName) > 200 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`request.last_name`, *ut.LastName, utf8.RuneCountInString(*ut.LastName), 200, false))\n\t\t}\n\t}\n\tif ut.Password != nil {\n\t\tif utf8.RuneCountInString(*ut.Password) < 5 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`request.password`, *ut.Password, utf8.RuneCountInString(*ut.Password), 5, true))\n\t\t}\n\t}\n\tif ut.Password != nil {\n\t\tif utf8.RuneCountInString(*ut.Password) > 100 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`request.password`, *ut.Password, utf8.RuneCountInString(*ut.Password), 100, false))\n\t\t}\n\t}\n\treturn\n}", "func ValidateWarriorAccount(name string, email string, pwd1 string, pwd2 string) (WarriorName string, WarriorEmail string, WarriorPassword string, validateErr error) {\n\tv := validator.New()\n\ta := warriorAccount{\n\t\tName: name,\n\t\tEmail: email,\n\t\tPassword1: pwd1,\n\t\tPassword2: pwd2,\n\t}\n\terr := v.Struct(a)\n\n\treturn name, email, pwd1, err\n}", "func validateAttributes(attrs map[string]models.ValueType, allAttrs bool) error {\n\t// TBD: to finalize the attributes specifics\n\tattrsOK := false\n\tif vt, ok := attrs[AttrCred]; ok && vt.Kind == com.ValueTypeSecret {\n\t\tif !allAttrs {\n\t\t\tattrsOK = true\n\t\t} else if vt, ok := attrs[AttrZone]; ok && vt.Kind == com.ValueTypeString {\n\t\t\tattrsOK = true\n\t\t}\n\t}\n\tif !attrsOK {\n\t\tmsg := \"required domain attributes missing or invalid: need \" + AttrCred + \"[E]\"\n\t\tif allAttrs {\n\t\t\tmsg += \", \" + AttrZone + \"[S]\"\n\t\t}\n\t\treturn fmt.Errorf(msg)\n\t}\n\treturn nil\n}", "func (cc *CompanyCreate) check() error {\n\tif _, ok := cc.mutation.CreatedAt(); !ok {\n\t\treturn &ValidationError{Name: \"created_at\", err: errors.New(`ent: missing required field \"created_at\"`)}\n\t}\n\tif _, ok := cc.mutation.UpdatedAt(); !ok {\n\t\treturn &ValidationError{Name: \"updated_at\", err: errors.New(`ent: missing required field \"updated_at\"`)}\n\t}\n\tif _, ok := cc.mutation.Name(); !ok {\n\t\treturn &ValidationError{Name: \"name\", err: errors.New(`ent: missing required field \"name\"`)}\n\t}\n\tif v, ok := cc.mutation.Name(); ok {\n\t\tif err := company.NameValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"name\", err: fmt.Errorf(`ent: validator failed for field \"name\": %w`, err)}\n\t\t}\n\t}\n\tif _, ok := cc.mutation.Overview(); !ok {\n\t\treturn &ValidationError{Name: \"overview\", err: errors.New(`ent: missing required field \"overview\"`)}\n\t}\n\tif v, ok := cc.mutation.Overview(); ok {\n\t\tif err := company.OverviewValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"overview\", err: fmt.Errorf(`ent: validator failed for field \"overview\": %w`, err)}\n\t\t}\n\t}\n\tif _, ok := cc.mutation.Website(); !ok {\n\t\treturn &ValidationError{Name: \"website\", err: errors.New(`ent: missing required field \"website\"`)}\n\t}\n\tif v, ok := cc.mutation.Website(); ok {\n\t\tif err := company.WebsiteValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"website\", err: fmt.Errorf(`ent: validator failed for field \"website\": %w`, err)}\n\t\t}\n\t}\n\tif _, ok := cc.mutation.LogoURL(); !ok {\n\t\treturn &ValidationError{Name: \"logo_url\", err: errors.New(`ent: missing required field \"logo_url\"`)}\n\t}\n\tif v, ok := cc.mutation.LogoURL(); ok {\n\t\tif err := company.LogoURLValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"logo_url\", err: fmt.Errorf(`ent: validator failed for field \"logo_url\": %w`, err)}\n\t\t}\n\t}\n\tif _, ok := cc.mutation.Size(); !ok {\n\t\treturn &ValidationError{Name: \"size\", err: errors.New(`ent: missing required field \"size\"`)}\n\t}\n\tif v, ok := cc.mutation.Size(); ok {\n\t\tif err := company.SizeValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"size\", err: fmt.Errorf(`ent: validator failed for field \"size\": %w`, err)}\n\t\t}\n\t}\n\tif _, ok := cc.mutation.FoundedAt(); !ok {\n\t\treturn &ValidationError{Name: \"founded_at\", err: errors.New(`ent: missing required field \"founded_at\"`)}\n\t}\n\tif v, ok := cc.mutation.FoundedAt(); ok {\n\t\tif err := company.FoundedAtValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"founded_at\", err: fmt.Errorf(`ent: validator failed for field \"founded_at\": %w`, err)}\n\t\t}\n\t}\n\treturn nil\n}", "func (m *ProviderAccountPreferences) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func ValidateGetAccountInternalResponseBody(body *GetAccountInternalResponseBody) (err error) {\n\tif body.Name == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"name\", \"body\"))\n\t}\n\tif body.ID == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"id\", \"body\"))\n\t}\n\tif body.Message == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"message\", \"body\"))\n\t}\n\tif body.Temporary == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"temporary\", \"body\"))\n\t}\n\tif body.Timeout == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"timeout\", \"body\"))\n\t}\n\tif body.Fault == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"fault\", \"body\"))\n\t}\n\treturn\n}", "func (o *Virtualserver) validate(dbRecord *common.DbRecord) (ok bool, err error) {\n\t////////////////////////////////////////////////////////////////////////////\n\t// Marshal data interface.\n\t////////////////////////////////////////////////////////////////////////////\n\tvar data virtualserver.Data\n\terr = shared.MarshalInterface(dbRecord.Data, &data)\n\tif err != nil {\n\t\treturn\n\t}\n\t////////////////////////////////////////////////////////////////////////////\n\t// Test required fields.\n\t////////////////////////////////////////////////////////////////////////////\n\tok = true\n\trequired := make(map[string]bool)\n\trequired[\"ProductCode\"] = false\n\trequired[\"IP\"] = false\n\trequired[\"Port\"] = false\n\trequired[\"LoadBalancerIP\"] = false\n\trequired[\"Name\"] = false\n\t////////////////////////////////////////////////////////////////////////////\n\tif data.ProductCode != 0 {\n\t\trequired[\"ProductCode\"] = true\n\t}\n\tif len(dbRecord.LoadBalancerIP) > 0 {\n\t\trequired[\"LoadBalancerIP\"] = true\n\t}\n\tif len(data.Ports) != 0 {\n\t\trequired[\"Port\"] = true\n\t}\n\tif data.IP != \"\" {\n\t\trequired[\"IP\"] = true\n\t}\n\tif data.Name != \"\" {\n\t\trequired[\"Name\"] = true\n\t}\n\tfor _, val := range required {\n\t\tif val == false {\n\t\t\tok = false\n\t\t}\n\t}\n\tif !ok {\n\t\terr = fmt.Errorf(\"missing required fields - %+v\", required)\n\t}\n\treturn\n}", "func (user *User) Validate(action string) map[string]string {\n\tvar errMessages = make(map[string]string)\n\tvar err error\n\n\tswitch strings.ToLower(action) {\n\tcase \"update\":\n\t\tif user.Email == \"\" {\n\t\t\terrMessages[\"email_required\"] = \"email required\"\n\t\t}\n\n\t\tif user.Email != \"\" {\n\t\t\tif err = checkmail.ValidateFormat(user.Email); err != nil {\n\t\t\t\terrMessages[\"invalid_email\"] = \"invalid email\"\n\t\t\t}\n\t\t}\n\tcase \"login\":\n\t\tif user.Password == \"\" {\n\t\t\terrMessages[\"password_required\"] = \"password is required\"\n\t\t}\n\n\t\tif user.Email == \"\" {\n\t\t\terrMessages[\"email_required\"] = \"email required\"\n\t\t}\n\n\t\tif user.Email != \"\" {\n\t\t\tif err = checkmail.ValidateFormat(user.Email); err != nil {\n\t\t\t\terrMessages[\"invalid_email\"] = \"invalid email\"\n\t\t\t}\n\t\t}\n\tcase \"forgotpassword\":\n\t\tif user.Email == \"\" {\n\t\t\terrMessages[\"email_required\"] = \"email required\"\n\t\t}\n\t\tif user.Email != \"\" {\n\t\t\tif err = checkmail.ValidateFormat(user.Email); err != nil {\n\t\t\t\terrMessages[\"invalid_email\"] = \"please provide a valid email\"\n\t\t\t}\n\t\t}\n\tdefault:\n\t\tif user.FirstName == \"\" {\n\t\t\terrMessages[\"firstname_required\"] = \"first name is required\"\n\t\t}\n\n\t\tif user.LastName == \"\" {\n\t\t\terrMessages[\"lastname_required\"] = \"last name is required\"\n\t\t}\n\n\t\tif user.Password == \"\" {\n\t\t\terrMessages[\"password_required\"] = \"password is required\"\n\t\t}\n\n\t\tif user.Password != \"\" && len(user.Password) < 6 {\n\t\t\terrMessages[\"invalid_password\"] = \"password should be at least 6 characters\"\n\t\t}\n\n\t\tif user.Email == \"\" {\n\t\t\terrMessages[\"email_required\"] = \"email is required\"\n\t\t}\n\n\t\tif user.Email != \"\" {\n\t\t\tif err = checkmail.ValidateFormat(user.Email); err != nil {\n\t\t\t\terrMessages[\"invalid_email\"] = \"please provide a valid email\"\n\t\t\t}\n\t\t}\n\t}\n\n\treturn errMessages\n}", "func (a *Application) Validate(tx *pop.Connection) (*validate.Errors, error) {\n\treturn validate.Validate(\n\t\t&validators.StringIsPresent{Field: a.FirstName, Name: \"FirstName\"},\n\t\t&validators.StringIsPresent{Field: a.LastName, Name: \"LastName\"},\n\t), nil\n}", "func (uuo *UserUpdateOne) check() error {\n\tif v, ok := uuo.mutation.Username(); ok {\n\t\tif err := user.UsernameValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"username\", err: fmt.Errorf(\"ent: validator failed for field \\\"username\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.Fullname(); ok {\n\t\tif err := user.FullnameValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"fullname\", err: fmt.Errorf(\"ent: validator failed for field \\\"fullname\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.Password(); ok {\n\t\tif err := user.PasswordValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"password\", err: fmt.Errorf(\"ent: validator failed for field \\\"password\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.Email(); ok {\n\t\tif err := user.EmailValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"email\", err: fmt.Errorf(\"ent: validator failed for field \\\"email\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.Phone(); ok {\n\t\tif err := user.PhoneValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"phone\", err: fmt.Errorf(\"ent: validator failed for field \\\"phone\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.Bio(); ok {\n\t\tif err := user.BioValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"bio\", err: fmt.Errorf(\"ent: validator failed for field \\\"bio\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.Intro(); ok {\n\t\tif err := user.IntroValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"intro\", err: fmt.Errorf(\"ent: validator failed for field \\\"intro\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.GithubProfile(); ok {\n\t\tif err := user.GithubProfileValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"github_profile\", err: fmt.Errorf(\"ent: validator failed for field \\\"github_profile\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.ProfilePictureURL(); ok {\n\t\tif err := user.ProfilePictureURLValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"profile_picture_url\", err: fmt.Errorf(\"ent: validator failed for field \\\"profile_picture_url\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.Status(); ok {\n\t\tif err := user.StatusValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"status\", err: fmt.Errorf(\"ent: validator failed for field \\\"status\\\": %w\", err)}\n\t\t}\n\t}\n\treturn nil\n}", "func (r updateReq) Validate() error {\n\terr := r.addReq.Validate()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif r.ServiceAccountID != r.Body.ID {\n\t\treturn fmt.Errorf(\"service account ID mismatch, you requested to update ServiceAccount = %s but body contains ServiceAccount = %s\", r.ServiceAccountID, r.Body.ID)\n\t}\n\treturn nil\n}", "func (bu *BankdetailUpdate) check() error {\n\tif v, ok := bu.mutation.BankAccountNo(); ok {\n\t\tif err := bankdetail.BankAccountNoValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"Bank_AccountNo\", err: fmt.Errorf(\"ent: validator failed for field \\\"Bank_AccountNo\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := bu.mutation.BankName(); ok {\n\t\tif err := bankdetail.BankNameValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"Bank_Name\", err: fmt.Errorf(\"ent: validator failed for field \\\"Bank_Name\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := bu.mutation.BankAccountName(); ok {\n\t\tif err := bankdetail.BankAccountNameValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"Bank_AccountName\", err: fmt.Errorf(\"ent: validator failed for field \\\"Bank_AccountName\\\": %w\", err)}\n\t\t}\n\t}\n\treturn nil\n}", "func (rc *RentalCreate) check() error {\n\tif _, ok := rc.mutation.Date(); !ok {\n\t\treturn &ValidationError{Name: \"date\", err: errors.New(`ent: missing required field \"Rental.date\"`)}\n\t}\n\tif _, ok := rc.mutation.UserID(); !ok {\n\t\treturn &ValidationError{Name: \"user_id\", err: errors.New(`ent: missing required field \"Rental.user_id\"`)}\n\t}\n\tif _, ok := rc.mutation.CarID(); !ok {\n\t\treturn &ValidationError{Name: \"car_id\", err: errors.New(`ent: missing required field \"Rental.car_id\"`)}\n\t}\n\tif _, ok := rc.mutation.UserID(); !ok {\n\t\treturn &ValidationError{Name: \"user\", err: errors.New(`ent: missing required edge \"Rental.user\"`)}\n\t}\n\tif _, ok := rc.mutation.CarID(); !ok {\n\t\treturn &ValidationError{Name: \"car\", err: errors.New(`ent: missing required edge \"Rental.car\"`)}\n\t}\n\treturn nil\n}", "func (m *ContactAccountAttributesAccountWith) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (m *Customer) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateAutoCollection(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateBalances(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateBillingAddress(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateBillingDateMode(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateBillingDayOfWeek(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateBillingDayOfWeekMode(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateContacts(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateEntityCode(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateFraudFlag(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validatePaymentMethod(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateReferralUrls(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateTaxability(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (m *OBWriteInternational3DataInitiationDebtorAccount) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateIdentification(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateName(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateSchemeName(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateSecondaryIdentification(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (m *ClusterVcenterAccount) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (e *RetrieveBalance) Validate(\n\tr *http.Request,\n) error {\n\tctx := r.Context()\n\n\t// Validate id.\n\tid, owner, token, err := ValidateID(ctx, pat.Param(r, \"balance\"))\n\tif err != nil {\n\t\treturn errors.Trace(err)\n\t}\n\te.ID = *id\n\te.Token = *token\n\te.Owner = *owner\n\n\treturn nil\n}", "func (u *User) Validate() ([]app.Invalid, error) {\n\tvar inv []app.Invalid\n\n\tif u.UserType == 0 {\n\t\tinv = append(inv, app.Invalid{Fld: \"UserType\", Err: \"The value of UserType cannot be 0.\"})\n\t}\n\n\tif u.FirstName == \"\" {\n\t\tinv = append(inv, app.Invalid{Fld: \"FirstName\", Err: \"A value of FirstName cannot be empty.\"})\n\t}\n\n\tif u.LastName == \"\" {\n\t\tinv = append(inv, app.Invalid{Fld: \"LastName\", Err: \"A value of LastName cannot be empty.\"})\n\t}\n\n\tif u.Email == \"\" {\n\t\tinv = append(inv, app.Invalid{Fld: \"Email\", Err: \"A value of Email cannot be empty.\"})\n\t}\n\n\tif u.Company == \"\" {\n\t\tinv = append(inv, app.Invalid{Fld: \"Company\", Err: \"A value of Company cannot be empty.\"})\n\t}\n\n\tif len(u.Addresses) == 0 {\n\t\tinv = append(inv, app.Invalid{Fld: \"Addresses\", Err: \"There must be at least one address.\"})\n\t} else {\n\t\tfor _, ua := range u.Addresses {\n\t\t\tif va, err := ua.Validate(); err != nil {\n\t\t\t\tinv = append(inv, va...)\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(inv) > 0 {\n\t\treturn inv, errors.New(\"Validation failures identified\")\n\t}\n\n\treturn nil, nil\n}", "func ValidateGetAccountResponseBody(body *GetAccountResponseBody) (err error) {\n\tif body.Account != nil {\n\t\tif err2 := ValidateRelayerAccountResponseBody(body.Account); err2 != nil {\n\t\t\terr = goa.MergeErrors(err, err2)\n\t\t}\n\t}\n\treturn\n}", "func (p *Pass) FieldsValid() bool {\n\tfmt.Printf(\"validating: \")\n\tvalid := true\n\tfor k, v := range *p {\n\t\tfmt.Printf(\"%v...\", k)\n\t\tv := isFieldValid(k, v)\n\t\tvalid = valid && v\n\t\tif v {\n\t\t\tfmt.Printf(\"VALID \")\n\t\t} else {\n\t\t\tfmt.Printf(\"INVALID \")\n\t\t}\n\t}\n\n\tfmt.Println(\"\")\n\treturn valid\n}", "func (t AuthToken) Validate() error {\n\t// Holds names of empty fields\n\tempty := []string{}\n\n\t// Check user id\n\tif len(t.UserID) == 0 {\n\t\tempty = append(empty, \"UserID\")\n\t}\n\n\t// Check device id\n\tif len(t.DeviceID) == 0 {\n\t\tempty = append(empty, \"DeviceID\")\n\t}\n\n\t// Check if any empty fields\n\tif len(empty) != 0 {\n\t\treturn fmt.Errorf(\"the following fields were empty: %s\",\n\t\t\tStrings.join(empty))\n\t}\n\n\t// All good\n\treturn nil\n}", "func (p *Passport) ValidateStrict(input string) {\r\n\tbyr := regexp.MustCompile(`byr:(\\d*)`)\r\n\tif byr.MatchString(input) {\r\n\t\tmatches := byr.FindStringSubmatch(input)\r\n\t\tf, err := NewYearField(matches[1], byrMin, byrMax)\r\n\t\tif err == nil {\r\n\t\t\tp.byr = f\r\n\t\t}\r\n\t}\r\n\r\n\tiyr := regexp.MustCompile(`iyr:(\\d*)`)\r\n\tif iyr.MatchString(input) {\r\n\t\tmatches := iyr.FindStringSubmatch(input)\r\n\t\tf, err := NewYearField(matches[1], iyrMin, iyrMax)\r\n\t\tif err == nil {\r\n\t\t\tp.iyr = f\r\n\t\t}\r\n\t}\r\n\r\n\teyr := regexp.MustCompile(`eyr:(\\d*)`)\r\n\tif eyr.MatchString(input) {\r\n\t\tmatches := eyr.FindStringSubmatch(input)\r\n\t\tf, err := NewYearField(matches[1], eyrMin, eyrMax)\r\n\t\tif err == nil {\r\n\t\t\tp.eyr = f\r\n\t\t}\r\n\t}\r\n\r\n\thgt := regexp.MustCompile(`hgt:(\\d*)(cm|in)?`)\r\n\tif hgt.MatchString(input) {\r\n\t\tmatches := hgt.FindStringSubmatch(input)\r\n\t\tf, err := NewHeightField(matches[1], matches[2])\r\n\t\tif err == nil {\r\n\t\t\tp.hgt = f\r\n\t\t}\r\n\t}\r\n\r\n\thcl := regexp.MustCompile(`hcl:(#[a-f0-9]*)`)\r\n\tif hcl.MatchString(input) {\r\n\t\tmatches := hcl.FindStringSubmatch(input)\r\n\t\tf, err := NewTextField(matches[1], hclExp)\r\n\t\tif err == nil {\r\n\t\t\tp.hcl = f\r\n\t\t}\r\n\t}\r\n\r\n\tecl := regexp.MustCompile(`ecl:(\\w*)`)\r\n\tif ecl.MatchString(input) {\r\n\t\tmatches := ecl.FindStringSubmatch(input)\r\n\t\tf, err := NewTextField(matches[1], eclExp)\r\n\t\tif err == nil {\r\n\t\t\tp.ecl = f\r\n\t\t}\r\n\t}\r\n\r\n\tpid := regexp.MustCompile(`pid:(\\d*)`)\r\n\tif pid.MatchString(input) {\r\n\t\tmatches := pid.FindStringSubmatch(input)\r\n\t\tf, err := NewTextField(matches[1], pidExp)\r\n\t\tif err == nil {\r\n\t\t\tp.pid = f\r\n\t\t}\r\n\t}\r\n}", "func (u *User) Validate(tx *pop.Connection) (*validate.Errors, error) {\n\treturn validate.Validate(\n\t\t&validators.StringIsPresent{Field: u.Email, Name: \"Email\"},\n\t\t&validators.StringIsPresent{Field: u.FirstName, Name: \"FirstName\"},\n\t\t&validators.StringIsPresent{Field: u.LastName, Name: \"LastName\"},\n\t\t&validators.StringIsPresent{Field: u.Nickname, Name: \"Nickname\"},\n\t\t&validators.UUIDIsPresent{Field: u.UUID, Name: \"UUID\"},\n\t\t&NullsStringIsURL{Field: u.AuthPhotoURL, Name: \"AuthPhotoURL\"},\n\t\t&domain.StringIsVisible{Field: u.Nickname, Name: \"Nickname\"},\n\t), nil\n}", "func (r *registrationRequest) isValid() error {\n\n\t//check recaptcha\n\trc := recaptcha.R{Secret: config.CaptchaSecretKey}\n\tif !rc.VerifyResponse(r.Captcha) {\n\t\treturn fmt.Errorf(\"ReCaptcha error: %s\", strings.Join(rc.LastError()[1:], \", \"))\n\t}\n\n\t// check if any of this is empty\n\tif r.Email == \"\" || r.Password == \"\" || r.PasswordConfirmation == \"\" ||\n\t\tr.First == \"\" || r.Last == \"\" {\n\t\treturn fmt.Errorf(\"%s\\n\", \"You entered incomplete data. First and last name, email and \"+\n\t\t\t\"password are mandatory fields.\")\n\t}\n\n\t// check if the password match and that the length is at least 8 chars\n\treturn passwordsAreValid(r.Password, r.PasswordConfirmation)\n}", "func (i *infoOptions) validate() error {\n\t// date-field required\n\tif len(i.DateField) == 0 {\n\t\treturn errors.New(`date-field required`)\n\t}\n\n\t// date-field index value if sep is present\n\tif len(i.Sep) > 0 {\n\t\t// attempt to convert DateField to int\n\t\tvar err error\n\t\t_, err = strconv.Atoi(i.DateField)\n\t\tif err != nil {\n\t\t\treturn errors.New(`date-field must be an integer when using a csv field separator`)\n\t\t}\n\t}\n\n\t// dest-template required\n\tif i.DestTemplate == \"\" {\n\t\treturn errors.New(`dest-template required`)\n\t}\n\n\treturn nil\n}", "func (p paymentJson) Validate() error {\n\tif p.AccountId == \"\" {\n\t\treturn errors.New(\"missing customer id\")\n\t}\n\tif p.Amount == 0 {\n\t\treturn errors.New(\"missing amount\")\n\t}\n\treturn nil\n}", "func Validation(a User) error {\n\tfmt.Println(\"user :: \", a)\n\tvar rxEmail = regexp.MustCompile(\"^[a-zA-Z0-9.!#$%&'*+\\\\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$\")\n\tswitch {\n\tcase len(strings.TrimSpace(a.Password)) == 0:\n\t\treturn ErrPasswordInvalid\n\tcase len(strings.TrimSpace(a.Email)) == 0 || !rxEmail.MatchString(a.Email):\n\t\treturn ErrEmailInvalid\n\tdefault:\n\t\treturn nil\n\t}\n}", "func (account *DatabaseAccount) createValidations() []func() (admission.Warnings, error) {\n\treturn []func() (admission.Warnings, error){account.validateResourceReferences, account.validateSecretDestinations}\n}" ]
[ "0.6950377", "0.6660194", "0.6604518", "0.660115", "0.6589453", "0.6474401", "0.6469365", "0.6463922", "0.64215875", "0.63889915", "0.6362919", "0.63358384", "0.6252108", "0.62329525", "0.6229978", "0.61784095", "0.61675555", "0.61494285", "0.6107046", "0.6084981", "0.6062506", "0.6018709", "0.59835136", "0.5935781", "0.59250987", "0.5920425", "0.5918846", "0.5906061", "0.58879864", "0.5874278", "0.5862281", "0.5844713", "0.5843288", "0.58394945", "0.58318245", "0.58267343", "0.5805197", "0.5782027", "0.577867", "0.5762948", "0.57397187", "0.57109004", "0.5670878", "0.5664908", "0.5659827", "0.56587", "0.5648205", "0.5621579", "0.55948484", "0.55917954", "0.55910474", "0.5587459", "0.55859625", "0.55767894", "0.5549079", "0.5528815", "0.5525437", "0.5523396", "0.551239", "0.55084354", "0.55050844", "0.54942113", "0.54916596", "0.5487635", "0.5478365", "0.54646176", "0.54524314", "0.54512787", "0.5443251", "0.54331243", "0.5430431", "0.54267573", "0.54245096", "0.5422896", "0.54207206", "0.54192007", "0.54148257", "0.540501", "0.5398671", "0.5397307", "0.5396947", "0.5394909", "0.53946984", "0.53905594", "0.53878796", "0.5384738", "0.5380616", "0.53800863", "0.53762895", "0.5367286", "0.5357383", "0.5353596", "0.5347578", "0.5342094", "0.5340789", "0.53367335", "0.5334526", "0.5331692", "0.5330748", "0.532834" ]
0.567482
42
MarshalYAML returns the YAML representation of a BaseVestingAccount.
func (bva BaseVestingAccount) MarshalYAML() (interface{}, error) { accAddr, err := sdk.AccAddressFromBech32(bva.Address) if err != nil { return nil, err } out := vestingAccountYAML{ Address: accAddr, AccountNumber: bva.AccountNumber, PubKey: getPKString(bva), Sequence: bva.Sequence, OriginalVesting: bva.OriginalVesting, DelegatedFree: bva.DelegatedFree, DelegatedVesting: bva.DelegatedVesting, EndTime: bva.EndTime, } return marshalYaml(out) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (va ClawbackVestingAccount) MarshalYAML() (interface{}, error) {\n\taccAddr, err := sdk.AccAddressFromBech32(va.Address)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tout := vestingAccountYAML{\n\t\tAddress: accAddr,\n\t\tAccountNumber: va.AccountNumber,\n\t\tPubKey: getPKString(va),\n\t\tSequence: va.Sequence,\n\t\tOriginalVesting: va.OriginalVesting,\n\t\tDelegatedFree: va.DelegatedFree,\n\t\tDelegatedVesting: va.DelegatedVesting,\n\t\tEndTime: va.EndTime,\n\t\tStartTime: va.StartTime,\n\t\tVestingPeriods: va.VestingPeriods,\n\t}\n\treturn marshalYaml(out)\n}", "func (cva ContinuousVestingAccount) MarshalYAML() (interface{}, error) {\n\taccAddr, err := sdk.AccAddressFromBech32(cva.Address)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tout := vestingAccountYAML{\n\t\tAddress: accAddr,\n\t\tAccountNumber: cva.AccountNumber,\n\t\tPubKey: getPKString(cva),\n\t\tSequence: cva.Sequence,\n\t\tOriginalVesting: cva.OriginalVesting,\n\t\tDelegatedFree: cva.DelegatedFree,\n\t\tDelegatedVesting: cva.DelegatedVesting,\n\t\tEndTime: cva.EndTime,\n\t\tStartTime: cva.StartTime,\n\t}\n\treturn marshalYaml(out)\n}", "func (pva PeriodicVestingAccount) MarshalYAML() (interface{}, error) {\n\taccAddr, err := sdk.AccAddressFromBech32(pva.Address)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tout := vestingAccountYAML{\n\t\tAddress: accAddr,\n\t\tAccountNumber: pva.AccountNumber,\n\t\tPubKey: getPKString(pva),\n\t\tSequence: pva.Sequence,\n\t\tOriginalVesting: pva.OriginalVesting,\n\t\tDelegatedFree: pva.DelegatedFree,\n\t\tDelegatedVesting: pva.DelegatedVesting,\n\t\tEndTime: pva.EndTime,\n\t\tStartTime: pva.StartTime,\n\t\tVestingPeriods: pva.VestingPeriods,\n\t}\n\treturn marshalYaml(out)\n}", "func (vva ValidatorVestingAccount) MarshalYAML() (interface{}, error) {\n\tvar bs []byte\n\tvar err error\n\tvar pubkey string\n\n\tif vva.PubKey != nil {\n\t\tpubkey, err = sdk.Bech32ifyAccPub(vva.PubKey)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tbs, err = yaml.Marshal(struct {\n\t\tAddress sdk.AccAddress\n\t\tCoins sdk.Coins\n\t\tPubKey string\n\t\tAccountNumber uint64\n\t\tSequence uint64\n\t\tOriginalVesting sdk.Coins\n\t\tDelegatedFree sdk.Coins\n\t\tDelegatedVesting sdk.Coins\n\t\tEndTime int64\n\t\tStartTime int64\n\t\tVestingPeriods vestingtypes.Periods\n\t\tValidatorAddress sdk.ConsAddress\n\t\tReturnAddress sdk.AccAddress\n\t\tSigningThreshold int64\n\t\tCurrentPeriodProgress CurrentPeriodProgress\n\t\tVestingPeriodProgress []VestingProgress\n\t\tDebtAfterFailedVesting sdk.Coins\n\t}{\n\t\tAddress: vva.Address,\n\t\tCoins: vva.Coins,\n\t\tPubKey: pubkey,\n\t\tAccountNumber: vva.AccountNumber,\n\t\tSequence: vva.Sequence,\n\t\tOriginalVesting: vva.OriginalVesting,\n\t\tDelegatedFree: vva.DelegatedFree,\n\t\tDelegatedVesting: vva.DelegatedVesting,\n\t\tEndTime: vva.EndTime,\n\t\tStartTime: vva.StartTime,\n\t\tVestingPeriods: vva.VestingPeriods,\n\t\tValidatorAddress: vva.ValidatorAddress,\n\t\tReturnAddress: vva.ReturnAddress,\n\t\tSigningThreshold: vva.SigningThreshold,\n\t\tCurrentPeriodProgress: vva.CurrentPeriodProgress,\n\t\tVestingPeriodProgress: vva.VestingPeriodProgress,\n\t\tDebtAfterFailedVesting: vva.DebtAfterFailedVesting,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn string(bs), err\n}", "func (r RetryConfig) MarshalYAML() (interface{}, error) {\n\tdummy := dummyRetryConfig{\n\t\tOutput: r.Output,\n\t\tConfig: r.Config,\n\t}\n\tif r.Output == nil {\n\t\tdummy.Output = struct{}{}\n\t}\n\treturn dummy, nil\n}", "func (i Instance) MarshalYAML() (interface{}, error) {\n\treturn i.Vars, nil\n}", "func (b *Backend) MarshalYAML() (interface{}, error) {\n\tb.mu.RLock()\n\tdefer b.mu.RUnlock()\n\n\tpayload := struct {\n\t\tAddress string\n\t\tDisabledUntil time.Time `yaml:\"disabledUntil\"`\n\t\tForcePromotionsAfter time.Duration `yaml:\"forcePromotionsAfter\"`\n\t\tLatency time.Duration `yaml:\"latency\"`\n\t\tMaxConnections int `yaml:\"maxConnections\"`\n\t\tTier int `yaml:\"tier\"`\n\t}{\n\t\tAddress: b.addr.String(),\n\t\tDisabledUntil: b.mu.disabledUntil,\n\t\tForcePromotionsAfter: b.mu.forcePromotionAfter,\n\t\tLatency: b.mu.lastLatency,\n\t\tMaxConnections: b.mu.maxConnections,\n\t\tTier: b.mu.tier,\n\t}\n\treturn payload, nil\n}", "func (o *OAuthFlow) MarshalYAML() (interface{}, error) {\n\tnb := high.NewNodeBuilder(o, o.low)\n\treturn nb.Render(), nil\n}", "func (p *Parameter) MarshalYAML() (interface{}, error) {\n\tnb := high.NewNodeBuilder(p, p.low)\n\treturn nb.Render(), nil\n}", "func (v Validator) MarshalYAML() (interface{}, error) {\n\tbs, err := yaml.Marshal(struct {\n\t\tStatus sdk.BondStatus\n\t\tJailed bool\n\t\tUnbondingHeight int64\n\t\tConsPubKey string\n\t\tOperatorAddress sdk.ValAddress\n\t\tTokens sdk.Int\n\t\tDelegatorShares sdk.Dec\n\t\tDescription Description\n\t\tUnbondingCompletionTime time.Time\n\t\tCommission Commission\n\t\tMinSelfDelegation sdk.Dec\n\t}{\n\t\tOperatorAddress: v.OperatorAddress,\n\t\tConsPubKey: MustBech32ifyConsPub(v.ConsPubKey),\n\t\tJailed: v.Jailed,\n\t\tStatus: v.Status,\n\t\tTokens: v.Tokens,\n\t\tDelegatorShares: v.DelegatorShares,\n\t\tDescription: v.Description,\n\t\tUnbondingHeight: v.UnbondingHeight,\n\t\tUnbondingCompletionTime: v.UnbondingCompletionTime,\n\t\tCommission: v.Commission,\n\t\tMinSelfDelegation: v.MinSelfDelegation,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn string(bs), nil\n}", "func (a ApprovalStrategy) MarshalYAML() (interface{}, error) {\n\treturn approvalStrategyToString[a], nil\n\t//buffer := bytes.NewBufferString(`\"`)\n\t//buffer.WriteString(approvalStrategyToString[*s])\n\t//buffer.WriteString(`\"`)\n\t//return buffer.Bytes(), nil\n}", "func (i UserGroupAccess) MarshalYAML() (interface{}, error) {\n\treturn i.String(), nil\n}", "func (r OAuthFlow) MarshalYAML() (interface{}, error) {\n\tobj := make(map[string]interface{})\n\n\tobj[\"authorizationUrl\"] = r.AuthorizationURL\n\n\tobj[\"tokenUrl\"] = r.TokenURL\n\n\tif r.RefreshURL != \"\" {\n\t\tobj[\"refreshUrl\"] = r.RefreshURL\n\t}\n\n\tobj[\"scopes\"] = r.Scopes\n\n\tfor key, val := range r.Extensions {\n\t\tobj[key] = val\n\t}\n\n\treturn obj, nil\n}", "func (key PrivateKey) MarshalYAML() (interface{}, error) {\n\treturn key.String(), nil\n}", "func (export WebAuthnDeviceExport) MarshalYAML() (any, error) {\n\treturn export.ToData(), nil\n}", "func (key PublicKey) MarshalYAML() (interface{}, error) {\n\treturn key.String(), nil\n}", "func (d *WebAuthnDevice) MarshalYAML() (any, error) {\n\treturn d.ToData(), nil\n}", "func (r ReadUntilConfig) MarshalYAML() (interface{}, error) {\n\tdummy := dummyReadUntilConfig{\n\t\tInput: r.Input,\n\t\tRestart: r.Restart,\n\t\tCheck: r.Check,\n\t}\n\tif r.Input == nil {\n\t\tdummy.Input = struct{}{}\n\t}\n\treturn dummy, nil\n}", "func (p Params) MarshalYAML() (interface{}, error) {\n\treturn p.String(), nil\n}", "func (c *Components) MarshalYAML() (interface{}, error) {\n\tnb := high.NewNodeBuilder(c, c.low)\n\treturn nb.Render(), nil\n}", "func Marshal(v interface{}) ([]byte, error) {\n\tvar buf bytes.Buffer\n\tenc := yaml.NewEncoder(&buf)\n\tenc.SetIndent(2)\n\terr := enc.Encode(v)\n\treturn buf.Bytes(), err\n}", "func (z Z) MarshalYAML() (interface{}, error) {\n\ttype Z struct {\n\t\tS string `json:\"s\"`\n\t\tI int32 `json:\"iVal\"`\n\t\tHash string\n\t\tMultiplyIByTwo int64 `json:\"multipliedByTwo\"`\n\t}\n\tvar enc Z\n\tenc.S = z.S\n\tenc.I = z.I\n\tenc.Hash = z.Hash()\n\tenc.MultiplyIByTwo = int64(z.MultiplyIByTwo())\n\treturn &enc, nil\n}", "func (d *Discriminator) MarshalYAML() (interface{}, error) {\n\tnb := low2.NewNodeBuilder(d, d.low)\n\treturn nb.Render(), nil\n}", "func (v *VersionInfo) MarshalYAML() (interface{}, error) {\n\n\treturn &struct {\n\t\tSemVer string `yaml:\"semver\"`\n\t\tShaLong string `yaml:\"shaLong\"`\n\t\tBuildTimestamp int64 `yaml:\"buildTimestamp\"`\n\t\tBranch string `yaml:\"branch\"`\n\t\tArch string `yaml:\"arch\"`\n\t}{\n\t\tSemVer: v.SemVer,\n\t\tShaLong: v.ShaLong,\n\t\tBuildTimestamp: v.BuildTimestamp.Unix(),\n\t\tBranch: v.Branch,\n\t\tArch: v.Arch,\n\t}, nil\n}", "func (d Rate) MarshalYAML() (interface{}, error) {\n\treturn d.String(), nil\n}", "func (r Discriminator) MarshalYAML() (interface{}, error) {\n\tobj := make(map[string]interface{})\n\n\tobj[\"propertyName\"] = r.PropertyName\n\n\tif len(r.Mapping) > 0 {\n\t\tobj[\"mapping\"] = r.Mapping\n\t}\n\n\treturn obj, nil\n}", "func (s GitEvent) MarshalYAML() (interface{}, error) {\n\treturn toString[s], nil\n}", "func (f Fixed8) MarshalYAML() (interface{}, error) {\n\treturn f.String(), nil\n}", "func (ep Endpoint) MarshalYAML() (interface{}, error) {\n\ts, err := ep.toString()\n\treturn s, err\n}", "func (v *Int8) MarshalYAML() (interface{}, error) {\n\tif v.IsAssigned {\n\t\treturn v.Val, nil\n\t}\n\treturn nil, nil\n}", "func (f BodyField) MarshalYAML() (interface{}, error) {\n\treturn toJSONDot(f), nil\n}", "func (i Interface) MarshalYAML() (interface{}, error) {\n\treturn i.String(), nil\n}", "func (d *DefaultOptions) MarshalYAML() (interface{}, error) {\n\treturn util.MarshalYAMLWithDescriptions(d)\n}", "func (b ByteCount) MarshalYAML() (interface{}, error) {\n\treturn uint64(b), nil\n}", "func (ss StdSignature) MarshalYAML() (interface{}, error) {\n\tpk := \"\"\n\tif ss.PubKey != nil {\n\t\tpk = ss.PubKey.String()\n\t}\n\n\tbz, err := yaml.Marshal(struct {\n\t\tPubKey string `json:\"pub_key\"`\n\t\tSignature string `json:\"signature\"`\n\t}{\n\t\tpk,\n\t\tfmt.Sprintf(\"%X\", ss.Signature),\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn string(bz), err\n}", "func (m MixinDeclaration) MarshalYAML() (interface{}, error) {\n\tif m.Config == nil {\n\t\treturn m.Name, nil\n\t}\n\n\traw := map[string]interface{}{\n\t\tm.Name: m.Config,\n\t}\n\treturn raw, nil\n}", "func MarshalYAML(v interface{}, extensions map[string]interface{}) (interface{}, error) {\n\tif len(extensions) == 0 {\n\t\treturn v, nil\n\t}\n\tmarshaled, err := yaml.Marshal(v)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar unmarshaled map[string]interface{}\n\tif err := yaml.Unmarshal(marshaled, &unmarshaled); err != nil {\n\t\treturn nil, err\n\t}\n\tfor k, v := range extensions {\n\t\tunmarshaled[k] = v\n\t}\n\treturn unmarshaled, nil\n}", "func (m *BootstrapMode) MarshalYAML() (interface{}, error) {\n\treturn m.String(), nil\n}", "func (bc *ByteCount) MarshalYAML() (interface{}, error) {\n\treturn uint64(AtomicLoadByteCount(bc)), nil\n}", "func (s Secret) MarshalYAML() (interface{}, error) {\n\tif s != \"\" {\n\t\treturn \"<secret>\", nil\n\t}\n\treturn nil, nil\n}", "func (s Secret) MarshalYAML() (interface{}, error) {\n\tif s != \"\" {\n\t\treturn \"<secret>\", nil\n\t}\n\treturn nil, nil\n}", "func (i ChannelName) MarshalYAML() (interface{}, error) {\n\treturn i.String(), nil\n}", "func (n Nil) MarshalYAML() (interface{}, error) {\n\treturn nil, nil\n}", "func (d LegacyDec) MarshalYAML() (interface{}, error) {\n\treturn d.String(), nil\n}", "func (o *OpenAPI3SchemaExtension) MarshalYAML() (interface{}, error) {\n\treturn util.MarshalYAMLWithDescriptions(o)\n}", "func MarshalToYaml(obj runtime.Object, gv schema.GroupVersion) ([]byte, error) {\n\treturn MarshalToYamlForCodecs(obj, gv, clientsetscheme.Codecs)\n}", "func (r *Regexp) MarshalYAML() (interface{}, error) {\n\treturn r.String(), nil\n}", "func (o *OpenAPI3PathExtension) MarshalYAML() (interface{}, error) {\n\treturn util.MarshalYAMLWithDescriptions(o)\n}", "func (o *OpenAPI3ResponseExtension) MarshalYAML() (interface{}, error) {\n\treturn util.MarshalYAMLWithDescriptions(o)\n}", "func (op OpFlatten) MarshalYAML() (interface{}, error) {\n\treturn op.Field.String(), nil\n}", "func (schema SchemaType) MarshalYAML() (interface{}, error) {\n\treturn schema.String(), nil\n}", "func (ec EllipticCurve) MarshalYAML() (interface{}, error) {\n\treturn ec.String(), nil\n}", "func (op OpRetain) MarshalYAML() (interface{}, error) {\n\treturn op.Fields, nil\n}", "func (i UOM) MarshalYAML() (interface{}, error) {\n\treturn i.String(), nil\n}", "func (cp *CertPool) MarshalYAML() (interface{}, error) {\n\treturn cp.Files, nil\n}", "func (d Document) MarshalYAML() (interface{}, error) {\n\treturn d.raw, nil\n}", "func (re Regexp) MarshalYAML() (interface{}, error) {\n\tif re.original != \"\" {\n\t\treturn re.original, nil\n\t}\n\treturn nil, nil\n}", "func (re Regexp) MarshalYAML() (interface{}, error) {\n\tif re.original != \"\" {\n\t\treturn re.original, nil\n\t}\n\treturn nil, nil\n}", "func (f Flag) MarshalYAML() (interface{}, error) {\n\treturn f.Name, nil\n}", "func (s SensitiveString) MarshalYAML() (interface{}, error) {\n\treturn s.String(), nil\n}", "func (i Int) MarshalYAML() (interface{}, error) {\n\tif !i.IsPresent() {\n\t\treturn nil, nil\n\t}\n\treturn i.value, nil\n}", "func ToYAML(v interface{}) ([]byte, error) {\n\treturn yaml.Marshal(v)\n}", "func (o Op) MarshalYAML() (interface{}, error) {\n\treturn map[string]interface{}{\n\t\to.Type(): o.OpApplier,\n\t}, nil\n}", "func (o *Output) MarshalYAML() (interface{}, error) {\n\tif o.ShowValue {\n\t\treturn withvalue(*o), nil\n\t}\n\to.Value = nil // explicitly make empty\n\to.Sensitive = false // explicitly make empty\n\treturn *o, nil\n}", "func (v *Uint16) MarshalYAML() (interface{}, error) {\n\tif v.IsAssigned {\n\t\treturn v.Val, nil\n\t}\n\treturn nil, nil\n}", "func (m OrderedMap[K, V]) MarshalYAML() ([]byte, error) {\n\tvar s yaml.MapSlice\n\tfor _, item := range m.ToSlice() {\n\t\ts = append(s, yaml.MapItem{\n\t\t\tKey: item.Key,\n\t\t\tValue: item.Value,\n\t\t})\n\t}\n\treturn yaml.Marshal(s)\n}", "func (o *OpenAPI3Options) MarshalYAML() (interface{}, error) {\n\treturn util.MarshalYAMLWithDescriptions(o)\n}", "func (vm ValidationMap) AsYAML() (string, error) {\n\tdata, err := yaml.Marshal(vm)\n\treturn string(data), err\n}", "func (b Bool) MarshalYAML() (interface{}, error) {\n\tif !b.IsPresent() {\n\t\treturn nil, nil\n\t}\n\treturn b.value, nil\n}", "func (u *URL) MarshalYAML() (interface{}, error) {\n\treturn u.String(), nil\n}", "func SortYAML(in io.Reader, out io.Writer, indent int) error {\n\n\tincomingYAML, err := ioutil.ReadAll(in)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"can't read input: %v\", err)\n\t}\n\n\tvar hasNoStartingLabel bool\n\trootIndent, err := detectRootIndent(incomingYAML)\n\tif err != nil {\n\t\tif !errors.Is(err, ErrNoStartingLabel) {\n\t\t\tfmt.Fprint(out, string(incomingYAML))\n\t\t\treturn fmt.Errorf(\"can't detect root indentation: %v\", err)\n\t\t}\n\n\t\thasNoStartingLabel = true\n\t}\n\n\tif hasNoStartingLabel {\n\t\tincomingYAML = append([]byte(CustomLabel+\"\\n\"), incomingYAML...)\n\t}\n\n\tvar value map[string]interface{}\n\tif err := yaml.Unmarshal(incomingYAML, &value); err != nil {\n\t\tfmt.Fprint(out, string(incomingYAML))\n\n\t\treturn fmt.Errorf(\"can't decode YAML: %v\", err)\n\t}\n\n\tvar outgoingYAML bytes.Buffer\n\tencoder := yaml.NewEncoder(&outgoingYAML)\n\tencoder.SetIndent(indent)\n\n\tif err := encoder.Encode(&value); err != nil {\n\t\tfmt.Fprint(out, string(incomingYAML))\n\t\treturn fmt.Errorf(\"can't re-encode YAML: %v\", err)\n\t}\n\n\treindentedYAML, err := indentYAML(outgoingYAML.String(), rootIndent, indent, hasNoStartingLabel)\n\tif err != nil {\n\t\tfmt.Fprint(out, string(incomingYAML))\n\t\treturn fmt.Errorf(\"can't re-indent YAML: %v\", err)\n\t}\n\n\tfmt.Fprint(out, reindentedYAML)\n\treturn nil\n}", "func (k *Kluster) YAML() ([]byte, error) {\n\treturn yaml.Marshal(k)\n}", "func (date Date) MarshalYAML() (interface{}, error) {\n\tvar d = string(date)\n\tif err := checkDateFormat(d); err != nil {\n\t\treturn nil, err\n\t}\n\treturn d, nil\n}", "func (s DescribeAccountAuditConfigurationOutput) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.AuditCheckConfigurations != nil {\n\t\tv := s.AuditCheckConfigurations\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"auditCheckConfigurations\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetFields(k1, v1)\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.AuditNotificationTargetConfigurations != nil {\n\t\tv := s.AuditNotificationTargetConfigurations\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"auditNotificationTargetConfigurations\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetFields(k1, v1)\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.RoleArn != nil {\n\t\tv := *s.RoleArn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"roleArn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (d Duration) MarshalYAML() (interface{}, error) {\n\treturn d.String(), nil\n}", "func (c CompressionType) MarshalYAML() (interface{}, error) {\n\treturn compressionTypeID[c], nil\n}", "func (d Duration) MarshalYAML() (interface{}, error) {\n\treturn d.Duration.String(), nil\n}", "func toYAML(v interface{}) string {\n\tdata, err := yaml.Marshal(v)\n\tif err != nil {\n\t\t// Swallow errors inside of a template.\n\t\treturn \"\"\n\t}\n\n\treturn strings.TrimSuffix(string(data), \"\\n\")\n}", "func (c *Config) YAML() ([]byte, error) {\n\treturn yaml.Marshal(c)\n}", "func Dump(v interface{}) ([]byte, error) {\n\treturn yaml.Marshal(v)\n}", "func (r ParseKind) MarshalYAML() ([]byte, error) {\n\tif s, ok := interface{}(r).(fmt.Stringer); ok {\n\t\treturn yaml.Marshal(s.String())\n\t}\n\ts, ok := _ParseKindValueToName[r]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"invalid ParseKind: %d\", r)\n\t}\n\treturn yaml.Marshal(s)\n}", "func FormatAsYAML(obj interface{}, indent int) string {\n\tif obj == nil {\n\t\treturn \"none\"\n\t}\n\tdata, err := yaml.Marshal(obj)\n\tif err != nil {\n\t\treturn fmt.Sprintf(\"Error during yaml serialization: %s\", err.Error())\n\t}\n\t// add an additional newline to properly inline\n\treturn ApplyIdent(\"\\n\"+string(data), indent)\n}", "func (u *URL) MarshalYAML() (interface{}, error) {\n\tif u.url == nil {\n\t\treturn nil, nil\n\t}\n\treturn u.url.String(), nil\n}", "func (a *Account) Marshal() ([]byte, error) {\n\treturn a.account.Bytes()\n}", "func (c Configuration) YAML() ([]byte, error) {\n\treturn yaml.Marshal(c)\n}", "func (d DurationMinutes) MarshalYAML() (interface{}, error) {\n\tif !d.IsPresent() {\n\t\treturn nil, nil\n\t}\n\treturn int(d.value / time.Minute), nil\n}", "func (f *Fzp) ToYAML() ([]byte, error) {\n\tdata, err := yaml.Marshal(f)\n\treturn data, err\n}", "func (s String) MarshalYAML() (interface{}, error) {\n\tif !s.IsPresent() {\n\t\treturn nil, nil\n\t}\n\treturn s.value, nil\n}", "func (c *Configmap) AsYAML() []byte {\n\tresult, err := yaml.Marshal(*c)\n\tif err != nil {\n\t\tlog.Printf(\"error marshaling YAML: %s\", err)\n\t}\n\treturn result\n}", "func (v Values) YAML() (string, error) {\n\tb, err := yaml.Marshal(v)\n\treturn string(b), err\n}", "func ToYaml(v interface{}) (yamlstr string) {\n\tdata, err := yaml.Marshal(v)\n\tif err != nil {\n\t\t// error is handled\n\t\tyamlstr = fmt.Sprintf(\"error: %s\", err.Error())\n\t\treturn\n\t}\n\n\tyamlstr = string(data)\n\treturn\n}", "func toYaml(v interface{}) string {\n\tdata, err := yaml.Marshal(v)\n\tif err != nil {\n\t\t// Swallow errors inside of a template.\n\t\treturn \"\"\n\t}\n\treturn string(data)\n}", "func (s *Siegfried) YAML() string {\n\tversion := config.Version()\n\tstr := fmt.Sprintf(\n\t\t\"---\\nsiegfried : %d.%d.%d\\nscandate : %v\\nsignature : %s\\ncreated : %v\\nidentifiers : \\n\",\n\t\tversion[0], version[1], version[2],\n\t\ttime.Now().Format(time.RFC3339),\n\t\tconfig.SignatureBase(),\n\t\ts.C.Format(time.RFC3339))\n\tfor _, id := range s.ids {\n\t\td := id.Describe()\n\t\tstr += fmt.Sprintf(\" - name : '%v'\\n details : '%v'\\n\", d[0], d[1])\n\t}\n\treturn str\n}", "func SPrintYAML(a interface{}) (string, error) {\n\tb, err := MarshalJSON(a)\n\t// doing yaml this way because at times you have nested proto structs\n\t// that need to be cleaned.\n\tyam, err := yamlconv.JSONToYAML(b)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(yam), nil\n}", "func (s *Schema) ToYAML() ([]byte, error) {\n\treturn yaml.Marshal(s)\n}", "func Marshal(o interface{}) ([]byte, error) {\n\tj, err := json.Marshal(o)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error marshaling into JSON: %v\", err)\n\t}\n\n\ty, err := JSONToYAML(j)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error converting JSON to YAML: %v\", err)\n\t}\n\n\treturn y, nil\n}", "func PrintYAML(obj interface{}) {\n\tmarshal, err := yaml.Marshal(&obj)\n\tif err != nil {\n\t\tPrintIfError(err)\n\n\t\treturn\n\t}\n\n\t_, err = os.Stdout.Write(marshal)\n\tPrintIfError(err)\n}", "func ToYaml(v interface{}) Dest {\n\treturn ToBuffer(func(buf *bytes.Buffer) error {\n\t\treturn yaml.Unmarshal(buf.Bytes(), v)\n\t})\n}", "func (d DurationMillis) MarshalYAML() (interface{}, error) {\n\tif !d.IsPresent() {\n\t\treturn nil, nil\n\t}\n\treturn int(d.value / time.Millisecond), nil\n}", "func (dd *AccountDoc) Marshal() ([]byte, error) {\n\treturn Marshal(dd)\n}" ]
[ "0.7984123", "0.78136253", "0.77950466", "0.77011955", "0.61860657", "0.6162082", "0.61555004", "0.61256987", "0.59841114", "0.59818166", "0.59726924", "0.594863", "0.5947269", "0.58972937", "0.5799432", "0.57685477", "0.5696263", "0.5608591", "0.56004035", "0.55417204", "0.5532058", "0.5521611", "0.5517035", "0.5496716", "0.54903287", "0.548061", "0.5449422", "0.54030937", "0.5391724", "0.537445", "0.53701305", "0.53541905", "0.53477764", "0.5345091", "0.5331879", "0.53165156", "0.530302", "0.52752006", "0.5250181", "0.5249235", "0.5249235", "0.5244357", "0.52398443", "0.5214958", "0.5211833", "0.52113277", "0.5184091", "0.5175093", "0.5173018", "0.5165076", "0.51577747", "0.5115257", "0.510102", "0.507777", "0.50535077", "0.5051937", "0.5042669", "0.5042669", "0.50177866", "0.5006765", "0.4991391", "0.49482775", "0.4912435", "0.49098033", "0.49013838", "0.48830777", "0.48691916", "0.48269653", "0.47927094", "0.47480956", "0.47449687", "0.47391447", "0.472811", "0.47150794", "0.47051612", "0.46953034", "0.4690402", "0.46810874", "0.46395752", "0.4629854", "0.46080402", "0.4591622", "0.45784584", "0.45581457", "0.45574042", "0.45547485", "0.45543584", "0.4526609", "0.4512707", "0.44925398", "0.4489739", "0.44388238", "0.44163558", "0.44090536", "0.440416", "0.4399723", "0.4397419", "0.43891206", "0.43854883", "0.43848008" ]
0.8440805
0
NewContinuousVestingAccountRaw creates a new ContinuousVestingAccount object from BaseVestingAccount
func NewContinuousVestingAccountRaw(bva *BaseVestingAccount, startTime int64) *ContinuousVestingAccount { return &ContinuousVestingAccount{ BaseVestingAccount: bva, StartTime: startTime, } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func NewContinuousVestingAccount(baseAcc *authtypes.BaseAccount, originalVesting sdk.Coins, startTime, endTime int64) *ContinuousVestingAccount {\n\tbaseVestingAcc := &BaseVestingAccount{\n\t\tBaseAccount: baseAcc,\n\t\tOriginalVesting: originalVesting,\n\t\tEndTime: endTime,\n\t}\n\n\treturn &ContinuousVestingAccount{\n\t\tStartTime: startTime,\n\t\tBaseVestingAccount: baseVestingAcc,\n\t}\n}", "func NewPeriodicVestingAccountRaw(bva *BaseVestingAccount, startTime int64, periods Periods) *PeriodicVestingAccount {\n\treturn &PeriodicVestingAccount{\n\t\tBaseVestingAccount: bva,\n\t\tStartTime: startTime,\n\t\tVestingPeriods: periods,\n\t}\n}", "func NewBaseVestingAccount(baseAccount *authtypes.BaseAccount, originalVesting sdk.Coins, endTime int64) *BaseVestingAccount {\n\treturn &BaseVestingAccount{\n\t\tBaseAccount: baseAccount,\n\t\tOriginalVesting: originalVesting,\n\t\tDelegatedFree: sdk.NewCoins(),\n\t\tDelegatedVesting: sdk.NewCoins(),\n\t\tEndTime: endTime,\n\t}\n}", "func NewValidatorVestingAccountRaw(bva *vestingtypes.BaseVestingAccount,\n\tstartTime int64, periods vestingtypes.Periods, validatorAddress sdk.ConsAddress, returnAddress sdk.AccAddress, signingThreshold int64) *ValidatorVestingAccount {\n\n\tpva := &vestingtypes.PeriodicVestingAccount{\n\t\tBaseVestingAccount: bva,\n\t\tStartTime: startTime,\n\t\tVestingPeriods: periods,\n\t}\n\tvar vestingPeriodProgress []VestingProgress\n\tfor i := 0; i < len(periods); i++ {\n\t\tvestingPeriodProgress = append(vestingPeriodProgress, VestingProgress{false, false})\n\t}\n\n\treturn &ValidatorVestingAccount{\n\t\tPeriodicVestingAccount: pva,\n\t\tValidatorAddress: validatorAddress,\n\t\tReturnAddress: returnAddress,\n\t\tSigningThreshold: signingThreshold,\n\t\tCurrentPeriodProgress: CurrentPeriodProgress{0, 0},\n\t\tVestingPeriodProgress: vestingPeriodProgress,\n\t\tDebtAfterFailedVesting: sdk.NewCoins(),\n\t}\n}", "func NewDelayedVestingAccountRaw(bva *BaseVestingAccount) *DelayedVestingAccount {\n\treturn &DelayedVestingAccount{\n\t\tBaseVestingAccount: bva,\n\t}\n}", "func NewPeriodicVestingAccount(baseAcc *authtypes.BaseAccount, originalVesting sdk.Coins, startTime int64, periods Periods) *PeriodicVestingAccount {\n\tendTime := startTime\n\tfor _, p := range periods {\n\t\tendTime += p.Length\n\t}\n\tbaseVestingAcc := &BaseVestingAccount{\n\t\tBaseAccount: baseAcc,\n\t\tOriginalVesting: originalVesting,\n\t\tEndTime: endTime,\n\t}\n\n\treturn &PeriodicVestingAccount{\n\t\tBaseVestingAccount: baseVestingAcc,\n\t\tStartTime: startTime,\n\t\tVestingPeriods: periods,\n\t}\n}", "func newPeriodicVestingAccount(address sdk.AccAddress, periods vestingtypes.Periods, firstPeriodStartTimestamp int64) *vestingtypes.PeriodicVestingAccount {\n\tbaseAccount := authtypes.NewBaseAccount(address, nil, 0, 0)\n\n\toriginalVesting := sdk.NewCoins()\n\tfor _, p := range periods {\n\t\toriginalVesting = originalVesting.Add(p.Amount...)\n\t}\n\n\tvar totalPeriods int64\n\tfor _, p := range periods {\n\t\ttotalPeriods += p.Length\n\t}\n\tendTime := firstPeriodStartTimestamp + totalPeriods\n\n\tbaseVestingAccount := vestingtypes.NewBaseVestingAccount(baseAccount, originalVesting, endTime)\n\treturn vestingtypes.NewPeriodicVestingAccountRaw(baseVestingAccount, firstPeriodStartTimestamp, periods)\n}", "func newAccount() *Account {\n\treturn &Account{\n\t\tblocks: make(map[string]uint64),\n\t}\n}", "func NewClawbackVestingAccount(baseAcc *authtypes.BaseAccount, funder sdk.AccAddress, originalVesting sdk.Coins, startTime int64, lockupPeriods, vestingPeriods Periods) *ClawbackVestingAccount {\n\t// copy and align schedules to avoid mutating inputs\n\tlp := make(Periods, len(lockupPeriods))\n\tcopy(lp, lockupPeriods)\n\tvp := make(Periods, len(vestingPeriods))\n\tcopy(vp, vestingPeriods)\n\t_, endTime := AlignSchedules(startTime, startTime, lp, vp)\n\tbaseVestingAcc := &BaseVestingAccount{\n\t\tBaseAccount: baseAcc,\n\t\tOriginalVesting: originalVesting,\n\t\tEndTime: endTime,\n\t}\n\n\treturn &ClawbackVestingAccount{\n\t\tBaseVestingAccount: baseVestingAcc,\n\t\tFunderAddress: funder.String(),\n\t\tStartTime: startTime,\n\t\tLockupPeriods: lp,\n\t\tVestingPeriods: vp,\n\t}\n}", "func NewValidatorVestingAccount(baseAcc *authtypes.BaseAccount, startTime int64, periods vestingtypes.Periods, validatorAddress sdk.ConsAddress, returnAddress sdk.AccAddress, signingThreshold int64) *ValidatorVestingAccount {\n\n\tendTime := startTime\n\tfor _, p := range periods {\n\t\tendTime += p.Length\n\t}\n\tbaseVestingAcc := &vestingtypes.BaseVestingAccount{\n\t\tBaseAccount: baseAcc,\n\t\tOriginalVesting: baseAcc.Coins,\n\t\tEndTime: endTime,\n\t}\n\tpva := &vestingtypes.PeriodicVestingAccount{\n\t\tBaseVestingAccount: baseVestingAcc,\n\t\tStartTime: startTime,\n\t\tVestingPeriods: periods,\n\t}\n\tvar vestingPeriodProgress []VestingProgress\n\tfor i := 0; i < len(periods); i++ {\n\t\tvestingPeriodProgress = append(vestingPeriodProgress, VestingProgress{false, false})\n\t}\n\n\treturn &ValidatorVestingAccount{\n\t\tPeriodicVestingAccount: pva,\n\t\tValidatorAddress: validatorAddress,\n\t\tReturnAddress: returnAddress,\n\t\tSigningThreshold: signingThreshold,\n\t\tCurrentPeriodProgress: CurrentPeriodProgress{0, 0},\n\t\tVestingPeriodProgress: vestingPeriodProgress,\n\t\tDebtAfterFailedVesting: sdk.NewCoins(),\n\t}\n}", "func NewCoinbase(proof, score, R []byte) *Coinbase {\n\treturn &Coinbase{\n\t\tProof: proof,\n\t\tScore: score,\n\t\tR: R,\n\t}\n}", "func (c *Jrpc) CreateRawTransaction(in *pty.ReqCreatePrivacyTx, result *interface{}) error {\n\treply, err := c.cli.CreateRawTransaction(context.Background(), in)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t*result = hex.EncodeToString(types.Encode(reply))\n\treturn err\n}", "func NewDelayedVestingAccount(baseAcc *authtypes.BaseAccount, originalVesting sdk.Coins, endTime int64) *DelayedVestingAccount {\n\tbaseVestingAcc := &BaseVestingAccount{\n\t\tBaseAccount: baseAcc,\n\t\tOriginalVesting: originalVesting,\n\t\tEndTime: endTime,\n\t}\n\n\treturn &DelayedVestingAccount{baseVestingAcc}\n}", "func (account *Account) New() {\n\n\tparams, _ := pbc.NewParamsFromString(crypto.Params)\n\tpairing := params.NewPairing()\n\n\tA := pairing.NewG1()\n\tAT := pairing.NewG1()\n\ta := pairing.NewZr()\n\n\ta.Rand()\n\n\tG := pairing.NewG1()\n\tT := pairing.NewG1()\n\tG.SetString(crypto.G, 10)\n\tT.SetString(crypto.T, 10)\n\n\tA.PowZn(G, a)\n\tAT.PowZn(T, a)\n\n\taccount.a = a.String()\n\taccount.A = A.String()\n\taccount.AT = AT.String()\n}", "func NewCoinbaseTX(to, data string) *Transaction {\n\tif data == \"\" {\n\t\trandData := make([]byte, 20)\n\t\t_, err := rand.Read(randData)\n\t\tif err != nil {\n\t\t\tlog.Panic(err)\n\t\t}\n\t\tdata = fmt.Sprintf(\"%x\", randData)\n\t}\n\ttxin := TXInput{[]byte{}, -1, nil, []byte(data)} // remember this tx need no previous tx output\n\ttxout := NewTXOutput(subsidy, to)\n\ttx := Transaction{nil, []TXInput{txin}, []TXOutput{*txout}}\n\ttx.ID = tx.Hash() // New way\n\treturn &tx\n}", "func (c *CoinTest) newAccount(stub shim.ChaincodeStubInterface, args []string) pb.Response {\r\n\tvar id string\r\n\tvar asset int\r\n\tvar err error\r\n\r\n\tif len(args) == 1{\r\n\t\tid = args[0]\r\n\t\tasset = 0\r\n\t}else if len(args) == 2{\r\n\t\tid = args[0]\r\n\t\t//asset, err = strconv.Atoi(args[1])\r\n\t\t//if err != nil{\r\n\t\t//\treturn shim.Error(\"Invalid asset amount, expecting a integer value\")\r\n\t\t//}\r\n\t\tasset = 0;\r\n\t}else{\r\n\t\treturn shim.Error(\"Incorrect number of arguments.\")\r\n\t}\r\n\r\n\t//deliver 0 number of TolakCoin to user\r\n\ttolakCoin.Token.Deliver(token.Address(id), int(asset))\r\n\r\n\t//write to ledger\r\n\terr = stub.PutState(id, []byte(strconv.Itoa(asset)))\r\n\tif err != nil{\r\n\t\treturn shim.Error(err.Error())\r\n\t}\r\n\r\n\treturn shim.Success(nil)\r\n}", "func (g *testGenerator) createCoinbaseTx(blockHeight uint32, numVotes uint16) *wire.MsgTx {\n\t// Calculate the subsidy proportions based on the block height and the\n\t// number of votes the block will include.\n\tfullSubsidy := g.calcFullSubsidy(blockHeight)\n\tdevSubsidy := g.calcDevSubsidy(fullSubsidy, blockHeight, numVotes)\n\tpowSubsidy := g.calcPoWSubsidy(fullSubsidy, blockHeight, numVotes)\n\n\ttx := wire.NewMsgTx()\n\ttx.AddTxIn(&wire.TxIn{\n\t\t// Coinbase transactions have no inputs, so previous outpoint is\n\t\t// zero hash and max index.\n\t\tPreviousOutPoint: *wire.NewOutPoint(&chainhash.Hash{},\n\t\t\twire.MaxPrevOutIndex, wire.TxTreeRegular),\n\t\tSequence: wire.MaxTxInSequenceNum,\n\t\tValueIn: int64(devSubsidy + powSubsidy),\n\t\tBlockHeight: wire.NullBlockHeight,\n\t\tBlockIndex: wire.NullBlockIndex,\n\t\tSignatureScript: coinbaseSigScript,\n\t})\n\n\tg.addCoinbaseTxOutputs(tx, blockHeight, devSubsidy, powSubsidy)\n\n\treturn tx\n}", "func createCoinbaseTx() *Tx {\n\ttxIns := []*TxIn{{\"\", -1, coinbaseAddress}}\n\ttxOuts := []*TxOut{{wallet.Wallet().Address, minerReward}}\n\ttx := Tx{\n\t\tId: \"\",\n\t\tTimestamp: int(time.Now().Unix()),\n\t\tTxIns: txIns,\n\t\tTxOuts: txOuts,\n\t}\n\ttx.getId() // attach an ID to the given transaction via hashing\n\treturn &tx\n}", "func (a API) CreateRawTransaction(cmd *btcjson.CreateRawTransactionCmd) (e error) {\n\tRPCHandlers[\"createrawtransaction\"].Call <-API{a.Ch, cmd, nil}\n\treturn\n}", "func (*tenantR) NewStruct() *tenantR {\n\treturn &tenantR{}\n}", "func NewAccount(val string) AccountField {\n\treturn AccountField{quickfix.FIXString(val)}\n}", "func NewAccount() *Account {\n\n\tcreatedAccount := Account{}\n\n\tnewPrivateKey, err := generatePrivateKey(4096)\n\tif err != nil {\n\t\tlog.Fatal(\"Error generating rsa private key \", err)\n\t}\n\tnewPublicKey, err := generatePublicKey(&newPrivateKey.PublicKey)\n\tif err != nil {\n\t\tlog.Fatal(\"Error generating rsa public key \", err)\n\t}\n\tcreatedAccount.privateKey = newPrivateKey\n\tcreatedAccount.Address = string(newPublicKey)\n\tcreatedAccount.Amount = 0\n\n\treturn &createdAccount\n}", "func NewAccount(txr *repository.Transactioner) repository.Account {\n\treturn &account{txr: txr}\n}", "func NewMsgCreatePeriodicVestingAccount(fromAddr, toAddr sdk.AccAddress, startTime int64, periods []Period) *MsgCreatePeriodicVestingAccount {\n\treturn &MsgCreatePeriodicVestingAccount{\n\t\tFromAddress: fromAddr.String(),\n\t\tToAddress: toAddr.String(),\n\t\tStartTime: startTime,\n\t\tVestingPeriods: periods,\n\t}\n}", "func NewTrainCar() TrainCar {\n c := TrainCar{name: \"TrainCar\", vehicle: \"TrainCar\", speed: 30, capacity: 30, railway: \"CNR\"}\n return c\n}", "func MakeNewAccount(name string) (*MyAccount, error) {\n\tkeys, err := NewKeypair()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &MyAccount{\n\t\tFields: make(map[string]string),\n\t\tKeys: keys,\n\t\tName: name,\n\t}, nil\n}", "func NewAccount(\n\tconfig *accounts.AccountConfig,\n\taccountCoin *Coin,\n\thttpClient *http.Client,\n\tlog *logrus.Entry,\n) *Account {\n\tlog = log.WithField(\"group\", \"eth\").\n\t\tWithFields(logrus.Fields{\"coin\": accountCoin.String(), \"code\": config.Config.Code, \"name\": config.Config.Name})\n\tlog.Debug(\"Creating new account\")\n\n\taccount := &Account{\n\t\tBaseAccount: accounts.NewBaseAccount(config, accountCoin, log),\n\t\tcoin: accountCoin,\n\t\tdbSubfolder: \"\", // set in Initialize()\n\t\tsigningConfiguration: nil,\n\t\thttpClient: httpClient,\n\t\tbalance: coin.NewAmountFromInt64(0),\n\n\t\tenqueueUpdateCh: make(chan struct{}),\n\t\tquitChan: make(chan struct{}),\n\n\t\tlog: log,\n\t}\n\n\treturn account\n}", "func NewAccount(owner string) *Account {\n\treturn &Account{owner: owner, balance: 0}\n}", "func (*withdrawalCryptoR) NewStruct() *withdrawalCryptoR {\n\treturn &withdrawalCryptoR{}\n}", "func NewAccount(user, apiKey string) *Account {\n\treturn &Account{user: user, apiKey: apiKey}\n}", "func NewCoinbaseTX(to, data string) *Transaction {\n\tif data != \"\" {\n\t\tdata = fmt.Sprintf(\"Reward to '%s'\", to)\n\t}\n\n\ttxIn := []TxInput{{Txid: []byte{}, Vout: -1, ScriptSig: data}}\n\ttxOut := []TxOutput{{Value: subsidy, ScriptPubKey: to}}\n\ttx := Transaction{id: nil, Vin: txIn, Vout: txOut}\n\ttx.SetID()\n\n\treturn &tx\n}", "func (e Account) EntNew() ent.Ent { return &Account{} }", "func (e Account) EntNew() ent.Ent { return &Account{} }", "func newBase() *base {\n\treturn &base{shared.NewUUID(), time.Now().UTC(), time.Now().UTC(), false/*, shared.NewUUID()*/}\n}", "func newRawAuthentication(value string) httpAuthentication {\n\treturn &basicAuthentication{\n\t\tauthorizationValue: value,\n\t}\n}", "func NewAllocAccount(val string) AllocAccountField {\n\treturn AllocAccountField{quickfix.FIXString(val)}\n}", "func NewRPCCtx(embed Ctx) *RPCCtx {\n\tret := &RPCCtx{\n\t\tembed: embed,\n\t\tServices: finder.New(),\n\t\tLog: &ggt.VoidLog{},\n\t\tSession: &ggt.VoidSession{},\n\t\tUpload: &ggt.FileProvider{},\n\t}\n\tret.Log.Handle(nil, nil, nil, \"constructor\", \"RPCCtx\")\n\treturn ret\n}", "func NewMsgCreateVestingAccount(fromAddr, toAddr sdk.AccAddress, amount sdk.Coins, endTime int64, delayed bool) *MsgCreateVestingAccount {\n\treturn &MsgCreateVestingAccount{\n\t\tFromAddress: fromAddr.String(),\n\t\tToAddress: toAddr.String(),\n\t\tAmount: amount,\n\t\tEndTime: endTime,\n\t\tDelayed: delayed,\n\t}\n}", "func (*currencyR) NewStruct() *currencyR {\n\treturn &currencyR{}\n}", "func NewAccount(id string, name string, primary bool, type_ string, currency Currency, balance AccountBalance, createdAt time.Time, updatedAt time.Time, resource string, resourcePath string, ready bool) *Account {\n\tthis := Account{}\n\tthis.Id = id\n\tthis.Name = name\n\tthis.Primary = primary\n\tthis.Type = type_\n\tthis.Currency = currency\n\tthis.Balance = balance\n\tthis.CreatedAt = createdAt\n\tthis.UpdatedAt = updatedAt\n\tthis.Resource = resource\n\tthis.ResourcePath = resourcePath\n\tthis.Ready = ready\n\treturn &this\n}", "func NewAccount(addr, amount string) *Account {\n\tam := big.NewInt(0)\n\tam.SetString(amount, 0)\n\treturn &Account{Address: addr, Amount: am}\n}", "func (*btcTXOutputR) NewStruct() *btcTXOutputR {\n\treturn &btcTXOutputR{}\n}", "func NewAccount(address string) *Account {\n\treturn &Account{\n\t\tAddress: address,\n\t\tHeight: \"0\",\n\t\tGoldTokenBalance: \"0\",\n\t\tTotalLockedGoldBalance: \"0\",\n\t\tNonVotingLockedGoldBalance: \"0\",\n\t\tVotingLockedGoldBalance: \"0\",\n\t\tPendingWithdrawalBalance: \"0\",\n\t\tCeloUSDValue: \"0\",\n\t\tDelegations: []*Delegation{},\n\t}\n\n}", "func NewRawClient(ctx sdkclient.Context, key string) RawClient {\n\treturn &rawclient{ctx: ctx, key: key}\n}", "func (w *Wallet) NewAccount(index *uint32) (a *Account, err error) {\n\tindex2 := w.nextIndex\n\tif index != nil {\n\t\tindex2 = *index\n\t}\n\ta = &Account{w: w, index: index2}\n\tif err = w.impl.deriveAccount(a); err != nil {\n\t\treturn\n\t}\n\tpubkeyToAddress := util.PubkeyToAddress\n\tif w.isBanano {\n\t\tpubkeyToAddress = util.PubkeyToBananoAddress\n\t}\n\tif a.address, err = pubkeyToAddress(a.pubkey); err != nil {\n\t\treturn\n\t}\n\tif index == nil {\n\t\tw.nextIndex++\n\t}\n\tif _, ok := w.accounts[a.address]; !ok {\n\t\tw.accounts[a.address] = a\n\t} else if index == nil {\n\t\treturn w.NewAccount(nil)\n\t}\n\treturn\n}", "func (ga *GenesisAccount) ToAccount() auth.Account {\n\tbacc := &auth.BaseAccount{\n\t\tAddress: ga.Address,\n\t\tCoins: ga.Coins.Sort(),\n\t\tAccountNumber: ga.AccountNumber,\n\t\tSequence: ga.Sequence,\n\t}\n\n\tif !ga.OriginalVesting.IsZero() {\n\t\tbaseVestingAcc := &auth.BaseVestingAccount{\n\t\t\tBaseAccount: bacc,\n\t\t\tOriginalVesting: ga.OriginalVesting,\n\t\t\tDelegatedFree: ga.DelegatedFree,\n\t\t\tDelegatedVesting: ga.DelegatedVesting,\n\t\t\tEndTime: ga.EndTime,\n\t\t}\n\n\t\tif ga.StartTime != 0 && ga.EndTime != 0 {\n\t\t\treturn &auth.ContinuousVestingAccount{\n\t\t\t\tBaseVestingAccount: baseVestingAcc,\n\t\t\t\tStartTime: ga.StartTime,\n\t\t\t}\n\t\t} else if ga.EndTime != 0 {\n\t\t\treturn &auth.DelayedVestingAccount{\n\t\t\t\tBaseVestingAccount: baseVestingAcc,\n\t\t\t}\n\t\t} else {\n\t\t\tpanic(fmt.Sprintf(\"invalid genesis vesting account: %+v\", ga))\n\t\t}\n\t}\n\n\treturn bacc\n}", "func NewAccount(id string) esfazz.Aggregate {\n\tacc := AccountModel()\n\tacc.Id = id\n\treturn acc\n}", "func CreateAuthRawTxCmd() *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse: \"auth\",\n\t\tShort: \"one key get authorize input data\",\n\t\tRun: authSecret,\n\t}\n\tauthSecretCmdFlags(cmd)\n\treturn cmd\n}", "func CreateDepositRawTxCmd() *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse: \"deposit\",\n\t\tShort: \"one key get deposit input data\",\n\t\tRun: depositSecret,\n\t}\n\tdepositSecretCmdFlags(cmd)\n\treturn cmd\n}", "func (*oauthClientR) NewStruct() *oauthClientR {\n\treturn &oauthClientR{}\n}", "func (ba *BankAccount) New() Resource {\n\tvar obj = &BankAccount{}\n\treturn obj\n}", "func newJWTBase(ctx context.Context, cfg Config) (string, error) {\n\tserviceAccount, project, tokenSource, err := getServiceAccountInfo(ctx, cfg)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"unable to get service account from environment\")\n\t}\n\n\tpayload, err := json.Marshal(map[string]interface{}{\n\t\t\"aud\": \"vault/\" + cfg.Role,\n\t\t\"sub\": serviceAccount,\n\t\t\"exp\": time.Now().UTC().Add(5 * time.Minute).Unix(),\n\t})\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"unable to encode JWT payload\")\n\t}\n\n\thc := getHTTPClient(ctx, cfg)\n\t// reuse base transport and timeout but sprinkle on the token source for IAM access\n\thcIAM := &http.Client{\n\t\tTimeout: hc.Timeout,\n\t\tTransport: &oauth2.Transport{\n\t\t\tSource: tokenSource,\n\t\t\tBase: hc.Transport,\n\t\t},\n\t}\n\tiamClient, err := iam.New(hcIAM)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"unable to init IAM client\")\n\t}\n\n\tif cfg.IAMAddress != \"\" {\n\t\tiamClient.BasePath = cfg.IAMAddress\n\t}\n\n\tresp, err := iamClient.Projects.ServiceAccounts.SignJwt(\n\t\tfmt.Sprintf(\"projects/%s/serviceAccounts/%s\",\n\t\t\tproject, serviceAccount),\n\t\t&iam.SignJwtRequest{Payload: string(payload)}).Context(ctx).Do()\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"unable to sign JWT\")\n\t}\n\treturn resp.SignedJwt, nil\n}", "func CreateWithdrawRawTxCmd() *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse: \"withdraw\",\n\t\tShort: \"one key get withdraw proof input data\",\n\t\tRun: withdrawSecret,\n\t}\n\twithdrawSecretCmdFlags(cmd)\n\treturn cmd\n}", "func NewGenesisAccount(aa *UserAccount) *GenesisAccount {\n\treturn &GenesisAccount{\n\t\tId: aa.Id,\n\t\tAddress: aa.Address,\n\t\tCoins: aa.Coins.Sort(),\n\t}\n}", "func CreateTransferRawTxCmd() *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse: \"transfer\",\n\t\tShort: \"one key get transfer input output data\",\n\t\tRun: transferSecret,\n\t}\n\ttransferSecretCmdFlags(cmd)\n\treturn cmd\n}", "func (*customerR) NewStruct() *customerR {\n\treturn &customerR{}\n}", "func NewAccount() *Account {\n\tpriv, _ := ecdsa.GenerateKey(crypto.S256(), cryptorand.Reader)\n\tpub := base64.URLEncoding.EncodeToString(\n\t\tcrypto.FromECDSAPub(&priv.PublicKey))\n\taddr := hex.EncodeToString(crypto.PubkeyToAddress(priv.PublicKey).Bytes())\n\treturn &Account{\n\t\tID: NewUUID(),\n\t\tEthAddr: addr,\n\t\tPublicKey: pub,\n\t\tPrivateKey: base64.URLEncoding.EncodeToString(crypto.FromECDSA(priv)),\n\t}\n}", "func NewBaseCoin(purpose int, coin int, account int) *BaseCoin {\n\treturn &BaseCoin{Purpose: purpose, Coin: coin, Account: account}\n}", "func NewAccount(instanceID uuid.UUID, name, aud string) (*Account, error) {\n\tid, err := uuid.NewV4()\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"Error generating unique id\")\n\t}\n\n\taccount := &Account{\n\t\tInstanceID: instanceID,\n\t\tID: id,\n\t\tAud: aud,\n\t\tName: name,\n\t}\n\treturn account, nil\n}", "func NewAccount(addr *Address) *Account {\n\treturn &Account{\n\t\taccount: common.NewAccount(common.BytesToAddress(addr.Bytes())),\n\t}\n}", "func NewAccount(acc *types.Account) *Account {\n\treturn &Account{\n\t\tAccount: *acc,\n\t}\n}", "func AccountFromBase58(accountBase58Encoded string) (*Account, error) {\n\t// Decode the account\n\taccountDecoded := util.FromBase58(accountBase58Encoded)\n\tif 0 == len(accountDecoded) {\n\t\treturn nil, fault.CannotDecodeAccount\n\t}\n\n\t// Parse the key variant\n\tkeyVariant, keyVariantLength := util.FromVarint64(accountDecoded)\n\n\t// Check key type\n\tif 0 == keyVariantLength || keyVariant&publicKeyCode != publicKeyCode {\n\t\treturn nil, fault.NotPublicKey\n\t}\n\n\t// compute algorithm\n\tkeyAlgorithm := keyVariant >> algorithmShift\n\tif keyAlgorithm >= algorithmLimit {\n\t\treturn nil, fault.InvalidKeyType\n\t}\n\n\t// network selection\n\tisTest := 0 != keyVariant&testKeyCode\n\n\t// Compute key length\n\tkeyLength := len(accountDecoded) - keyVariantLength - checksumLength\n\tif keyLength <= 0 {\n\t\treturn nil, fault.InvalidKeyLength\n\t}\n\n\t// Checksum\n\tchecksumStart := len(accountDecoded) - checksumLength\n\tchecksum := sha3.Sum256(accountDecoded[:checksumStart])\n\tif !bytes.Equal(checksum[:checksumLength], accountDecoded[checksumStart:]) {\n\t\treturn nil, fault.ChecksumMismatch\n\t}\n\n\t// return a pointer to the specific account type\n\tswitch keyAlgorithm {\n\tcase ED25519:\n\t\tif keyLength != ed25519.PublicKeySize {\n\t\t\treturn nil, fault.InvalidKeyLength\n\t\t}\n\t\tpublicKey := accountDecoded[keyVariantLength:checksumStart]\n\t\taccount := &Account{\n\t\t\tAccountInterface: &ED25519Account{\n\t\t\t\tTest: isTest,\n\t\t\t\tPublicKey: publicKey,\n\t\t\t},\n\t\t}\n\t\treturn account, nil\n\tcase Nothing:\n\t\tif 2 != keyLength {\n\t\t\treturn nil, fault.InvalidKeyLength\n\t\t}\n\t\tpublicKey := accountDecoded[keyVariantLength:checksumStart]\n\t\taccount := &Account{\n\t\t\tAccountInterface: &NothingAccount{\n\t\t\t\tTest: isTest,\n\t\t\t\tPublicKey: publicKey,\n\t\t\t},\n\t\t}\n\t\treturn account, nil\n\tdefault:\n\t\treturn nil, fault.InvalidKeyType\n\t}\n}", "func NewCoinbaseTransaction(to wallet.Address) *Transaction {\n\t// Create a slice a bytes\n\tranddata := make([]byte, 24)\n\t// Add random data to the slice of bytes\n\t_, err := rand.Read(randdata)\n\tif err != nil {\n\t\t// Log a fatal error\n\t\tlogrus.WithFields(logrus.Fields{\"error\": err}).Fatalln(\"failed to generate random bytes.\")\n\t}\n\n\t// Collect the data from the hexadecimal interpretation of the random bytes\n\tdata := fmt.Sprintf(\"%x\", randdata)\n\n\t// Create a transaction input with no reference to a previous output\n\tinputs := TXI{ID: []byte{}, OutIndex: -1, Signature: nil, PublicKey: []byte(data)}\n\t// Create a transaction output with the token reward\n\toutputs := *NewTXO(25, to)\n\n\t// Construct a transaction with no ID, and the set of inputs and outputs\n\ttxn := Transaction{\n\t\tID: nil,\n\t\tInputs: TXIList{inputs},\n\t\tOutputs: TXOList{outputs},\n\t}\n\n\t// Set the ID (hash) for the transaction\n\ttxn.ID = txn.GenerateHash()\n\n\t// Return the transaction\n\treturn &txn\n}", "func NewRawCardSignerWithCtx(pointer unsafe.Pointer) *RawCardSigner {\n\tctx := (*C.vssc_raw_card_signer_t /*ct2*/)(pointer)\n\tobj := &RawCardSigner{\n\t\tcCtx: ctx,\n\t}\n\truntime.SetFinalizer(obj, (*RawCardSigner).Delete)\n\treturn obj\n}", "func New(raw []byte) (*BytesObj, error) {\n\tbo := new(BytesObj)\n\tif err := bo.UnmarshalJSON(raw); err != nil {\n\t\treturn nil, err\n\t}\n\treturn bo, nil\n}", "func NewTestAccount(sb *collections.SchemaBuilder) (TestAccount, error) {\n\tta := TestAccount{\n\t\tItem: collections.NewItem(sb, itemPrefix, \"test\", collections.Uint64Value),\n\t}\n\treturn ta, nil\n}", "func (k *kubeclient) CreateRaw(upgradeResultObj *apis.UpgradeResult) ([]byte, error) {\n\tur, err := k.Create(upgradeResultObj)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn json.Marshal(ur)\n}", "func newTransaction(kvScheduler scheduler_api.KVScheduler) *kvSchedulerTxn {\n\treturn &kvSchedulerTxn{\n\t\tkvScheduler: kvScheduler,\n\t\tvalues: make(api.KeyValuePairs),\n\t\tmerged: make(api.KeyValuePairs),\n\t}\n}", "func NewAccount() *Account {\n\tacc := &Account{}\n\tpriv, pub := newKeyPair()\n\tacc.PriKey = priv\n\tacc.PubKey = pub\n\treturn acc\n}", "func newTx(ctx context.Context, drv dialect.Driver) (*txDriver, error) {\n\ttx, err := drv.Tx(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &txDriver{tx: tx, drv: drv}, nil\n}", "func newTx(ctx context.Context, drv dialect.Driver) (*txDriver, error) {\n\ttx, err := drv.Tx(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &txDriver{tx: tx, drv: drv}, nil\n}", "func (ak AccountKeeper) NewAccount(ctx sdk.Context, acc exported.Account) exported.Account {\n\t// FIXME: update account number\n\treturn acc\n}", "func New(conn *bindings.Conn, id uint64) *Txn {\n\treturn &Txn{\n\t\tconn: conn,\n\t\tid: id,\n\t\tmachine: newMachine(),\n\t}\n}", "func NewTransaction(p *requestParams) {\n\tw, r, c, u := p.w, p.r, p.c, p.u\n\n\td := json.NewDecoder(r.Body)\n\tvar request TransactionRequest\n\tif err := d.Decode(&request); err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tif len(request.Amounts) != len(request.Accounts) {\n\t\thttp.Error(w, \"Amounts and accounts of different lengths\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tdate, err := time.Parse(dateStringFormat, request.Date)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tuserKey := userKey(c, u)\n\ttransactionId := uuid.NewRandom().String()\n\taccountKeys := make([]*datastore.Key, len(request.Accounts))\n\tsplitKeys := make([]*datastore.Key, len(request.Accounts))\n\tsplits := make([]*transaction.Split, len(request.Accounts))\n\n\tfor i := range request.Accounts {\n\t\taccountKeys[i] = datastore.NewKey(c, \"Account\", \"\", request.Accounts[i], userKey)\n\t\tsplitKeys[i] = datastore.NewKey(c, \"Split\", transactionId, 0, accountKeys[i])\n\t\tsplits[i] = &transaction.Split{\n\t\t\tAmount: request.Amounts[i],\n\t\t\tAccount: request.Accounts[i],\n\t\t\tMemo: request.Memo,\n\t\t\tDate: date,\n\t\t}\n\t}\n\n\tx := transaction.NewTransaction()\n\tx.AddSplits(splits)\n\n\tif err := x.ValidateAmount(); err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\terr = datastore.RunInTransaction(c, func(c appengine.Context) error {\n\t\taccounts := make([]transaction.Account, len(accountKeys))\n\t\tif err := datastore.GetMulti(c, accountKeys, accounts); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfor i := range accounts {\n\t\t\tx.AddAccount(&accounts[i], accountKeys[i].IntID())\n\t\t}\n\n\t\tif err := x.Commit(); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tputStatus := make(chan error)\n\n\t\tgo func() {\n\t\t\t_, err := datastore.PutMulti(c, accountKeys, accounts)\n\t\t\tputStatus <- err\n\t\t}()\n\t\tgo func() {\n\t\t\t_, err := datastore.PutMulti(c, splitKeys, splits)\n\t\t\tputStatus <- err\n\t\t}()\n\n\t\terr := <-putStatus\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn <-putStatus\n\t}, nil)\n\tif err != nil {\n\t\t// TODO(cjc25): This might not be a 400: if e.g. datastore failed it should\n\t\t// be a 500. Interpret err and return the right thing.\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n}", "func NewAccount(username string) (*AccountRow, error) {\n\tquery := `\n\t\tinsert into accounts (user_name)\n\t\t\tvalues ($1)\n\t\t\ton conflict (user_name)\n\t\t\t\tdo nothing\n\t\treturning\n\t\t\tid, user_name`\n\n\trowData := &AccountRow{}\n\trow := GlobalConn.QueryRow(query, username)\n\n\tif err := row.Scan(&rowData.ID, &rowData.Name); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn rowData, nil\n}", "func (*ticketR) NewStruct() *ticketR {\n\treturn &ticketR{}\n}", "func (ws *WebServer) NewAccount(c *gin.Context) {\n\tnetwork := ws.nodeConfig.GetNetwork()\n\tif network == \"\" {\n\t\tReturnError(c, 500, ErrorNoNetwork.Error())\n\t\treturn\n\t}\n\tn := sdk.Testnet\n\tif network == \"bitmark\" {\n\t\tn = sdk.Livenet\n\t}\n\tseedFile := filepath.Join(ws.rootPath, \"bitmarkd\", network, \"proof.sign\")\n\tif _, err := os.Stat(seedFile); err == nil {\n\t\tReturnError(c, 500, ErrorNoSeedFile.Error())\n\t\treturn\n\t}\n\n\ta, err := sdk.NewAccount(n)\n\tif err != nil {\n\t\tReturnError(c, 500, ErrorCreateAccount.Error())\n\t\treturn\n\t}\n\tseed := a.Seed()\n\n\tf, err := os.OpenFile(seedFile, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0600)\n\tif err != nil {\n\t\tReturnError(c, 500, ErrorOpenSeedFile.Error())\n\t\treturn\n\t}\n\tdefer f.Close()\n\n\t_, err = f.WriteString(fmt.Sprintf(\"SEED:%s\", seed))\n\tif err != nil {\n\t\tReturnError(c, 500, ErrorToWriteSeedFile.Error())\n\t\treturn\n\t}\n\tws.SetAccount(a.AccountNumber(), seed, network) // Record in AccountInfo in memory\n\terr = ws.saveAcct()\n\tif nil != err {\n\t\tReturnError(c, 500, ErrorAutoSaveAccount.Error())\n\t\treturn\n\n\t}\n\tc.JSON(200, map[string]interface{}{\n\t\t\"ok\": 1,\n\t})\n}", "func tNewUser(lbl string) *tUser {\n\tintBytes := make([]byte, 4)\n\tbinary.BigEndian.PutUint32(intBytes, acctCounter)\n\tacctID := account.AccountID{}\n\tcopy(acctID[:], acctTemplate[:])\n\tcopy(acctID[account.HashSize-4:], intBytes)\n\taddr := strconv.Itoa(int(acctCounter))\n\tsig := []byte{0xab} // Just to differentiate from the addr.\n\tsig = append(sig, intBytes...)\n\tsigHex := hex.EncodeToString(sig)\n\tacctCounter++\n\treturn &tUser{\n\t\tsig: sig,\n\t\tsigHex: sigHex,\n\t\tacct: acctID,\n\t\taddr: addr,\n\t\tlbl: lbl,\n\t}\n}", "func (s SecureValueTypeRentalAgreement) construct() SecureValueTypeClass { return &s }", "func New(ccHost, username, password, clusterID, clusterToken string) *ContrailCommand {\n\treturn &ContrailCommand{\n\t\tAuthHost: ccHost,\n\t\tUsername: username,\n\t\tPassword: password,\n\t\tClusterID: clusterID,\n\t\tClusterToken: clusterToken,\n\t\tAuthPath: \"/keystone/v3/auth/tokens\",\n\t\tUserDomain: \"default\",\n\t\tProjectName: \"admin\",\n\t\tProjectDomain: \"default\",\n\t}\n}", "func New(accessKey string, secretKey string) *Coinsbank {\n\treturn &Coinsbank{\n\t\tAccessKey: accessKey,\n\t\tSecretKey: secretKey,\n\t}\n}", "func (*exchangeCurrencyR) NewStruct() *exchangeCurrencyR {\n\treturn &exchangeCurrencyR{}\n}", "func newDummyCredit(t *testing.T, dbtx walletdb.ReadWriteTx, pool *Pool, series uint32, index Index, branch Branch,\n\ttxHash []byte, outpointIdx uint32) Credit {\n\tvar hash chainhash.Hash\n\tif err := hash.SetBytes(txHash); err != nil {\n\t\tt.Fatal(err)\n\t}\n\t// Ensure the address defined by the given series/branch/index is present on\n\t// the set of used addresses as that's a requirement of WithdrawalAddress.\n\tTstEnsureUsedAddr(t, dbtx, pool, series, branch, index)\n\taddr := TstNewWithdrawalAddress(t, dbtx, pool, series, branch, index)\n\tc := wtxmgr.Credit{\n\t\tOutPoint: wire.OutPoint{\n\t\t\tHash: hash,\n\t\t\tIndex: outpointIdx,\n\t\t},\n\t}\n\treturn newCredit(c, *addr)\n}", "func NewAccount(opts ...AccountCreationOption) (*Account, error) {\n\taccount := &Account{\n\t\tBalance: big.NewInt(0),\n\t\tvotingWeight: big.NewInt(0),\n\t\taccountType: 1,\n\t}\n\tfor _, opt := range opts {\n\t\tif err := opt(account); err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"failed to apply account creation option\")\n\t\t}\n\t}\n\treturn account, nil\n}", "func New(card string) *CardBinCheckResponse {\n\tvar cbcr CardBinCheckResponse\n\n\tcb, err := bank.Get(card)\n\tif err != nil {\n\t\treturn makeErrorCardBinCheckResponse(card, err)\n\t}\n\n\tcbcr.Stat = \"ok\"\n\tcbcr.Key = card\n\tcbcr.Validated = true\n\tcbcr.CardType = cb.Type\n\tcbcr.Bank = cb.Bank\n\tcbcr.CardBIN = cb.Bin\n\n\treturn &cbcr\n}", "func (oc *contractTransmitter) FromAccount() (ocrtypes.Account, error) {\n\treturn ocrtypes.Account(oc.transmitter.FromAddress().String()), nil\n}", "func (*vendorR) NewStruct() *vendorR {\n\treturn &vendorR{}\n}", "func newTestContext() (tc *testContext, err error) {\n\ttc = new(testContext)\n\n\tconst genesisHash = \"0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e2206\"\n\tif tc.netParams, err = tc.createNetParams(genesisHash); err != nil {\n\t\treturn\n\t}\n\n\tconst block1Hex = \"0000002006226e46111a0b59caaf126043eb5bbf28c34f3a5e332a1fc7b2b73cf188910fadbb20ea41a8423ea937e76e8151636bf6093b70eaff942930d20576600521fdc30f9858ffff7f20000000000101000000010000000000000000000000000000000000000000000000000000000000000000ffffffff03510101ffffffff0100f2052a010000001976a9143ca33c2e4446f4a305f23c80df8ad1afdcf652f988ac00000000\"\n\tif tc.block1, err = blockFromHex(block1Hex); err != nil {\n\t\terr = fmt.Errorf(\"Failed to parse serialized block: %v\", err)\n\t\treturn\n\t}\n\n\tconst fundingInputPrivKeyHex = \"6bd078650fcee8444e4e09825227b801a1ca928debb750eb36e6d56124bb20e8\"\n\ttc.fundingInputPrivKey, err = privkeyFromHex(fundingInputPrivKeyHex)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Failed to parse serialized privkey: %v\", err)\n\t\treturn\n\t}\n\n\tconst localFundingPrivKeyHex = \"30ff4956bbdd3222d44cc5e8a1261dab1e07957bdac5ae88fe3261ef321f3749\"\n\ttc.localFundingPrivKey, err = privkeyFromHex(localFundingPrivKeyHex)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Failed to parse serialized privkey: %v\", err)\n\t\treturn\n\t}\n\n\tconst localPaymentPrivKeyHex = \"bb13b121cdc357cd2e608b0aea294afca36e2b34cf958e2e6451a2f274694491\"\n\ttc.localPaymentPrivKey, err = privkeyFromHex(localPaymentPrivKeyHex)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Failed to parse serialized privkey: %v\", err)\n\t\treturn\n\t}\n\n\tconst localFundingPubKeyHex = \"023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb\"\n\ttc.localFundingPubKey, err = pubkeyFromHex(localFundingPubKeyHex)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Failed to parse serialized pubkey: %v\", err)\n\t\treturn\n\t}\n\n\tconst remoteFundingPubKeyHex = \"030e9f7b623d2ccc7c9bd44d66d5ce21ce504c0acf6385a132cec6d3c39fa711c1\"\n\ttc.remoteFundingPubKey, err = pubkeyFromHex(remoteFundingPubKeyHex)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Failed to parse serialized pubkey: %v\", err)\n\t\treturn\n\t}\n\n\tconst localRevocationPubKeyHex = \"0212a140cd0c6539d07cd08dfe09984dec3251ea808b892efeac3ede9402bf2b19\"\n\ttc.localRevocationPubKey, err = pubkeyFromHex(localRevocationPubKeyHex)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Failed to parse serialized pubkey: %v\", err)\n\t\treturn\n\t}\n\n\tconst localPaymentPubKeyHex = \"030d417a46946384f88d5f3337267c5e579765875dc4daca813e21734b140639e7\"\n\ttc.localPaymentPubKey, err = pubkeyFromHex(localPaymentPubKeyHex)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Failed to parse serialized pubkey: %v\", err)\n\t\treturn\n\t}\n\n\tconst remotePaymentPubKeyHex = \"0394854aa6eab5b2a8122cc726e9dded053a2184d88256816826d6231c068d4a5b\"\n\ttc.remotePaymentPubKey, err = pubkeyFromHex(remotePaymentPubKeyHex)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Failed to parse serialized pubkey: %v\", err)\n\t\treturn\n\t}\n\n\tconst localDelayPubKeyHex = \"03fd5960528dc152014952efdb702a88f71e3c1653b2314431701ec77e57fde83c\"\n\ttc.localDelayPubKey, err = pubkeyFromHex(localDelayPubKeyHex)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Failed to parse serialized pubkey: %v\", err)\n\t\treturn\n\t}\n\n\tconst commitmentPointHex = \"025f7117a78150fe2ef97db7cfc83bd57b2e2c0d0dd25eaf467a4a1c2a45ce1486\"\n\ttc.commitmentPoint, err = pubkeyFromHex(commitmentPointHex)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Failed to parse serialized pubkey: %v\", err)\n\t\treturn\n\t}\n\n\tconst localPaymentBasePointHex = \"034f355bdcb7cc0af728ef3cceb9615d90684bb5b2ca5f859ab0f0b704075871aa\"\n\ttc.localPaymentBasePoint, err = pubkeyFromHex(localPaymentBasePointHex)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Failed to parse serialized pubkey: %v\", err)\n\t\treturn\n\t}\n\n\tconst remotePaymentBasePointHex = \"032c0b7cf95324a07d05398b240174dc0c2be444d96b159aa6c7f7b1e668680991\"\n\ttc.remotePaymentBasePoint, err = pubkeyFromHex(remotePaymentBasePointHex)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Failed to parse serialized pubkey: %v\", err)\n\t\treturn\n\t}\n\n\tconst fundingChangeAddressStr = \"bcrt1qgyeqfmptyh780dsk32qawsvdffc2g5q5sxamg0\"\n\ttc.fundingChangeAddress, err = btcutil.DecodeAddress(\n\t\tfundingChangeAddressStr, tc.netParams)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Failed to parse address: %v\", err)\n\t\treturn\n\t}\n\n\ttc.fundingInputUtxo, tc.fundingInputTxOut, err = tc.extractFundingInput()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tconst fundingTxHex = \"0200000001adbb20ea41a8423ea937e76e8151636bf6093b70eaff942930d20576600521fd000000006b48304502210090587b6201e166ad6af0227d3036a9454223d49a1f11839c1a362184340ef0240220577f7cd5cca78719405cbf1de7414ac027f0239ef6e214c90fcaab0454d84b3b012103535b32d5eb0a6ed0982a0479bbadc9868d9836f6ba94dd5a63be16d875069184ffffffff028096980000000000220020c015c4a6be010e21657068fc2e6a9d02b27ebe4d490a25846f7237f104d1a3cd20256d29010000001600143ca33c2e4446f4a305f23c80df8ad1afdcf652f900000000\"\n\tif tc.fundingTx, err = txFromHex(fundingTxHex); err != nil {\n\t\terr = fmt.Errorf(\"Failed to parse serialized tx: %v\", err)\n\t\treturn\n\t}\n\n\ttc.fundingOutpoint = wire.OutPoint{\n\t\tHash: *tc.fundingTx.Hash(),\n\t\tIndex: 0,\n\t}\n\n\ttc.shortChanID = lnwire.ShortChannelID{\n\t\tBlockHeight: 1,\n\t\tTxIndex: 0,\n\t\tTxPosition: 0,\n\t}\n\n\thtlcData := []struct {\n\t\tincoming bool\n\t\tamount lnwire.MilliSatoshi\n\t\texpiry uint32\n\t\tpreimage string\n\t}{\n\t\t{\n\t\t\tincoming: true,\n\t\t\tamount: 1000000,\n\t\t\texpiry: 500,\n\t\t\tpreimage: \"0000000000000000000000000000000000000000000000000000000000000000\",\n\t\t},\n\t\t{\n\t\t\tincoming: true,\n\t\t\tamount: 2000000,\n\t\t\texpiry: 501,\n\t\t\tpreimage: \"0101010101010101010101010101010101010101010101010101010101010101\",\n\t\t},\n\t\t{\n\t\t\tincoming: false,\n\t\t\tamount: 2000000,\n\t\t\texpiry: 502,\n\t\t\tpreimage: \"0202020202020202020202020202020202020202020202020202020202020202\",\n\t\t},\n\t\t{\n\t\t\tincoming: false,\n\t\t\tamount: 3000000,\n\t\t\texpiry: 503,\n\t\t\tpreimage: \"0303030303030303030303030303030303030303030303030303030303030303\",\n\t\t},\n\t\t{\n\t\t\tincoming: true,\n\t\t\tamount: 4000000,\n\t\t\texpiry: 504,\n\t\t\tpreimage: \"0404040404040404040404040404040404040404040404040404040404040404\",\n\t\t},\n\t}\n\n\ttc.htlcs = make([]channeldb.HTLC, len(htlcData))\n\tfor i, htlc := range htlcData {\n\t\tpreimage, decodeErr := hex.DecodeString(htlc.preimage)\n\t\tif decodeErr != nil {\n\t\t\terr = fmt.Errorf(\"Failed to decode HTLC preimage: %v\", decodeErr)\n\t\t\treturn\n\t\t}\n\n\t\ttc.htlcs[i].RHash = sha256.Sum256(preimage)\n\t\ttc.htlcs[i].Amt = htlc.amount\n\t\ttc.htlcs[i].RefundTimeout = htlc.expiry\n\t\ttc.htlcs[i].Incoming = htlc.incoming\n\t}\n\n\ttc.localCsvDelay = 144\n\ttc.fundingAmount = 10000000\n\ttc.dustLimit = 546\n\ttc.feePerKW = 15000\n\n\treturn\n}", "func (*utxoR) NewStruct() *utxoR {\n\treturn &utxoR{}\n}", "func (c Client) New(params *stripe.TreasuryCreditReversalParams) (*stripe.TreasuryCreditReversal, error) {\n\tcreditreversal := &stripe.TreasuryCreditReversal{}\n\terr := c.B.Call(\n\t\thttp.MethodPost,\n\t\t\"/v1/treasury/credit_reversals\",\n\t\tc.Key,\n\t\tparams,\n\t\tcreditreversal,\n\t)\n\treturn creditreversal, err\n}", "func (m *MockCustomResourceClient) CreateCustomResourceRaw(apiGroup, version, namespace, kind string, data []byte) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"CreateCustomResourceRaw\", apiGroup, version, namespace, kind, data)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func createCoinbaseTx(subsidyCache *standalone.SubsidyCache,\n\tcoinbaseScript []byte, opReturnPkScript []byte, nextBlockHeight int64,\n\taddr stdaddr.Address, voters uint16, params *chaincfg.Params,\n\tisTreasuryEnabled bool,\n\tsubsidySplitVariant standalone.SubsidySplitVariant) *dcrutil.Tx {\n\n\t// Coinbase transactions have no inputs, so previous outpoint is zero hash\n\t// and max index.\n\tcoinbaseInput := &wire.TxIn{\n\t\tPreviousOutPoint: *wire.NewOutPoint(&chainhash.Hash{},\n\t\t\twire.MaxPrevOutIndex, wire.TxTreeRegular),\n\t\tSequence: wire.MaxTxInSequenceNum,\n\t\tBlockHeight: wire.NullBlockHeight,\n\t\tBlockIndex: wire.NullBlockIndex,\n\t\tSignatureScript: coinbaseScript,\n\t}\n\n\t// Block one is a special block that might pay out tokens to a ledger.\n\tif nextBlockHeight == 1 && len(params.BlockOneLedger) != 0 {\n\t\ttx := wire.NewMsgTx()\n\t\ttx.Version = 1\n\t\ttx.AddTxIn(coinbaseInput)\n\t\ttx.TxIn[0].ValueIn = params.BlockOneSubsidy()\n\n\t\tfor _, payout := range params.BlockOneLedger {\n\t\t\ttx.AddTxOut(&wire.TxOut{\n\t\t\t\tValue: payout.Amount,\n\t\t\t\tVersion: payout.ScriptVersion,\n\t\t\t\tPkScript: payout.Script,\n\t\t\t})\n\t\t}\n\n\t\treturn dcrutil.NewTx(tx)\n\t}\n\n\t// Prior to the decentralized treasury agenda, the transaction version must\n\t// be 1 and there is an additional output that either pays to organization\n\t// associated with the treasury or a provably pruneable zero-value output\n\t// script when it is disabled.\n\t//\n\t// Once the decentralized treasury agenda is active, the transaction version\n\t// must be the new expected version and there is no treasury output since it\n\t// is included in the stake tree instead.\n\tvar txVersion = uint16(1)\n\tvar treasuryOutput *wire.TxOut\n\tvar treasurySubsidy int64\n\tif !isTreasuryEnabled {\n\t\tif params.BlockTaxProportion > 0 {\n\t\t\t// Create the treasury output with the correct subsidy and public\n\t\t\t// key script for the organization associated with the treasury.\n\t\t\ttreasurySubsidy = subsidyCache.CalcTreasurySubsidy(nextBlockHeight,\n\t\t\t\tvoters, isTreasuryEnabled)\n\t\t\ttreasuryOutput = &wire.TxOut{\n\t\t\t\tValue: treasurySubsidy,\n\t\t\t\tPkScript: params.OrganizationPkScript,\n\t\t\t}\n\t\t} else {\n\t\t\t// Treasury disabled.\n\t\t\ttreasuryOutput = &wire.TxOut{\n\t\t\t\tValue: 0,\n\t\t\t\tPkScript: opTrueScript,\n\t\t\t}\n\t\t}\n\t} else {\n\t\t// Set the transaction version to the new version required by the\n\t\t// decentralized treasury agenda.\n\t\ttxVersion = wire.TxVersionTreasury\n\t}\n\n\t// Create the script to pay to the provided payment address if one was\n\t// specified. Otherwise create a script that allows the coinbase to be\n\t// redeemable by anyone.\n\tworkSubsidyScriptVer := uint16(0)\n\tworkSubsidyScript := opTrueScript\n\tif addr != nil {\n\t\tworkSubsidyScriptVer, workSubsidyScript = addr.PaymentScript()\n\t}\n\n\t// Create a coinbase with expected inputs and outputs.\n\t//\n\t// Inputs:\n\t// - A single input with input value set to the total payout amount.\n\t//\n\t// Outputs:\n\t// - Potential treasury output prior to the decentralized treasury agenda\n\t// - Output that includes the block height and potential extra nonce used\n\t// to ensure a unique hash\n\t// - Output that pays the work subsidy to the miner\n\tworkSubsidy := subsidyCache.CalcWorkSubsidyV3(nextBlockHeight, voters,\n\t\tsubsidySplitVariant)\n\ttx := wire.NewMsgTx()\n\ttx.Version = txVersion\n\ttx.AddTxIn(coinbaseInput)\n\ttx.TxIn[0].ValueIn = workSubsidy + treasurySubsidy\n\tif treasuryOutput != nil {\n\t\ttx.AddTxOut(treasuryOutput)\n\t}\n\ttx.AddTxOut(&wire.TxOut{\n\t\tValue: 0,\n\t\tPkScript: opReturnPkScript,\n\t})\n\ttx.AddTxOut(&wire.TxOut{\n\t\tValue: workSubsidy,\n\t\tVersion: workSubsidyScriptVer,\n\t\tPkScript: workSubsidyScript,\n\t})\n\treturn dcrutil.NewTx(tx)\n}", "func NewAccount(firstName string) *Account {\n\tthis := Account{}\n\tthis.FirstName = firstName\n\treturn &this\n}", "func NewRaw(id, netID string, args ...string) *CmdMsg {\n\tcmd := NewCmd(id, \"raw\", args...)\n\tcmd.Network.Init(netID, \"net\")\n\treturn cmd\n}", "func newVertex(x, y, theta, v, w float64, parent *Vertex) *Vertex {\n\treturn &Vertex{Point{X: x, Y: y, Theta: theta, V: v, W: w}, parent, nil}\n}", "func (client *Client) CreateRawSendFromWithData(watchAddress, destinationAddress string, assets map[string]float64, data []string) (Response, error) {\n\n\tmsg := client.Command(\n\t\t\"createrawsendfrom\",\n\t\t[]interface{}{\n\t\t\twatchAddress,\n\t\t\tmap[string]interface{}{\n\t\t\t\tdestinationAddress: assets,\n\t\t\t},\n\t\t\tdata,\n\t\t},\n\t)\n\n\treturn client.Post(msg)\n}", "func NewGenericContract(addr *common.Address, block *Block, trx *Transaction) *Contract {\n\t// make the contract\n\treturn &Contract{\n\t\tType: AccountTypeContract,\n\t\tAddress: *addr,\n\t\tTransactionHash: trx.Hash,\n\t\tTimeStamp: block.TimeStamp,\n\t\tName: \"\",\n\t\tVersion: \"\",\n\t\tSupportContact: \"\",\n\t\tLicense: \"\",\n\t\tCompiler: \"\",\n\t\tIsOptimized: false,\n\t\tOptimizeRuns: 0,\n\t\tSourceCode: \"\",\n\t\tSourceCodeHash: nil,\n\t\tAbi: \"\",\n\t\tValidated: nil,\n\t}\n}", "func (*trainingCostR) NewStruct() *trainingCostR {\n\treturn &trainingCostR{}\n}", "func (*premiumCodeR) NewStruct() *premiumCodeR {\n\treturn &premiumCodeR{}\n}", "func (cva ContinuousVestingAccount) Validate() error {\n\tif cva.GetStartTime() >= cva.GetEndTime() {\n\t\treturn errors.New(\"vesting start-time cannot be before end-time\")\n\t}\n\n\treturn cva.BaseVestingAccount.Validate()\n}" ]
[ "0.73651177", "0.7098843", "0.6828235", "0.6757991", "0.669836", "0.6251848", "0.6140739", "0.59896034", "0.57978946", "0.5668212", "0.5430953", "0.5397485", "0.5344448", "0.5326911", "0.53231484", "0.5315272", "0.5190769", "0.51356536", "0.5125424", "0.5110819", "0.5089053", "0.5081272", "0.5078559", "0.5058398", "0.5023924", "0.49956164", "0.4980368", "0.49685884", "0.49645633", "0.49621898", "0.49417073", "0.4936396", "0.4936396", "0.4896527", "0.48932496", "0.489257", "0.48827308", "0.486143", "0.48560083", "0.48379925", "0.48356396", "0.48050702", "0.47865763", "0.47865108", "0.47852993", "0.47626644", "0.47501206", "0.47480845", "0.47371703", "0.47370094", "0.47307244", "0.47301987", "0.47263962", "0.47227535", "0.4715878", "0.47136617", "0.4706034", "0.47024566", "0.469848", "0.46970367", "0.46956468", "0.4688354", "0.467425", "0.46668825", "0.4665885", "0.46654427", "0.46631822", "0.46489266", "0.46447727", "0.46344778", "0.46344778", "0.46274146", "0.46264648", "0.46260205", "0.461525", "0.4610659", "0.4608361", "0.4598828", "0.4591068", "0.45883986", "0.45844206", "0.45751178", "0.4569567", "0.45637563", "0.45589447", "0.45339036", "0.45334986", "0.45288232", "0.4524412", "0.45226896", "0.45164883", "0.451321", "0.45103204", "0.45095325", "0.4500586", "0.44976133", "0.44909447", "0.44790405", "0.44765958", "0.44740856" ]
0.8007365
0
NewContinuousVestingAccount returns a new ContinuousVestingAccount
func NewContinuousVestingAccount(baseAcc *authtypes.BaseAccount, originalVesting sdk.Coins, startTime, endTime int64) *ContinuousVestingAccount { baseVestingAcc := &BaseVestingAccount{ BaseAccount: baseAcc, OriginalVesting: originalVesting, EndTime: endTime, } return &ContinuousVestingAccount{ StartTime: startTime, BaseVestingAccount: baseVestingAcc, } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func NewContinuousVestingAccountRaw(bva *BaseVestingAccount, startTime int64) *ContinuousVestingAccount {\n\treturn &ContinuousVestingAccount{\n\t\tBaseVestingAccount: bva,\n\t\tStartTime: startTime,\n\t}\n}", "func NewPeriodicVestingAccount(baseAcc *authtypes.BaseAccount, originalVesting sdk.Coins, startTime int64, periods Periods) *PeriodicVestingAccount {\n\tendTime := startTime\n\tfor _, p := range periods {\n\t\tendTime += p.Length\n\t}\n\tbaseVestingAcc := &BaseVestingAccount{\n\t\tBaseAccount: baseAcc,\n\t\tOriginalVesting: originalVesting,\n\t\tEndTime: endTime,\n\t}\n\n\treturn &PeriodicVestingAccount{\n\t\tBaseVestingAccount: baseVestingAcc,\n\t\tStartTime: startTime,\n\t\tVestingPeriods: periods,\n\t}\n}", "func newPeriodicVestingAccount(address sdk.AccAddress, periods vestingtypes.Periods, firstPeriodStartTimestamp int64) *vestingtypes.PeriodicVestingAccount {\n\tbaseAccount := authtypes.NewBaseAccount(address, nil, 0, 0)\n\n\toriginalVesting := sdk.NewCoins()\n\tfor _, p := range periods {\n\t\toriginalVesting = originalVesting.Add(p.Amount...)\n\t}\n\n\tvar totalPeriods int64\n\tfor _, p := range periods {\n\t\ttotalPeriods += p.Length\n\t}\n\tendTime := firstPeriodStartTimestamp + totalPeriods\n\n\tbaseVestingAccount := vestingtypes.NewBaseVestingAccount(baseAccount, originalVesting, endTime)\n\treturn vestingtypes.NewPeriodicVestingAccountRaw(baseVestingAccount, firstPeriodStartTimestamp, periods)\n}", "func NewBaseVestingAccount(baseAccount *authtypes.BaseAccount, originalVesting sdk.Coins, endTime int64) *BaseVestingAccount {\n\treturn &BaseVestingAccount{\n\t\tBaseAccount: baseAccount,\n\t\tOriginalVesting: originalVesting,\n\t\tDelegatedFree: sdk.NewCoins(),\n\t\tDelegatedVesting: sdk.NewCoins(),\n\t\tEndTime: endTime,\n\t}\n}", "func NewClawbackVestingAccount(baseAcc *authtypes.BaseAccount, funder sdk.AccAddress, originalVesting sdk.Coins, startTime int64, lockupPeriods, vestingPeriods Periods) *ClawbackVestingAccount {\n\t// copy and align schedules to avoid mutating inputs\n\tlp := make(Periods, len(lockupPeriods))\n\tcopy(lp, lockupPeriods)\n\tvp := make(Periods, len(vestingPeriods))\n\tcopy(vp, vestingPeriods)\n\t_, endTime := AlignSchedules(startTime, startTime, lp, vp)\n\tbaseVestingAcc := &BaseVestingAccount{\n\t\tBaseAccount: baseAcc,\n\t\tOriginalVesting: originalVesting,\n\t\tEndTime: endTime,\n\t}\n\n\treturn &ClawbackVestingAccount{\n\t\tBaseVestingAccount: baseVestingAcc,\n\t\tFunderAddress: funder.String(),\n\t\tStartTime: startTime,\n\t\tLockupPeriods: lp,\n\t\tVestingPeriods: vp,\n\t}\n}", "func newAccount() *Account {\n\treturn &Account{\n\t\tblocks: make(map[string]uint64),\n\t}\n}", "func NewDelayedVestingAccount(baseAcc *authtypes.BaseAccount, originalVesting sdk.Coins, endTime int64) *DelayedVestingAccount {\n\tbaseVestingAcc := &BaseVestingAccount{\n\t\tBaseAccount: baseAcc,\n\t\tOriginalVesting: originalVesting,\n\t\tEndTime: endTime,\n\t}\n\n\treturn &DelayedVestingAccount{baseVestingAcc}\n}", "func NewValidatorVestingAccount(baseAcc *authtypes.BaseAccount, startTime int64, periods vestingtypes.Periods, validatorAddress sdk.ConsAddress, returnAddress sdk.AccAddress, signingThreshold int64) *ValidatorVestingAccount {\n\n\tendTime := startTime\n\tfor _, p := range periods {\n\t\tendTime += p.Length\n\t}\n\tbaseVestingAcc := &vestingtypes.BaseVestingAccount{\n\t\tBaseAccount: baseAcc,\n\t\tOriginalVesting: baseAcc.Coins,\n\t\tEndTime: endTime,\n\t}\n\tpva := &vestingtypes.PeriodicVestingAccount{\n\t\tBaseVestingAccount: baseVestingAcc,\n\t\tStartTime: startTime,\n\t\tVestingPeriods: periods,\n\t}\n\tvar vestingPeriodProgress []VestingProgress\n\tfor i := 0; i < len(periods); i++ {\n\t\tvestingPeriodProgress = append(vestingPeriodProgress, VestingProgress{false, false})\n\t}\n\n\treturn &ValidatorVestingAccount{\n\t\tPeriodicVestingAccount: pva,\n\t\tValidatorAddress: validatorAddress,\n\t\tReturnAddress: returnAddress,\n\t\tSigningThreshold: signingThreshold,\n\t\tCurrentPeriodProgress: CurrentPeriodProgress{0, 0},\n\t\tVestingPeriodProgress: vestingPeriodProgress,\n\t\tDebtAfterFailedVesting: sdk.NewCoins(),\n\t}\n}", "func MakeNewAccount(name string) (*MyAccount, error) {\n\tkeys, err := NewKeypair()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &MyAccount{\n\t\tFields: make(map[string]string),\n\t\tKeys: keys,\n\t\tName: name,\n\t}, nil\n}", "func (c *CoinTest) newAccount(stub shim.ChaincodeStubInterface, args []string) pb.Response {\r\n\tvar id string\r\n\tvar asset int\r\n\tvar err error\r\n\r\n\tif len(args) == 1{\r\n\t\tid = args[0]\r\n\t\tasset = 0\r\n\t}else if len(args) == 2{\r\n\t\tid = args[0]\r\n\t\t//asset, err = strconv.Atoi(args[1])\r\n\t\t//if err != nil{\r\n\t\t//\treturn shim.Error(\"Invalid asset amount, expecting a integer value\")\r\n\t\t//}\r\n\t\tasset = 0;\r\n\t}else{\r\n\t\treturn shim.Error(\"Incorrect number of arguments.\")\r\n\t}\r\n\r\n\t//deliver 0 number of TolakCoin to user\r\n\ttolakCoin.Token.Deliver(token.Address(id), int(asset))\r\n\r\n\t//write to ledger\r\n\terr = stub.PutState(id, []byte(strconv.Itoa(asset)))\r\n\tif err != nil{\r\n\t\treturn shim.Error(err.Error())\r\n\t}\r\n\r\n\treturn shim.Success(nil)\r\n}", "func NewAccount(user, apiKey string) *Account {\n\treturn &Account{user: user, apiKey: apiKey}\n}", "func newServiceAccount(cr *argoprojv1a1.ArgoCD) *corev1.ServiceAccount {\n\treturn &corev1.ServiceAccount{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: cr.Name,\n\t\t\tNamespace: cr.Namespace,\n\t\t\tLabels: argoutil.LabelsForCluster(cr),\n\t\t},\n\t}\n}", "func NewAccount(txr *repository.Transactioner) repository.Account {\n\treturn &account{txr: txr}\n}", "func NewAccount(\n\tconfig *accounts.AccountConfig,\n\taccountCoin *Coin,\n\thttpClient *http.Client,\n\tlog *logrus.Entry,\n) *Account {\n\tlog = log.WithField(\"group\", \"eth\").\n\t\tWithFields(logrus.Fields{\"coin\": accountCoin.String(), \"code\": config.Config.Code, \"name\": config.Config.Name})\n\tlog.Debug(\"Creating new account\")\n\n\taccount := &Account{\n\t\tBaseAccount: accounts.NewBaseAccount(config, accountCoin, log),\n\t\tcoin: accountCoin,\n\t\tdbSubfolder: \"\", // set in Initialize()\n\t\tsigningConfiguration: nil,\n\t\thttpClient: httpClient,\n\t\tbalance: coin.NewAmountFromInt64(0),\n\n\t\tenqueueUpdateCh: make(chan struct{}),\n\t\tquitChan: make(chan struct{}),\n\n\t\tlog: log,\n\t}\n\n\treturn account\n}", "func NewPeriodicVestingAccountRaw(bva *BaseVestingAccount, startTime int64, periods Periods) *PeriodicVestingAccount {\n\treturn &PeriodicVestingAccount{\n\t\tBaseVestingAccount: bva,\n\t\tStartTime: startTime,\n\t\tVestingPeriods: periods,\n\t}\n}", "func NewTrainCar() TrainCar {\n c := TrainCar{name: \"TrainCar\", vehicle: \"TrainCar\", speed: 30, capacity: 30, railway: \"CNR\"}\n return c\n}", "func (ws *WebServer) NewAccount(c *gin.Context) {\n\tnetwork := ws.nodeConfig.GetNetwork()\n\tif network == \"\" {\n\t\tReturnError(c, 500, ErrorNoNetwork.Error())\n\t\treturn\n\t}\n\tn := sdk.Testnet\n\tif network == \"bitmark\" {\n\t\tn = sdk.Livenet\n\t}\n\tseedFile := filepath.Join(ws.rootPath, \"bitmarkd\", network, \"proof.sign\")\n\tif _, err := os.Stat(seedFile); err == nil {\n\t\tReturnError(c, 500, ErrorNoSeedFile.Error())\n\t\treturn\n\t}\n\n\ta, err := sdk.NewAccount(n)\n\tif err != nil {\n\t\tReturnError(c, 500, ErrorCreateAccount.Error())\n\t\treturn\n\t}\n\tseed := a.Seed()\n\n\tf, err := os.OpenFile(seedFile, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0600)\n\tif err != nil {\n\t\tReturnError(c, 500, ErrorOpenSeedFile.Error())\n\t\treturn\n\t}\n\tdefer f.Close()\n\n\t_, err = f.WriteString(fmt.Sprintf(\"SEED:%s\", seed))\n\tif err != nil {\n\t\tReturnError(c, 500, ErrorToWriteSeedFile.Error())\n\t\treturn\n\t}\n\tws.SetAccount(a.AccountNumber(), seed, network) // Record in AccountInfo in memory\n\terr = ws.saveAcct()\n\tif nil != err {\n\t\tReturnError(c, 500, ErrorAutoSaveAccount.Error())\n\t\treturn\n\n\t}\n\tc.JSON(200, map[string]interface{}{\n\t\t\"ok\": 1,\n\t})\n}", "func (e Account) EntNew() ent.Ent { return &Account{} }", "func (e Account) EntNew() ent.Ent { return &Account{} }", "func NewAccount() *Account {\n\n\tcreatedAccount := Account{}\n\n\tnewPrivateKey, err := generatePrivateKey(4096)\n\tif err != nil {\n\t\tlog.Fatal(\"Error generating rsa private key \", err)\n\t}\n\tnewPublicKey, err := generatePublicKey(&newPrivateKey.PublicKey)\n\tif err != nil {\n\t\tlog.Fatal(\"Error generating rsa public key \", err)\n\t}\n\tcreatedAccount.privateKey = newPrivateKey\n\tcreatedAccount.Address = string(newPublicKey)\n\tcreatedAccount.Amount = 0\n\n\treturn &createdAccount\n}", "func New(ccHost, username, password, clusterID, clusterToken string) *ContrailCommand {\n\treturn &ContrailCommand{\n\t\tAuthHost: ccHost,\n\t\tUsername: username,\n\t\tPassword: password,\n\t\tClusterID: clusterID,\n\t\tClusterToken: clusterToken,\n\t\tAuthPath: \"/keystone/v3/auth/tokens\",\n\t\tUserDomain: \"default\",\n\t\tProjectName: \"admin\",\n\t\tProjectDomain: \"default\",\n\t}\n}", "func NewMsgCreatePeriodicVestingAccount(fromAddr, toAddr sdk.AccAddress, startTime int64, periods []Period) *MsgCreatePeriodicVestingAccount {\n\treturn &MsgCreatePeriodicVestingAccount{\n\t\tFromAddress: fromAddr.String(),\n\t\tToAddress: toAddr.String(),\n\t\tStartTime: startTime,\n\t\tVestingPeriods: periods,\n\t}\n}", "func (ak AccountKeeper) NewAccount(ctx sdk.Context, acc exported.Account) exported.Account {\n\t// FIXME: update account number\n\treturn acc\n}", "func newServiceAccountWithName(name string, cr *argoprojv1a1.ArgoCD) *corev1.ServiceAccount {\n\tsa := newServiceAccount(cr)\n\tsa.ObjectMeta.Name = getServiceAccountName(cr.Name, name)\n\n\tlbls := sa.ObjectMeta.Labels\n\tlbls[common.ArgoCDKeyName] = name\n\tsa.ObjectMeta.Labels = lbls\n\n\treturn sa\n}", "func NewAccount(acc *types.Account) *Account {\n\treturn &Account{\n\t\tAccount: *acc,\n\t}\n}", "func NewAccount(id string, name string, primary bool, type_ string, currency Currency, balance AccountBalance, createdAt time.Time, updatedAt time.Time, resource string, resourcePath string, ready bool) *Account {\n\tthis := Account{}\n\tthis.Id = id\n\tthis.Name = name\n\tthis.Primary = primary\n\tthis.Type = type_\n\tthis.Currency = currency\n\tthis.Balance = balance\n\tthis.CreatedAt = createdAt\n\tthis.UpdatedAt = updatedAt\n\tthis.Resource = resource\n\tthis.ResourcePath = resourcePath\n\tthis.Ready = ready\n\treturn &this\n}", "func NewMsgCreateVestingAccount(fromAddr, toAddr sdk.AccAddress, amount sdk.Coins, endTime int64, delayed bool) *MsgCreateVestingAccount {\n\treturn &MsgCreateVestingAccount{\n\t\tFromAddress: fromAddr.String(),\n\t\tToAddress: toAddr.String(),\n\t\tAmount: amount,\n\t\tEndTime: endTime,\n\t\tDelayed: delayed,\n\t}\n}", "func NewAccount(owner string) *Account {\n\treturn &Account{owner: owner, balance: 0}\n}", "func NewAccount(opts ...AccountCreationOption) (*Account, error) {\n\taccount := &Account{\n\t\tBalance: big.NewInt(0),\n\t\tvotingWeight: big.NewInt(0),\n\t\taccountType: 1,\n\t}\n\tfor _, opt := range opts {\n\t\tif err := opt(account); err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"failed to apply account creation option\")\n\t\t}\n\t}\n\treturn account, nil\n}", "func (account *Account) New() {\n\n\tparams, _ := pbc.NewParamsFromString(crypto.Params)\n\tpairing := params.NewPairing()\n\n\tA := pairing.NewG1()\n\tAT := pairing.NewG1()\n\ta := pairing.NewZr()\n\n\ta.Rand()\n\n\tG := pairing.NewG1()\n\tT := pairing.NewG1()\n\tG.SetString(crypto.G, 10)\n\tT.SetString(crypto.T, 10)\n\n\tA.PowZn(G, a)\n\tAT.PowZn(T, a)\n\n\taccount.a = a.String()\n\taccount.A = A.String()\n\taccount.AT = AT.String()\n}", "func NewAccount(val string) AccountField {\n\treturn AccountField{quickfix.FIXString(val)}\n}", "func NewAllocAccount(val string) AllocAccountField {\n\treturn AllocAccountField{quickfix.FIXString(val)}\n}", "func NewAccount() *Account {\n\tacc := &Account{}\n\tpriv, pub := newKeyPair()\n\tacc.PriKey = priv\n\tacc.PubKey = pub\n\treturn acc\n}", "func NewAccount(addr, amount string) *Account {\n\tam := big.NewInt(0)\n\tam.SetString(amount, 0)\n\treturn &Account{Address: addr, Amount: am}\n}", "func NewAccount(firstName string) *Account {\n\tthis := Account{}\n\tthis.FirstName = firstName\n\treturn &this\n}", "func NewAccount(instanceID uuid.UUID, name, aud string) (*Account, error) {\n\tid, err := uuid.NewV4()\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"Error generating unique id\")\n\t}\n\n\taccount := &Account{\n\t\tInstanceID: instanceID,\n\t\tID: id,\n\t\tAud: aud,\n\t\tName: name,\n\t}\n\treturn account, nil\n}", "func NewValidatorVestingAccountRaw(bva *vestingtypes.BaseVestingAccount,\n\tstartTime int64, periods vestingtypes.Periods, validatorAddress sdk.ConsAddress, returnAddress sdk.AccAddress, signingThreshold int64) *ValidatorVestingAccount {\n\n\tpva := &vestingtypes.PeriodicVestingAccount{\n\t\tBaseVestingAccount: bva,\n\t\tStartTime: startTime,\n\t\tVestingPeriods: periods,\n\t}\n\tvar vestingPeriodProgress []VestingProgress\n\tfor i := 0; i < len(periods); i++ {\n\t\tvestingPeriodProgress = append(vestingPeriodProgress, VestingProgress{false, false})\n\t}\n\n\treturn &ValidatorVestingAccount{\n\t\tPeriodicVestingAccount: pva,\n\t\tValidatorAddress: validatorAddress,\n\t\tReturnAddress: returnAddress,\n\t\tSigningThreshold: signingThreshold,\n\t\tCurrentPeriodProgress: CurrentPeriodProgress{0, 0},\n\t\tVestingPeriodProgress: vestingPeriodProgress,\n\t\tDebtAfterFailedVesting: sdk.NewCoins(),\n\t}\n}", "func (w *Wallet) NewAccount(index *uint32) (a *Account, err error) {\n\tindex2 := w.nextIndex\n\tif index != nil {\n\t\tindex2 = *index\n\t}\n\ta = &Account{w: w, index: index2}\n\tif err = w.impl.deriveAccount(a); err != nil {\n\t\treturn\n\t}\n\tpubkeyToAddress := util.PubkeyToAddress\n\tif w.isBanano {\n\t\tpubkeyToAddress = util.PubkeyToBananoAddress\n\t}\n\tif a.address, err = pubkeyToAddress(a.pubkey); err != nil {\n\t\treturn\n\t}\n\tif index == nil {\n\t\tw.nextIndex++\n\t}\n\tif _, ok := w.accounts[a.address]; !ok {\n\t\tw.accounts[a.address] = a\n\t} else if index == nil {\n\t\treturn w.NewAccount(nil)\n\t}\n\treturn\n}", "func NewDelayedVestingAccountRaw(bva *BaseVestingAccount) *DelayedVestingAccount {\n\treturn &DelayedVestingAccount{\n\t\tBaseVestingAccount: bva,\n\t}\n}", "func NewAccount(email string) *Account {\n\treturn &Account{email: email}\n}", "func newReconciledServiceAccount() *corev1.ServiceAccount {\n\treturn NewServiceAccount(newEventSource())()\n}", "func NewAccount(newid AccountIDType, newemail string) *Account {\n\treturn &Account{\n\t\tid: newid,\n\t\temail: newemail,\n\t}\n}", "func NewAccount(id string) esfazz.Aggregate {\n\tacc := AccountModel()\n\tacc.Id = id\n\treturn acc\n}", "func newServiceAccount(cr *storagev1.CSIPowerMaxRevProxy) *v1.ServiceAccount {\n\treturn &v1.ServiceAccount{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: ReverseProxyName,\n\t\t\tNamespace: cr.Namespace,\n\t\t\tOwnerReferences: getOwnerReferences(cr),\n\t\t},\n\t}\n}", "func (c Client) NewAccount(privateKey crypto.Signer, onlyReturnExisting, termsOfServiceAgreed bool, contact ...string) (Account, error) {\n\tvar opts []NewAccountOptionFunc\n\tif onlyReturnExisting {\n\t\topts = append(opts, NewAcctOptOnlyReturnExisting())\n\t}\n\tif termsOfServiceAgreed {\n\t\topts = append(opts, NewAcctOptAgreeTOS())\n\t}\n\tif contact != nil && len(contact) > 0 {\n\t\topts = append(opts, NewAcctOptWithContacts(contact...))\n\t}\n\n\treturn c.NewAccountOptions(privateKey, opts...)\n}", "func NewAccount(address string) *Account {\n\treturn &Account{\n\t\tAddress: address,\n\t\tHeight: \"0\",\n\t\tGoldTokenBalance: \"0\",\n\t\tTotalLockedGoldBalance: \"0\",\n\t\tNonVotingLockedGoldBalance: \"0\",\n\t\tVotingLockedGoldBalance: \"0\",\n\t\tPendingWithdrawalBalance: \"0\",\n\t\tCeloUSDValue: \"0\",\n\t\tDelegations: []*Delegation{},\n\t}\n\n}", "func newJiraPVC(j *v1alpha1.Jira) error {\n\tif !j.IsPVEnabled() {\n\t\treturn nil\n\t}\n\tpvc := &v1.PersistentVolumeClaim{\n\t\tTypeMeta: metav1.TypeMeta{\n\t\t\tKind: \"PersistentVolumeClaim\",\n\t\t\tAPIVersion: \"v1\",\n\t\t},\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: j.Name,\n\t\t\tNamespace: j.Namespace,\n\t\t\tLabels: jiraLabels(j),\n\t\t},\n\t\tSpec: *j.Spec.Pod.PersistentVolumeClaimSpec,\n\t}\n\treturn createResource(j, pvc)\n}", "func newVppAgentComposite(configuration *common.NSConfiguration) *vppagentComposite {\n\t// ensure the env variables are processed\n\tif configuration == nil {\n\t\tconfiguration = &common.NSConfiguration{}\n\t}\n\tconfiguration.CompleteNSConfiguration()\n\n\tnewVppAgentComposite := &vppagentComposite{\n\t\tvppAgentEndpoint: defaultVPPAgentEndpoint,\n\t\tworkspace: configuration.Workspace,\n\t}\n\tif err := newVppAgentComposite.Reset(); err != nil {\n\t\treturn nil\n\t}\n\n\treturn newVppAgentComposite\n}", "func NewFundedAccount() *keypair.Full {\n\tkp, err := keypair.Random()\n\tif err != nil {\n\t\tlog.Fatal(err, \"generating random keypair\")\n\t}\n\terr = FundAccount(kp.Address())\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tlog.Printf(\"successfully funded %s\", kp.Address())\n\treturn kp\n}", "func (m *MockIAccountController) NewAccount(c *gin.Context) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"NewAccount\", c)\n}", "func NewAccount(addr *Address) *Account {\n\treturn &Account{\n\t\taccount: common.NewAccount(common.BytesToAddress(addr.Bytes())),\n\t}\n}", "func NewAccount() *Account {\n\tpriv, _ := ecdsa.GenerateKey(crypto.S256(), cryptorand.Reader)\n\tpub := base64.URLEncoding.EncodeToString(\n\t\tcrypto.FromECDSAPub(&priv.PublicKey))\n\taddr := hex.EncodeToString(crypto.PubkeyToAddress(priv.PublicKey).Bytes())\n\treturn &Account{\n\t\tID: NewUUID(),\n\t\tEthAddr: addr,\n\t\tPublicKey: pub,\n\t\tPrivateKey: base64.URLEncoding.EncodeToString(crypto.FromECDSA(priv)),\n\t}\n}", "func NewAccount(username string) (*AccountRow, error) {\n\tquery := `\n\t\tinsert into accounts (user_name)\n\t\t\tvalues ($1)\n\t\t\ton conflict (user_name)\n\t\t\t\tdo nothing\n\t\treturning\n\t\t\tid, user_name`\n\n\trowData := &AccountRow{}\n\trow := GlobalConn.QueryRow(query, username)\n\n\tif err := row.Scan(&rowData.ID, &rowData.Name); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn rowData, nil\n}", "func createRequestAccount() *data.Account {\n\taccount := test.NewAccountDataFromFile(\"create-request.json\")\n\treturn &account.Account\n}", "func NewCoinbase(proof, score, R []byte) *Coinbase {\n\treturn &Coinbase{\n\t\tProof: proof,\n\t\tScore: score,\n\t\tR: R,\n\t}\n}", "func NewAccount(id, entityID string) *Account {\n\treturn &Account{\n\t\tID: id,\n\t\tEntityID: entityID,\n\t\tWallets: make([]Wallet, 0),\n\t}\n}", "func (*tenantR) NewStruct() *tenantR {\n\treturn &tenantR{}\n}", "func (ga *GenesisAccount) ToAccount() auth.Account {\n\tbacc := &auth.BaseAccount{\n\t\tAddress: ga.Address,\n\t\tCoins: ga.Coins.Sort(),\n\t\tAccountNumber: ga.AccountNumber,\n\t\tSequence: ga.Sequence,\n\t}\n\n\tif !ga.OriginalVesting.IsZero() {\n\t\tbaseVestingAcc := &auth.BaseVestingAccount{\n\t\t\tBaseAccount: bacc,\n\t\t\tOriginalVesting: ga.OriginalVesting,\n\t\t\tDelegatedFree: ga.DelegatedFree,\n\t\t\tDelegatedVesting: ga.DelegatedVesting,\n\t\t\tEndTime: ga.EndTime,\n\t\t}\n\n\t\tif ga.StartTime != 0 && ga.EndTime != 0 {\n\t\t\treturn &auth.ContinuousVestingAccount{\n\t\t\t\tBaseVestingAccount: baseVestingAcc,\n\t\t\t\tStartTime: ga.StartTime,\n\t\t\t}\n\t\t} else if ga.EndTime != 0 {\n\t\t\treturn &auth.DelayedVestingAccount{\n\t\t\t\tBaseVestingAccount: baseVestingAcc,\n\t\t\t}\n\t\t} else {\n\t\t\tpanic(fmt.Sprintf(\"invalid genesis vesting account: %+v\", ga))\n\t\t}\n\t}\n\n\treturn bacc\n}", "func (controller *Auth) CreateNewAccount() {\n\tpage := \"register-form-page\"\n\tcontroller.RegisterCaptchaAction(page)\n\n\tif !controller.IsCaptchaValid(page) {\n\t\tcontroller.DisplaySimpleError(\"Please enter a valid code!\")\n\t} else {\n\t\tcontroller.createNewAccount()\n\t}\n}", "func newTestContext() (tc *testContext, err error) {\n\ttc = new(testContext)\n\n\tconst genesisHash = \"0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e2206\"\n\tif tc.netParams, err = tc.createNetParams(genesisHash); err != nil {\n\t\treturn\n\t}\n\n\tconst block1Hex = \"0000002006226e46111a0b59caaf126043eb5bbf28c34f3a5e332a1fc7b2b73cf188910fadbb20ea41a8423ea937e76e8151636bf6093b70eaff942930d20576600521fdc30f9858ffff7f20000000000101000000010000000000000000000000000000000000000000000000000000000000000000ffffffff03510101ffffffff0100f2052a010000001976a9143ca33c2e4446f4a305f23c80df8ad1afdcf652f988ac00000000\"\n\tif tc.block1, err = blockFromHex(block1Hex); err != nil {\n\t\terr = fmt.Errorf(\"Failed to parse serialized block: %v\", err)\n\t\treturn\n\t}\n\n\tconst fundingInputPrivKeyHex = \"6bd078650fcee8444e4e09825227b801a1ca928debb750eb36e6d56124bb20e8\"\n\ttc.fundingInputPrivKey, err = privkeyFromHex(fundingInputPrivKeyHex)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Failed to parse serialized privkey: %v\", err)\n\t\treturn\n\t}\n\n\tconst localFundingPrivKeyHex = \"30ff4956bbdd3222d44cc5e8a1261dab1e07957bdac5ae88fe3261ef321f3749\"\n\ttc.localFundingPrivKey, err = privkeyFromHex(localFundingPrivKeyHex)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Failed to parse serialized privkey: %v\", err)\n\t\treturn\n\t}\n\n\tconst localPaymentPrivKeyHex = \"bb13b121cdc357cd2e608b0aea294afca36e2b34cf958e2e6451a2f274694491\"\n\ttc.localPaymentPrivKey, err = privkeyFromHex(localPaymentPrivKeyHex)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Failed to parse serialized privkey: %v\", err)\n\t\treturn\n\t}\n\n\tconst localFundingPubKeyHex = \"023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb\"\n\ttc.localFundingPubKey, err = pubkeyFromHex(localFundingPubKeyHex)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Failed to parse serialized pubkey: %v\", err)\n\t\treturn\n\t}\n\n\tconst remoteFundingPubKeyHex = \"030e9f7b623d2ccc7c9bd44d66d5ce21ce504c0acf6385a132cec6d3c39fa711c1\"\n\ttc.remoteFundingPubKey, err = pubkeyFromHex(remoteFundingPubKeyHex)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Failed to parse serialized pubkey: %v\", err)\n\t\treturn\n\t}\n\n\tconst localRevocationPubKeyHex = \"0212a140cd0c6539d07cd08dfe09984dec3251ea808b892efeac3ede9402bf2b19\"\n\ttc.localRevocationPubKey, err = pubkeyFromHex(localRevocationPubKeyHex)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Failed to parse serialized pubkey: %v\", err)\n\t\treturn\n\t}\n\n\tconst localPaymentPubKeyHex = \"030d417a46946384f88d5f3337267c5e579765875dc4daca813e21734b140639e7\"\n\ttc.localPaymentPubKey, err = pubkeyFromHex(localPaymentPubKeyHex)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Failed to parse serialized pubkey: %v\", err)\n\t\treturn\n\t}\n\n\tconst remotePaymentPubKeyHex = \"0394854aa6eab5b2a8122cc726e9dded053a2184d88256816826d6231c068d4a5b\"\n\ttc.remotePaymentPubKey, err = pubkeyFromHex(remotePaymentPubKeyHex)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Failed to parse serialized pubkey: %v\", err)\n\t\treturn\n\t}\n\n\tconst localDelayPubKeyHex = \"03fd5960528dc152014952efdb702a88f71e3c1653b2314431701ec77e57fde83c\"\n\ttc.localDelayPubKey, err = pubkeyFromHex(localDelayPubKeyHex)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Failed to parse serialized pubkey: %v\", err)\n\t\treturn\n\t}\n\n\tconst commitmentPointHex = \"025f7117a78150fe2ef97db7cfc83bd57b2e2c0d0dd25eaf467a4a1c2a45ce1486\"\n\ttc.commitmentPoint, err = pubkeyFromHex(commitmentPointHex)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Failed to parse serialized pubkey: %v\", err)\n\t\treturn\n\t}\n\n\tconst localPaymentBasePointHex = \"034f355bdcb7cc0af728ef3cceb9615d90684bb5b2ca5f859ab0f0b704075871aa\"\n\ttc.localPaymentBasePoint, err = pubkeyFromHex(localPaymentBasePointHex)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Failed to parse serialized pubkey: %v\", err)\n\t\treturn\n\t}\n\n\tconst remotePaymentBasePointHex = \"032c0b7cf95324a07d05398b240174dc0c2be444d96b159aa6c7f7b1e668680991\"\n\ttc.remotePaymentBasePoint, err = pubkeyFromHex(remotePaymentBasePointHex)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Failed to parse serialized pubkey: %v\", err)\n\t\treturn\n\t}\n\n\tconst fundingChangeAddressStr = \"bcrt1qgyeqfmptyh780dsk32qawsvdffc2g5q5sxamg0\"\n\ttc.fundingChangeAddress, err = btcutil.DecodeAddress(\n\t\tfundingChangeAddressStr, tc.netParams)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Failed to parse address: %v\", err)\n\t\treturn\n\t}\n\n\ttc.fundingInputUtxo, tc.fundingInputTxOut, err = tc.extractFundingInput()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tconst fundingTxHex = \"0200000001adbb20ea41a8423ea937e76e8151636bf6093b70eaff942930d20576600521fd000000006b48304502210090587b6201e166ad6af0227d3036a9454223d49a1f11839c1a362184340ef0240220577f7cd5cca78719405cbf1de7414ac027f0239ef6e214c90fcaab0454d84b3b012103535b32d5eb0a6ed0982a0479bbadc9868d9836f6ba94dd5a63be16d875069184ffffffff028096980000000000220020c015c4a6be010e21657068fc2e6a9d02b27ebe4d490a25846f7237f104d1a3cd20256d29010000001600143ca33c2e4446f4a305f23c80df8ad1afdcf652f900000000\"\n\tif tc.fundingTx, err = txFromHex(fundingTxHex); err != nil {\n\t\terr = fmt.Errorf(\"Failed to parse serialized tx: %v\", err)\n\t\treturn\n\t}\n\n\ttc.fundingOutpoint = wire.OutPoint{\n\t\tHash: *tc.fundingTx.Hash(),\n\t\tIndex: 0,\n\t}\n\n\ttc.shortChanID = lnwire.ShortChannelID{\n\t\tBlockHeight: 1,\n\t\tTxIndex: 0,\n\t\tTxPosition: 0,\n\t}\n\n\thtlcData := []struct {\n\t\tincoming bool\n\t\tamount lnwire.MilliSatoshi\n\t\texpiry uint32\n\t\tpreimage string\n\t}{\n\t\t{\n\t\t\tincoming: true,\n\t\t\tamount: 1000000,\n\t\t\texpiry: 500,\n\t\t\tpreimage: \"0000000000000000000000000000000000000000000000000000000000000000\",\n\t\t},\n\t\t{\n\t\t\tincoming: true,\n\t\t\tamount: 2000000,\n\t\t\texpiry: 501,\n\t\t\tpreimage: \"0101010101010101010101010101010101010101010101010101010101010101\",\n\t\t},\n\t\t{\n\t\t\tincoming: false,\n\t\t\tamount: 2000000,\n\t\t\texpiry: 502,\n\t\t\tpreimage: \"0202020202020202020202020202020202020202020202020202020202020202\",\n\t\t},\n\t\t{\n\t\t\tincoming: false,\n\t\t\tamount: 3000000,\n\t\t\texpiry: 503,\n\t\t\tpreimage: \"0303030303030303030303030303030303030303030303030303030303030303\",\n\t\t},\n\t\t{\n\t\t\tincoming: true,\n\t\t\tamount: 4000000,\n\t\t\texpiry: 504,\n\t\t\tpreimage: \"0404040404040404040404040404040404040404040404040404040404040404\",\n\t\t},\n\t}\n\n\ttc.htlcs = make([]channeldb.HTLC, len(htlcData))\n\tfor i, htlc := range htlcData {\n\t\tpreimage, decodeErr := hex.DecodeString(htlc.preimage)\n\t\tif decodeErr != nil {\n\t\t\terr = fmt.Errorf(\"Failed to decode HTLC preimage: %v\", decodeErr)\n\t\t\treturn\n\t\t}\n\n\t\ttc.htlcs[i].RHash = sha256.Sum256(preimage)\n\t\ttc.htlcs[i].Amt = htlc.amount\n\t\ttc.htlcs[i].RefundTimeout = htlc.expiry\n\t\ttc.htlcs[i].Incoming = htlc.incoming\n\t}\n\n\ttc.localCsvDelay = 144\n\ttc.fundingAmount = 10000000\n\ttc.dustLimit = 546\n\ttc.feePerKW = 15000\n\n\treturn\n}", "func newDummyCredit(t *testing.T, dbtx walletdb.ReadWriteTx, pool *Pool, series uint32, index Index, branch Branch,\n\ttxHash []byte, outpointIdx uint32) Credit {\n\tvar hash chainhash.Hash\n\tif err := hash.SetBytes(txHash); err != nil {\n\t\tt.Fatal(err)\n\t}\n\t// Ensure the address defined by the given series/branch/index is present on\n\t// the set of used addresses as that's a requirement of WithdrawalAddress.\n\tTstEnsureUsedAddr(t, dbtx, pool, series, branch, index)\n\taddr := TstNewWithdrawalAddress(t, dbtx, pool, series, branch, index)\n\tc := wtxmgr.Credit{\n\t\tOutPoint: wire.OutPoint{\n\t\t\tHash: hash,\n\t\t\tIndex: outpointIdx,\n\t\t},\n\t}\n\treturn newCredit(c, *addr)\n}", "func NewAccount(file string) (*AccountRoot, error) {\n\tif file == \"\" {\n\t\treturn nil, errors.New(\"config file should be passed\")\n\t}\n\n\tvar err error\n\tconf, err := loadAccount(file)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// debug\n\t// grok.Value(conf)\n\n\t// validate\n\tif err = conf.validate(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn conf, nil\n}", "func (controller *AccountController) NewAccount(ctx *gin.Context) {\n\tname, ok := ctx.GetPostForm(\"name\")\n\tif !ok {\n\t\tlog.WithFields(log.Fields{\"URL\": ctx.Request.URL.String()}).Warn(\"No name found in postform\")\n\n\t\terrResp, _ := restapi.NewErrorResponse(\"No name given\").Marshal()\n\t\tfmt.Fprint(ctx.Writer, string(errResp))\n\t\tctx.Abort()\n\t\treturn\n\t}\n\n\tinfo, err := authStuff.GetLoginInfoFromCtx(ctx)\n\tif err != nil {\n\t\tresponse, _ := restapi.NewErrorResponse(err.Error()).Marshal()\n\t\tfmt.Fprint(ctx.Writer, string(response))\n\t\tctx.Abort()\n\t\treturn\n\t}\n\n\tacc, err := controller.service.CreateAdd(name, info.Name, permissions.CRUD)\n\tif err != nil {\n\t\tlog.WithFields(log.Fields{\"user\": info.Name}).WithError(err).Error(\"Account Error New\")\n\n\t\tresponse, _ := restapi.NewErrorResponse(\"Couldn't create account: \" + err.Error()).Marshal()\n\t\tfmt.Fprint(ctx.Writer, string(response))\n\t\tctx.Abort()\n\t\treturn\n\t}\n\tresponse, _ := restapi.NewOkResponse(acc).Marshal()\n\tfmt.Fprint(ctx.Writer, string(response))\n\tctx.Next()\n}", "func (*ACMEIssuer) newAccount(email string) (acme.Account, error) {\n\tvar acct acme.Account\n\tif email != \"\" {\n\t\tacct.Contact = []string{\"mailto:\" + email} // TODO: should we abstract the contact scheme?\n\t}\n\tprivateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)\n\tif err != nil {\n\t\treturn acct, fmt.Errorf(\"generating private key: %v\", err)\n\t}\n\tacct.PrivateKey = privateKey\n\treturn acct, nil\n}", "func New() *Accounts {\n\treturn &Accounts{\n\t\tdata: make(map[string]*Account),\n\t}\n}", "func tNewUser(lbl string) *tUser {\n\tintBytes := make([]byte, 4)\n\tbinary.BigEndian.PutUint32(intBytes, acctCounter)\n\tacctID := account.AccountID{}\n\tcopy(acctID[:], acctTemplate[:])\n\tcopy(acctID[account.HashSize-4:], intBytes)\n\taddr := strconv.Itoa(int(acctCounter))\n\tsig := []byte{0xab} // Just to differentiate from the addr.\n\tsig = append(sig, intBytes...)\n\tsigHex := hex.EncodeToString(sig)\n\tacctCounter++\n\treturn &tUser{\n\t\tsig: sig,\n\t\tsigHex: sigHex,\n\t\tacct: acctID,\n\t\taddr: addr,\n\t\tlbl: lbl,\n\t}\n}", "func NewTestAccount(sb *collections.SchemaBuilder) (TestAccount, error) {\n\tta := TestAccount{\n\t\tItem: collections.NewItem(sb, itemPrefix, \"test\", collections.Uint64Value),\n\t}\n\treturn ta, nil\n}", "func (c *AccountController) Create(ctx echo.Context) error {\n\tmodel := account.Account{}\n\terr := ctx.Bind(&model)\n\tif err != nil {\n\t\treturn ctx.JSON(http.StatusUnprocessableEntity, err.Error())\n\t}\n\n\tres, err := c.AccountUsecase.Create(&model)\n\tif err != nil {\n\t\treturn ctx.JSON(http.StatusInternalServerError, err.Error())\n\t}\n\n\treturn ctx.JSON(http.StatusCreated, res)\n}", "func NewGenesisAccount(aa *UserAccount) *GenesisAccount {\n\treturn &GenesisAccount{\n\t\tId: aa.Id,\n\t\tAddress: aa.Address,\n\t\tCoins: aa.Coins.Sort(),\n\t}\n}", "func (as *Service) Create(name, iamRole, externalID string) (*Account, error) {\n\n\tbody := map[string]map[string]string{\n\t\t\"account\": {\"name\": name},\n\t}\n\n\tlog.Printf(\"Making request %v\\n\", body)\n\treq, err := as.httpClient.NewRequest(http.MethodPost, \"/setup/account\", &body)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar v common.Response\n\t_, err = as.httpClient.Do(req, &v)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(v.Response.Items) == 0 {\n\t\treturn nil, errors.New(\"Couldn't create account\")\n\t}\n\tvar account Account\n\n\tfmt.Println(string(v.Response.Items[0]))\n\n\terr = json.Unmarshal(v.Response.Items[0], &account)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttime.Sleep(time.Second * 5)\n\n\terr = as.setupCloudCredentials(account.ID, iamRole, externalID)\n\n\tif err != nil {\n\t\t_ = as.Delete(account.ID)\n\t\treturn nil, err\n\t}\n\n\treturn &account, nil\n}", "func NewTransaction(p *requestParams) {\n\tw, r, c, u := p.w, p.r, p.c, p.u\n\n\td := json.NewDecoder(r.Body)\n\tvar request TransactionRequest\n\tif err := d.Decode(&request); err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tif len(request.Amounts) != len(request.Accounts) {\n\t\thttp.Error(w, \"Amounts and accounts of different lengths\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tdate, err := time.Parse(dateStringFormat, request.Date)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tuserKey := userKey(c, u)\n\ttransactionId := uuid.NewRandom().String()\n\taccountKeys := make([]*datastore.Key, len(request.Accounts))\n\tsplitKeys := make([]*datastore.Key, len(request.Accounts))\n\tsplits := make([]*transaction.Split, len(request.Accounts))\n\n\tfor i := range request.Accounts {\n\t\taccountKeys[i] = datastore.NewKey(c, \"Account\", \"\", request.Accounts[i], userKey)\n\t\tsplitKeys[i] = datastore.NewKey(c, \"Split\", transactionId, 0, accountKeys[i])\n\t\tsplits[i] = &transaction.Split{\n\t\t\tAmount: request.Amounts[i],\n\t\t\tAccount: request.Accounts[i],\n\t\t\tMemo: request.Memo,\n\t\t\tDate: date,\n\t\t}\n\t}\n\n\tx := transaction.NewTransaction()\n\tx.AddSplits(splits)\n\n\tif err := x.ValidateAmount(); err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\terr = datastore.RunInTransaction(c, func(c appengine.Context) error {\n\t\taccounts := make([]transaction.Account, len(accountKeys))\n\t\tif err := datastore.GetMulti(c, accountKeys, accounts); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfor i := range accounts {\n\t\t\tx.AddAccount(&accounts[i], accountKeys[i].IntID())\n\t\t}\n\n\t\tif err := x.Commit(); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tputStatus := make(chan error)\n\n\t\tgo func() {\n\t\t\t_, err := datastore.PutMulti(c, accountKeys, accounts)\n\t\t\tputStatus <- err\n\t\t}()\n\t\tgo func() {\n\t\t\t_, err := datastore.PutMulti(c, splitKeys, splits)\n\t\t\tputStatus <- err\n\t\t}()\n\n\t\terr := <-putStatus\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn <-putStatus\n\t}, nil)\n\tif err != nil {\n\t\t// TODO(cjc25): This might not be a 400: if e.g. datastore failed it should\n\t\t// be a 500. Interpret err and return the right thing.\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n}", "func newTx(ctx context.Context, drv dialect.Driver) (*txDriver, error) {\n\ttx, err := drv.Tx(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &txDriver{tx: tx, drv: drv}, nil\n}", "func newTx(ctx context.Context, drv dialect.Driver) (*txDriver, error) {\n\ttx, err := drv.Tx(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &txDriver{tx: tx, drv: drv}, nil\n}", "func (policy *ticketPolicy) OnCreateNewAccount(acc *types.Account) {\n}", "func CreateCreditAccount(chargeCh chan float64) *CreditAccount {\n\t//empty struct\n\tcreditAccount := &CreditAccount{}\n\n\tgo func(chargeCh chan float64) {\n\t\tfor amount := range chargeCh {\n\t\t\tcreditAccount.processPayment(amount)\n\t\t}\n\t}(chargeCh)\n\n\treturn creditAccount\n}", "func NewVc(vCapHint, cCapHint int) *Gini {\n\tg := &Gini{\n\t\txo: xo.NewSVc(vCapHint, cCapHint)}\n\n\treturn g\n}", "func NewScratchAccount(privKey []byte, pubKey []byte) (*ScratchAccount, error) {\n\tif len(privKey) > 0 {\n\t\treturn newScratchAccountFromPrivKey(privKey)\n\t} else {\n\t\treturn newScratchAccountFromPubKey(pubKey)\n\t}\n}", "func NewCoinbaseTX(to, data string) *Transaction {\n\tif data == \"\" {\n\t\trandData := make([]byte, 20)\n\t\t_, err := rand.Read(randData)\n\t\tif err != nil {\n\t\t\tlog.Panic(err)\n\t\t}\n\t\tdata = fmt.Sprintf(\"%x\", randData)\n\t}\n\ttxin := TXInput{[]byte{}, -1, nil, []byte(data)} // remember this tx need no previous tx output\n\ttxout := NewTXOutput(subsidy, to)\n\ttx := Transaction{nil, []TXInput{txin}, []TXOutput{*txout}}\n\ttx.ID = tx.Hash() // New way\n\treturn &tx\n}", "func CreateTestAccount(t *testing.T, store SimpleStore) api.Account {\n\tt.Helper()\n\n\tcreateQuery := `INSERT INTO accounts (username, email, status, form_type, form_version, external_id) VALUES ($1, $1, $2, $3, $4, $5) RETURNING id, username, email, status, form_type, form_version, external_id`\n\n\temail := randomEmail()\n\n\tresult := api.Account{}\n\n\texternalID := uuid.New().String()\n\n\tcreateErr := store.db.Get(&result, createQuery, email, api.StatusIncomplete, \"SF86\", \"2017-07\", externalID)\n\tif createErr != nil {\n\t\tt.Log(\"Failed to create Account\", createErr)\n\t\tt.Fatal()\n\t}\n\n\treturn result\n}", "func New(conn *bindings.Conn, id uint64) *Txn {\n\treturn &Txn{\n\t\tconn: conn,\n\t\tid: id,\n\t\tmachine: newMachine(),\n\t}\n}", "func golangciConstructor(project *Project) (*file, error) { //nolint:unparam // project is not needed when no variables\n\treturn newProjectFile(newFile(golangciIdentifier, golangciFilename, golangciTemplate))\n}", "func NewFoo() *Foo {\n return &Foo{}\n}", "func CreateAccount(t *testing.T) (priv *rsa.PrivateKey, address string) {\n\tvar err error\n\tpriv, err = rsa.GenerateKey(rand.Reader, 1024)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\taddress, err = PrivateKeyToAddress(priv)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\treturn\n}", "func accountCreate(ctx *cli.Context) error {\n\n\tdataDir := ctx.GlobalString(utils.DataDirFlag.Name)\n\t//get keyStoreDir from KeyStoreDirFlag, if not use the default value\n\tkeyStoreDir := ctx.GlobalString(utils.KeyStoreDirFlag.Name)\n\tif keyStoreDir == \"\" {\n\t\tkeyStoreDir = keystore.KeyStoreScheme\n\t}\n\tkeyStoreDir = filepath.Join(dataDir, keyStoreDir)\n\tpassword := getPassPhrase(\"Your new account is locked with a password. Please give a password. Do not forget this password.\", true, 0, utils.MakePasswordList(ctx))\n\t_, err := utils.NewAccount(keyStoreDir, password)\n\n\treturn err\n}", "func NewAccount(email string, password string) (*Account, error) {\n\taccount := &Account{Email: email}\n\tencryptedPassword, err := utils.Encrypt(password)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\taccount.ID = primitive.NewObjectID()\n\taccount.Password = string(encryptedPassword)\n\ttNow := time.Now()\n\taccount.CreatedAt = &tNow\n\taccount.repo = repoimpl.GetAccountRepo()\n\treturn account, nil\n}", "func (suite *serviceAccountSuite) serviceAccountSuiteNewNuxeo() *v1alpha1.Nuxeo {\n\treturn &v1alpha1.Nuxeo{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tNamespace: suite.namespace,\n\t\t},\n\t}\n}", "func NewTx(resource string, revision uint64, leases Set) *Tx {\n\treturn &Tx{\n\t\tresource: resource,\n\t\trevision: revision,\n\t\tleases: leases,\n\t}\n}", "func NewVerifyAccountCreated() *VerifyAccountCreated {\n\n\treturn &VerifyAccountCreated{}\n}", "func newVertex(x, y, theta, v, w float64, parent *Vertex) *Vertex {\n\treturn &Vertex{Point{X: x, Y: y, Theta: theta, V: v, W: w}, parent, nil}\n}", "func CreateAccount(u usecase.UseCase) gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\t\tvar a presenter.Account\n\t\terr := c.BindJSON(&a)\n\t\tif err != nil {\n\t\t\tresponseFailure(c, http.StatusText(http.StatusInternalServerError),\n\t\t\t\t\"Account can't be created\",\n\t\t\t\t\"Error when converting the parameters sent to json\", \"\", http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\n\t\tacc, err := u.NewAccount(&account.Account{\n\t\t\tID: a.ID, DocumentNumber: a.DocumentNumber,\n\t\t\tAvailableCreditLimit: a.AvailableCreditLimit,\n\t\t})\n\t\tif err != nil {\n\t\t\tresponseFailure(c, http.StatusText(http.StatusInternalServerError),\n\t\t\t\t\"Account can't be created\",\n\t\t\t\tfmt.Sprintf(\"Internal server error when creating a new account - datails err: %s\", err.Error()), \"\", http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t\tc.JSON(http.StatusCreated, acc)\n\t}\n}", "func newLocalClaimWithName(config *localTestConfig, name string) *v1.PersistentVolumeClaim {\n\tclaim := v1.PersistentVolumeClaim{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: name,\n\t\t\tNamespace: config.ns,\n\t\t},\n\t\tSpec: v1.PersistentVolumeClaimSpec{\n\t\t\tStorageClassName: &config.scName,\n\t\t\tAccessModes: []v1.PersistentVolumeAccessMode{\n\t\t\t\tv1.ReadWriteOnce,\n\t\t\t},\n\t\t\tResources: v1.ResourceRequirements{\n\t\t\t\tRequests: v1.ResourceList{\n\t\t\t\t\tv1.ResourceName(v1.ResourceStorage): resource.MustParse(testRequestSize),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\treturn &claim\n}", "func New() {\n\ttypeOfProject()\n}", "func (c Client) New(params *stripe.TreasuryCreditReversalParams) (*stripe.TreasuryCreditReversal, error) {\n\tcreditreversal := &stripe.TreasuryCreditReversal{}\n\terr := c.B.Call(\n\t\thttp.MethodPost,\n\t\t\"/v1/treasury/credit_reversals\",\n\t\tc.Key,\n\t\tparams,\n\t\tcreditreversal,\n\t)\n\treturn creditreversal, err\n}", "func (s Service) CreateNewAccount(ctx context.Context, acc *account.Account, password string) (id, url, tmpToken string, err error) {\n\tspan := s.tracer.MakeSpan(ctx, \"CreateNewAccount\")\n\tdefer span.Finish()\n\n\t// pass data in context\n\ts.passContext(&ctx)\n\n\tacc.FirstName = strings.TrimSpace(acc.FirstName)\n\tacc.Lastname = strings.TrimSpace(acc.Lastname)\n\tacc.Emails[0].Email = strings.TrimSpace(acc.Emails[0].Email)\n\tacc.Emails[0].Email = strings.ToLower(acc.Emails[0].Email)\n\tacc.Username = strings.ToLower(acc.Username)\n\tacc.Username = strings.TrimSpace(acc.Username)\n\n\tyear, month, day := acc.Birthday.Birthday.Date()\n\tacc.BirthdayDate = account.Date{\n\t\tDay: day,\n\t\tMonth: int(month),\n\t\tYear: year,\n\t}\n\n\terr = emptyValidator(acc.FirstName, acc.Lastname, acc.Username)\n\tif err != nil {\n\t\treturn \"\", \"\", \"\", err\n\t}\n\terr = fromTwoToSixtyFour(acc.FirstName)\n\tif err != nil {\n\t\treturn \"\", \"\", \"\", err\n\t}\n\terr = fromTwoToHundredTwentyEight(acc.Lastname)\n\tif err != nil {\n\t\treturn \"\", \"\", \"\", err\n\t}\n\n\terr = userNameValidator(acc.Username)\n\tif err != nil {\n\t\treturn \"\", \"\", \"\", err\n\t}\n\tif len(acc.Emails) > 0 {\n\t\terr = emailValidator(acc.Emails[0].Email)\n\t\tif err != nil {\n\t\t\treturn \"\", \"\", \"\", err\n\t\t}\n\t} else {\n\t\treturn \"\", \"\", \"\", errors.New(\"Please Enter Email\")\n\t}\n\terr = validPassword(password)\n\tif err != nil {\n\t\treturn \"\", \"\", \"\", err\n\t}\n\n\t// TODO: trim data!\n\t// TODO: make first letter capital in some fields!\n\n\t// check if email is not busy\n\tinUse, err := s.repository.Users.IsEmailAlreadyInUse(ctx, acc.Emails[0].Email)\n\tif err != nil {\n\t\ts.tracer.LogError(span, err)\n\t}\n\tif inUse {\n\t\terr = errors.New(\"this_email_already_in_use\") // TODO: how it return as gRPC status?\n\t\treturn\n\t}\n\n\t// check if usernmae is not busy\n\tusernameInUse, err := s.repository.Users.IsUsernameBusy(ctx, acc.Username)\n\tif err != nil {\n\t\ts.tracer.LogError(span, err)\n\t}\n\tif usernameInUse {\n\t\terr = errors.New(\"this_username_already_in_use\") // TODO: how it return as gRPC status?\n\t\treturn\n\t}\n\n\t// TODO: check phone is not busy yet (in future)\n\n\t// define location by IP address\n\tvar ip string\n\tmd, ok := metadata.FromIncomingContext(ctx)\n\tif !ok {\n\t\ts.tracer.LogError(span, errors.New(\"coudn't resolve ip address\"))\n\t} else {\n\t\tstrArr := md.Get(\"ip\")\n\t\tif len(strArr) > 0 {\n\t\t\tip = strArr[0]\n\t\t}\n\t}\n\tcountry, err := s.repository.GeoIP.GetCountryISOCode(net.ParseIP(ip))\n\tif err != nil {\n\t\ts.tracer.LogError(span, err)\n\t}\n\tif country != \"\" {\n\t\tacc.Location = &account.UserLocation{\n\t\t\tLocation: location.Location{\n\t\t\t\tCountry: &location.Country{\n\t\t\t\t\tID: country,\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t}\n\n\tid = acc.GenerateID()\n\turl = acc.GenerateURL()\n\tacc.Status = status.UserStatusNotActivated // set not_activated status\n\tacc.CreatedAt = time.Now() // set date of registration\n\tacc.Emails[0].Primary = true // set email as primary\n\tacc.Emails[0].GenerateID()\n\n\t// encode password\n\tencryptedPass, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)\n\tif err != nil {\n\t\ts.tracer.LogError(span, err)\n\t}\n\n\terr = s.repository.Users.SaveNewAccount(ctx, acc, string(encryptedPass))\n\tif err != nil {\n\t\ts.tracer.LogError(span, err)\n\t}\n\n\temptyString := \"\"\n\n\terr = s.repository.arrangoRepo.SaveUser(ctx, &arangorepo.User{\n\t\tID: acc.GetID(),\n\t\tCreatedAt: time.Now(),\n\t\tFirstname: acc.FirstName,\n\t\tLastname: acc.Lastname,\n\t\tStatus: \"ACTIVATED\",\n\t\tURL: acc.URL,\n\t\tPrimaryEmail: acc.Emails[0].Email,\n\t\tGender: arangorepo.Gender{\n\t\t\tGender: acc.Gender.Gender,\n\t\t\tType: &emptyString,\n\t\t},\n\t})\n\tif err != nil {\n\t\tlog.Println(\"arrangoRepo.SaveUser:\", err)\n\t}\n\n\tif acc.GetInvitedByID() != \"\" {\n\t\ts.AddGoldCoinsToWallet(ctx, acc.GetInvitedByID(), 1)\n\t}\n\n\t// generate tmp code for activation\n\ttmpCode, err := s.repository.Cache.CreateTemporaryCodeForEmailActivation(ctx, id, acc.Emails[0].Email)\n\tif err != nil {\n\t\ts.tracer.LogError(span, err)\n\t}\n\n\t// log.Println(\"activation code:\", tmpCode) // TODO: delete later\n\t// log.Println(\"user id:\", id) // TODO: delete later\n\n\t// send email\n\t// err = s.mailRPC.SendEmail(\n\t// \tctx,\n\t// \tacc.Emails[0].Email,\n\t// \tfmt.Sprint(\"<html><body><a target='_blank' href='https://\"+s.Host+\"/api/activate/user?token=\", tmpCode, \"&user_id=\", id, \"'>Activate</a></body></html>\")) // TODO: write template for message\n\t// if err != nil {\n\t// \ts.tracer.LogError(span, err)\n\t// }\n\t// // fmt.Println(fmt.Sprint(\"https://\"+s.Host+\"/api/activate/user?token=\", tmpCode, \"&user_id=\", id)) // TODO: delete later\n\n\t// emailMessage := fmt.Sprint(\"<html><body><a target='_blank' href='https://\"+s.Host+\"/api/activate/user?token=\", tmpCode, \"&user_id=\", id, \"'>Activate</a></body></html>\")\n\temailMessage := s.tpl.GetActivationMessage(fmt.Sprint( /*\"https://\"+s.Host+\"/api/activate/user?token=\", tmpCode, \"&user_id=\", id)*/ tmpCode))\n\t// log.Println(acc.Emails[0].Email, emailMessage)\n\n\terr = s.mq.SendEmail(acc.Emails[0].Email, \"Activation\", emailMessage)\n\tif err != nil {\n\t\ts.tracer.LogError(span, err)\n\t}\n\n\t// generate tmp token for not activated user\n\ttmpToken, err = s.repository.Cache.CreateTemporaryCodeForNotActivatedUser(id)\n\tif err != nil {\n\t\ts.tracer.LogError(span, err)\n\t}\n\n\terr = s.CreateWalletAccount(ctx, id)\n\tif err != nil {\n\t\ts.tracer.LogError(span, err)\n\t}\n\n\treturn id, url, tmpToken, nil\n}", "func CreateFaucetSubAccount(faucetName, faucetPasswd, faucetAddr string, subAccNum int) ([]types.AccountInfo, error) {\n\tvar (\n\t\tmethod = \"CreateFaucetSubAccount\"\n\t\tcreatedAccs, subAccs []types.AccountInfo\n\t)\n\n\tkeyChan := make(chan types.AccountInfo)\n\n\t// create sub account\n\tfor i := 1; i <= subAccNum; i++ {\n\t\tkeyName := fmt.Sprintf(\"%v_%v\", faucetName, i)\n\t\tgo CreateKey(keyName, keyChan)\n\t}\n\n\tcounter := 0\n\tfor {\n\t\taccInfo := <-keyChan\n\t\tif accInfo.Address != \"\" {\n\t\t\tcreatedAccs = append(createdAccs, accInfo)\n\t\t}\n\t\tcounter++\n\t\tif counter == subAccNum {\n\t\t\tlog.Printf(\"%v: all create sub faucet key goroutine over\\n\", method)\n\t\t\tlog.Printf(\"%v: except create %v accounts, successful create %v accounts\",\n\t\t\t\tmethod, subAccNum, len(createdAccs))\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// distribute token\n\n\t// get sender info\n\tsenderInfo := types.AccountInfo{\n\t\tLocalAccountName: faucetName,\n\t\tPassword: faucetPasswd,\n\t\tAddress: faucetAddr,\n\t}\n\taccInfo, err := account.GetAccountInfo(senderInfo.Address)\n\tif err != nil {\n\t\tlog.Printf(\"%v: get faucet info fail: %v\\n\", method, err)\n\t\treturn subAccs, err\n\t}\n\tsenderInfo.AccountNumber = accInfo.AccountNumber\n\tsenderSequence, err := helper.ConvertStrToInt64(accInfo.Sequence)\n\tif err != nil {\n\t\tlog.Printf(\"%v: convert sequence to int64 fail: %v\\n\", method, err)\n\t\treturn subAccs, err\n\t}\n\n\t// get transfer amount which equal senderBalance / subAccNum\n\tamt, err := parseCoins(accInfo.Coins)\n\tif err != nil {\n\t\tlog.Printf(\"%v: parse coin failed: %v\\n\", method, err)\n\t\treturn subAccs, err\n\t}\n\ttransferAmt := fmt.Sprintf(\"%v%s\", parseFloat64ToStr(amt/float64(subAccNum+1)), constants.Denom)\n\n\t// distribute token to created accounts\n\tfor _, acc := range createdAccs {\n\t\tsenderInfo.Sequence = fmt.Sprintf(\"%v\", senderSequence)\n\t\tacc, err := DistributeToken(senderInfo, acc, transferAmt)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"%v: distribute token to %v failed: %v\\n\",\n\t\t\t\tmethod, acc.LocalAccountName, err)\n\t\t} else {\n\t\t\tsubAccs = append(subAccs, acc)\n\t\t\tsenderSequence += 1\n\t\t}\n\t}\n\n\treturn subAccs, err\n}", "func NewAccount(email, password string) (*Account, error) {\n\thashedPassword, err := hash(password)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Account{\n\t\tEmail: email,\n\t\tPassword: hashedPassword,\n\t\tVerified: false,\n\t\tVerificationID: uuid.New().String(),\n\t}, nil\n}", "func NewServiceAccount(name string, namespace string, operatorVersion string) *corev1.ServiceAccount {\n\treturn &corev1.ServiceAccount{\n\t\tTypeMeta: metav1.TypeMeta{\n\t\t\tAPIVersion: \"v1\",\n\t\t\tKind: \"ServiceAccount\",\n\t\t},\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tNamespace: namespace,\n\t\t\tName: name,\n\t\t\tLabels: map[string]string{\n\t\t\t\tmrv1.SchemeGroupVersion.Group: \"\",\n\t\t\t\tmrv1.SchemeGroupVersion.Group + \"/version\": operatorVersion,\n\t\t\t},\n\t\t},\n\t}\n}", "func CreateAccount (owner string) *Account {\n\taccount := Account{owner: owner, balance: 0}\n\treturn &account\n}", "func New(OrganisationID string, BaseURL string) *Client {\n\tconfig := config{\n\t\tURL: BaseURL,\n\t\tOrganisationID: OrganisationID,\n\t\tclient: &http.Client{},\n\t}\n\treturn &Client{\n\t\tAccount: AccountEndpoint{\n\t\t\tconfig: &config,\n\t\t},\n\t}\n}", "func NewMoney(a int, c string) *Money {\n\treturn &Money{amount: a, currency: c}\n}" ]
[ "0.69132036", "0.6623393", "0.6615625", "0.63697267", "0.6276726", "0.6014245", "0.5949236", "0.591252", "0.5813441", "0.57447326", "0.5703966", "0.56493205", "0.5621344", "0.5587428", "0.55520993", "0.5498668", "0.54740584", "0.5446518", "0.5446518", "0.54291975", "0.5412927", "0.54108405", "0.5407447", "0.54015833", "0.53761077", "0.5374377", "0.53601146", "0.5328003", "0.5324687", "0.5313606", "0.52926934", "0.5273013", "0.52670807", "0.5261925", "0.52381396", "0.5233324", "0.51944244", "0.51837915", "0.5166851", "0.51557034", "0.5141323", "0.5136489", "0.5133078", "0.5120421", "0.50891453", "0.5085527", "0.503182", "0.5030709", "0.5023607", "0.5021786", "0.5017512", "0.5012479", "0.49890617", "0.49854165", "0.49715826", "0.49690014", "0.49565202", "0.49253133", "0.4914815", "0.49023938", "0.48916772", "0.48877674", "0.4872492", "0.48681977", "0.48476517", "0.48407602", "0.48109052", "0.48084256", "0.4799762", "0.47980887", "0.4798054", "0.4785657", "0.4785657", "0.47835347", "0.4764579", "0.4753401", "0.4746682", "0.47410083", "0.4739711", "0.47350797", "0.47215867", "0.47121567", "0.47111514", "0.4704581", "0.47041896", "0.46968615", "0.46912354", "0.46741918", "0.46573326", "0.46527028", "0.46503583", "0.4649358", "0.46419892", "0.4641852", "0.4641063", "0.4640832", "0.4637968", "0.46374142", "0.46355247", "0.46285912" ]
0.8187087
0
GetVestedCoins returns the total number of vested coins. If no coins are vested, nil is returned.
func (cva ContinuousVestingAccount) GetVestedCoins(blockTime time.Time) sdk.Coins { var vestedCoins sdk.Coins // We must handle the case where the start time for a vesting account has // been set into the future or when the start of the chain is not exactly // known. if blockTime.Unix() <= cva.StartTime { return vestedCoins } else if blockTime.Unix() >= cva.EndTime { return cva.OriginalVesting } // calculate the vesting scalar x := blockTime.Unix() - cva.StartTime y := cva.EndTime - cva.StartTime s := sdk.NewDec(x).Quo(sdk.NewDec(y)) for _, ovc := range cva.OriginalVesting { vestedAmt := ovc.Amount.ToDec().Mul(s).RoundInt() vestedCoins = append(vestedCoins, sdk.NewCoin(ovc.Denom, vestedAmt)) } return vestedCoins }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (plva PermanentLockedAccount) GetVestedCoins(_ time.Time) sdk.Coins {\n\treturn nil\n}", "func (pva PeriodicVestingAccount) GetVestedCoins(blockTime time.Time) sdk.Coins {\n\tcoins := ReadSchedule(pva.StartTime, pva.EndTime, pva.VestingPeriods, pva.OriginalVesting, blockTime.Unix())\n\tif coins.IsZero() {\n\t\treturn nil\n\t}\n\treturn coins\n}", "func (va ClawbackVestingAccount) GetVestedCoins(blockTime time.Time) sdk.Coins {\n\t// It's likely that one or the other schedule will be nearly trivial,\n\t// so there should be little overhead in recomputing the conjunction each time.\n\tcoins := coinsMin(va.GetUnlockedOnly(blockTime), va.GetVestedOnly(blockTime))\n\tif coins.IsZero() {\n\t\treturn nil\n\t}\n\treturn coins\n}", "func (dva DelayedVestingAccount) GetVestedCoins(blockTime time.Time) sdk.Coins {\n\tif blockTime.Unix() >= dva.EndTime {\n\t\treturn dva.OriginalVesting\n\t}\n\n\treturn nil\n}", "func (vva ValidatorVestingAccount) GetVestedCoins(blockTime time.Time) sdk.Coins {\n\tvar vestedCoins sdk.Coins\n\tif blockTime.Unix() <= vva.StartTime {\n\t\treturn vestedCoins\n\t}\n\tcurrentPeriodStartTime := vva.StartTime\n\tnumberPeriods := len(vva.VestingPeriods)\n\tfor i := 0; i < numberPeriods; i++ {\n\t\tx := blockTime.Unix() - currentPeriodStartTime\n\t\tif x >= vva.VestingPeriods[i].Length {\n\t\t\tif vva.VestingPeriodProgress[i].PeriodComplete {\n\t\t\t\tvestedCoins = vestedCoins.Add(vva.VestingPeriods[i].Amount)\n\t\t\t}\n\t\t\tcurrentPeriodStartTime += vva.VestingPeriods[i].Length\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn vestedCoins\n\n}", "func (cva ContinuousVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn cva.OriginalVesting.Sub(cva.GetVestedCoins(blockTime))\n}", "func (vva ValidatorVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn vva.OriginalVesting.Sub(vva.GetVestedCoins(blockTime))\n}", "func (va ClawbackVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn va.OriginalVesting.Sub(va.GetVestedCoins(blockTime))\n}", "func (dva DelayedVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn dva.OriginalVesting.Sub(dva.GetVestedCoins(blockTime))\n}", "func (pva PeriodicVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn pva.OriginalVesting.Sub(pva.GetVestedCoins(blockTime))\n}", "func (plva PermanentLockedAccount) GetVestingCoins(_ time.Time) sdk.Coins {\n\treturn plva.OriginalVesting\n}", "func (vva ValidatorVestingAccount) GetFailedVestedCoins() sdk.Coins {\n\tvar failedVestedCoins sdk.Coins\n\tnumberPeriods := len(vva.VestingPeriods)\n\tfor i := 0; i < numberPeriods; i++ {\n\t\tif vva.VestingPeriodProgress[i].PeriodComplete {\n\t\t\tif !vva.VestingPeriodProgress[i].VestingSuccessful {\n\t\t\t\tfailedVestedCoins = failedVestedCoins.Add(vva.VestingPeriods[i].Amount)\n\t\t\t}\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn failedVestedCoins\n}", "func (keeper ViewKeeper) GetCoins(ctx sdk.Context, addr sdk.Address) sdk.Coins {\n\treturn getCoins(ctx, keeper.am, addr)\n}", "func (keeper BaseViewKeeper) GetCoins(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins {\n\treturn getCoins(ctx, keeper.am, addr)\n}", "func GetCoins() (coins []Coin, error error) {\n\tvar c = []Coin{}\n\tvar d struct {\n\t\tCrypto []Coin `json:\"crypto\"`\n\t}\n\tjsonData, err := doTauRequest(1, \"GET\", \"data/coins\", nil)\n\tif err != nil {\n\t\treturn c, err\n\t}\n\tif err := json.Unmarshal(jsonData, &d); err != nil {\n\t\treturn c, err\n\t}\n\treturn d.Crypto, nil\n}", "func (keeper SendKeeper) GetCoins(ctx sdk.Context, addr sdk.Address) sdk.Coins {\n\treturn getCoins(ctx, keeper.am, addr)\n}", "func (cva ContinuousVestingAccount) LockedCoins(ctx sdk.Context) sdk.Coins {\n\treturn cva.BaseVestingAccount.LockedCoinsFromVesting(cva.GetVestingCoins(ctx.BlockTime()))\n}", "func (keeper Keeper) GetCoins(ctx sdk.Context, addr sdk.Address) sdk.Coins {\n\treturn getCoins(ctx, keeper.am, addr)\n}", "func (vva ValidatorVestingAccount) SpendableCoins(blockTime time.Time) sdk.Coins {\n\treturn vva.BaseVestingAccount.SpendableCoinsVestingAccount(vva.GetVestingCoins(blockTime))\n}", "func (va ClawbackVestingAccount) LockedCoins(ctx sdk.Context) sdk.Coins {\n\treturn va.BaseVestingAccount.LockedCoinsFromVesting(va.GetVestingCoins(ctx.BlockTime()))\n}", "func (ck CoinKeeper) GetCoins(ctx sdk.Context, addr sdk.Address, amt sdk.Coins) sdk.Coins {\n\tacc := ck.am.GetAccount(ctx, addr)\n\treturn acc.GetCoins()\n}", "func (t *TauAPI) GetCoins() (coins []Coin, error error) {\n\tvar c = []Coin{}\n\tvar d struct {\n\t\tCrypto []Coin `json:\"cryto\"` //typo from api\n\t\tFiat []Coin `json:\"fiat\"`\n\t}\n\tjsonData, err := t.doTauRequest(&TauReq{\n\t\tVersion: 2,\n\t\tMethod: \"GET\",\n\t\tPath: \"coins\",\n\t})\n\tif err != nil {\n\t\treturn c, err\n\t}\n\tif err := json.Unmarshal(jsonData, &d); err != nil {\n\t\treturn c, err\n\t}\n\tc = append(d.Crypto, d.Fiat...)\n\treturn c, nil\n}", "func (va ClawbackVestingAccount) GetVestedOnly(blockTime time.Time) sdk.Coins {\n\treturn ReadSchedule(va.StartTime, va.EndTime, va.VestingPeriods, va.OriginalVesting, blockTime.Unix())\n}", "func (pva PeriodicVestingAccount) LockedCoins(ctx sdk.Context) sdk.Coins {\n\treturn pva.BaseVestingAccount.LockedCoinsFromVesting(pva.GetVestingCoins(ctx.BlockTime()))\n}", "func (candidate *Candidate) GetTotalBipStake() *big.Int {\n\tcandidate.lock.RLock()\n\tdefer candidate.lock.RUnlock()\n\n\treturn big.NewInt(0).Set(candidate.totalBipStake)\n}", "func (dva DelayedVestingAccount) LockedCoins(ctx sdk.Context) sdk.Coins {\n\treturn dva.BaseVestingAccount.LockedCoinsFromVesting(dva.GetVestingCoins(ctx.BlockTime()))\n}", "func (m *Client) GetCoins() ([]string, error) {\n\tresp, err := m.Service.GetCoins()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error requesting coin list: %s\", err)\n\t}\n\tdefer resp.Body.Close()\n\n\tvar response []string\n\terr = json.NewDecoder(resp.Body).Decode(&response)\n\tif err != nil {\n\t\tmsg, _ := ioutil.ReadAll(resp.Body)\n\t\treturn nil, fmt.Errorf(\"error decoding coin list: %s: %s\", msg, err)\n\t}\n\n\treturn response, nil\n}", "func (k Keeper) GetWinnerIncentives(ctx sdk.Context) float32 {\n\tgames := float32(k.GetGames(ctx))\n\tvotes := float32(k.GetVotes(ctx))\n\tgVR := float32(k.GetParams(ctx).GameVoteRatio) / 100\n\treturn games / (votes*gVR + games)\n}", "func (r *ParseResult) GetVoutAmount(vout int) (*big.Int, error) {\n\tamt := big.NewInt(0)\n\n\tif !(r.TokenType == TokenTypeFungible01 ||\n\t\tr.TokenType == TokenTypeNft1Child41 ||\n\t\tr.TokenType == TokenTypeNft1Group81) {\n\t\treturn nil, errors.New(\"cannot extract amount for not type 1 or NFT1 token\")\n\t}\n\n\tif vout == 0 {\n\t\treturn amt, nil\n\t}\n\n\tif r.TransactionType == TransactionTypeSend {\n\t\tif vout > len(r.Data.(SlpSend).Amounts) {\n\t\t\treturn amt, nil\n\t\t}\n\t\treturn amt.Add(amt, new(big.Int).SetUint64(r.Data.(SlpSend).Amounts[vout-1])), nil\n\t} else if r.TransactionType == TransactionTypeMint {\n\t\tif vout == 1 {\n\t\t\treturn amt.Add(amt, new(big.Int).SetUint64(r.Data.(SlpMint).Qty)), nil\n\t\t}\n\t\treturn amt, nil\n\t} else if r.TransactionType == TransactionTypeGenesis {\n\t\tif vout == 1 {\n\t\t\treturn amt.Add(amt, new(big.Int).SetUint64(r.Data.(SlpGenesis).Qty)), nil\n\t\t}\n\t\treturn amt, nil\n\t}\n\treturn nil, errors.New(\"unknown error getting vout amount\")\n}", "func (_TokenVesting *TokenVestingCaller) VestedAmount(opts *bind.CallOpts, _token common.Address) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _TokenVesting.contract.Call(opts, out, \"vestedAmount\", _token)\n\treturn *ret0, err\n}", "func (_TokenVesting *TokenVestingCallerSession) VestedAmount(_token common.Address) (*big.Int, error) {\n\treturn _TokenVesting.Contract.VestedAmount(&_TokenVesting.CallOpts, _token)\n}", "func (_TokenVesting *TokenVestingSession) VestedAmount(_token common.Address) (*big.Int, error) {\n\treturn _TokenVesting.Contract.VestedAmount(&_TokenVesting.CallOpts, _token)\n}", "func (_Bindings *BindingsCallerSession) TotalReserves() (*big.Int, error) {\n\treturn _Bindings.Contract.TotalReserves(&_Bindings.CallOpts)\n}", "func coins(a int) int {\n\tif a == 0 {\n\t\treturn 0\n\t}\n\treturn doCoins(a, 25)\n}", "func GetCoins(accCoins []types.Coin) AccountCoins {\n\tcoins := make(AccountCoins, 0)\n\tfor _, coin := range accCoins {\n\t\tcoins = append(coins, AccountCoin{Amount: uint64(coin.Amount), Denom: coin.Denom})\n\t}\n\treturn coins\n}", "func (bva BaseVestingAccount) LockedCoinsFromVesting(vestingCoins sdk.Coins) sdk.Coins {\n\tlockedCoins := vestingCoins.Sub(vestingCoins.Min(bva.DelegatedVesting))\n\tif lockedCoins == nil {\n\t\treturn sdk.Coins{}\n\t}\n\treturn lockedCoins\n}", "func (o *LoyaltySubLedger) GetTotalSpentPoints() float32 {\n\tif o == nil {\n\t\tvar ret float32\n\t\treturn ret\n\t}\n\n\treturn o.TotalSpentPoints\n}", "func (r *Repository) GetAmountsOfManageCandidates(ctx context.Context, companyID string) (int32, int32, error) {\n\tobjCompanyID, err := primitive.ObjectIDFromHex(companyID)\n\tif err != nil {\n\t\treturn 0, 0, errors.New(`wrong_id`)\n\t}\n\n\tamount := struct {\n\t\tSaved int32 `bson:\"saved_candidates\"`\n\t\tSkipped int32 `bson:\"skipped_candidates\"`\n\t\t// Alerts int32 `bson:\"alerts\"`\n\t}{}\n\n\tcursor, err := r.companiesCollection.Aggregate(\n\t\tctx,\n\t\t[]bson.M{\n\t\t\t{\n\t\t\t\t\"$match\": bson.M{\n\t\t\t\t\t\"company_id\": objCompanyID,\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\t\"$addFields\": bson.M{\n\t\t\t\t\t\"saved_candidates\": bson.M{\n\t\t\t\t\t\t\"$size\": \"$saved_candidates\",\n\t\t\t\t\t},\n\t\t\t\t\t\"skipped_candidates\": bson.M{\n\t\t\t\t\t\t\"$size\": \"$skipped_candidates\",\n\t\t\t\t\t},\n\t\t\t\t\t// \"alerts\": bson.M{\n\t\t\t\t\t// \t\"$size\": \"$alerts\", // TODO:\n\t\t\t\t\t// },\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\t\"$project\": bson.M{\n\t\t\t\t\t\"saved_candidates\": 1,\n\t\t\t\t\t\"skipped_candidates\": 1,\n\t\t\t\t\t// \"alerts\": 1,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t)\n\tif err != nil {\n\t\tif err == mongo.ErrNoDocuments {\n\t\t\treturn 0, 0, errors.New(`not_found`)\n\t\t}\n\t\treturn 0, 0, err\n\t}\n\tdefer cursor.Close(ctx)\n\n\tif cursor.Next(ctx) {\n\t\terr = cursor.Decode(&amount)\n\t\tif err != nil {\n\t\t\treturn 0, 0, err\n\t\t}\n\t}\n\n\treturn amount.Saved, amount.Skipped, nil\n}", "func (_Bindings *BindingsSession) TotalReserves() (*big.Int, error) {\n\treturn _Bindings.Contract.TotalReserves(&_Bindings.CallOpts)\n}", "func (o *Transaction) GetCounterparties() []TransactionCounterparty {\n\tif o == nil || o.Counterparties == nil {\n\t\tvar ret []TransactionCounterparty\n\t\treturn ret\n\t}\n\treturn *o.Counterparties\n}", "func (_CrToken *CrTokenCallerSession) TotalReserves() (*big.Int, error) {\n\treturn _CrToken.Contract.TotalReserves(&_CrToken.CallOpts)\n}", "func (_Bindings *BindingsCaller) TotalReserves(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _Bindings.contract.Call(opts, out, \"totalReserves\")\n\treturn *ret0, err\n}", "func (c Cart) GetVoucherSavings() domain.Price {\n\tprice := domain.Price{}\n\tvar err error\n\n\tfor _, item := range c.Totalitems {\n\t\tif item.Type == TotalsTypeVoucher {\n\t\t\tprice, err = price.Add(item.Price)\n\t\t\tif err != nil {\n\t\t\t\treturn price\n\t\t\t}\n\t\t}\n\t}\n\n\tif price.IsNegative() {\n\t\treturn domain.Price{}\n\t}\n\n\treturn price\n}", "func (_CrToken *CrTokenCaller) TotalReserves(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _CrToken.contract.Call(opts, &out, \"totalReserves\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (_CrToken *CrTokenSession) TotalReserves() (*big.Int, error) {\n\treturn _CrToken.Contract.TotalReserves(&_CrToken.CallOpts)\n}", "func (p *Player) CashSpentTotal() int {\n\treturn p.AdditionalPlayerInformation.TotalCashSpent\n}", "func (keeper ViewKeeper) HasCoins(ctx sdk.Context, addr sdk.Address, amt sdk.Coins) bool {\n\treturn hasCoins(ctx, keeper.am, addr, amt)\n}", "func (keeper BaseViewKeeper) HasCoins(ctx sdk.Context, addr sdk.AccAddress, amt sdk.Coins) bool {\n\treturn hasCoins(ctx, keeper.am, addr, amt)\n}", "func (keeper Keeper) SubtractCoins(ctx sdk.Context, addr sdk.Address, amt sdk.Coins) (sdk.Coins, sdk.Error) {\n\treturn subtractCoins(ctx, keeper.am, addr, amt)\n}", "func (cm *ConnectionManager) sumDeposits() *big.Int {\n\tchs := cm.openChannels()\n\tvar sum = big.NewInt(0)\n\tfor _, c := range chs {\n\t\tsum.Add(sum, c.OurContractBalance)\n\t}\n\treturn sum\n}", "func (_Vault *VaultCaller) GetDecimals(opts *bind.CallOpts, token common.Address) (uint8, error) {\n\tvar (\n\t\tret0 = new(uint8)\n\t)\n\tout := ret0\n\terr := _Vault.contract.Call(opts, out, \"getDecimals\", token)\n\treturn *ret0, err\n}", "func (plva PermanentLockedAccount) LockedCoins(_ sdk.Context) sdk.Coins {\n\treturn plva.BaseVestingAccount.LockedCoinsFromVesting(plva.OriginalVesting)\n}", "func (e *Election) Votes() int {\n\tcount := 0\n\tfor _, ballot := range e.ballots {\n\t\tif ballot {\n\t\t\tcount++\n\t\t}\n\t}\n\treturn count\n}", "func (o *AllocationList) GetInvested() float64 {\n\tif o == nil {\n\t\tvar ret float64\n\t\treturn ret\n\t}\n\n\treturn o.Invested\n}", "func (_Vault *VaultCallerSession) GetDecimals(token common.Address) (uint8, error) {\n\treturn _Vault.Contract.GetDecimals(&_Vault.CallOpts, token)\n}", "func (_Vault *VaultSession) GetDecimals(token common.Address) (uint8, error) {\n\treturn _Vault.Contract.GetDecimals(&_Vault.CallOpts, token)\n}", "func (dcr *ExchangeWallet) ReturnCoins(unspents asset.Coins) error {\n\tdcr.fundingMtx.Lock()\n\tdefer dcr.fundingMtx.Unlock()\n\treturn dcr.returnCoins(unspents)\n}", "func (b *rpcVestingBalance) delegated() (sdk.Coins, sdk.Coins, error) {\n\tdelegatedCoins, err := b.totalDelegated()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tunbondingCoins, err := b.totalUnbondingDelegations()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tdelegated := delegatedCoins.AmountOf(stakingDenom)\n\tunbonding := unbondingCoins.AmountOf(stakingDenom)\n\ttotalStaked := delegated.Add(unbonding)\n\tdelegatedFree := b.vacc.GetDelegatedFree().AmountOf(stakingDenom)\n\n\t// total number of staked and unbonding tokens considered to be liquid\n\ttotalFree := sdk.MinInt(totalStaked, delegatedFree)\n\t// any coins that are not considered liquid, are vesting up to a maximum of delegated\n\tstakedVesting := sdk.MinInt(totalStaked.Sub(totalFree), delegated)\n\t// staked free coins are left over\n\tstakedFree := delegated.Sub(stakedVesting)\n\n\tliquidCoins := sdk.NewCoins(newKavaCoin(stakedFree))\n\tvestingCoins := sdk.NewCoins(newKavaCoin(stakedVesting))\n\treturn liquidCoins, vestingCoins, nil\n}", "func (_Contracts *ContractsCaller) VotersCount(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _Contracts.contract.Call(opts, out, \"votersCount\")\n\treturn *ret0, err\n}", "func (cs *Coins) CoinSelect(amount uint64, asset string) (unspents []explorer.Utxo, change uint64, err error) {\n\tchange = 0\n\tunspents = []explorer.Utxo{}\n\tavailableSats := uint64(0)\n\n\tfor index, unspent := range cs.Utxos {\n\t\tu := unspent\n\t\tassetHash := u.Asset()\n\t\tamountSatoshis := u.Value()\n\t\tif len(u.AssetCommitment()) > 0 && len(u.ValueCommitment()) > 0 {\n\t\t\tbk := cs.BlindingKey\n\t\t\tif len(cs.BlindingKeys) > 0 {\n\t\t\t\tbk = cs.BlindingKeys[index]\n\t\t\t}\n\t\t\tav, err := unblindUxto(u, bk)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, 0, err\n\t\t\t}\n\t\t\tassetHash = av.asset\n\t\t\tamountSatoshis = av.value\n\t\t}\n\t\tif asset == assetHash {\n\t\t\tunspents = append(unspents, unspent)\n\t\t\tavailableSats += amountSatoshis\n\n\t\t\tif availableSats >= amount {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\tif availableSats < amount {\n\t\treturn nil, 0, errors.New(\"You do not have enough coins\")\n\t}\n\n\tchange = availableSats - amount\n\n\treturn unspents, change, nil\n}", "func (_Cakevault *CakevaultSession) TotalShares() (*big.Int, error) {\n\treturn _Cakevault.Contract.TotalShares(&_Cakevault.CallOpts)\n}", "func (_Contracts *ContractsCaller) VotesCount(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _Contracts.contract.Call(opts, out, \"votesCount\")\n\treturn *ret0, err\n}", "func (_Cakevault *CakevaultCallerSession) TotalShares() (*big.Int, error) {\n\treturn _Cakevault.Contract.TotalShares(&_Cakevault.CallOpts)\n}", "func (keeper Keeper) GetVotes(ctx sdk.Context, proposalID uint64) (votes types.Votes) {\n\tkeeper.IterateVotes(ctx, proposalID, func(vote types.Vote) bool {\n\t\tvotes = append(votes, vote)\n\t\treturn false\n\t})\n\treturn\n}", "func TotalCoinsInvariant(ak auth.AccountKeeper, totalSupplyFn func() sdk.Coins) sdk.Invariant {\n\treturn func(ctx sdk.Context) error {\n\t\ttotalCoins := sdk.NewCoins()\n\n\t\tchkAccount := func(acc auth.Account) bool {\n\t\t\tcoins := acc.GetCoins()\n\t\t\ttotalCoins = totalCoins.Add(coins)\n\t\t\treturn false\n\t\t}\n\n\t\tak.IterateAccounts(ctx, chkAccount)\n\t\tif !totalSupplyFn().IsEqual(totalCoins) {\n\t\t\treturn errors.New(\"total calculated coins doesn't equal expected coins\")\n\t\t}\n\t\treturn nil\n\t}\n}", "func (dcr *ExchangeWallet) FundingCoins(ids []dex.Bytes) (asset.Coins, error) {\n\t// First check if we have the coins in cache.\n\tcoins := make(asset.Coins, 0, len(ids))\n\tnotFound := make(map[outPoint]bool)\n\tdcr.fundingMtx.Lock()\n\tdefer dcr.fundingMtx.Unlock() // stay locked until we update the map and lock them in the wallet\n\tfor _, id := range ids {\n\t\ttxHash, vout, err := decodeCoinID(id)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tpt := newOutPoint(txHash, vout)\n\t\tfundingCoin, found := dcr.fundingCoins[pt]\n\t\tif found {\n\t\t\tcoins = append(coins, fundingCoin.op)\n\t\t\tcontinue\n\t\t}\n\t\tnotFound[pt] = true\n\t}\n\tif len(notFound) == 0 {\n\t\treturn coins, nil\n\t}\n\n\t// Check locked outputs for not found coins.\n\tlockedOutputs, err := dcr.lockedOutputs()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor _, output := range lockedOutputs {\n\t\ttxHash, err := chainhash.NewHashFromStr(output.Txid)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error decoding txid from rpc server %s: %w\", output.Txid, err)\n\t\t}\n\t\tpt := newOutPoint(txHash, output.Vout)\n\t\tif !notFound[pt] {\n\t\t\tcontinue\n\t\t}\n\t\ttxOut, err := dcr.node.GetTxOut(dcr.ctx, txHash, output.Vout, true)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"gettxout error for locked output %v: %w\", pt.String(), translateRPCCancelErr(err))\n\t\t}\n\t\tvar address string\n\t\tif len(txOut.ScriptPubKey.Addresses) > 0 {\n\t\t\taddress = txOut.ScriptPubKey.Addresses[0]\n\t\t}\n\t\tcoin := newOutput(txHash, output.Vout, toAtoms(output.Amount), output.Tree)\n\t\tcoins = append(coins, coin)\n\t\tdcr.fundingCoins[pt] = &fundingCoin{\n\t\t\top: coin,\n\t\t\taddr: address,\n\t\t}\n\t\tdelete(notFound, pt)\n\t\tif len(notFound) == 0 {\n\t\t\treturn coins, nil\n\t\t}\n\t}\n\n\t// Some funding coins still not found after checking locked outputs.\n\t// Check wallet unspent outputs as last resort. Lock the coins if found.\n\tunspents, err := dcr.unspents()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcoinsToLock := make([]*wire.OutPoint, 0, len(notFound))\n\tfor _, txout := range unspents {\n\t\ttxHash, err := chainhash.NewHashFromStr(txout.TxID)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error decoding txid from rpc server %s: %w\", txout.TxID, err)\n\t\t}\n\t\tpt := newOutPoint(txHash, txout.Vout)\n\t\tif !notFound[pt] {\n\t\t\tcontinue\n\t\t}\n\t\tcoinsToLock = append(coinsToLock, wire.NewOutPoint(txHash, txout.Vout, txout.Tree))\n\t\tcoin := newOutput(txHash, txout.Vout, toAtoms(txout.Amount), txout.Tree)\n\t\tcoins = append(coins, coin)\n\t\tdcr.fundingCoins[pt] = &fundingCoin{\n\t\t\top: coin,\n\t\t\taddr: txout.Address,\n\t\t}\n\t\tdelete(notFound, pt)\n\t\tif len(notFound) == 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\tif len(notFound) != 0 {\n\t\tids := make([]string, 0, len(notFound))\n\t\tfor pt := range notFound {\n\t\t\tids = append(ids, pt.String())\n\t\t}\n\t\treturn nil, fmt.Errorf(\"funding coins not found: %s\", strings.Join(ids, \", \"))\n\t}\n\tdcr.log.Debugf(\"Locking funding coins that were unlocked %v\", coinsToLock)\n\terr = dcr.node.LockUnspent(dcr.ctx, false, coinsToLock)\n\tif err != nil {\n\t\treturn nil, translateRPCCancelErr(err)\n\t}\n\n\treturn coins, nil\n}", "func (o *Transaction) GetCounterpartiesOk() (*[]TransactionCounterparty, bool) {\n\tif o == nil || o.Counterparties == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Counterparties, true\n}", "func (_MonsterOwnership *MonsterOwnershipSession) TotalSupply() (*big.Int, error) {\n\treturn _MonsterOwnership.Contract.TotalSupply(&_MonsterOwnership.CallOpts)\n}", "func (gc *GovernanceContract) TotalVotingPower() (hexutil.Big, error) {\n\treturn gc.repo.GovernanceTotalWeight(&gc.Address)\n}", "func (o *AvailableBudget) GetSpentInBudgets() []BudgetSpent {\n\tif o == nil || o.SpentInBudgets == nil {\n\t\tvar ret []BudgetSpent\n\t\treturn ret\n\t}\n\treturn *o.SpentInBudgets\n}", "func (_Gatekeeper *GatekeeperCaller) GetRootsCount(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _Gatekeeper.contract.Call(opts, out, \"GetRootsCount\")\n\treturn *ret0, err\n}", "func (c *CoordinatorHelper) Coins(\n\tctx context.Context,\n\tdbTx storage.DatabaseTransaction,\n\taccountIdentifier *types.AccountIdentifier,\n\tcurrency *types.Currency,\n) ([]*types.Coin, error) {\n\tcoins, _, err := c.coinStorage.GetCoinsTransactional(\n\t\tctx,\n\t\tdbTx,\n\t\taccountIdentifier,\n\t)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"%w: unable to get coins\", err)\n\t}\n\n\tcoinsToReturn := []*types.Coin{}\n\tfor _, coin := range coins {\n\t\tif types.Hash(coin.Amount.Currency) != types.Hash(currency) {\n\t\t\tcontinue\n\t\t}\n\n\t\tcoinsToReturn = append(coinsToReturn, coin)\n\t}\n\n\treturn coinsToReturn, nil\n}", "func (s *Store) GetTotalSupply() *big.Int {\n\tamountBytes, err := s.table.TotalSupply.Get([]byte(\"c\"))\n\tif err != nil {\n\t\ts.Log.Crit(\"Failed to get key-value\", \"err\", err)\n\t}\n\tif amountBytes == nil {\n\t\treturn big.NewInt(0)\n\t}\n\treturn new(big.Int).SetBytes(amountBytes)\n}", "func (a *Account) TotalReceived(confirms int) (float64, error) {\n\tbs, err := GetCurBlock()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tvar totalSatoshis int64\n\tfor _, record := range a.TxStore.SortedRecords() {\n\t\ttxout, ok := record.(*tx.RecvTxOut)\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Ignore change.\n\t\tif txout.Change() {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Tally if the appropiate number of block confirmations have passed.\n\t\tif confirmed(confirms, txout.Height(), bs.Height) {\n\t\t\ttotalSatoshis += txout.Value()\n\t\t}\n\t}\n\n\treturn float64(totalSatoshis) / float64(btcutil.SatoshiPerBitcoin), nil\n}", "func (r SlpSend) GetVoutValue(vout int) (*big.Int, bool) {\n\tif vout == 0 {\n\t\treturn nil, false\n\t}\n\n\tif vout > len(r.Amounts) {\n\t\treturn nil, false\n\t}\n\n\treturn new(big.Int).SetUint64(r.Amounts[vout-1]), false\n}", "func (m *TeamSummary) GetGuestsCount()(*int32) {\n return m.guestsCount\n}", "func (dcr *ExchangeWallet) FundingCoins(ids []dex.Bytes) (asset.Coins, error) {\n\t// First check if we have the coins in cache.\n\tcoins := make(asset.Coins, 0, len(ids))\n\tnotFound := make(map[outPoint]bool)\n\tdcr.fundingMtx.Lock()\n\tdefer dcr.fundingMtx.Unlock() // stay locked until we update the map and lock them in the wallet\n\tfor _, id := range ids {\n\t\ttxHash, vout, err := decodeCoinID(id)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tpt := newOutPoint(txHash, vout)\n\t\tfundingCoin, found := dcr.fundingCoins[pt]\n\t\tif found {\n\t\t\tcoins = append(coins, fundingCoin.op)\n\t\t\tcontinue\n\t\t}\n\t\tnotFound[pt] = true\n\t}\n\tif len(notFound) == 0 {\n\t\treturn coins, nil\n\t}\n\n\t// Check locked outputs for not found coins.\n\tfor _, acct := range dcr.fundingAccounts() {\n\t\tlockedOutputs, err := dcr.wallet.LockedOutputs(dcr.ctx, acct)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfor _, output := range lockedOutputs {\n\t\t\ttxHash, err := chainhash.NewHashFromStr(output.Txid)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"error decoding txid from rpc server %s: %w\", output.Txid, err)\n\t\t\t}\n\t\t\tpt := newOutPoint(txHash, output.Vout)\n\t\t\tif !notFound[pt] {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ttxOut, err := dcr.wallet.UnspentOutput(dcr.ctx, txHash, output.Vout, output.Tree)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"gettxout error for locked output %v: %w\", pt.String(), err)\n\t\t\t}\n\t\t\tvar address string\n\t\t\tif len(txOut.Addresses) > 0 {\n\t\t\t\taddress = txOut.Addresses[0]\n\t\t\t}\n\t\t\tcoin := newOutput(txHash, output.Vout, toAtoms(output.Amount), output.Tree)\n\t\t\tcoins = append(coins, coin)\n\t\t\tdcr.fundingCoins[pt] = &fundingCoin{\n\t\t\t\top: coin,\n\t\t\t\taddr: address,\n\t\t\t}\n\t\t\tdelete(notFound, pt)\n\t\t\tif len(notFound) == 0 {\n\t\t\t\treturn coins, nil\n\t\t\t}\n\t\t}\n\t}\n\n\t// Some funding coins still not found after checking locked outputs.\n\t// Check wallet unspent outputs as last resort. Lock the coins if found.\n\tcoinsToLock := make([]*wire.OutPoint, 0, len(notFound))\n\tfor _, acct := range dcr.fundingAccounts() {\n\t\tunspents, err := dcr.wallet.Unspents(dcr.ctx, acct)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfor _, txout := range unspents {\n\t\t\ttxHash, err := chainhash.NewHashFromStr(txout.TxID)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"error decoding txid from rpc server %s: %w\", txout.TxID, err)\n\t\t\t}\n\t\t\tpt := newOutPoint(txHash, txout.Vout)\n\t\t\tif !notFound[pt] {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tcoinsToLock = append(coinsToLock, wire.NewOutPoint(txHash, txout.Vout, txout.Tree))\n\t\t\tcoin := newOutput(txHash, txout.Vout, toAtoms(txout.Amount), txout.Tree)\n\t\t\tcoins = append(coins, coin)\n\t\t\tdcr.fundingCoins[pt] = &fundingCoin{\n\t\t\t\top: coin,\n\t\t\t\taddr: txout.Address,\n\t\t\t}\n\t\t\tdelete(notFound, pt)\n\t\t\tif len(notFound) == 0 {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\t// Return an error if some coins are still not found.\n\tif len(notFound) != 0 {\n\t\tids := make([]string, 0, len(notFound))\n\t\tfor pt := range notFound {\n\t\t\tids = append(ids, pt.String())\n\t\t}\n\t\treturn nil, fmt.Errorf(\"funding coins not found: %s\", strings.Join(ids, \", \"))\n\t}\n\n\tdcr.log.Debugf(\"Locking funding coins that were unlocked %v\", coinsToLock)\n\terr := dcr.wallet.LockUnspent(dcr.ctx, false, coinsToLock)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn coins, nil\n}", "func (_BtlCoin *BtlCoinSession) TotalSupply() (*big.Int, error) {\n\treturn _BtlCoin.Contract.TotalSupply(&_BtlCoin.CallOpts)\n}", "func (u *User) GetTotalPrivateRepos() int {\n\tif u == nil || u.TotalPrivateRepos == nil {\n\t\treturn 0\n\t}\n\treturn *u.TotalPrivateRepos\n}", "func (k Keeper) GetTotalSupply(ctx sdk.Context, denom string) uint64 {\n\tstore := ctx.KVStore(k.storeKey)\n\tbz := store.Get(types.KeyCollection(denom))\n\tif len(bz) == 0 {\n\t\treturn 0\n\t}\n\n\tvar supply uint64\n\tk.cdc.MustUnmarshalBinaryLengthPrefixed(bz, &supply)\n\treturn supply\n}", "func (keeper Keeper) HasCoins(ctx sdk.Context, addr sdk.Address, amt sdk.Coins) bool {\n\treturn hasCoins(ctx, keeper.am, addr, amt)\n}", "func (c Checkout) Total() int {\n\ttotal := 0\n\tfor code, quantity := range c.basket {\n\t\toffer, exists := offers[code]\n\t\tif exists {\n\t\t\ttotal += calculateOfferPrice(code, quantity, offer)\n\t\t} else {\n\t\t\ttotal += calculatePrice(code, quantity)\n\t\t}\n\t}\n\treturn total\n}", "func (supply Supply) GetTotal() sdk.Coins {\n\treturn supply.Total\n}", "func (k *Keeper) GetVaultTotalShares(\n\tctx sdk.Context,\n\tdenom string,\n) (types.VaultShare, bool) {\n\tvault, found := k.GetVaultRecord(ctx, denom)\n\tif !found {\n\t\treturn types.VaultShare{}, false\n\t}\n\n\treturn vault.TotalShares, true\n}", "func (keeper SendKeeper) HasCoins(ctx sdk.Context, addr sdk.Address, amt sdk.Coins) bool {\n\treturn hasCoins(ctx, keeper.am, addr, amt)\n}", "func (k Keeper) GetVotes(ctx sdk.Context) int64 {\n\treturn k.GetRunningAverageTotal(ctx, Votes24ValueKey)\n}", "func subtractCoins(ctx sdk.Context, am sdk.AccountMapper, addr sdk.Address, amt sdk.Coins) (sdk.Coins, sdk.Error) {\n\toldCoins := getCoins(ctx, am, addr)\n\tnewCoins := oldCoins.Minus(amt)\n\tif !newCoins.IsNotNegative() {\n\t\treturn amt, sdk.ErrInsufficientCoins(fmt.Sprintf(\"%s < %s\", oldCoins, amt))\n\t}\n\terr := setCoins(ctx, am, addr, newCoins)\n\treturn newCoins, err\n}", "func (_MonsterOwnership *MonsterOwnershipCaller) TotalSupply(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _MonsterOwnership.contract.Call(opts, out, \"totalSupply\")\n\treturn *ret0, err\n}", "func (_Cakevault *CakevaultCaller) TotalShares(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _Cakevault.contract.Call(opts, &out, \"totalShares\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (_Bindings *BindingsSession) TotalSupply() (*big.Int, error) {\n\treturn _Bindings.Contract.TotalSupply(&_Bindings.CallOpts)\n}", "func (_MonsterOwnership *MonsterOwnershipCallerSession) TotalSupply() (*big.Int, error) {\n\treturn _MonsterOwnership.Contract.TotalSupply(&_MonsterOwnership.CallOpts)\n}", "func (btc *ExchangeWallet) ReturnCoins(unspents asset.Coins) error {\n\tif len(unspents) == 0 {\n\t\treturn fmt.Errorf(\"cannot return zero coins\")\n\t}\n\tops := make([]*output, 0, len(unspents))\n\tbtc.fundingMtx.Lock()\n\tdefer btc.fundingMtx.Unlock()\n\tfor _, unspent := range unspents {\n\t\top, err := btc.convertCoin(unspent)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error converting coin: %v\", err)\n\t\t}\n\t\tops = append(ops, op)\n\t\tdelete(btc.fundingCoins, outpointID(op.txHash.String(), op.vout))\n\t}\n\treturn btc.wallet.LockUnspent(true, ops)\n}", "func (_Lmc *LmcSession) TotalStaked() (*big.Int, error) {\n\treturn _Lmc.Contract.TotalStaked(&_Lmc.CallOpts)\n}", "func (_Contracts *ContractsCallerSession) VotersCount() (*big.Int, error) {\n\treturn _Contracts.Contract.VotersCount(&_Contracts.CallOpts)\n}", "func (a *Agent) GetPeersCount() uint32 {\n\treturn atomic.LoadUint32(&a.peersCount)\n}", "func (_Bep20 *Bep20Caller) GetCurrentVotes(opts *bind.CallOpts, account common.Address) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _Bep20.contract.Call(opts, &out, \"getCurrentVotes\", account)\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (_Contract *ContractSession) TotalSupply() (*big.Int, error) {\n\treturn _Contract.Contract.TotalSupply(&_Contract.CallOpts)\n}", "func (v *Vending) Get(c echo.Context) error {\n\tif v.chocolate == 0 {\n\t\treturn c.String(http.StatusOK, \"Out of chocolate please refill\")\n\t}\n\treturn c.String(http.StatusOK, fmt.Sprintf(\"There are %v pieces of chocolate left.\", v.chocolate))\n}", "func (p *PostgresDb) GetDueAmount(customerID int) (float64, error) {\n\tvar dueAmount float64\n\tpaymentsQuery := `\n\t\tSELECT COALESCE(SUM(amount), 0) \n\t\tFROM payment \n\t\tWHERE customer_id=$1 \n\t\tGROUP BY customer_id\n\t`\n\tvar sumPayments float64\n\terr := p.dbConn.Get(&sumPayments, paymentsQuery, customerID)\n\tif err != nil {\n\t\tlog.Println(\"Error getting sum payments:\", err)\n\t}\n\n\tcreditsQuery := `\t\n\t\tSELECT COALESCE(SUM(amount), 0) \n\t\tFROM credit \n\t\tWHERE customer_id=$1 \n\t\tGROUP BY customer_id\n\t`\n\tvar sumCredits float64\n\terr = p.dbConn.Get(&sumCredits, creditsQuery, customerID)\n\tif err != nil {\n\t\tlog.Println(\"Error getting sum credits:\", err)\n\t}\n\tdueAmount = sumCredits - sumPayments\n\n\treturn dueAmount, nil\n}", "func (_BtlCoin *BtlCoinCallerSession) TotalSupply() (*big.Int, error) {\n\treturn _BtlCoin.Contract.TotalSupply(&_BtlCoin.CallOpts)\n}" ]
[ "0.7471018", "0.73165536", "0.7279293", "0.721522", "0.6924047", "0.67499995", "0.6716838", "0.6667183", "0.6614427", "0.6604512", "0.6459922", "0.56289953", "0.5569631", "0.5512179", "0.54447544", "0.5326714", "0.5267492", "0.52399915", "0.5184446", "0.51647353", "0.51332", "0.51141435", "0.50317156", "0.50293607", "0.5008641", "0.4940991", "0.48962206", "0.48936057", "0.48576105", "0.47992873", "0.47835487", "0.47819436", "0.47590125", "0.47214925", "0.4704407", "0.46983805", "0.46978578", "0.46942836", "0.4692597", "0.46826506", "0.4665952", "0.46646446", "0.46430415", "0.46104795", "0.45938027", "0.4569276", "0.45543596", "0.4552141", "0.4532232", "0.45163238", "0.44996226", "0.4497621", "0.4493118", "0.44930124", "0.44883513", "0.44845527", "0.44751486", "0.44602427", "0.44508135", "0.4439027", "0.4424233", "0.4394798", "0.43452075", "0.43291035", "0.43279403", "0.42836547", "0.42788476", "0.42715365", "0.42689794", "0.42659956", "0.426377", "0.42554805", "0.42497912", "0.4237208", "0.42278206", "0.4226505", "0.4222482", "0.4220306", "0.4217448", "0.42149568", "0.4206257", "0.42025518", "0.41966802", "0.41953444", "0.41913095", "0.41665226", "0.41648978", "0.41637787", "0.41560644", "0.4152675", "0.4150058", "0.41421318", "0.41396427", "0.41385826", "0.41368917", "0.41350225", "0.41209182", "0.4113419", "0.4107479", "0.41003484" ]
0.70652676
4
GetVestingCoins returns the total number of vesting coins. If no coins are vesting, nil is returned.
func (cva ContinuousVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins { return cva.OriginalVesting.Sub(cva.GetVestedCoins(blockTime)) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (vva ValidatorVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn vva.OriginalVesting.Sub(vva.GetVestedCoins(blockTime))\n}", "func (va ClawbackVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn va.OriginalVesting.Sub(va.GetVestedCoins(blockTime))\n}", "func (pva PeriodicVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn pva.OriginalVesting.Sub(pva.GetVestedCoins(blockTime))\n}", "func (dva DelayedVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn dva.OriginalVesting.Sub(dva.GetVestedCoins(blockTime))\n}", "func (plva PermanentLockedAccount) GetVestingCoins(_ time.Time) sdk.Coins {\n\treturn plva.OriginalVesting\n}", "func (cva ContinuousVestingAccount) GetVestedCoins(blockTime time.Time) sdk.Coins {\n\tvar vestedCoins sdk.Coins\n\n\t// We must handle the case where the start time for a vesting account has\n\t// been set into the future or when the start of the chain is not exactly\n\t// known.\n\tif blockTime.Unix() <= cva.StartTime {\n\t\treturn vestedCoins\n\t} else if blockTime.Unix() >= cva.EndTime {\n\t\treturn cva.OriginalVesting\n\t}\n\n\t// calculate the vesting scalar\n\tx := blockTime.Unix() - cva.StartTime\n\ty := cva.EndTime - cva.StartTime\n\ts := sdk.NewDec(x).Quo(sdk.NewDec(y))\n\n\tfor _, ovc := range cva.OriginalVesting {\n\t\tvestedAmt := ovc.Amount.ToDec().Mul(s).RoundInt()\n\t\tvestedCoins = append(vestedCoins, sdk.NewCoin(ovc.Denom, vestedAmt))\n\t}\n\n\treturn vestedCoins\n}", "func (dva DelayedVestingAccount) GetVestedCoins(blockTime time.Time) sdk.Coins {\n\tif blockTime.Unix() >= dva.EndTime {\n\t\treturn dva.OriginalVesting\n\t}\n\n\treturn nil\n}", "func (vva ValidatorVestingAccount) GetVestedCoins(blockTime time.Time) sdk.Coins {\n\tvar vestedCoins sdk.Coins\n\tif blockTime.Unix() <= vva.StartTime {\n\t\treturn vestedCoins\n\t}\n\tcurrentPeriodStartTime := vva.StartTime\n\tnumberPeriods := len(vva.VestingPeriods)\n\tfor i := 0; i < numberPeriods; i++ {\n\t\tx := blockTime.Unix() - currentPeriodStartTime\n\t\tif x >= vva.VestingPeriods[i].Length {\n\t\t\tif vva.VestingPeriodProgress[i].PeriodComplete {\n\t\t\t\tvestedCoins = vestedCoins.Add(vva.VestingPeriods[i].Amount)\n\t\t\t}\n\t\t\tcurrentPeriodStartTime += vva.VestingPeriods[i].Length\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn vestedCoins\n\n}", "func (pva PeriodicVestingAccount) GetVestedCoins(blockTime time.Time) sdk.Coins {\n\tcoins := ReadSchedule(pva.StartTime, pva.EndTime, pva.VestingPeriods, pva.OriginalVesting, blockTime.Unix())\n\tif coins.IsZero() {\n\t\treturn nil\n\t}\n\treturn coins\n}", "func (va ClawbackVestingAccount) GetVestedCoins(blockTime time.Time) sdk.Coins {\n\t// It's likely that one or the other schedule will be nearly trivial,\n\t// so there should be little overhead in recomputing the conjunction each time.\n\tcoins := coinsMin(va.GetUnlockedOnly(blockTime), va.GetVestedOnly(blockTime))\n\tif coins.IsZero() {\n\t\treturn nil\n\t}\n\treturn coins\n}", "func (plva PermanentLockedAccount) GetVestedCoins(_ time.Time) sdk.Coins {\n\treturn nil\n}", "func GetCoins() (coins []Coin, error error) {\n\tvar c = []Coin{}\n\tvar d struct {\n\t\tCrypto []Coin `json:\"crypto\"`\n\t}\n\tjsonData, err := doTauRequest(1, \"GET\", \"data/coins\", nil)\n\tif err != nil {\n\t\treturn c, err\n\t}\n\tif err := json.Unmarshal(jsonData, &d); err != nil {\n\t\treturn c, err\n\t}\n\treturn d.Crypto, nil\n}", "func (keeper ViewKeeper) GetCoins(ctx sdk.Context, addr sdk.Address) sdk.Coins {\n\treturn getCoins(ctx, keeper.am, addr)\n}", "func (keeper BaseViewKeeper) GetCoins(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins {\n\treturn getCoins(ctx, keeper.am, addr)\n}", "func (bva BaseVestingAccount) LockedCoinsFromVesting(vestingCoins sdk.Coins) sdk.Coins {\n\tlockedCoins := vestingCoins.Sub(vestingCoins.Min(bva.DelegatedVesting))\n\tif lockedCoins == nil {\n\t\treturn sdk.Coins{}\n\t}\n\treturn lockedCoins\n}", "func (keeper SendKeeper) GetCoins(ctx sdk.Context, addr sdk.Address) sdk.Coins {\n\treturn getCoins(ctx, keeper.am, addr)\n}", "func (vva ValidatorVestingAccount) GetFailedVestedCoins() sdk.Coins {\n\tvar failedVestedCoins sdk.Coins\n\tnumberPeriods := len(vva.VestingPeriods)\n\tfor i := 0; i < numberPeriods; i++ {\n\t\tif vva.VestingPeriodProgress[i].PeriodComplete {\n\t\t\tif !vva.VestingPeriodProgress[i].VestingSuccessful {\n\t\t\t\tfailedVestedCoins = failedVestedCoins.Add(vva.VestingPeriods[i].Amount)\n\t\t\t}\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn failedVestedCoins\n}", "func (cva ContinuousVestingAccount) LockedCoins(ctx sdk.Context) sdk.Coins {\n\treturn cva.BaseVestingAccount.LockedCoinsFromVesting(cva.GetVestingCoins(ctx.BlockTime()))\n}", "func (va ClawbackVestingAccount) LockedCoins(ctx sdk.Context) sdk.Coins {\n\treturn va.BaseVestingAccount.LockedCoinsFromVesting(va.GetVestingCoins(ctx.BlockTime()))\n}", "func (t *TauAPI) GetCoins() (coins []Coin, error error) {\n\tvar c = []Coin{}\n\tvar d struct {\n\t\tCrypto []Coin `json:\"cryto\"` //typo from api\n\t\tFiat []Coin `json:\"fiat\"`\n\t}\n\tjsonData, err := t.doTauRequest(&TauReq{\n\t\tVersion: 2,\n\t\tMethod: \"GET\",\n\t\tPath: \"coins\",\n\t})\n\tif err != nil {\n\t\treturn c, err\n\t}\n\tif err := json.Unmarshal(jsonData, &d); err != nil {\n\t\treturn c, err\n\t}\n\tc = append(d.Crypto, d.Fiat...)\n\treturn c, nil\n}", "func (keeper Keeper) GetCoins(ctx sdk.Context, addr sdk.Address) sdk.Coins {\n\treturn getCoins(ctx, keeper.am, addr)\n}", "func coins(a int) int {\n\tif a == 0 {\n\t\treturn 0\n\t}\n\treturn doCoins(a, 25)\n}", "func (vva ValidatorVestingAccount) SpendableCoins(blockTime time.Time) sdk.Coins {\n\treturn vva.BaseVestingAccount.SpendableCoinsVestingAccount(vva.GetVestingCoins(blockTime))\n}", "func (pva PeriodicVestingAccount) LockedCoins(ctx sdk.Context) sdk.Coins {\n\treturn pva.BaseVestingAccount.LockedCoinsFromVesting(pva.GetVestingCoins(ctx.BlockTime()))\n}", "func (dva DelayedVestingAccount) LockedCoins(ctx sdk.Context) sdk.Coins {\n\treturn dva.BaseVestingAccount.LockedCoinsFromVesting(dva.GetVestingCoins(ctx.BlockTime()))\n}", "func GetCoins(accCoins []types.Coin) AccountCoins {\n\tcoins := make(AccountCoins, 0)\n\tfor _, coin := range accCoins {\n\t\tcoins = append(coins, AccountCoin{Amount: uint64(coin.Amount), Denom: coin.Denom})\n\t}\n\treturn coins\n}", "func (m *Client) GetCoins() ([]string, error) {\n\tresp, err := m.Service.GetCoins()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error requesting coin list: %s\", err)\n\t}\n\tdefer resp.Body.Close()\n\n\tvar response []string\n\terr = json.NewDecoder(resp.Body).Decode(&response)\n\tif err != nil {\n\t\tmsg, _ := ioutil.ReadAll(resp.Body)\n\t\treturn nil, fmt.Errorf(\"error decoding coin list: %s: %s\", msg, err)\n\t}\n\n\treturn response, nil\n}", "func (ck CoinKeeper) GetCoins(ctx sdk.Context, addr sdk.Address, amt sdk.Coins) sdk.Coins {\n\tacc := ck.am.GetAccount(ctx, addr)\n\treturn acc.GetCoins()\n}", "func (bva BaseVestingAccount) GetOriginalVesting() sdk.Coins {\n\treturn bva.OriginalVesting\n}", "func (k Keeper) GetWinnerIncentives(ctx sdk.Context) float32 {\n\tgames := float32(k.GetGames(ctx))\n\tvotes := float32(k.GetVotes(ctx))\n\tgVR := float32(k.GetParams(ctx).GameVoteRatio) / 100\n\treturn games / (votes*gVR + games)\n}", "func (o *Transaction) GetCounterparties() []TransactionCounterparty {\n\tif o == nil || o.Counterparties == nil {\n\t\tvar ret []TransactionCounterparty\n\t\treturn ret\n\t}\n\treturn *o.Counterparties\n}", "func (cs *Coins) CoinSelect(amount uint64, asset string) (unspents []explorer.Utxo, change uint64, err error) {\n\tchange = 0\n\tunspents = []explorer.Utxo{}\n\tavailableSats := uint64(0)\n\n\tfor index, unspent := range cs.Utxos {\n\t\tu := unspent\n\t\tassetHash := u.Asset()\n\t\tamountSatoshis := u.Value()\n\t\tif len(u.AssetCommitment()) > 0 && len(u.ValueCommitment()) > 0 {\n\t\t\tbk := cs.BlindingKey\n\t\t\tif len(cs.BlindingKeys) > 0 {\n\t\t\t\tbk = cs.BlindingKeys[index]\n\t\t\t}\n\t\t\tav, err := unblindUxto(u, bk)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, 0, err\n\t\t\t}\n\t\t\tassetHash = av.asset\n\t\t\tamountSatoshis = av.value\n\t\t}\n\t\tif asset == assetHash {\n\t\t\tunspents = append(unspents, unspent)\n\t\t\tavailableSats += amountSatoshis\n\n\t\t\tif availableSats >= amount {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\tif availableSats < amount {\n\t\treturn nil, 0, errors.New(\"You do not have enough coins\")\n\t}\n\n\tchange = availableSats - amount\n\n\treturn unspents, change, nil\n}", "func (candidate *Candidate) GetTotalBipStake() *big.Int {\n\tcandidate.lock.RLock()\n\tdefer candidate.lock.RUnlock()\n\n\treturn big.NewInt(0).Set(candidate.totalBipStake)\n}", "func (_TokenVesting *TokenVestingCaller) VestedAmount(opts *bind.CallOpts, _token common.Address) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _TokenVesting.contract.Call(opts, out, \"vestedAmount\", _token)\n\treturn *ret0, err\n}", "func (m *TeamSummary) GetGuestsCount()(*int32) {\n return m.guestsCount\n}", "func (_TokenVesting *TokenVestingSession) VestedAmount(_token common.Address) (*big.Int, error) {\n\treturn _TokenVesting.Contract.VestedAmount(&_TokenVesting.CallOpts, _token)\n}", "func (_Contracts *ContractsCaller) VotersCount(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _Contracts.contract.Call(opts, out, \"votersCount\")\n\treturn *ret0, err\n}", "func (_TokenVesting *TokenVestingCallerSession) VestedAmount(_token common.Address) (*big.Int, error) {\n\treturn _TokenVesting.Contract.VestedAmount(&_TokenVesting.CallOpts, _token)\n}", "func (gc *GovernanceContract) TotalVotingPower() (hexutil.Big, error) {\n\treturn gc.repo.GovernanceTotalWeight(&gc.Address)\n}", "func (m *TeamSummary) GetOwnersCount()(*int32) {\n return m.ownersCount\n}", "func (o *Transaction) GetCounterpartiesOk() (*[]TransactionCounterparty, bool) {\n\tif o == nil || o.Counterparties == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Counterparties, true\n}", "func (r *ParseResult) GetVoutAmount(vout int) (*big.Int, error) {\n\tamt := big.NewInt(0)\n\n\tif !(r.TokenType == TokenTypeFungible01 ||\n\t\tr.TokenType == TokenTypeNft1Child41 ||\n\t\tr.TokenType == TokenTypeNft1Group81) {\n\t\treturn nil, errors.New(\"cannot extract amount for not type 1 or NFT1 token\")\n\t}\n\n\tif vout == 0 {\n\t\treturn amt, nil\n\t}\n\n\tif r.TransactionType == TransactionTypeSend {\n\t\tif vout > len(r.Data.(SlpSend).Amounts) {\n\t\t\treturn amt, nil\n\t\t}\n\t\treturn amt.Add(amt, new(big.Int).SetUint64(r.Data.(SlpSend).Amounts[vout-1])), nil\n\t} else if r.TransactionType == TransactionTypeMint {\n\t\tif vout == 1 {\n\t\t\treturn amt.Add(amt, new(big.Int).SetUint64(r.Data.(SlpMint).Qty)), nil\n\t\t}\n\t\treturn amt, nil\n\t} else if r.TransactionType == TransactionTypeGenesis {\n\t\tif vout == 1 {\n\t\t\treturn amt.Add(amt, new(big.Int).SetUint64(r.Data.(SlpGenesis).Qty)), nil\n\t\t}\n\t\treturn amt, nil\n\t}\n\treturn nil, errors.New(\"unknown error getting vout amount\")\n}", "func (va ClawbackVestingAccount) GetVestedOnly(blockTime time.Time) sdk.Coins {\n\treturn ReadSchedule(va.StartTime, va.EndTime, va.VestingPeriods, va.OriginalVesting, blockTime.Unix())\n}", "func (b *rpcVestingBalance) delegated() (sdk.Coins, sdk.Coins, error) {\n\tdelegatedCoins, err := b.totalDelegated()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tunbondingCoins, err := b.totalUnbondingDelegations()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tdelegated := delegatedCoins.AmountOf(stakingDenom)\n\tunbonding := unbondingCoins.AmountOf(stakingDenom)\n\ttotalStaked := delegated.Add(unbonding)\n\tdelegatedFree := b.vacc.GetDelegatedFree().AmountOf(stakingDenom)\n\n\t// total number of staked and unbonding tokens considered to be liquid\n\ttotalFree := sdk.MinInt(totalStaked, delegatedFree)\n\t// any coins that are not considered liquid, are vesting up to a maximum of delegated\n\tstakedVesting := sdk.MinInt(totalStaked.Sub(totalFree), delegated)\n\t// staked free coins are left over\n\tstakedFree := delegated.Sub(stakedVesting)\n\n\tliquidCoins := sdk.NewCoins(newKavaCoin(stakedFree))\n\tvestingCoins := sdk.NewCoins(newKavaCoin(stakedVesting))\n\treturn liquidCoins, vestingCoins, nil\n}", "func (r *Repository) GetAmountsOfManageCandidates(ctx context.Context, companyID string) (int32, int32, error) {\n\tobjCompanyID, err := primitive.ObjectIDFromHex(companyID)\n\tif err != nil {\n\t\treturn 0, 0, errors.New(`wrong_id`)\n\t}\n\n\tamount := struct {\n\t\tSaved int32 `bson:\"saved_candidates\"`\n\t\tSkipped int32 `bson:\"skipped_candidates\"`\n\t\t// Alerts int32 `bson:\"alerts\"`\n\t}{}\n\n\tcursor, err := r.companiesCollection.Aggregate(\n\t\tctx,\n\t\t[]bson.M{\n\t\t\t{\n\t\t\t\t\"$match\": bson.M{\n\t\t\t\t\t\"company_id\": objCompanyID,\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\t\"$addFields\": bson.M{\n\t\t\t\t\t\"saved_candidates\": bson.M{\n\t\t\t\t\t\t\"$size\": \"$saved_candidates\",\n\t\t\t\t\t},\n\t\t\t\t\t\"skipped_candidates\": bson.M{\n\t\t\t\t\t\t\"$size\": \"$skipped_candidates\",\n\t\t\t\t\t},\n\t\t\t\t\t// \"alerts\": bson.M{\n\t\t\t\t\t// \t\"$size\": \"$alerts\", // TODO:\n\t\t\t\t\t// },\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\t\"$project\": bson.M{\n\t\t\t\t\t\"saved_candidates\": 1,\n\t\t\t\t\t\"skipped_candidates\": 1,\n\t\t\t\t\t// \"alerts\": 1,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t)\n\tif err != nil {\n\t\tif err == mongo.ErrNoDocuments {\n\t\t\treturn 0, 0, errors.New(`not_found`)\n\t\t}\n\t\treturn 0, 0, err\n\t}\n\tdefer cursor.Close(ctx)\n\n\tif cursor.Next(ctx) {\n\t\terr = cursor.Decode(&amount)\n\t\tif err != nil {\n\t\t\treturn 0, 0, err\n\t\t}\n\t}\n\n\treturn amount.Saved, amount.Skipped, nil\n}", "func distributeCoins(root *TreeNode) int {\n\tres := 0\n\tif root.Left != nil {\n\t\tres += distributeCoins(root.Left)\n\t\troot.Val += root.Left.Val - 1\n\t\tres += int(math.Abs(float64(root.Left.Val - 1)))\n\t}\n\tif root.Right != nil {\n\t\tres += distributeCoins(root.Right)\n\t\troot.Val += root.Right.Val - 1\n\t\tres += int(math.Abs(float64(root.Right.Val - 1)))\n\t}\n\treturn res\n}", "func TestGetSupportCoins(t *testing.T) {\n\tt.Parallel()\n\tif _, err := ok.GetSupportCoins(context.Background()); err != nil {\n\t\tt.Error(\"Okx GetSupportCoins() error\", err)\n\t}\n}", "func (plva PermanentLockedAccount) LockedCoins(_ sdk.Context) sdk.Coins {\n\treturn plva.BaseVestingAccount.LockedCoinsFromVesting(plva.OriginalVesting)\n}", "func (keeper BaseViewKeeper) HasCoins(ctx sdk.Context, addr sdk.AccAddress, amt sdk.Coins) bool {\n\treturn hasCoins(ctx, keeper.am, addr, amt)\n}", "func (c *CoordinatorHelper) Coins(\n\tctx context.Context,\n\tdbTx storage.DatabaseTransaction,\n\taccountIdentifier *types.AccountIdentifier,\n\tcurrency *types.Currency,\n) ([]*types.Coin, error) {\n\tcoins, _, err := c.coinStorage.GetCoinsTransactional(\n\t\tctx,\n\t\tdbTx,\n\t\taccountIdentifier,\n\t)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"%w: unable to get coins\", err)\n\t}\n\n\tcoinsToReturn := []*types.Coin{}\n\tfor _, coin := range coins {\n\t\tif types.Hash(coin.Amount.Currency) != types.Hash(currency) {\n\t\t\tcontinue\n\t\t}\n\n\t\tcoinsToReturn = append(coinsToReturn, coin)\n\t}\n\n\treturn coinsToReturn, nil\n}", "func (n Network) VestingAccounts(ctx context.Context, launchID uint64) (vestingAccs []networktypes.VestingAccount, err error) {\n\tn.ev.Send(events.New(events.StatusOngoing, \"Fetching genesis vesting accounts\"))\n\tres, err := n.launchQuery.\n\t\tVestingAccountAll(ctx,\n\t\t\t&launchtypes.QueryAllVestingAccountRequest{\n\t\t\t\tLaunchID: launchID,\n\t\t\t},\n\t\t)\n\tif err != nil {\n\t\treturn vestingAccs, err\n\t}\n\n\tfor i, acc := range res.VestingAccount {\n\t\tparsedAcc, err := networktypes.ToVestingAccount(acc)\n\t\tif err != nil {\n\t\t\treturn vestingAccs, errors.Wrapf(err, \"error parsing vesting account %d\", i)\n\t\t}\n\n\t\tvestingAccs = append(vestingAccs, parsedAcc)\n\t}\n\n\treturn vestingAccs, nil\n}", "func (_Contracts *ContractsCaller) VotesCount(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _Contracts.contract.Call(opts, out, \"votesCount\")\n\treturn *ret0, err\n}", "func (c Cart) GetVoucherSavings() domain.Price {\n\tprice := domain.Price{}\n\tvar err error\n\n\tfor _, item := range c.Totalitems {\n\t\tif item.Type == TotalsTypeVoucher {\n\t\t\tprice, err = price.Add(item.Price)\n\t\t\tif err != nil {\n\t\t\t\treturn price\n\t\t\t}\n\t\t}\n\t}\n\n\tif price.IsNegative() {\n\t\treturn domain.Price{}\n\t}\n\n\treturn price\n}", "func (keeper ViewKeeper) HasCoins(ctx sdk.Context, addr sdk.Address, amt sdk.Coins) bool {\n\treturn hasCoins(ctx, keeper.am, addr, amt)\n}", "func distributeCoins(root *TreeNode) int {\n\tres := 0\n\tvar dfs func(root *TreeNode) int\n\tabs := func(a int) int {\n\t\tif a < 0 {\n\t\t\treturn -a\n\t\t}\n\t\treturn a\n\t}\n\tdfs = func(root *TreeNode) int {\n\t\tif root == nil {\n\t\t\treturn 0\n\t\t}\n\t\tleft := dfs(root.Left)\n\t\tright := dfs(root.Right)\n\t\tres += abs(left) + abs(right)\n\t\treturn left + right + root.Val - 1\n\t}\n\tdfs(root)\n\treturn res\n}", "func (_Bindings *BindingsCallerSession) TotalReserves() (*big.Int, error) {\n\treturn _Bindings.Contract.TotalReserves(&_Bindings.CallOpts)\n}", "func newCoins() sdk.Coins {\n\treturn sdk.Coins{\n\t\tsdk.NewInt64Coin(\"atom\", 10000000),\n\t}\n}", "func (_Gatekeeper *GatekeeperCaller) GetRootsCount(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _Gatekeeper.contract.Call(opts, out, \"GetRootsCount\")\n\treturn *ret0, err\n}", "func (dcr *ExchangeWallet) FundingCoins(ids []dex.Bytes) (asset.Coins, error) {\n\t// First check if we have the coins in cache.\n\tcoins := make(asset.Coins, 0, len(ids))\n\tnotFound := make(map[outPoint]bool)\n\tdcr.fundingMtx.Lock()\n\tdefer dcr.fundingMtx.Unlock() // stay locked until we update the map and lock them in the wallet\n\tfor _, id := range ids {\n\t\ttxHash, vout, err := decodeCoinID(id)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tpt := newOutPoint(txHash, vout)\n\t\tfundingCoin, found := dcr.fundingCoins[pt]\n\t\tif found {\n\t\t\tcoins = append(coins, fundingCoin.op)\n\t\t\tcontinue\n\t\t}\n\t\tnotFound[pt] = true\n\t}\n\tif len(notFound) == 0 {\n\t\treturn coins, nil\n\t}\n\n\t// Check locked outputs for not found coins.\n\tlockedOutputs, err := dcr.lockedOutputs()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor _, output := range lockedOutputs {\n\t\ttxHash, err := chainhash.NewHashFromStr(output.Txid)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error decoding txid from rpc server %s: %w\", output.Txid, err)\n\t\t}\n\t\tpt := newOutPoint(txHash, output.Vout)\n\t\tif !notFound[pt] {\n\t\t\tcontinue\n\t\t}\n\t\ttxOut, err := dcr.node.GetTxOut(dcr.ctx, txHash, output.Vout, true)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"gettxout error for locked output %v: %w\", pt.String(), translateRPCCancelErr(err))\n\t\t}\n\t\tvar address string\n\t\tif len(txOut.ScriptPubKey.Addresses) > 0 {\n\t\t\taddress = txOut.ScriptPubKey.Addresses[0]\n\t\t}\n\t\tcoin := newOutput(txHash, output.Vout, toAtoms(output.Amount), output.Tree)\n\t\tcoins = append(coins, coin)\n\t\tdcr.fundingCoins[pt] = &fundingCoin{\n\t\t\top: coin,\n\t\t\taddr: address,\n\t\t}\n\t\tdelete(notFound, pt)\n\t\tif len(notFound) == 0 {\n\t\t\treturn coins, nil\n\t\t}\n\t}\n\n\t// Some funding coins still not found after checking locked outputs.\n\t// Check wallet unspent outputs as last resort. Lock the coins if found.\n\tunspents, err := dcr.unspents()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcoinsToLock := make([]*wire.OutPoint, 0, len(notFound))\n\tfor _, txout := range unspents {\n\t\ttxHash, err := chainhash.NewHashFromStr(txout.TxID)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error decoding txid from rpc server %s: %w\", txout.TxID, err)\n\t\t}\n\t\tpt := newOutPoint(txHash, txout.Vout)\n\t\tif !notFound[pt] {\n\t\t\tcontinue\n\t\t}\n\t\tcoinsToLock = append(coinsToLock, wire.NewOutPoint(txHash, txout.Vout, txout.Tree))\n\t\tcoin := newOutput(txHash, txout.Vout, toAtoms(txout.Amount), txout.Tree)\n\t\tcoins = append(coins, coin)\n\t\tdcr.fundingCoins[pt] = &fundingCoin{\n\t\t\top: coin,\n\t\t\taddr: txout.Address,\n\t\t}\n\t\tdelete(notFound, pt)\n\t\tif len(notFound) == 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\tif len(notFound) != 0 {\n\t\tids := make([]string, 0, len(notFound))\n\t\tfor pt := range notFound {\n\t\t\tids = append(ids, pt.String())\n\t\t}\n\t\treturn nil, fmt.Errorf(\"funding coins not found: %s\", strings.Join(ids, \", \"))\n\t}\n\tdcr.log.Debugf(\"Locking funding coins that were unlocked %v\", coinsToLock)\n\terr = dcr.node.LockUnspent(dcr.ctx, false, coinsToLock)\n\tif err != nil {\n\t\treturn nil, translateRPCCancelErr(err)\n\t}\n\n\treturn coins, nil\n}", "func (_Bindings *BindingsSession) TotalReserves() (*big.Int, error) {\n\treturn _Bindings.Contract.TotalReserves(&_Bindings.CallOpts)\n}", "func (cm *ConnectionManager) sumDeposits() *big.Int {\n\tchs := cm.openChannels()\n\tvar sum = big.NewInt(0)\n\tfor _, c := range chs {\n\t\tsum.Add(sum, c.OurContractBalance)\n\t}\n\treturn sum\n}", "func (_Bep20 *Bep20Caller) GetCurrentVotes(opts *bind.CallOpts, account common.Address) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _Bep20.contract.Call(opts, &out, \"getCurrentVotes\", account)\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func drawCoins() int {\n\treturn rand.Intn(maxCoins+1-minCoins) + minCoins\n}", "func (_Contracts *ContractsCallerSession) VotersCount() (*big.Int, error) {\n\treturn _Contracts.Contract.VotersCount(&_Contracts.CallOpts)\n}", "func (_CrToken *CrTokenCallerSession) TotalReserves() (*big.Int, error) {\n\treturn _CrToken.Contract.TotalReserves(&_CrToken.CallOpts)\n}", "func (dcr *ExchangeWallet) FundingCoins(ids []dex.Bytes) (asset.Coins, error) {\n\t// First check if we have the coins in cache.\n\tcoins := make(asset.Coins, 0, len(ids))\n\tnotFound := make(map[outPoint]bool)\n\tdcr.fundingMtx.Lock()\n\tdefer dcr.fundingMtx.Unlock() // stay locked until we update the map and lock them in the wallet\n\tfor _, id := range ids {\n\t\ttxHash, vout, err := decodeCoinID(id)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tpt := newOutPoint(txHash, vout)\n\t\tfundingCoin, found := dcr.fundingCoins[pt]\n\t\tif found {\n\t\t\tcoins = append(coins, fundingCoin.op)\n\t\t\tcontinue\n\t\t}\n\t\tnotFound[pt] = true\n\t}\n\tif len(notFound) == 0 {\n\t\treturn coins, nil\n\t}\n\n\t// Check locked outputs for not found coins.\n\tfor _, acct := range dcr.fundingAccounts() {\n\t\tlockedOutputs, err := dcr.wallet.LockedOutputs(dcr.ctx, acct)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfor _, output := range lockedOutputs {\n\t\t\ttxHash, err := chainhash.NewHashFromStr(output.Txid)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"error decoding txid from rpc server %s: %w\", output.Txid, err)\n\t\t\t}\n\t\t\tpt := newOutPoint(txHash, output.Vout)\n\t\t\tif !notFound[pt] {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ttxOut, err := dcr.wallet.UnspentOutput(dcr.ctx, txHash, output.Vout, output.Tree)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"gettxout error for locked output %v: %w\", pt.String(), err)\n\t\t\t}\n\t\t\tvar address string\n\t\t\tif len(txOut.Addresses) > 0 {\n\t\t\t\taddress = txOut.Addresses[0]\n\t\t\t}\n\t\t\tcoin := newOutput(txHash, output.Vout, toAtoms(output.Amount), output.Tree)\n\t\t\tcoins = append(coins, coin)\n\t\t\tdcr.fundingCoins[pt] = &fundingCoin{\n\t\t\t\top: coin,\n\t\t\t\taddr: address,\n\t\t\t}\n\t\t\tdelete(notFound, pt)\n\t\t\tif len(notFound) == 0 {\n\t\t\t\treturn coins, nil\n\t\t\t}\n\t\t}\n\t}\n\n\t// Some funding coins still not found after checking locked outputs.\n\t// Check wallet unspent outputs as last resort. Lock the coins if found.\n\tcoinsToLock := make([]*wire.OutPoint, 0, len(notFound))\n\tfor _, acct := range dcr.fundingAccounts() {\n\t\tunspents, err := dcr.wallet.Unspents(dcr.ctx, acct)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfor _, txout := range unspents {\n\t\t\ttxHash, err := chainhash.NewHashFromStr(txout.TxID)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"error decoding txid from rpc server %s: %w\", txout.TxID, err)\n\t\t\t}\n\t\t\tpt := newOutPoint(txHash, txout.Vout)\n\t\t\tif !notFound[pt] {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tcoinsToLock = append(coinsToLock, wire.NewOutPoint(txHash, txout.Vout, txout.Tree))\n\t\t\tcoin := newOutput(txHash, txout.Vout, toAtoms(txout.Amount), txout.Tree)\n\t\t\tcoins = append(coins, coin)\n\t\t\tdcr.fundingCoins[pt] = &fundingCoin{\n\t\t\t\top: coin,\n\t\t\t\taddr: txout.Address,\n\t\t\t}\n\t\t\tdelete(notFound, pt)\n\t\t\tif len(notFound) == 0 {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\t// Return an error if some coins are still not found.\n\tif len(notFound) != 0 {\n\t\tids := make([]string, 0, len(notFound))\n\t\tfor pt := range notFound {\n\t\t\tids = append(ids, pt.String())\n\t\t}\n\t\treturn nil, fmt.Errorf(\"funding coins not found: %s\", strings.Join(ids, \", \"))\n\t}\n\n\tdcr.log.Debugf(\"Locking funding coins that were unlocked %v\", coinsToLock)\n\terr := dcr.wallet.LockUnspent(dcr.ctx, false, coinsToLock)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn coins, nil\n}", "func (e *Election) Votes() int {\n\tcount := 0\n\tfor _, ballot := range e.ballots {\n\t\tif ballot {\n\t\t\tcount++\n\t\t}\n\t}\n\treturn count\n}", "func (keeper Keeper) SubtractCoins(ctx sdk.Context, addr sdk.Address, amt sdk.Coins) (sdk.Coins, sdk.Error) {\n\treturn subtractCoins(ctx, keeper.am, addr, amt)\n}", "func (_Contracts *ContractsSession) VotersCount() (*big.Int, error) {\n\treturn _Contracts.Contract.VotersCount(&_Contracts.CallOpts)\n}", "func (bva BaseVestingAccount) GetDelegatedVesting() sdk.Coins {\n\treturn bva.DelegatedVesting\n}", "func getOVMETHTotalSupply(inStateDB *state.StateDB) *big.Int {\n\tposition := common.Big2\n\tkey := common.BytesToHash(common.LeftPadBytes(position.Bytes(), 32))\n\treturn inStateDB.GetState(OVMETHAddress, key).Big()\n}", "func (p *Player) CashSpentTotal() int {\n\treturn p.AdditionalPlayerInformation.TotalCashSpent\n}", "func (_CrToken *CrTokenSession) TotalReserves() (*big.Int, error) {\n\treturn _CrToken.Contract.TotalReserves(&_CrToken.CallOpts)\n}", "func (a *Agent) GetPeersCount() uint32 {\n\treturn atomic.LoadUint32(&a.peersCount)\n}", "func (c Checkout) Total() int {\n\ttotal := 0\n\tfor code, quantity := range c.basket {\n\t\toffer, exists := offers[code]\n\t\tif exists {\n\t\t\ttotal += calculateOfferPrice(code, quantity, offer)\n\t\t} else {\n\t\t\ttotal += calculatePrice(code, quantity)\n\t\t}\n\t}\n\treturn total\n}", "func (btc *ExchangeWallet) FundingCoins(ids []dex.Bytes) (asset.Coins, error) {\n\t// First check if we have the coins in cache.\n\tcoins := make(asset.Coins, 0, len(ids))\n\tnotFound := make(map[string]struct{})\n\tbtc.fundingMtx.RLock()\n\tfor _, id := range ids {\n\t\ttxHash, vout, err := decodeCoinID(id)\n\t\tif err != nil {\n\t\t\tbtc.fundingMtx.RUnlock()\n\t\t\treturn nil, err\n\t\t}\n\t\topID := outpointID(txHash.String(), vout)\n\t\tfundingCoin, found := btc.fundingCoins[opID]\n\t\tif found {\n\t\t\tcoins = append(coins, newOutput(btc.node, txHash, vout, fundingCoin.amount, fundingCoin.redeemScript))\n\t\t\tcontinue\n\t\t}\n\t\tnotFound[opID] = struct{}{}\n\t}\n\tbtc.fundingMtx.RUnlock()\n\tif len(notFound) == 0 {\n\t\treturn coins, nil\n\t}\n\t_, utxoMap, _, err := btc.spendableUTXOs(0)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlockers := make([]*output, 0, len(ids))\n\tbtc.fundingMtx.Lock()\n\tdefer btc.fundingMtx.Unlock()\n\tfor _, id := range ids {\n\t\ttxHash, vout, err := decodeCoinID(id)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\topID := outpointID(txHash.String(), vout)\n\t\tutxo, found := utxoMap[opID]\n\t\tif !found {\n\t\t\treturn nil, fmt.Errorf(\"funding coin %s not found\", opID)\n\t\t}\n\t\tbtc.fundingCoins[opID] = utxo\n\t\tcoin := newOutput(btc.node, utxo.txHash, utxo.vout, utxo.amount, utxo.redeemScript)\n\t\tcoins = append(coins, coin)\n\t\tlockers = append(lockers, coin)\n\t\tdelete(notFound, opID)\n\t\tif len(notFound) == 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\tif len(notFound) != 0 {\n\t\tids := make([]string, 0, len(notFound))\n\t\tfor opID := range notFound {\n\t\t\tids = append(ids, opID)\n\t\t}\n\t\treturn nil, fmt.Errorf(\"coins not found: %s\", strings.Join(ids, \", \"))\n\t}\n\terr = btc.wallet.LockUnspent(false, lockers)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn coins, nil\n}", "func (_Vault *VaultSession) GetDecimals(token common.Address) (uint8, error) {\n\treturn _Vault.Contract.GetDecimals(&_Vault.CallOpts, token)\n}", "func (_Bindings *BindingsCaller) TotalReserves(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _Bindings.contract.Call(opts, out, \"totalReserves\")\n\treturn *ret0, err\n}", "func (_Vault *VaultCaller) GetDecimals(opts *bind.CallOpts, token common.Address) (uint8, error) {\n\tvar (\n\t\tret0 = new(uint8)\n\t)\n\tout := ret0\n\terr := _Vault.contract.Call(opts, out, \"getDecimals\", token)\n\treturn *ret0, err\n}", "func arrangeCoins(n int) int {\n\tcount := 1\n\tfor n >= count {\n\t\tn -= count\n\t\tcount++\n\t}\n\treturn count - 1\n}", "func (_Vault *VaultCallerSession) GetDecimals(token common.Address) (uint8, error) {\n\treturn _Vault.Contract.GetDecimals(&_Vault.CallOpts, token)\n}", "func (dcr *ExchangeWallet) ReturnCoins(unspents asset.Coins) error {\n\tdcr.fundingMtx.Lock()\n\tdefer dcr.fundingMtx.Unlock()\n\treturn dcr.returnCoins(unspents)\n}", "func (_Cakevault *CakevaultSession) TotalShares() (*big.Int, error) {\n\treturn _Cakevault.Contract.TotalShares(&_Cakevault.CallOpts)\n}", "func getMoneyAmount(n int) int {\n \n}", "func (_Bep20 *Bep20CallerSession) GetCurrentVotes(account common.Address) (*big.Int, error) {\n\treturn _Bep20.Contract.GetCurrentVotes(&_Bep20.CallOpts, account)\n}", "func TotalCoinsInvariant(ak auth.AccountKeeper, totalSupplyFn func() sdk.Coins) sdk.Invariant {\n\treturn func(ctx sdk.Context) error {\n\t\ttotalCoins := sdk.NewCoins()\n\n\t\tchkAccount := func(acc auth.Account) bool {\n\t\t\tcoins := acc.GetCoins()\n\t\t\ttotalCoins = totalCoins.Add(coins)\n\t\t\treturn false\n\t\t}\n\n\t\tak.IterateAccounts(ctx, chkAccount)\n\t\tif !totalSupplyFn().IsEqual(totalCoins) {\n\t\t\treturn errors.New(\"total calculated coins doesn't equal expected coins\")\n\t\t}\n\t\treturn nil\n\t}\n}", "func ChooseBestOutCoinsToSpent(utxos []*crypto.InputCoin, amount uint64) (\n\tresultOutputCoins []*crypto.InputCoin,\n\tremainOutputCoins []*crypto.InputCoin,\n\ttotalResultOutputCoinAmount uint64, err error) {\n\n\tresultOutputCoins = make([]*crypto.InputCoin, 0)\n\tremainOutputCoins = make([]*crypto.InputCoin, 0)\n\ttotalResultOutputCoinAmount = uint64(0)\n\n\t// either take the smallest coins, or a single largest one\n\tvar outCoinOverLimit *crypto.InputCoin\n\toutCoinsUnderLimit := make([]*crypto.InputCoin, 0)\n\tfor _, outCoin := range utxos {\n\t\tif outCoin.CoinDetails.GetValue() < amount {\n\t\t\toutCoinsUnderLimit = append(outCoinsUnderLimit, outCoin)\n\t\t} else if outCoinOverLimit == nil {\n\t\t\toutCoinOverLimit = outCoin\n\t\t} else if outCoinOverLimit.CoinDetails.GetValue() > outCoin.CoinDetails.GetValue() {\n\t\t\tremainOutputCoins = append(remainOutputCoins, outCoin)\n\t\t} else {\n\t\t\tremainOutputCoins = append(remainOutputCoins, outCoinOverLimit)\n\t\t\toutCoinOverLimit = outCoin\n\t\t}\n\t}\n\tsort.Slice(outCoinsUnderLimit, func(i, j int) bool {\n\t\treturn outCoinsUnderLimit[i].CoinDetails.GetValue() < outCoinsUnderLimit[j].CoinDetails.GetValue()\n\t})\n\tfor _, outCoin := range outCoinsUnderLimit {\n\t\tif totalResultOutputCoinAmount < amount {\n\t\t\ttotalResultOutputCoinAmount += outCoin.CoinDetails.GetValue()\n\t\t\tresultOutputCoins = append(resultOutputCoins, outCoin)\n\t\t} else {\n\t\t\tremainOutputCoins = append(remainOutputCoins, outCoin)\n\t\t}\n\t}\n\tif outCoinOverLimit != nil && (outCoinOverLimit.CoinDetails.GetValue() > 2*amount || totalResultOutputCoinAmount < amount) {\n\t\tremainOutputCoins = append(remainOutputCoins, resultOutputCoins...)\n\t\tresultOutputCoins = []*crypto.InputCoin{outCoinOverLimit}\n\t\ttotalResultOutputCoinAmount = outCoinOverLimit.CoinDetails.GetValue()\n\t} else if outCoinOverLimit != nil {\n\t\tremainOutputCoins = append(remainOutputCoins, outCoinOverLimit)\n\t}\n\tif totalResultOutputCoinAmount < amount {\n\t\treturn resultOutputCoins, remainOutputCoins, totalResultOutputCoinAmount, errors.New(\"Not enough coin\")\n\t} else {\n\t\treturn resultOutputCoins, remainOutputCoins, totalResultOutputCoinAmount, nil\n\t}\n}", "func (_CrToken *CrTokenCaller) TotalReserves(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _CrToken.contract.Call(opts, &out, \"totalReserves\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func GetTotalVestingPeriodLength(periods vesting.Periods) int64 {\n\tlength := int64(0)\n\tfor _, period := range periods {\n\t\tlength += period.Length\n\t}\n\treturn length\n}", "func (_ReserveSpenderMultiSig *ReserveSpenderMultiSigCaller) GetTransactionCount(opts *bind.CallOpts, pending bool, executed bool) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _ReserveSpenderMultiSig.contract.Call(opts, out, \"getTransactionCount\", pending, executed)\n\treturn *ret0, err\n}", "func GetTotalVestingPeriodLength(periods vestingtypes.Periods) int64 {\n\tlength := int64(0)\n\tfor _, period := range periods {\n\t\tlength += period.Length\n\t}\n\treturn length\n}", "func (m *Machine) ReturnCoins() {\n\tcoins := m.cashEngine.DropCoins()\n\n\ts := fmt.Sprintf(\"-> \")\n\tfor i, c := range coins {\n\t\tif i == len(coins)-1 {\n\t\t\ts += fmt.Sprintf(\"%s\", c.value.String())\n\t\t\tcontinue\n\t\t}\n\t\ts += fmt.Sprintf(\"%s, \", c.value.String())\n\t}\n\n\tm.logger.Println(s)\n}", "func (_Bep20 *Bep20Session) GetCurrentVotes(account common.Address) (*big.Int, error) {\n\treturn _Bep20.Contract.GetCurrentVotes(&_Bep20.CallOpts, account)\n}", "func (keeper SendKeeper) HasCoins(ctx sdk.Context, addr sdk.Address, amt sdk.Coins) bool {\n\treturn hasCoins(ctx, keeper.am, addr, amt)\n}", "func (serv *ExchangeServer) GetSupportCoins() []string {\n\tsymbols := make([]string, len(serv.coins))\n\ti := 0\n\tfor _, coin := range serv.coins {\n\t\tsymbols[i] = coin.Symbol()\n\t\ti++\n\t}\n\treturn symbols\n}", "func (o *AllocationList) GetInvested() float64 {\n\tif o == nil {\n\t\tvar ret float64\n\t\treturn ret\n\t}\n\n\treturn o.Invested\n}", "func (_Gatekeeper *GatekeeperCaller) GetTransactionCount(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _Gatekeeper.contract.Call(opts, out, \"GetTransactionCount\")\n\treturn *ret0, err\n}", "func (t *TezTracker) GetStakingRatio() (float64, error) {\n\tlockedBalanceEstimate, err := t.getLockedBalance()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tar := t.repoProvider.GetAccount()\n\tliquidBalance, err := ar.TotalBalance()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tbr := t.repoProvider.GetBaker()\n\tstakedBalance, err := br.TotalStakingBalance()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tsupply := liquidBalance + lockedBalanceEstimate\n\tif supply == 0 {\n\t\treturn 0, nil\n\t}\n\n\tlastBlock, err := t.repoProvider.GetBlock().Last()\n\tif err != nil {\n\t\treturn 0, nil\n\t}\n\n\tbakingRewards, err := br.TotalBakingRewards(\"\", lastBlock.MetaCycle-PreservedCycles, lastBlock.MetaCycle)\n\tif err != nil {\n\t\treturn 0, nil\n\t}\n\n\tendorsementRewards, err := br.TotalEndorsementRewards(\"\", lastBlock.MetaCycle-PreservedCycles, lastBlock.MetaCycle)\n\tif err != nil {\n\t\treturn 0, nil\n\t}\n\n\tstakedBalance = stakedBalance - bakingRewards - endorsementRewards\n\tratio := float64(stakedBalance) / float64(supply)\n\n\treturn ratio, nil\n}", "func ConvertSdkCoinsToWasmCoins(coins []sdk.Coin) wasmvmtypes.Coins {\n\tconverted := make(wasmvmtypes.Coins, len(coins))\n\tfor i, c := range coins {\n\t\tconverted[i] = ConvertSdkCoinToWasmCoin(c)\n\t}\n\treturn converted\n}", "func (n *treeNode) getVisits() uint64 {\n\tif n == nil {\n\t\treturn 0\n\t}\n\treturn n.visits\n}" ]
[ "0.7440926", "0.7270496", "0.7146478", "0.7128266", "0.701217", "0.67097694", "0.6679312", "0.6637209", "0.66212606", "0.65089613", "0.64136815", "0.5599231", "0.55402213", "0.54796225", "0.53980273", "0.53526527", "0.5304157", "0.5291654", "0.52657443", "0.52640676", "0.5240795", "0.5228725", "0.51933634", "0.508509", "0.5012063", "0.49285847", "0.49232614", "0.49060127", "0.4853242", "0.48494065", "0.48287106", "0.47897694", "0.47665054", "0.4611861", "0.45822543", "0.45751876", "0.45653257", "0.45469913", "0.45289996", "0.4524154", "0.45180503", "0.4512275", "0.44734904", "0.44678488", "0.44568878", "0.4450316", "0.4417196", "0.4414695", "0.44135398", "0.44106692", "0.44058567", "0.44042936", "0.4401126", "0.43839014", "0.43773785", "0.4367112", "0.43438148", "0.4331821", "0.4327068", "0.43254882", "0.43187243", "0.43100032", "0.42947105", "0.42849052", "0.42677864", "0.42546415", "0.42511737", "0.4222501", "0.4221749", "0.42082533", "0.41877636", "0.4185462", "0.4182498", "0.4180626", "0.4180112", "0.41774115", "0.41772726", "0.41729712", "0.41721207", "0.4171583", "0.41671672", "0.41660064", "0.4162345", "0.4161638", "0.41552794", "0.41535833", "0.4148403", "0.41380766", "0.4134133", "0.41314772", "0.4126107", "0.41218016", "0.41213426", "0.41144195", "0.41082418", "0.40999237", "0.4096867", "0.40947884", "0.40941975", "0.40935332" ]
0.72649264
2
LockedCoins returns the set of coins that are not spendable (i.e. locked), defined as the vesting coins that are not delegated.
func (cva ContinuousVestingAccount) LockedCoins(ctx sdk.Context) sdk.Coins { return cva.BaseVestingAccount.LockedCoinsFromVesting(cva.GetVestingCoins(ctx.BlockTime())) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (pva PeriodicVestingAccount) LockedCoins(ctx sdk.Context) sdk.Coins {\n\treturn pva.BaseVestingAccount.LockedCoinsFromVesting(pva.GetVestingCoins(ctx.BlockTime()))\n}", "func (dva DelayedVestingAccount) LockedCoins(ctx sdk.Context) sdk.Coins {\n\treturn dva.BaseVestingAccount.LockedCoinsFromVesting(dva.GetVestingCoins(ctx.BlockTime()))\n}", "func (va ClawbackVestingAccount) LockedCoins(ctx sdk.Context) sdk.Coins {\n\treturn va.BaseVestingAccount.LockedCoinsFromVesting(va.GetVestingCoins(ctx.BlockTime()))\n}", "func (plva PermanentLockedAccount) LockedCoins(_ sdk.Context) sdk.Coins {\n\treturn plva.BaseVestingAccount.LockedCoinsFromVesting(plva.OriginalVesting)\n}", "func (bva BaseVestingAccount) LockedCoinsFromVesting(vestingCoins sdk.Coins) sdk.Coins {\n\tlockedCoins := vestingCoins.Sub(vestingCoins.Min(bva.DelegatedVesting))\n\tif lockedCoins == nil {\n\t\treturn sdk.Coins{}\n\t}\n\treturn lockedCoins\n}", "func (plva PermanentLockedAccount) GetVestingCoins(_ time.Time) sdk.Coins {\n\treturn plva.OriginalVesting\n}", "func (plva PermanentLockedAccount) GetVestedCoins(_ time.Time) sdk.Coins {\n\treturn nil\n}", "func (dcr *ExchangeWallet) lockedOutputs() ([]chainjson.TransactionInput, error) {\n\tvar locked []chainjson.TransactionInput\n\terr := dcr.nodeRawRequest(methodListLockUnspent, anylist{dcr.acct}, &locked)\n\treturn locked, err\n}", "func (w *rpcWallet) LockedOutputs(ctx context.Context, acctName string) ([]chainjson.TransactionInput, error) {\n\tvar locked []chainjson.TransactionInput\n\terr := w.rpcClientRawRequest(ctx, methodListLockUnspent, anylist{acctName}, &locked)\n\treturn locked, translateRPCCancelErr(err)\n}", "func (w *Wallet) LockedOutpoints() []btcjson.TransactionInput {\n\tlocked := make([]btcjson.TransactionInput, len(w.lockedOutpoints))\n\ti := 0\n\tfor op := range w.lockedOutpoints {\n\t\tlocked[i] = btcjson.TransactionInput{\n\t\t\tTxid: op.Hash.String(),\n\t\t\tVout: op.Index,\n\t\t}\n\t\ti++\n\t}\n\treturn locked\n}", "func (a *Account) LockedOutpoints() []btcjson.TransactionInput {\n\tlocked := make([]btcjson.TransactionInput, len(a.lockedOutpoints))\n\ti := 0\n\tfor op := range a.lockedOutpoints {\n\t\tlocked[i] = btcjson.TransactionInput{\n\t\t\tTxid: op.Hash.String(),\n\t\t\tVout: op.Index,\n\t\t}\n\t\ti++\n\t}\n\treturn locked\n}", "func (b *Bitcoind) ListLockUnspent() (unspendableOutputs []UnspendableOutput, err error) {\n\tr, err := b.client.call(\"listlockunspent\", nil)\n\tif err = handleError(err, &r); err != nil {\n\t\treturn\n\t}\n\n\terr = json.Unmarshal(r.Result, &unspendableOutputs)\n\treturn\n}", "func (btc *ExchangeWallet) lockedSats() (uint64, error) {\n\tlockedOutpoints, err := btc.wallet.ListLockUnspent()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tvar sum uint64\n\tbtc.fundingMtx.Lock()\n\tdefer btc.fundingMtx.Unlock()\n\tfor _, outPoint := range lockedOutpoints {\n\t\topID := outpointID(outPoint.TxID, outPoint.Vout)\n\t\tutxo, found := btc.fundingCoins[opID]\n\t\tif found {\n\t\t\tsum += utxo.amount\n\t\t\tcontinue\n\t\t}\n\t\ttxHash, err := chainhash.NewHashFromStr(outPoint.TxID)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\ttxOut, err := btc.node.GetTxOut(txHash, outPoint.Vout, true)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\tif txOut == nil {\n\t\t\t// Must be spent now?\n\t\t\tbtc.log.Debugf(\"ignoring output from listlockunspent that wasn't found with gettxout. %s\", opID)\n\t\t\tcontinue\n\t\t}\n\t\tsum += toSatoshi(txOut.Value)\n\t}\n\treturn sum, nil\n}", "func (dva DelayedVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn dva.OriginalVesting.Sub(dva.GetVestedCoins(blockTime))\n}", "func (dcr *ExchangeWallet) FundingCoins(ids []dex.Bytes) (asset.Coins, error) {\n\t// First check if we have the coins in cache.\n\tcoins := make(asset.Coins, 0, len(ids))\n\tnotFound := make(map[outPoint]bool)\n\tdcr.fundingMtx.Lock()\n\tdefer dcr.fundingMtx.Unlock() // stay locked until we update the map and lock them in the wallet\n\tfor _, id := range ids {\n\t\ttxHash, vout, err := decodeCoinID(id)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tpt := newOutPoint(txHash, vout)\n\t\tfundingCoin, found := dcr.fundingCoins[pt]\n\t\tif found {\n\t\t\tcoins = append(coins, fundingCoin.op)\n\t\t\tcontinue\n\t\t}\n\t\tnotFound[pt] = true\n\t}\n\tif len(notFound) == 0 {\n\t\treturn coins, nil\n\t}\n\n\t// Check locked outputs for not found coins.\n\tlockedOutputs, err := dcr.lockedOutputs()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor _, output := range lockedOutputs {\n\t\ttxHash, err := chainhash.NewHashFromStr(output.Txid)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error decoding txid from rpc server %s: %w\", output.Txid, err)\n\t\t}\n\t\tpt := newOutPoint(txHash, output.Vout)\n\t\tif !notFound[pt] {\n\t\t\tcontinue\n\t\t}\n\t\ttxOut, err := dcr.node.GetTxOut(dcr.ctx, txHash, output.Vout, true)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"gettxout error for locked output %v: %w\", pt.String(), translateRPCCancelErr(err))\n\t\t}\n\t\tvar address string\n\t\tif len(txOut.ScriptPubKey.Addresses) > 0 {\n\t\t\taddress = txOut.ScriptPubKey.Addresses[0]\n\t\t}\n\t\tcoin := newOutput(txHash, output.Vout, toAtoms(output.Amount), output.Tree)\n\t\tcoins = append(coins, coin)\n\t\tdcr.fundingCoins[pt] = &fundingCoin{\n\t\t\top: coin,\n\t\t\taddr: address,\n\t\t}\n\t\tdelete(notFound, pt)\n\t\tif len(notFound) == 0 {\n\t\t\treturn coins, nil\n\t\t}\n\t}\n\n\t// Some funding coins still not found after checking locked outputs.\n\t// Check wallet unspent outputs as last resort. Lock the coins if found.\n\tunspents, err := dcr.unspents()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcoinsToLock := make([]*wire.OutPoint, 0, len(notFound))\n\tfor _, txout := range unspents {\n\t\ttxHash, err := chainhash.NewHashFromStr(txout.TxID)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error decoding txid from rpc server %s: %w\", txout.TxID, err)\n\t\t}\n\t\tpt := newOutPoint(txHash, txout.Vout)\n\t\tif !notFound[pt] {\n\t\t\tcontinue\n\t\t}\n\t\tcoinsToLock = append(coinsToLock, wire.NewOutPoint(txHash, txout.Vout, txout.Tree))\n\t\tcoin := newOutput(txHash, txout.Vout, toAtoms(txout.Amount), txout.Tree)\n\t\tcoins = append(coins, coin)\n\t\tdcr.fundingCoins[pt] = &fundingCoin{\n\t\t\top: coin,\n\t\t\taddr: txout.Address,\n\t\t}\n\t\tdelete(notFound, pt)\n\t\tif len(notFound) == 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\tif len(notFound) != 0 {\n\t\tids := make([]string, 0, len(notFound))\n\t\tfor pt := range notFound {\n\t\t\tids = append(ids, pt.String())\n\t\t}\n\t\treturn nil, fmt.Errorf(\"funding coins not found: %s\", strings.Join(ids, \", \"))\n\t}\n\tdcr.log.Debugf(\"Locking funding coins that were unlocked %v\", coinsToLock)\n\terr = dcr.node.LockUnspent(dcr.ctx, false, coinsToLock)\n\tif err != nil {\n\t\treturn nil, translateRPCCancelErr(err)\n\t}\n\n\treturn coins, nil\n}", "func (bc *BlockChain) FindUnspentTransactions(addr string) []Transaction {\n\tvar unspentTXs []Transaction\n\tspentTXOutputs := make(map[string][]int)\n\titerator := bc.Iterator()\n\n\tfor {\n\t\t_block := iterator.Next()\n\n\t\tfor _, tx := range _block.Transactions {\n\t\t\ttxID := hex.EncodeToString(tx.ID)\n\n\t\tOutputs:\n\t\t\tfor outIdx, out := range tx.VOut {\n\t\t\t\tif spentTXOutputs[txID] != nil {\n\t\t\t\t\tfor _, spentOut := range spentTXOutputs[txID] {\n\t\t\t\t\t\tif spentOut == outIdx {\n\t\t\t\t\t\t\tcontinue Outputs\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif out.CanBeUnlockedWith(addr) {\n\t\t\t\t\tunspentTXs = append(unspentTXs, *tx)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif !tx.isCoinBaseTx() {\n\t\t\t\tfor _, in := range tx.VIn {\n\t\t\t\t\tif in.CanUnlockOutputWith(addr) {\n\t\t\t\t\t\tinTxID := hex.EncodeToString(in.TxID)\n\t\t\t\t\t\tspentTXOutputs[inTxID] = append(spentTXOutputs[inTxID], in.VOut)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif len(_block.Prev) == 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn unspentTXs\n}", "func (va ClawbackVestingAccount) GetVestedCoins(blockTime time.Time) sdk.Coins {\n\t// It's likely that one or the other schedule will be nearly trivial,\n\t// so there should be little overhead in recomputing the conjunction each time.\n\tcoins := coinsMin(va.GetUnlockedOnly(blockTime), va.GetVestedOnly(blockTime))\n\tif coins.IsZero() {\n\t\treturn nil\n\t}\n\treturn coins\n}", "func (dcr *ExchangeWallet) FundingCoins(ids []dex.Bytes) (asset.Coins, error) {\n\t// First check if we have the coins in cache.\n\tcoins := make(asset.Coins, 0, len(ids))\n\tnotFound := make(map[outPoint]bool)\n\tdcr.fundingMtx.Lock()\n\tdefer dcr.fundingMtx.Unlock() // stay locked until we update the map and lock them in the wallet\n\tfor _, id := range ids {\n\t\ttxHash, vout, err := decodeCoinID(id)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tpt := newOutPoint(txHash, vout)\n\t\tfundingCoin, found := dcr.fundingCoins[pt]\n\t\tif found {\n\t\t\tcoins = append(coins, fundingCoin.op)\n\t\t\tcontinue\n\t\t}\n\t\tnotFound[pt] = true\n\t}\n\tif len(notFound) == 0 {\n\t\treturn coins, nil\n\t}\n\n\t// Check locked outputs for not found coins.\n\tfor _, acct := range dcr.fundingAccounts() {\n\t\tlockedOutputs, err := dcr.wallet.LockedOutputs(dcr.ctx, acct)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfor _, output := range lockedOutputs {\n\t\t\ttxHash, err := chainhash.NewHashFromStr(output.Txid)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"error decoding txid from rpc server %s: %w\", output.Txid, err)\n\t\t\t}\n\t\t\tpt := newOutPoint(txHash, output.Vout)\n\t\t\tif !notFound[pt] {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ttxOut, err := dcr.wallet.UnspentOutput(dcr.ctx, txHash, output.Vout, output.Tree)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"gettxout error for locked output %v: %w\", pt.String(), err)\n\t\t\t}\n\t\t\tvar address string\n\t\t\tif len(txOut.Addresses) > 0 {\n\t\t\t\taddress = txOut.Addresses[0]\n\t\t\t}\n\t\t\tcoin := newOutput(txHash, output.Vout, toAtoms(output.Amount), output.Tree)\n\t\t\tcoins = append(coins, coin)\n\t\t\tdcr.fundingCoins[pt] = &fundingCoin{\n\t\t\t\top: coin,\n\t\t\t\taddr: address,\n\t\t\t}\n\t\t\tdelete(notFound, pt)\n\t\t\tif len(notFound) == 0 {\n\t\t\t\treturn coins, nil\n\t\t\t}\n\t\t}\n\t}\n\n\t// Some funding coins still not found after checking locked outputs.\n\t// Check wallet unspent outputs as last resort. Lock the coins if found.\n\tcoinsToLock := make([]*wire.OutPoint, 0, len(notFound))\n\tfor _, acct := range dcr.fundingAccounts() {\n\t\tunspents, err := dcr.wallet.Unspents(dcr.ctx, acct)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfor _, txout := range unspents {\n\t\t\ttxHash, err := chainhash.NewHashFromStr(txout.TxID)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"error decoding txid from rpc server %s: %w\", txout.TxID, err)\n\t\t\t}\n\t\t\tpt := newOutPoint(txHash, txout.Vout)\n\t\t\tif !notFound[pt] {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tcoinsToLock = append(coinsToLock, wire.NewOutPoint(txHash, txout.Vout, txout.Tree))\n\t\t\tcoin := newOutput(txHash, txout.Vout, toAtoms(txout.Amount), txout.Tree)\n\t\t\tcoins = append(coins, coin)\n\t\t\tdcr.fundingCoins[pt] = &fundingCoin{\n\t\t\t\top: coin,\n\t\t\t\taddr: txout.Address,\n\t\t\t}\n\t\t\tdelete(notFound, pt)\n\t\t\tif len(notFound) == 0 {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\t// Return an error if some coins are still not found.\n\tif len(notFound) != 0 {\n\t\tids := make([]string, 0, len(notFound))\n\t\tfor pt := range notFound {\n\t\t\tids = append(ids, pt.String())\n\t\t}\n\t\treturn nil, fmt.Errorf(\"funding coins not found: %s\", strings.Join(ids, \", \"))\n\t}\n\n\tdcr.log.Debugf(\"Locking funding coins that were unlocked %v\", coinsToLock)\n\terr := dcr.wallet.LockUnspent(dcr.ctx, false, coinsToLock)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn coins, nil\n}", "func (vva ValidatorVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn vva.OriginalVesting.Sub(vva.GetVestedCoins(blockTime))\n}", "func (va ClawbackVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn va.OriginalVesting.Sub(va.GetVestedCoins(blockTime))\n}", "func (dva DelayedVestingAccount) GetVestedCoins(blockTime time.Time) sdk.Coins {\n\tif blockTime.Unix() >= dva.EndTime {\n\t\treturn dva.OriginalVesting\n\t}\n\n\treturn nil\n}", "func (vva ValidatorVestingAccount) SpendableCoins(blockTime time.Time) sdk.Coins {\n\treturn vva.BaseVestingAccount.SpendableCoinsVestingAccount(vva.GetVestingCoins(blockTime))\n}", "func (vva ValidatorVestingAccount) GetVestedCoins(blockTime time.Time) sdk.Coins {\n\tvar vestedCoins sdk.Coins\n\tif blockTime.Unix() <= vva.StartTime {\n\t\treturn vestedCoins\n\t}\n\tcurrentPeriodStartTime := vva.StartTime\n\tnumberPeriods := len(vva.VestingPeriods)\n\tfor i := 0; i < numberPeriods; i++ {\n\t\tx := blockTime.Unix() - currentPeriodStartTime\n\t\tif x >= vva.VestingPeriods[i].Length {\n\t\t\tif vva.VestingPeriodProgress[i].PeriodComplete {\n\t\t\t\tvestedCoins = vestedCoins.Add(vva.VestingPeriods[i].Amount)\n\t\t\t}\n\t\t\tcurrentPeriodStartTime += vva.VestingPeriods[i].Length\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn vestedCoins\n\n}", "func (chain *BlockChain) FindUnspentTransactions(address string) []Transaction {\n\tvar unspentTxs []Transaction\n\n\tspentTxOs := make(map[string][]int)\n\n\titer := chain.Iterator()\n\n\tfor {\n\t\tblock := iter.Next()\n\n\t\tfor _, tx := range block.Transactions {\n\t\t\ttxID := hex.EncodeToString(tx.ID)\n\n\t\tOutputs:\n\t\t\tfor outIdx, out := range tx.Outputs {\n\t\t\t\tif spentTxOs[txID] != nil {\n\t\t\t\t\tfor _, spentOut := range spentTxOs[txID] {\n\t\t\t\t\t\tif spentOut == outIdx {\n\t\t\t\t\t\t\tcontinue Outputs\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif out.CanBeUnlocked(address) {\n\t\t\t\t\tunspentTxs = append(unspentTxs, *tx)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif tx.IsCoinbase() == false {\n\t\t\t\tfor _, in := range tx.Inputs {\n\t\t\t\t\tif in.CanUnlock(address) {\n\t\t\t\t\t\tinTxID := hex.EncodeToString(in.ID)\n\n\t\t\t\t\t\tspentTxOs[inTxID] = append(spentTxOs[inTxID], in.Out)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif len(block.PrevHash) == 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn unspentTxs\n}", "func (cva ContinuousVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn cva.OriginalVesting.Sub(cva.GetVestedCoins(blockTime))\n}", "func (pva PeriodicVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn pva.OriginalVesting.Sub(pva.GetVestedCoins(blockTime))\n}", "func (dcr *ExchangeWallet) lockFundingCoins(fCoins []*fundingCoin) error {\n\twireOPs := make([]*wire.OutPoint, 0, len(fCoins))\n\tfor _, c := range fCoins {\n\t\twireOPs = append(wireOPs, wire.NewOutPoint(c.op.txHash(), c.op.vout(), c.op.tree))\n\t}\n\terr := dcr.wallet.LockUnspent(dcr.ctx, false, wireOPs)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, c := range fCoins {\n\t\tdcr.fundingCoins[c.op.pt] = c\n\t}\n\treturn nil\n}", "func (b *Bitcoind) LockUnspent(lock bool, outputs []UnspendableOutput) (success bool, err error) {\n\tr, err := b.client.call(\"lockunspent\", []interface{}{lock, outputs})\n\tif err = handleError(err, &r); err != nil {\n\t\treturn\n\t}\n\n\terr = json.Unmarshal(r.Result, &success)\n\treturn\n}", "func (va ClawbackVestingAccount) GetUnlockedOnly(blockTime time.Time) sdk.Coins {\n\treturn ReadSchedule(va.StartTime, va.EndTime, va.LockupPeriods, va.OriginalVesting, blockTime.Unix())\n}", "func (dcr *ExchangeWallet) returnCoins(unspents asset.Coins) ([]*fundingCoin, error) {\n\tif len(unspents) == 0 {\n\t\treturn nil, fmt.Errorf(\"cannot return zero coins\")\n\t}\n\n\tops := make([]*wire.OutPoint, 0, len(unspents))\n\tfundingCoins := make([]*fundingCoin, 0, len(unspents))\n\n\tdcr.log.Debugf(\"returning coins %s\", unspents)\n\tfor _, unspent := range unspents {\n\t\top, err := dcr.convertCoin(unspent)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error converting coin: %w\", err)\n\t\t}\n\t\tops = append(ops, op.wireOutPoint()) // op.tree may be wire.TxTreeUnknown, but that's fine since wallet.LockUnspent doesn't rely on it\n\t\tif fCoin, ok := dcr.fundingCoins[op.pt]; ok {\n\t\t\tfundingCoins = append(fundingCoins, fCoin)\n\t\t\tdelete(dcr.fundingCoins, op.pt)\n\t\t} else {\n\t\t\tdcr.log.Warnf(\"returning coin %s that is not cached as a funding coin\", op)\n\t\t\tfundingCoins = append(fundingCoins, &fundingCoin{op: op})\n\t\t}\n\t}\n\n\treturn fundingCoins, dcr.wallet.LockUnspent(dcr.ctx, true, ops)\n}", "func (w *Wallet) Locked() bool {\n\treturn <-w.lockState\n}", "func (dcr *ExchangeWallet) lockFundingCoins(fCoins []*fundingCoin) error {\n\twireOPs := make([]*wire.OutPoint, 0, len(fCoins))\n\tfor _, c := range fCoins {\n\t\twireOPs = append(wireOPs, wire.NewOutPoint(c.op.txHash(), c.op.vout(), c.op.tree))\n\t}\n\terr := dcr.node.LockUnspent(dcr.ctx, false, wireOPs)\n\tif err != nil {\n\t\treturn translateRPCCancelErr(err)\n\t}\n\tfor _, c := range fCoins {\n\t\tdcr.fundingCoins[c.op.pt] = c\n\t}\n\treturn nil\n}", "func (cva ContinuousVestingAccount) GetVestedCoins(blockTime time.Time) sdk.Coins {\n\tvar vestedCoins sdk.Coins\n\n\t// We must handle the case where the start time for a vesting account has\n\t// been set into the future or when the start of the chain is not exactly\n\t// known.\n\tif blockTime.Unix() <= cva.StartTime {\n\t\treturn vestedCoins\n\t} else if blockTime.Unix() >= cva.EndTime {\n\t\treturn cva.OriginalVesting\n\t}\n\n\t// calculate the vesting scalar\n\tx := blockTime.Unix() - cva.StartTime\n\ty := cva.EndTime - cva.StartTime\n\ts := sdk.NewDec(x).Quo(sdk.NewDec(y))\n\n\tfor _, ovc := range cva.OriginalVesting {\n\t\tvestedAmt := ovc.Amount.ToDec().Mul(s).RoundInt()\n\t\tvestedCoins = append(vestedCoins, sdk.NewCoin(ovc.Denom, vestedAmt))\n\t}\n\n\treturn vestedCoins\n}", "func (dcr *ExchangeWallet) returnCoins(unspents asset.Coins) error {\n\tif len(unspents) == 0 {\n\t\treturn fmt.Errorf(\"cannot return zero coins\")\n\t}\n\tops := make([]*wire.OutPoint, 0, len(unspents))\n\n\tdcr.log.Debugf(\"returning coins %s\", unspents)\n\tfor _, unspent := range unspents {\n\t\top, err := dcr.convertCoin(unspent)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error converting coin: %w\", err)\n\t\t}\n\t\tops = append(ops, wire.NewOutPoint(op.txHash(), op.vout(), op.tree))\n\t\tdelete(dcr.fundingCoins, op.pt)\n\t}\n\treturn translateRPCCancelErr(dcr.node.LockUnspent(dcr.ctx, true, ops))\n}", "func (dcr *ExchangeWallet) Locked() bool {\n\tfor _, acct := range dcr.fundingAccounts() {\n\t\tunlocked, err := dcr.wallet.AccountUnlocked(dcr.ctx, acct)\n\t\tif err != nil {\n\t\t\tdcr.log.Errorf(\"error checking account lock status %v\", err)\n\t\t\tunlocked = false // assume wallet is unlocked?\n\t\t}\n\t\tif !unlocked {\n\t\t\treturn true // Locked is true if any of the funding accounts is locked.\n\t\t}\n\t}\n\treturn false\n}", "func (w *Wallet) ListUnspent(minconf, maxconf int32,\n\taddresses map[string]struct{}) ([]*btcjson.ListUnspentResult, er.R) {\n\n\tvar results []*btcjson.ListUnspentResult\n\terr := walletdb.View(w.db, func(tx walletdb.ReadTx) er.R {\n\t\taddrmgrNs := tx.ReadBucket(waddrmgrNamespaceKey)\n\t\ttxmgrNs := tx.ReadBucket(wtxmgrNamespaceKey)\n\n\t\tsyncBlock := w.Manager.SyncedTo()\n\n\t\tfilter := len(addresses) != 0\n\t\tunspent, err := w.TxStore.GetUnspentOutputs(txmgrNs)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tsort.Sort(sort.Reverse(creditSlice(unspent)))\n\n\t\tdefaultAccountName := \"default\"\n\n\t\tresults = make([]*btcjson.ListUnspentResult, 0, len(unspent))\n\t\tfor i := range unspent {\n\t\t\toutput := unspent[i]\n\n\t\t\t// Outputs with fewer confirmations than the minimum or more\n\t\t\t// confs than the maximum are excluded.\n\t\t\tconfs := confirms(output.Height, syncBlock.Height)\n\t\t\tif confs < minconf || confs > maxconf {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// Only mature coinbase outputs are included.\n\t\t\tif output.FromCoinBase {\n\t\t\t\ttarget := int32(w.ChainParams().CoinbaseMaturity)\n\t\t\t\tif !confirmed(target, output.Height, syncBlock.Height) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Exclude locked outputs from the result set.\n\t\t\tif w.LockedOutpoint(output.OutPoint) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// Lookup the associated account for the output. Use the\n\t\t\t// default account name in case there is no associated account\n\t\t\t// for some reason, although this should never happen.\n\t\t\t//\n\t\t\t// This will be unnecessary once transactions and outputs are\n\t\t\t// grouped under the associated account in the db.\n\t\t\tacctName := defaultAccountName\n\t\t\tsc, addrs, _, err := txscript.ExtractPkScriptAddrs(\n\t\t\t\toutput.PkScript, w.chainParams)\n\t\t\tif err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif len(addrs) > 0 {\n\t\t\t\tsmgr, acct, err := w.Manager.AddrAccount(addrmgrNs, addrs[0])\n\t\t\t\tif err == nil {\n\t\t\t\t\ts, err := smgr.AccountName(addrmgrNs, acct)\n\t\t\t\t\tif err == nil {\n\t\t\t\t\t\tacctName = s\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif filter {\n\t\t\t\tfor _, addr := range addrs {\n\t\t\t\t\t_, ok := addresses[addr.EncodeAddress()]\n\t\t\t\t\tif ok {\n\t\t\t\t\t\tgoto include\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\tinclude:\n\t\t\t// At the moment watch-only addresses are not supported, so all\n\t\t\t// recorded outputs that are not multisig are \"spendable\".\n\t\t\t// Multisig outputs are only \"spendable\" if all keys are\n\t\t\t// controlled by this wallet.\n\t\t\t//\n\t\t\t// TODO: Each case will need updates when watch-only addrs\n\t\t\t// is added. For P2PK, P2PKH, and P2SH, the address must be\n\t\t\t// looked up and not be watching-only. For multisig, all\n\t\t\t// pubkeys must belong to the manager with the associated\n\t\t\t// private key (currently it only checks whether the pubkey\n\t\t\t// exists, since the private key is required at the moment).\n\t\t\tvar spendable bool\n\t\tscSwitch:\n\t\t\tswitch sc {\n\t\t\tcase txscript.PubKeyHashTy:\n\t\t\t\tspendable = true\n\t\t\tcase txscript.PubKeyTy:\n\t\t\t\tspendable = true\n\t\t\tcase txscript.WitnessV0ScriptHashTy:\n\t\t\t\tspendable = true\n\t\t\tcase txscript.WitnessV0PubKeyHashTy:\n\t\t\t\tspendable = true\n\t\t\tcase txscript.MultiSigTy:\n\t\t\t\tfor _, a := range addrs {\n\t\t\t\t\t_, err := w.Manager.Address(addrmgrNs, a)\n\t\t\t\t\tif err == nil {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tif waddrmgr.ErrAddressNotFound.Is(err) {\n\t\t\t\t\t\tbreak scSwitch\n\t\t\t\t\t}\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tspendable = true\n\t\t\t}\n\n\t\t\tresult := &btcjson.ListUnspentResult{\n\t\t\t\tTxID: output.OutPoint.Hash.String(),\n\t\t\t\tVout: output.OutPoint.Index,\n\t\t\t\tAccount: acctName,\n\t\t\t\tScriptPubKey: hex.EncodeToString(output.PkScript),\n\t\t\t\tAmount: output.Amount.ToBTC(),\n\t\t\t\tConfirmations: int64(confs),\n\t\t\t\tSpendable: spendable,\n\t\t\t}\n\n\t\t\t// BUG: this should be a JSON array so that all\n\t\t\t// addresses can be included, or removed (and the\n\t\t\t// caller extracts addresses from the pkScript).\n\t\t\tif len(addrs) > 0 {\n\t\t\t\tresult.Address = addrs[0].EncodeAddress()\n\t\t\t}\n\n\t\t\tresults = append(results, result)\n\t\t}\n\t\treturn nil\n\t})\n\treturn results, err\n}", "func (wt *Wallet) Locked() bool {\n\treturn <-wt.lockState\n}", "func NewQueryLockedCoinsParams(accountID types.AccountID) QueryLockedCoinsParams {\n\treturn QueryLockedCoinsParams{\n\t\tAccountID: accountID,\n\t}\n}", "func (pva PeriodicVestingAccount) GetVestedCoins(blockTime time.Time) sdk.Coins {\n\tcoins := ReadSchedule(pva.StartTime, pva.EndTime, pva.VestingPeriods, pva.OriginalVesting, blockTime.Unix())\n\tif coins.IsZero() {\n\t\treturn nil\n\t}\n\treturn coins\n}", "func GetLockedDistributionAddresses() []string {\n\t// TODO -- once we reach 30% distribution, we can hardcode the\n\t// initial timestamp for releasing more coins\n\taddrs := make([]string, DistributionAddressesTotal-InitialUnlockedCount)\n\tfor i := range distributionAddresses[InitialUnlockedCount:] {\n\t\taddrs[i] = distributionAddresses[InitialUnlockedCount+uint64(i)]\n\t}\n\n\treturn addrs\n}", "func (btc *ExchangeWallet) ReturnCoins(unspents asset.Coins) error {\n\tif len(unspents) == 0 {\n\t\treturn fmt.Errorf(\"cannot return zero coins\")\n\t}\n\tops := make([]*output, 0, len(unspents))\n\tbtc.fundingMtx.Lock()\n\tdefer btc.fundingMtx.Unlock()\n\tfor _, unspent := range unspents {\n\t\top, err := btc.convertCoin(unspent)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error converting coin: %v\", err)\n\t\t}\n\t\tops = append(ops, op)\n\t\tdelete(btc.fundingCoins, outpointID(op.txHash.String(), op.vout))\n\t}\n\treturn btc.wallet.LockUnspent(true, ops)\n}", "func (r *Ring) InPot() []Box {\n\treturn r.Where(func(s *Seat) bool {\n\t\treturn s.State == seat.Play || s.State == seat.Bet || s.State == seat.AllIn\n\t})\n}", "func (dcr *ExchangeWallet) ReturnCoins(unspents asset.Coins) error {\n\tdcr.fundingMtx.Lock()\n\tdefer dcr.fundingMtx.Unlock()\n\treturn dcr.returnCoins(unspents)\n}", "func (keeper SendKeeper) GetCoins(ctx sdk.Context, addr sdk.Address) sdk.Coins {\n\treturn getCoins(ctx, keeper.am, addr)\n}", "func (txn TxnProbe) CollectLockedKeys() [][]byte {\n\treturn txn.collectLockedKeys()\n}", "func (keeper ViewKeeper) GetCoins(ctx sdk.Context, addr sdk.Address) sdk.Coins {\n\treturn getCoins(ctx, keeper.am, addr)\n}", "func GetUnspentOutputCoinsExceptSpendingUTXO(rpcClient *rpcclient.HttpClient, keyWallet *wallet.KeyWallet) ([]*crypto.InputCoin, error) {\n\tpublicKey := keyWallet.KeySet.PaymentAddress.Pk\n\n\t// check and remove utxo cache (these utxos in txs that were confirmed)\n\t//CheckAndRemoveUTXOFromCache(keyWallet.KeySet.PaymentAddress.Pk, inputCoins)\n\tCheckAndRemoveUTXOFromCacheV2(keyWallet.KeySet.PaymentAddress.Pk, rpcClient)\n\n\t// get unspent output coins from network\n\tutxos, err := GetUnspentOutputCoins(rpcClient, keyWallet)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tinputCoins := ConvertOutputCoinToInputCoin(utxos)\n\n\t// except spending utxos from unspent output coins\n\tutxosInCache := GetUTXOCacheByPublicKey(publicKey)\n\tfor serialNumberStr, _ := range utxosInCache {\n\t\tfor i, inputCoin := range inputCoins {\n\t\t\tsnStrTmp := base58.Base58Check{}.Encode(inputCoin.CoinDetails.GetSerialNumber().ToBytesS(), common.ZeroByte)\n\t\t\tif snStrTmp == serialNumberStr {\n\t\t\t\tinputCoins = removeElementFromSlice(inputCoins, i)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\treturn inputCoins, nil\n}", "func (btc *ExchangeWallet) FundingCoins(ids []dex.Bytes) (asset.Coins, error) {\n\t// First check if we have the coins in cache.\n\tcoins := make(asset.Coins, 0, len(ids))\n\tnotFound := make(map[string]struct{})\n\tbtc.fundingMtx.RLock()\n\tfor _, id := range ids {\n\t\ttxHash, vout, err := decodeCoinID(id)\n\t\tif err != nil {\n\t\t\tbtc.fundingMtx.RUnlock()\n\t\t\treturn nil, err\n\t\t}\n\t\topID := outpointID(txHash.String(), vout)\n\t\tfundingCoin, found := btc.fundingCoins[opID]\n\t\tif found {\n\t\t\tcoins = append(coins, newOutput(btc.node, txHash, vout, fundingCoin.amount, fundingCoin.redeemScript))\n\t\t\tcontinue\n\t\t}\n\t\tnotFound[opID] = struct{}{}\n\t}\n\tbtc.fundingMtx.RUnlock()\n\tif len(notFound) == 0 {\n\t\treturn coins, nil\n\t}\n\t_, utxoMap, _, err := btc.spendableUTXOs(0)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlockers := make([]*output, 0, len(ids))\n\tbtc.fundingMtx.Lock()\n\tdefer btc.fundingMtx.Unlock()\n\tfor _, id := range ids {\n\t\ttxHash, vout, err := decodeCoinID(id)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\topID := outpointID(txHash.String(), vout)\n\t\tutxo, found := utxoMap[opID]\n\t\tif !found {\n\t\t\treturn nil, fmt.Errorf(\"funding coin %s not found\", opID)\n\t\t}\n\t\tbtc.fundingCoins[opID] = utxo\n\t\tcoin := newOutput(btc.node, utxo.txHash, utxo.vout, utxo.amount, utxo.redeemScript)\n\t\tcoins = append(coins, coin)\n\t\tlockers = append(lockers, coin)\n\t\tdelete(notFound, opID)\n\t\tif len(notFound) == 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\tif len(notFound) != 0 {\n\t\tids := make([]string, 0, len(notFound))\n\t\tfor opID := range notFound {\n\t\t\tids = append(ids, opID)\n\t\t}\n\t\treturn nil, fmt.Errorf(\"coins not found: %s\", strings.Join(ids, \", \"))\n\t}\n\terr = btc.wallet.LockUnspent(false, lockers)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn coins, nil\n}", "func (vva ValidatorVestingAccount) GetFailedVestedCoins() sdk.Coins {\n\tvar failedVestedCoins sdk.Coins\n\tnumberPeriods := len(vva.VestingPeriods)\n\tfor i := 0; i < numberPeriods; i++ {\n\t\tif vva.VestingPeriodProgress[i].PeriodComplete {\n\t\t\tif !vva.VestingPeriodProgress[i].VestingSuccessful {\n\t\t\t\tfailedVestedCoins = failedVestedCoins.Add(vva.VestingPeriods[i].Amount)\n\t\t\t}\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn failedVestedCoins\n}", "func (o *AccountCollectionGetParams) SetLocked(locked *bool) {\n\to.Locked = locked\n}", "func (c *CoordinatorHelper) Coins(\n\tctx context.Context,\n\tdbTx storage.DatabaseTransaction,\n\taccountIdentifier *types.AccountIdentifier,\n\tcurrency *types.Currency,\n) ([]*types.Coin, error) {\n\tcoins, _, err := c.coinStorage.GetCoinsTransactional(\n\t\tctx,\n\t\tdbTx,\n\t\taccountIdentifier,\n\t)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"%w: unable to get coins\", err)\n\t}\n\n\tcoinsToReturn := []*types.Coin{}\n\tfor _, coin := range coins {\n\t\tif types.Hash(coin.Amount.Currency) != types.Hash(currency) {\n\t\t\tcontinue\n\t\t}\n\n\t\tcoinsToReturn = append(coinsToReturn, coin)\n\t}\n\n\treturn coinsToReturn, nil\n}", "func (dcr *ExchangeWallet) ReturnCoins(unspents asset.Coins) error {\n\tdcr.fundingMtx.Lock()\n\treturnedCoins, err := dcr.returnCoins(unspents)\n\tdcr.fundingMtx.Unlock()\n\tif err != nil || dcr.unmixedAccount == \"\" {\n\t\treturn err\n\t}\n\n\t// If any of these coins belong to the trading account, transfer them to the\n\t// unmixed account to be re-mixed into the primary account before being\n\t// re-selected for funding future orders. This doesn't apply to unspent\n\t// split tx outputs, which should remain in the trading account and be\n\t// selected from there for funding future orders.\n\tvar coinsToTransfer []asset.Coin\n\tfor _, coin := range returnedCoins {\n\t\tif coin.addr == \"\" {\n\t\t\ttxOut, err := dcr.wallet.UnspentOutput(dcr.ctx, coin.op.txHash(), coin.op.vout(), coin.op.tree)\n\t\t\tif err != nil {\n\t\t\t\tdcr.log.Errorf(\"wallet.UnspentOutput error for returned coin %s: %v\", coin.op, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif len(txOut.Addresses) == 0 {\n\t\t\t\tdcr.log.Errorf(\"no address in gettxout response for returned coin %s\", coin.op)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tcoin.addr = txOut.Addresses[0]\n\t\t}\n\t\taddrInfo, err := dcr.wallet.AddressInfo(dcr.ctx, coin.addr)\n\t\tif err != nil {\n\t\t\tdcr.log.Errorf(\"wallet.AddressInfo error for returned coin %s: %v\", coin.op, err)\n\t\t\tcontinue\n\t\t}\n\t\t// Move this coin to the unmixed account if it was sent to the internal\n\t\t// branch of the trading account. This excludes unspent split tx outputs\n\t\t// which are sent to the external branch of the trading account.\n\t\tif addrInfo.Branch == acctInternalBranch && addrInfo.Account == dcr.tradingAccount {\n\t\t\tcoinsToTransfer = append(coinsToTransfer, coin.op)\n\t\t}\n\t}\n\n\tif len(coinsToTransfer) > 0 {\n\t\ttx, totalSent, err := dcr.sendAll(coinsToTransfer, dcr.unmixedAccount)\n\t\tif err != nil {\n\t\t\tdcr.log.Errorf(\"unable to transfer unlocked swapped change from temp trading \"+\n\t\t\t\t\"account to unmixed account: %v\", err)\n\t\t} else {\n\t\t\tdcr.log.Infof(\"Transferred %s from temp trading account to unmixed account in tx %s.\",\n\t\t\t\tdcrutil.Amount(totalSent), tx.TxHash())\n\t\t}\n\t}\n\n\treturn nil\n}", "func GetCoins(accCoins []types.Coin) AccountCoins {\n\tcoins := make(AccountCoins, 0)\n\tfor _, coin := range accCoins {\n\t\tcoins = append(coins, AccountCoin{Amount: uint64(coin.Amount), Denom: coin.Denom})\n\t}\n\treturn coins\n}", "func (keeper BaseViewKeeper) GetCoins(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins {\n\treturn getCoins(ctx, keeper.am, addr)\n}", "func (b *BlockChain) GetUnspentTxns(address string) []Transaction {\n\tvar unspentTxns []Transaction\n\tvar spentTxnMap = make(map[string][]int) // map txnID -> output index\n\n\t// go over blocks one by one\n\titer := b.GetIterator()\n\tfor {\n\t\tblck := iter.Next()\n\n\t\t// go over all Transactions in this block\n\t\tfor _, txn := range blck.Transactions {\n\t\t\t// get string identifying this transaction\n\t\t\ttxID := hex.EncodeToString(txn.ID)\n\n\t\tOutputLoop:\n\t\t\t// go over all outputs in this Txn\n\t\t\tfor outIndex, output := range txn.Out {\n\n\t\t\t\t// check if this output is spent.\n\t\t\t\tif spentTxnMap[txID] != nil {\n\t\t\t\t\tfor _, indx := range spentTxnMap[txID] {\n\t\t\t\t\t\tif indx == outIndex {\n\t\t\t\t\t\t\tcontinue OutputLoop\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// check if this output belongs to this address\n\t\t\t\tif output.CheckOutputUnlock(address) {\n\t\t\t\t\tunspentTxns = append(unspentTxns, *txn)\n\t\t\t\t}\n\n\t\t\t\t// if this is not genesis block, go over all inputs\n\t\t\t\t// that refers to output that belongs to this address\n\t\t\t\t// and mark them as unspent\n\t\t\t\tif txn.IsCoinbase() == false {\n\t\t\t\t\tfor _, inp := range txn.In {\n\t\t\t\t\t\tif inp.CheckInputUnlock(address) {\n\t\t\t\t\t\t\tspentTxnMap[txID] = append(spentTxnMap[txID], inp.Out)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif len(blck.PrevBlockHash) == 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn unspentTxns\n}", "func (keeper Keeper) GetCoins(ctx sdk.Context, addr sdk.Address) sdk.Coins {\n\treturn getCoins(ctx, keeper.am, addr)\n}", "func (dcr *ExchangeWallet) Locked() bool {\n\twalletInfo, err := dcr.node.WalletInfo(dcr.ctx)\n\tif err != nil {\n\t\tdcr.log.Errorf(\"walletinfo error: %v\", err)\n\t\treturn false\n\t}\n\treturn !walletInfo.Unlocked\n}", "func GetUnspentOutputCoins(rpcClient *rpcclient.HttpClient, keyWallet *wallet.KeyWallet) ([]*crypto.OutputCoin, error) {\n\tprivateKey := &keyWallet.KeySet.PrivateKey\n\tpaymentAddressStr := keyWallet.Base58CheckSerialize(wallet.PaymentAddressType)\n\tviewingKeyStr := keyWallet.Base58CheckSerialize(wallet.ReadonlyKeyType)\n\n\toutputCoins, err := GetListOutputCoins(rpcClient, paymentAddressStr, viewingKeyStr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tserialNumbers, err := DeriveSerialNumbers(privateKey, outputCoins)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tisExisted, err := CheckExistenceSerialNumber(rpcClient, paymentAddressStr, serialNumbers)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tutxos := make([]*crypto.OutputCoin, 0)\n\tfor i, out := range outputCoins {\n\t\tif !isExisted[i] {\n\t\t\tutxos = append(utxos, out)\n\t\t}\n\t}\n\n\treturn utxos, nil\n}", "func (dcr *ExchangeWallet) lockedAtoms() (uint64, error) {\n\tlockedOutpoints, err := dcr.lockedOutputs()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tvar sum uint64\n\tfor _, op := range lockedOutpoints {\n\t\tsum += toAtoms(op.Amount)\n\t}\n\treturn sum, nil\n}", "func (u UTXOSet) FindUnspentTransactions(pubKeyHash []byte) []TxOutput {\n\tvar UTXOs []TxOutput\n\n\tdb := u.Blockchain.Database\n\n\terr := db.View(func(txn *badger.Txn) error {\n\t\topts := badger.DefaultIteratorOptions\n\n\t\tit := txn.NewIterator(opts)\n\t\tdefer it.Close()\n\n\t\t// iterate through UTXOS prefixes\n\t\tfor it.Seek(utxoPrefix); it.ValidForPrefix(utxoPrefix); it.Next() {\n\t\t\t// get the value of each utxo prefixed item\n\t\t\tv := valueHash(it.Item())\n\t\t\touts := DeserializeOutputs(v)\n\n\t\t\t// iterate through each output, check to see if it is locked by the provided hash address\n\t\t\tfor _, out := range outs.Outputs {\n\t\t\t\tif out.IsLockedWithKey(pubKeyHash) {\n\t\t\t\t\tUTXOs = append(UTXOs, out)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn nil\n\t})\n\thandle(err)\n\n\treturn UTXOs\n}", "func distributeLockedAmount(ctx coretypes.Sandbox, bets []*BetInfo, totalLockedAmount int64) bool {\n\tsumsByPlayers := make(map[coretypes.AgentID]int64)\n\ttotalWinningAmount := int64(0)\n\tfor _, bet := range bets {\n\t\tif _, ok := sumsByPlayers[bet.Player]; !ok {\n\t\t\tsumsByPlayers[bet.Player] = 0\n\t\t}\n\t\tsumsByPlayers[bet.Player] += bet.Sum\n\t\ttotalWinningAmount += bet.Sum\n\t}\n\n\t// NOTE 1: float64 was avoided for determinism reasons\n\t// NOTE 2: beware overflows\n\n\tfor player, sum := range sumsByPlayers {\n\t\tsumsByPlayers[player] = (totalLockedAmount * sum) / totalWinningAmount\n\t}\n\n\t// make deterministic sequence by sorting. Eliminate possible rounding effects\n\tseqPlayers := make([]coretypes.AgentID, 0, len(sumsByPlayers))\n\tresultSum := int64(0)\n\tfor player, sum := range sumsByPlayers {\n\t\tseqPlayers = append(seqPlayers, player)\n\t\tresultSum += sum\n\t}\n\tsort.Slice(seqPlayers, func(i, j int) bool {\n\t\treturn bytes.Compare(seqPlayers[i][:], seqPlayers[j][:]) < 0\n\t})\n\n\t// ensure we distribute not more than totalLockedAmount iotas\n\tif resultSum > totalLockedAmount {\n\t\tsumsByPlayers[seqPlayers[0]] -= resultSum - totalLockedAmount\n\t}\n\n\t// filter out those who proportionally got 0\n\tfinalWinners := seqPlayers[:0]\n\tfor _, player := range seqPlayers {\n\t\tif sumsByPlayers[player] <= 0 {\n\t\t\tcontinue\n\t\t}\n\t\tfinalWinners = append(finalWinners, player)\n\t}\n\t// distribute iotas\n\tfor i := range finalWinners {\n\n\t\tavailable := ctx.Balance(balance.ColorIOTA)\n\t\tctx.Event(fmt.Sprintf(\"sending reward iotas %d to the winner %s. Available iotas: %d\",\n\t\t\tsumsByPlayers[finalWinners[i]], finalWinners[i].String(), available))\n\n\t\t//if !ctx.MoveTokens(finalWinners[i], balance.ColorIOTA, sumsByPlayers[finalWinners[i]]) {\n\t\t//\treturn false\n\t\t//}\n\t}\n\treturn true\n}", "func (w *rpcWallet) LockUnspent(ctx context.Context, unlock bool, ops []*wire.OutPoint) error {\n\treturn translateRPCCancelErr(w.client().LockUnspent(ctx, unlock, ops))\n}", "func (ck CoinKeeper) GetCoins(ctx sdk.Context, addr sdk.Address, amt sdk.Coins) sdk.Coins {\n\tacc := ck.am.GetAccount(ctx, addr)\n\treturn acc.GetCoins()\n}", "func GetUnlockedDistributionAddresses() []string {\n\t// The first InitialUnlockedCount (25) addresses are unlocked by default.\n\t// Subsequent addresses will be unlocked at a rate of UnlockAddressRate (5) per year,\n\t// after the InitialUnlockedCount (25) addresses have no remaining balance.\n\t// The unlock timer will be enabled manually once the\n\t// InitialUnlockedCount (25) addresses are distributed.\n\n\t// NOTE: To have automatic unlocking, transaction verification would have\n\t// to be handled in visor rather than in coin.Transactions.Visor(), because\n\t// the coin package is agnostic to the state of the blockchain and cannot reference it.\n\t// Instead of automatic unlocking, we can hardcode the timestamp at which the first 30%\n\t// is distributed, then compute the unlocked addresses easily here.\n\n\taddrs := make([]string, InitialUnlockedCount)\n\tfor i := range distributionAddresses[:InitialUnlockedCount] {\n\t\taddrs[i] = distributionAddresses[i]\n\t}\n\treturn addrs\n}", "func WithoutBlocking(ctx context.Context) context.Context {\n\treturn context.WithValue(ctx, nonBlockingTxnCtxKey, &nonBlockingTxnOpt{})\n}", "func (b *Bitcoind) ListUnspent(minconf, maxconf uint32) (transactions []Transaction, err error) {\n\tif maxconf > 999999 {\n\t\tmaxconf = 999999\n\t}\n\n\tr, err := b.client.call(\"listunspent\", []interface{}{minconf, maxconf})\n\tif err = handleError(err, &r); err != nil {\n\t\treturn\n\t}\n\n\terr = json.Unmarshal(r.Result, &transactions)\n\treturn\n}", "func (am *AccountManager) ListUnspent(minconf, maxconf int,\n\taddresses map[string]bool) ([]*btcjson.ListUnspentResult, error) {\n\n\tbs, err := GetCurBlock()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfilter := len(addresses) != 0\n\n\tvar results []*btcjson.ListUnspentResult\n\tfor _, a := range am.AllAccounts() {\n\t\tunspent, err := a.TxStore.UnspentOutputs()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfor _, credit := range unspent {\n\t\t\tconfs := credit.Confirmations(bs.Height)\n\t\t\tif int(confs) < minconf || int(confs) > maxconf {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t_, addrs, _, _ := credit.Addresses(cfg.Net())\n\t\t\tif filter {\n\t\t\t\tfor _, addr := range addrs {\n\t\t\t\t\t_, ok := addresses[addr.EncodeAddress()]\n\t\t\t\t\tif ok {\n\t\t\t\t\t\tgoto include\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\t\tinclude:\n\t\t\tresult := &btcjson.ListUnspentResult{\n\t\t\t\tTxId: credit.Tx().Sha().String(),\n\t\t\t\tVout: credit.OutputIndex,\n\t\t\t\tAccount: a.Name(),\n\t\t\t\tScriptPubKey: hex.EncodeToString(credit.TxOut().PkScript),\n\t\t\t\tAmount: credit.Amount().ToUnit(btcutil.AmountBTC),\n\t\t\t\tConfirmations: int64(confs),\n\t\t\t}\n\n\t\t\t// BUG: this should be a JSON array so that all\n\t\t\t// addresses can be included, or removed (and the\n\t\t\t// caller extracts addresses from the pkScript).\n\t\t\tif len(addrs) > 0 {\n\t\t\t\tresult.Address = addrs[0].EncodeAddress()\n\t\t\t}\n\n\t\t\tresults = append(results, result)\n\t\t}\n\t}\n\n\treturn results, nil\n}", "func (w *Wallet) ResetLockedOutpoints() {\n\tw.lockedOutpoints = map[wire.OutPoint]struct{}{}\n}", "func (c *Channel) Locked() *big.Int {\n\treturn c.OurState.AmountLocked()\n}", "func (va ClawbackVestingAccount) GetVestedOnly(blockTime time.Time) sdk.Coins {\n\treturn ReadSchedule(va.StartTime, va.EndTime, va.VestingPeriods, va.OriginalVesting, blockTime.Unix())\n}", "func (c *Channel) Locked() *big.Int {\n\treturn c.OurState.amountLocked()\n}", "func (s *Store) ListLockedOutputs(ns walletdb.ReadBucket) ([]*LockedOutput,\n\terror) {\n\n\tvar outputs []*LockedOutput\n\terr := forEachLockedOutput(\n\t\tns, func(op wire.OutPoint, id LockID, expiration time.Time) {\n\t\t\t// Skip expired leases. They will be cleaned up with the\n\t\t\t// next call to DeleteExpiredLockedOutputs.\n\t\t\tif !s.clock.Now().Before(expiration) {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\toutputs = append(outputs, &LockedOutput{\n\t\t\t\tOutpoint: op,\n\t\t\t\tLockID: id,\n\t\t\t\tExpiration: expiration,\n\t\t\t})\n\t\t},\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn outputs, nil\n}", "func coinSupplyHandler(gateway Gatewayer) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tif r.Method != http.MethodGet {\n\t\t\twh.Error405(w)\n\t\t\treturn\n\t\t}\n\n\t\tallUnspents, err := gateway.GetUnspentOutputsSummary(nil)\n\t\tif err != nil {\n\t\t\terr = fmt.Errorf(\"gateway.GetUnspentOutputsSummary failed: %v\", err)\n\t\t\twh.Error500(w, err.Error())\n\t\t\treturn\n\t\t}\n\n\t\tunlockedAddrs := params.GetUnlockedDistributionAddressesDecoded()\n\t\t// Search map of unlocked addresses, used to filter unspents\n\t\tunlockedAddrSet := newAddrSet(unlockedAddrs)\n\n\t\tvar unlockedSupply uint64\n\t\t// check confirmed unspents only\n\t\tfor _, u := range allUnspents.Confirmed {\n\t\t\t// check if address is an unlocked distribution address\n\t\t\tif _, ok := unlockedAddrSet[u.Body.Address]; ok {\n\t\t\t\tvar err error\n\t\t\t\tunlockedSupply, err = mathutil.AddUint64(unlockedSupply, u.Body.Coins)\n\t\t\t\tif err != nil {\n\t\t\t\t\terr = fmt.Errorf(\"uint64 overflow while adding up unlocked supply coins: %v\", err)\n\t\t\t\t\twh.Error500(w, err.Error())\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// \"total supply\" is the number of coins unlocked.\n\t\t// Each distribution address was allocated params.DistributionAddressInitialBalance coins.\n\t\ttotalSupply := uint64(len(unlockedAddrs)) * params.DistributionAddressInitialBalance\n\t\ttotalSupply *= droplet.Multiplier\n\n\t\t// \"current supply\" is the number of coins distributed from the unlocked pool\n\t\tcurrentSupply := totalSupply - unlockedSupply\n\n\t\tcurrentSupplyStr, err := droplet.ToString(currentSupply)\n\t\tif err != nil {\n\t\t\terr = fmt.Errorf(\"Failed to convert coins to string: %v\", err)\n\t\t\twh.Error500(w, err.Error())\n\t\t\treturn\n\t\t}\n\n\t\ttotalSupplyStr, err := droplet.ToString(totalSupply)\n\t\tif err != nil {\n\t\t\terr = fmt.Errorf(\"Failed to convert coins to string: %v\", err)\n\t\t\twh.Error500(w, err.Error())\n\t\t\treturn\n\t\t}\n\n\t\tmaxSupplyStr, err := droplet.ToString(params.MaxCoinSupply * droplet.Multiplier)\n\t\tif err != nil {\n\t\t\terr = fmt.Errorf(\"Failed to convert coins to string: %v\", err)\n\t\t\twh.Error500(w, err.Error())\n\t\t\treturn\n\t\t}\n\n\t\t// locked distribution addresses\n\t\tlockedAddrs := params.GetLockedDistributionAddressesDecoded()\n\t\tlockedAddrSet := newAddrSet(lockedAddrs)\n\n\t\t// get total coins hours which excludes locked distribution addresses\n\t\tvar totalCoinHours uint64\n\t\tfor _, out := range allUnspents.Confirmed {\n\t\t\tif _, ok := lockedAddrSet[out.Body.Address]; !ok {\n\t\t\t\tvar err error\n\t\t\t\ttotalCoinHours, err = mathutil.AddUint64(totalCoinHours, out.CalculatedHours)\n\t\t\t\tif err != nil {\n\t\t\t\t\terr = fmt.Errorf(\"uint64 overflow while adding up total coin hours: %v\", err)\n\t\t\t\t\twh.Error500(w, err.Error())\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// get current coin hours which excludes all distribution addresses\n\t\tvar currentCoinHours uint64\n\t\tfor _, out := range allUnspents.Confirmed {\n\t\t\t// check if address not in locked distribution addresses\n\t\t\tif _, ok := lockedAddrSet[out.Body.Address]; !ok {\n\t\t\t\t// check if address not in unlocked distribution addresses\n\t\t\t\tif _, ok := unlockedAddrSet[out.Body.Address]; !ok {\n\t\t\t\t\tcurrentCoinHours += out.CalculatedHours\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif err != nil {\n\t\t\terr = fmt.Errorf(\"Failed to get total coinhours: %v\", err)\n\t\t\twh.Error500(w, err.Error())\n\t\t\treturn\n\t\t}\n\n\t\tcs := CoinSupply{\n\t\t\tCurrentSupply: currentSupplyStr,\n\t\t\tTotalSupply: totalSupplyStr,\n\t\t\tMaxSupply: maxSupplyStr,\n\t\t\tCurrentCoinHourSupply: strconv.FormatUint(currentCoinHours, 10),\n\t\t\tTotalCoinHourSupply: strconv.FormatUint(totalCoinHours, 10),\n\t\t\tUnlockedAddresses: params.GetUnlockedDistributionAddresses(),\n\t\t\tLockedAddresses: params.GetLockedDistributionAddresses(),\n\t\t}\n\n\t\twh.SendJSONOr500(logger, w, cs)\n\t}\n}", "func (dcr *ExchangeWallet) spendableUTXOs() ([]*compositeUTXO, error) {\n\tunspents, err := dcr.unspents()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(unspents) == 0 {\n\t\treturn nil, fmt.Errorf(\"insufficient funds. 0 DCR available to spend in %q account\", dcr.acct)\n\t}\n\n\t// Parse utxos to include script size for spending input.\n\t// Returned utxos will be sorted in ascending order by amount (smallest first).\n\tutxos, err := dcr.parseUTXOs(unspents)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error parsing unspent outputs: %w\", err)\n\t}\n\tif len(utxos) == 0 {\n\t\treturn nil, fmt.Errorf(\"no funds available\")\n\t}\n\treturn utxos, nil\n}", "func (s *Store) UnspentOutputs(ns walletdb.ReadBucket) ([]Credit, error) {\n\tvar unspent []Credit\n\n\tvar op wire.OutPoint\n\tvar block Block\n\terr := ns.NestedReadBucket(bucketUnspent).ForEach(func(k, v []byte) error {\n\t\terr := readCanonicalOutPoint(k, &op)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Skip the output if it's locked.\n\t\t_, _, isLocked := isLockedOutput(ns, op, s.clock.Now())\n\t\tif isLocked {\n\t\t\treturn nil\n\t\t}\n\n\t\tif existsRawUnminedInput(ns, k) != nil {\n\t\t\t// Output is spent by an unmined transaction.\n\t\t\t// Skip this k/v pair.\n\t\t\treturn nil\n\t\t}\n\n\t\terr = readUnspentBlock(v, &block)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tblockTime, err := fetchBlockTime(ns, block.Height)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// TODO(jrick): reading the entire transaction should\n\t\t// be avoidable. Creating the credit only requires the\n\t\t// output amount and pkScript.\n\t\trec, err := fetchTxRecord(ns, &op.Hash, &block)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unable to retrieve transaction %v: \"+\n\t\t\t\t\"%v\", op.Hash, err)\n\t\t}\n\t\ttxOut := rec.MsgTx.TxOut[op.Index]\n\t\tcred := Credit{\n\t\t\tOutPoint: op,\n\t\t\tBlockMeta: BlockMeta{\n\t\t\t\tBlock: block,\n\t\t\t\tTime: blockTime,\n\t\t\t},\n\t\t\tAmount: btcutil.Amount(txOut.Value),\n\t\t\tPkScript: txOut.PkScript,\n\t\t\tReceived: rec.Received,\n\t\t\tFromCoinBase: blockchain.IsCoinBaseTx(&rec.MsgTx),\n\t\t}\n\t\tunspent = append(unspent, cred)\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\tif _, ok := err.(Error); ok {\n\t\t\treturn nil, err\n\t\t}\n\t\tstr := \"failed iterating unspent bucket\"\n\t\treturn nil, storeError(ErrDatabase, str, err)\n\t}\n\n\terr = ns.NestedReadBucket(bucketUnminedCredits).ForEach(func(k, v []byte) error {\n\t\tif err := readCanonicalOutPoint(k, &op); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Skip the output if it's locked.\n\t\t_, _, isLocked := isLockedOutput(ns, op, s.clock.Now())\n\t\tif isLocked {\n\t\t\treturn nil\n\t\t}\n\n\t\tif existsRawUnminedInput(ns, k) != nil {\n\t\t\t// Output is spent by an unmined transaction.\n\t\t\t// Skip to next unmined credit.\n\t\t\treturn nil\n\t\t}\n\n\t\t// TODO(jrick): Reading/parsing the entire transaction record\n\t\t// just for the output amount and script can be avoided.\n\t\trecVal := existsRawUnmined(ns, op.Hash[:])\n\t\tvar rec TxRecord\n\t\terr = readRawTxRecord(&op.Hash, recVal, &rec)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unable to retrieve raw transaction \"+\n\t\t\t\t\"%v: %v\", op.Hash, err)\n\t\t}\n\n\t\ttxOut := rec.MsgTx.TxOut[op.Index]\n\t\tcred := Credit{\n\t\t\tOutPoint: op,\n\t\t\tBlockMeta: BlockMeta{\n\t\t\t\tBlock: Block{Height: -1},\n\t\t\t},\n\t\t\tAmount: btcutil.Amount(txOut.Value),\n\t\t\tPkScript: txOut.PkScript,\n\t\t\tReceived: rec.Received,\n\t\t\tFromCoinBase: blockchain.IsCoinBaseTx(&rec.MsgTx),\n\t\t}\n\t\tunspent = append(unspent, cred)\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\tif _, ok := err.(Error); ok {\n\t\t\treturn nil, err\n\t\t}\n\t\tstr := \"failed iterating unmined credits bucket\"\n\t\treturn nil, storeError(ErrDatabase, str, err)\n\t}\n\n\treturn unspent, nil\n}", "func (tx *Transaction) GetNewFromCoins() []FromCoin {\n\tnfcs := make([]FromCoin, 0)\n\tfor index, c := range tx.To.Coins {\n\t\tticket := Ticket{}\n\t\tticket.SetTxid(*tx.GetTxID())\n\t\tticket.SetIndex(uint32(index))\n\n\t\tnfc := FromCoin{}\n\t\tnfc.SetId(c.Id)\n\t\tnfc.AddTicket(&ticket)\n\n\t\tnfcs = append(nfcs, nfc)\n\t}\n\n\treturn nfcs\n}", "func (b *BlockChain) GetUnspentOutputs(address string) []TxOutput {\n\tvar unspentOuts []TxOutput\n\ttxns := b.GetUnspentTxns(address)\n\n\t// go over each txn and each output in it and collect ones which belongs to this address\n\tfor _, txn := range txns {\n\t\t// iterate over all outputs\n\t\tfor _, output := range txn.Out {\n\t\t\tif output.CheckOutputUnlock(address) {\n\t\t\t\tunspentOuts = append(unspentOuts, output)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn unspentOuts\n}", "func (serv *ExchangeServer) GetSupportCoins() []string {\n\tsymbols := make([]string, len(serv.coins))\n\ti := 0\n\tfor _, coin := range serv.coins {\n\t\tsymbols[i] = coin.Symbol()\n\t\ti++\n\t}\n\treturn symbols\n}", "func (o RunnerOutput) Locked() pulumi.BoolOutput {\n\treturn o.ApplyT(func(v *Runner) pulumi.BoolOutput { return v.Locked }).(pulumi.BoolOutput)\n}", "func (cb CommitteeBits) FilterNonParticipants(committee []ValidatorIndex) []ValidatorIndex {\n\tbitLen := cb.BitLen()\n\tout := committee[:0]\n\tif bitLen != uint64(len(committee)) {\n\t\tpanic(\"committee mismatch, bitfield length does not match\")\n\t}\n\tfor i := uint64(0); i < bitLen; i++ {\n\t\tif !cb.GetBit(i) {\n\t\t\tout = append(out, committee[i])\n\t\t}\n\t}\n\treturn out\n}", "func (cm *coinsMempool) Get(maxTransactions uint64, s state.State) ([]*primitives.Tx, state.State) {\n\tcm.lock.RLock()\n\tdefer cm.lock.RUnlock()\n\tallTransactions := make([]*primitives.Tx, 0, maxTransactions)\n\nouter:\n\tfor _, addr := range cm.mempool {\n\t\tfor _, tx := range addr.transactions {\n\t\t\tif err := s.ApplyTransactionSingle(tx, [20]byte{}, cm.params); err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tallTransactions = append(allTransactions, tx)\n\t\t\tif uint64(len(allTransactions)) >= maxTransactions {\n\t\t\t\tbreak outer\n\t\t\t}\n\t\t}\n\t}\n\n\t// we can prioritize here, but we aren't to keep it simple\n\treturn allTransactions, s\n}", "func (k Keeper) MintCoins(ctx sdk.Context, newCoins sdk.Coins) error {\n\tif newCoins.Empty() {\n\t\t// skip as no coins need to be minted\n\t\treturn nil\n\t}\n\treturn k.supplyKeeper.MintCoins(ctx, types.ModuleName, newCoins)\n}", "func (u UTXOSet) FindUnspentTransactionOutputs(pubKeyHash []byte) []TxOutput {\n\tvar UTXOs []TxOutput\n\n\tdb := u.BlockChain.Database\n\n\terr := db.View(func(txn *badger.Txn) error {\n\t\topts := badger.DefaultIteratorOptions\n\n\t\tit := txn.NewIterator(opts)\n\t\tdefer it.Close()\n\n\t\t// iterate through all transactions with UTXOs\n\t\tfor it.Seek(utxoPrefix); it.ValidForPrefix(utxoPrefix); it.Next() {\n\t\t\titem := it.Item()\n\t\t\tv, err := item.Value()\n\t\t\tHandle(err)\n\t\t\touts := DeserializeOutputs(v)\n\t\t\t// go through all outputs of that transaction\n\t\t\tfor _, out := range outs.Outputs {\n\t\t\t\t// check the output was locked with this address (belongs to this receiver and can be unlocked by this address to use as new input)\n\t\t\t\tif out.IsLockedWithKey(pubKeyHash) {\n\t\t\t\t\tUTXOs = append(UTXOs, out)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t})\n\tHandle(err)\n\treturn UTXOs\n}", "func (_TokensNetwork *TokensNetworkCaller) QueryUnlockedLocks(opts *bind.CallOpts, token common.Address, participant common.Address, partner common.Address, lockhash [32]byte) (bool, error) {\n\tvar (\n\t\tret0 = new(bool)\n\t)\n\tout := ret0\n\terr := _TokensNetwork.contract.Call(opts, out, \"queryUnlockedLocks\", token, participant, partner, lockhash)\n\treturn *ret0, err\n}", "func (rt *recvTxOut) SetLocked(locked bool) {\n\trt.locked = locked\n}", "func (rt *recvTxOut) Locked() bool {\n\treturn rt.locked\n}", "func (_TokensNetwork *TokensNetworkCallerSession) QueryUnlockedLocks(token common.Address, participant common.Address, partner common.Address, lockhash [32]byte) (bool, error) {\n\treturn _TokensNetwork.Contract.QueryUnlockedLocks(&_TokensNetwork.CallOpts, token, participant, partner, lockhash)\n}", "func (tp *TXPool) GetUnverifiedTxs(txs []*types.Transaction,\n\theight uint32) *CheckBlkResult {\n\ttp.Lock()\n\tdefer tp.Unlock()\n\tres := &CheckBlkResult{\n\t\tVerifiedTxs: make([]*VerifyTxResult, 0, len(txs)),\n\t\tUnverifiedTxs: make([]*types.Transaction, 0),\n\t\tOldTxs: make([]*types.Transaction, 0),\n\t}\n\tfor _, tx := range txs {\n\t\ttxEntry := tp.txList[tx.Hash()]\n\t\tif txEntry == nil {\n\t\t\tres.UnverifiedTxs = append(res.UnverifiedTxs,\n\t\t\t\ttx)\n\t\t\tcontinue\n\t\t}\n\n\t\tif !tp.compareTxHeight(txEntry, height) {\n\t\t\tdelete(tp.txList, tx.Hash())\n\t\t\tres.OldTxs = append(res.OldTxs, txEntry.Tx)\n\t\t\tcontinue\n\t\t}\n\n\t\tfor _, v := range txEntry.Attrs {\n\t\t\tif v.Type == vt.Stateful {\n\t\t\t\tentry := &VerifyTxResult{\n\t\t\t\t\tTx: tx,\n\t\t\t\t\tHeight: v.Height,\n\t\t\t\t\tErrCode: v.ErrCode,\n\t\t\t\t}\n\t\t\t\tres.VerifiedTxs = append(res.VerifiedTxs,\n\t\t\t\t\tentry)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\treturn res\n}", "func (_TokensNetwork *TokensNetworkSession) QueryUnlockedLocks(token common.Address, participant common.Address, partner common.Address, lockhash [32]byte) (bool, error) {\n\treturn _TokensNetwork.Contract.QueryUnlockedLocks(&_TokensNetwork.CallOpts, token, participant, partner, lockhash)\n}", "func (tb *transactionBuilder) FundCoins(amount types.Currency, refundAddress *types.UnlockHash, reuseRefundAddress bool) error {\n\ttb.wallet.mu.Lock()\n\tdefer tb.wallet.mu.Unlock()\n\n\tif !tb.wallet.unlocked {\n\t\treturn modules.ErrLockedWallet\n\t}\n\n\t// prepare fulfillable context\n\tctx := tb.wallet.getFulfillableContextForLatestBlock()\n\n\t// Collect a value-sorted set of fulfillable coin outputs.\n\tvar so sortedOutputs\n\tfor scoid, sco := range tb.wallet.coinOutputs {\n\t\tif !sco.Condition.Fulfillable(ctx) {\n\t\t\tcontinue\n\t\t}\n\t\tso.ids = append(so.ids, scoid)\n\t\tso.outputs = append(so.outputs, sco)\n\t}\n\t// Add all of the unconfirmed outputs as well.\n\tfor _, upt := range tb.wallet.unconfirmedProcessedTransactions {\n\t\tfor i, sco := range upt.Transaction.CoinOutputs {\n\t\t\tuh := sco.Condition.UnlockHash()\n\t\t\t// Determine if the output belongs to the wallet.\n\t\t\texists, err := tb.wallet.keyExists(uh)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif !exists || !sco.Condition.Fulfillable(ctx) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tso.ids = append(so.ids, upt.Transaction.CoinOutputID(uint64(i)))\n\t\t\tso.outputs = append(so.outputs, sco)\n\t\t}\n\t}\n\tsort.Sort(sort.Reverse(so))\n\n\t// Create a transaction that will add the correct amount of coins to the\n\t// transaction.\n\tvar fund types.Currency\n\t// potentialFund tracks the balance of the wallet including outputs that\n\t// have been spent in other unconfirmed transactions recently. This is to\n\t// provide the user with a more useful error message in the event that they\n\t// are overspending.\n\tvar potentialFund types.Currency\n\tvar spentScoids []types.CoinOutputID\n\tfor i := range so.ids {\n\t\tscoid := so.ids[i]\n\t\tsco := so.outputs[i]\n\t\t// Check that this output has not recently been spent by the wallet.\n\t\tspendHeight := tb.wallet.spentOutputs[types.OutputID(scoid)]\n\t\t// Prevent an underflow error.\n\t\tallowedHeight := tb.wallet.consensusSetHeight - RespendTimeout\n\t\tif tb.wallet.consensusSetHeight < RespendTimeout {\n\t\t\tallowedHeight = 0\n\t\t}\n\t\tif spendHeight > allowedHeight {\n\t\t\tpotentialFund = potentialFund.Add(sco.Value)\n\t\t\tcontinue\n\t\t}\n\n\t\t// prepare fulfillment, matching the output\n\t\tuh := sco.Condition.UnlockHash()\n\t\tvar ff types.MarshalableUnlockFulfillment\n\t\tswitch sco.Condition.ConditionType() {\n\t\tcase types.ConditionTypeUnlockHash, types.ConditionTypeTimeLock:\n\t\t\t// ConditionTypeTimeLock is fine, as we know it's fulfillable,\n\t\t\t// and that can only mean for now that it is using an internal unlockHashCondition or nilCondition\n\t\t\tpk, _, err := tb.wallet.getKey(uh)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tff = types.NewSingleSignatureFulfillment(pk)\n\t\tdefault:\n\t\t\tbuild.Severe(fmt.Errorf(\"unexpected condition type: %[1]v (%[1]T)\", sco.Condition))\n\t\t\treturn types.ErrUnexpectedUnlockCondition\n\t\t}\n\t\t// Add a coin input for this output.\n\t\tsci := types.CoinInput{\n\t\t\tParentID: scoid,\n\t\t\tFulfillment: types.NewFulfillment(ff),\n\t\t}\n\t\ttb.coinInputs = append(tb.coinInputs, inputSignContext{\n\t\t\tInputIndex: len(tb.transaction.CoinInputs),\n\t\t\tUnlockHash: uh,\n\t\t})\n\t\ttb.transaction.CoinInputs = append(tb.transaction.CoinInputs, sci)\n\n\t\tspentScoids = append(spentScoids, scoid)\n\n\t\t// Add the output to the total fund\n\t\tfund = fund.Add(sco.Value)\n\t\tpotentialFund = potentialFund.Add(sco.Value)\n\t\tif fund.Cmp(amount) >= 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\tif potentialFund.Cmp(amount) >= 0 && fund.Cmp(amount) < 0 {\n\t\treturn modules.ErrIncompleteTransactions\n\t}\n\tif fund.Cmp(amount) < 0 {\n\t\treturn modules.ErrLowBalance\n\t}\n\n\t// Create a refund output if needed.\n\tif !amount.Equals(fund) {\n\t\tvar refundUnlockHash types.UnlockHash\n\t\tif refundAddress != nil {\n\t\t\t// use specified refund address\n\t\t\trefundUnlockHash = *refundAddress\n\t\t} else if reuseRefundAddress {\n\t\t\t// use the fist coin input of this tx as refund address\n\t\t\tvar maxCoinAmount types.Currency\n\t\t\tfor _, ci := range tb.transaction.CoinInputs {\n\t\t\t\tco, exists := tb.wallet.coinOutputs[ci.ParentID]\n\t\t\t\tif !exists {\n\t\t\t\t\tco = tb.getCoFromUnconfirmedProcessedTransactions(ci.ParentID)\n\t\t\t\t}\n\t\t\t\tif maxCoinAmount.Cmp(co.Value) < 0 {\n\t\t\t\t\tmaxCoinAmount = co.Value\n\t\t\t\t\trefundUnlockHash = co.Condition.UnlockHash()\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\t// generate a new address\n\t\t\tvar err error\n\t\t\trefundUnlockHash, err = tb.wallet.nextPrimarySeedAddress()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\trefundOutput := types.CoinOutput{\n\t\t\tValue: fund.Sub(amount),\n\t\t\tCondition: types.NewCondition(types.NewUnlockHashCondition(refundUnlockHash)),\n\t\t}\n\t\ttb.transaction.CoinOutputs = append(tb.transaction.CoinOutputs, refundOutput)\n\t}\n\n\t// Mark all outputs that were spent as spent.\n\tfor _, scoid := range spentScoids {\n\t\ttb.wallet.spentOutputs[types.OutputID(scoid)] = tb.wallet.consensusSetHeight\n\t}\n\treturn nil\n}", "func (o AttachedDiskResponseOutput) Locked() pulumi.BoolOutput {\n\treturn o.ApplyT(func(v AttachedDiskResponse) bool { return v.Locked }).(pulumi.BoolOutput)\n}", "func (b *rpcVestingBalance) unbonding() (sdk.Coins, sdk.Coins, error) {\n\tunbondingCoins, err := b.totalUnbondingDelegations()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tunbonding := unbondingCoins.AmountOf(stakingDenom)\n\tdelegatedFree := b.vacc.GetDelegatedFree().AmountOf(stakingDenom)\n\n\tunbondingFree := sdk.MinInt(delegatedFree, unbonding)\n\tunbondingVesting := unbonding.Sub(unbondingFree)\n\n\tliquidCoins := sdk.NewCoins(newKavaCoin(unbondingFree))\n\tvestingCoins := sdk.NewCoins(newKavaCoin(unbondingVesting))\n\treturn liquidCoins, vestingCoins, nil\n}", "func (s *StakingKeeperMock) GetBondedValidatorsByPower(ctx sdk.Context) []stakingtypes.Validator {\n\treturn s.BondedValidators\n}", "func (s *Store) GetUnspentOutputs(ns walletdb.ReadBucket) ([]Credit, er.R) {\n\tvar unspent []Credit\n\terr := s.ForEachUnspentOutput(ns, nil, func(_ []byte, c *Credit) er.R {\n\t\tunspent = append(unspent, *c)\n\t\treturn nil\n\t})\n\treturn unspent, err\n}", "func (btc *ExchangeWallet) spendableUTXOs(confs uint32) ([]*compositeUTXO, map[string]*compositeUTXO, uint64, error) {\n\tunspents, err := btc.wallet.ListUnspent()\n\tif err != nil {\n\t\treturn nil, nil, 0, err\n\t}\n\tsort.Slice(unspents, func(i, j int) bool { return unspents[i].Amount < unspents[j].Amount })\n\tvar sum uint64\n\tutxos := make([]*compositeUTXO, 0, len(unspents))\n\tutxoMap := make(map[string]*compositeUTXO, len(unspents))\n\tfor _, txout := range unspents {\n\t\tif txout.Confirmations >= confs && txout.Safe {\n\t\t\tnfo, err := dexbtc.InputInfo(txout.ScriptPubKey, txout.RedeemScript, btc.chainParams)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, nil, 0, fmt.Errorf(\"error reading asset info: %v\", err)\n\t\t\t}\n\t\t\ttxHash, err := chainhash.NewHashFromStr(txout.TxID)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, nil, 0, fmt.Errorf(\"error decoding txid in ListUnspentResult: %v\", err)\n\t\t\t}\n\t\t\tutxo := &compositeUTXO{\n\t\t\t\ttxHash: txHash,\n\t\t\t\tvout: txout.Vout,\n\t\t\t\taddress: txout.Address,\n\t\t\t\tredeemScript: txout.RedeemScript,\n\t\t\t\tamount: toSatoshi(txout.Amount),\n\t\t\t\tinput: nfo,\n\t\t\t}\n\t\t\tutxos = append(utxos, utxo)\n\t\t\tutxoMap[outpointID(txout.TxID, txout.Vout)] = utxo\n\t\t\tsum += toSatoshi(txout.Amount)\n\t\t}\n\t}\n\treturn utxos, utxoMap, sum, nil\n}", "func (w *Wallet) GetUnspentBlockStakeOutputs() (unspent []types.UnspentBlockStakeOutput, err error) {\n\tw.mu.RLock()\n\tdefer w.mu.RUnlock()\n\n\tif !w.unlocked {\n\t\terr = modules.ErrLockedWallet\n\t\treturn\n\t}\n\n\tunspent = make([]types.UnspentBlockStakeOutput, 0)\n\n\t// prepare fulfillable context\n\tctx := w.getFulfillableContextForLatestBlock()\n\n\t// collect all fulfillable block stake outputs\n\tfor usbsoid, output := range w.blockstakeOutputs {\n\t\tif output.Condition.Fulfillable(ctx) {\n\t\t\tunspent = append(unspent, w.unspentblockstakeoutputs[usbsoid])\n\t\t}\n\t}\n\treturn\n}", "func (dcr *ExchangeWallet) spendableUTXOs() ([]*compositeUTXO, error) {\n\tunspents, err := dcr.wallet.Unspents(dcr.ctx, dcr.primaryAcct)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif dcr.tradingAccount != \"\" {\n\t\t// Trading account may contain spendable utxos such as unspent split tx\n\t\t// outputs that are unlocked/returned. TODO: Care should probably be\n\t\t// taken to ensure only unspent split tx outputs are selected and other\n\t\t// unmixed outputs in the trading account are ignored.\n\t\ttradingAcctSpendables, err := dcr.wallet.Unspents(dcr.ctx, dcr.tradingAccount)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tunspents = append(unspents, tradingAcctSpendables...)\n\t}\n\tif len(unspents) == 0 {\n\t\treturn nil, fmt.Errorf(\"insufficient funds. 0 DCR available to spend in account %q\", dcr.primaryAcct)\n\t}\n\n\t// Parse utxos to include script size for spending input. Returned utxos\n\t// will be sorted in ascending order by amount (smallest first).\n\tutxos, err := dcr.parseUTXOs(unspents)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error parsing unspent outputs: %w\", err)\n\t}\n\tif len(utxos) == 0 {\n\t\treturn nil, fmt.Errorf(\"no funds available\")\n\t}\n\treturn utxos, nil\n}", "func newCoins() sdk.Coins {\n\treturn sdk.Coins{\n\t\tsdk.NewInt64Coin(\"atom\", 10000000),\n\t}\n}", "func (m *Machine) ReturnCoins() {\n\tcoins := m.cashEngine.DropCoins()\n\n\ts := fmt.Sprintf(\"-> \")\n\tfor i, c := range coins {\n\t\tif i == len(coins)-1 {\n\t\t\ts += fmt.Sprintf(\"%s\", c.value.String())\n\t\t\tcontinue\n\t\t}\n\t\ts += fmt.Sprintf(\"%s, \", c.value.String())\n\t}\n\n\tm.logger.Println(s)\n}", "func (_DelegationController *DelegationControllerCaller) GetLockedInPendingDelegations(opts *bind.CallOpts, holder common.Address) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _DelegationController.contract.Call(opts, out, \"getLockedInPendingDelegations\", holder)\n\treturn *ret0, err\n}" ]
[ "0.75117767", "0.7437211", "0.7414191", "0.7314862", "0.6838447", "0.6392202", "0.6191451", "0.61146224", "0.58891666", "0.5810488", "0.56842095", "0.5653297", "0.56145257", "0.5558801", "0.55499065", "0.54996663", "0.547989", "0.5471419", "0.54146755", "0.53996265", "0.5391759", "0.53801906", "0.5366556", "0.5331209", "0.52814776", "0.52762425", "0.5267115", "0.52552867", "0.52510226", "0.5227577", "0.5201504", "0.5187646", "0.51759166", "0.5145159", "0.5144104", "0.5107058", "0.5098616", "0.5088944", "0.5075246", "0.5050111", "0.5027087", "0.49956703", "0.4962004", "0.4930688", "0.48913118", "0.48796943", "0.487169", "0.4869978", "0.48480642", "0.4837431", "0.48173493", "0.48125806", "0.48091683", "0.4801582", "0.479478", "0.4792796", "0.47915778", "0.47553122", "0.47416973", "0.47145435", "0.47129002", "0.4699172", "0.46981987", "0.46980542", "0.4693956", "0.46899366", "0.46785378", "0.46751997", "0.4660089", "0.46583098", "0.4655535", "0.4641713", "0.46123403", "0.45888072", "0.45717153", "0.45663372", "0.4552733", "0.4550473", "0.45406416", "0.45253915", "0.4524632", "0.45189652", "0.451539", "0.45054013", "0.45048034", "0.4493985", "0.44890448", "0.4483576", "0.4481345", "0.44683138", "0.44544452", "0.44451535", "0.44352993", "0.4432181", "0.4425865", "0.44254085", "0.44242823", "0.44238508", "0.44215846", "0.44145858" ]
0.7426922
2
TrackDelegation tracks a desired delegation amount by setting the appropriate values for the amount of delegated vesting, delegated free, and reducing the overall amount of base coins.
func (cva *ContinuousVestingAccount) TrackDelegation(blockTime time.Time, balance, amount sdk.Coins) { cva.BaseVestingAccount.TrackDelegation(balance, cva.GetVestingCoins(blockTime), amount) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (bva *BaseVestingAccount) TrackDelegation(balance, vestingCoins, amount sdk.Coins) {\n\tfor _, coin := range amount {\n\t\tbaseAmt := balance.AmountOf(coin.Denom)\n\t\tvestingAmt := vestingCoins.AmountOf(coin.Denom)\n\t\tdelVestingAmt := bva.DelegatedVesting.AmountOf(coin.Denom)\n\n\t\t// Panic if the delegation amount is zero or if the base coins does not\n\t\t// exceed the desired delegation amount.\n\t\tif coin.Amount.IsZero() || baseAmt.LT(coin.Amount) {\n\t\t\tpanic(\"delegation attempt with zero coins or insufficient funds\")\n\t\t}\n\n\t\t// compute x and y per the specification, where:\n\t\t// X := min(max(V - DV, 0), D)\n\t\t// Y := D - X\n\t\tx := sdk.MinInt(sdk.MaxInt(vestingAmt.Sub(delVestingAmt), sdk.ZeroInt()), coin.Amount)\n\t\ty := coin.Amount.Sub(x)\n\n\t\tif !x.IsZero() {\n\t\t\txCoin := sdk.NewCoin(coin.Denom, x)\n\t\t\tbva.DelegatedVesting = bva.DelegatedVesting.Add(xCoin)\n\t\t}\n\n\t\tif !y.IsZero() {\n\t\t\tyCoin := sdk.NewCoin(coin.Denom, y)\n\t\t\tbva.DelegatedFree = bva.DelegatedFree.Add(yCoin)\n\t\t}\n\t}\n}", "func (dva *DelayedVestingAccount) TrackDelegation(blockTime time.Time, balance, amount sdk.Coins) {\n\tdva.BaseVestingAccount.TrackDelegation(balance, dva.GetVestingCoins(blockTime), amount)\n}", "func (pva *PeriodicVestingAccount) TrackDelegation(blockTime time.Time, balance, amount sdk.Coins) {\n\tpva.BaseVestingAccount.TrackDelegation(balance, pva.GetVestingCoins(blockTime), amount)\n}", "func (vva *ValidatorVestingAccount) TrackDelegation(blockTime time.Time, amount sdk.Coins) {\n\tvva.BaseVestingAccount.TrackDelegation(vva.GetVestingCoins(blockTime), amount)\n}", "func (va *ClawbackVestingAccount) TrackDelegation(blockTime time.Time, balance, amount sdk.Coins) {\n\tva.BaseVestingAccount.TrackDelegation(balance, va.GetVestingCoins(blockTime), amount)\n}", "func (plva *PermanentLockedAccount) TrackDelegation(blockTime time.Time, balance, amount sdk.Coins) {\n\tplva.BaseVestingAccount.TrackDelegation(balance, plva.OriginalVesting, amount)\n}", "func (bva *BaseVestingAccount) TrackUndelegation(amount sdk.Coins) {\n\tfor _, coin := range amount {\n\t\t// panic if the undelegation amount is zero\n\t\tif coin.Amount.IsZero() {\n\t\t\tpanic(\"undelegation attempt with zero coins\")\n\t\t}\n\t\tdelegatedFree := bva.DelegatedFree.AmountOf(coin.Denom)\n\t\tdelegatedVesting := bva.DelegatedVesting.AmountOf(coin.Denom)\n\n\t\t// compute x and y per the specification, where:\n\t\t// X := min(DF, D)\n\t\t// Y := min(DV, D - X)\n\t\tx := sdk.MinInt(delegatedFree, coin.Amount)\n\t\ty := sdk.MinInt(delegatedVesting, coin.Amount.Sub(x))\n\n\t\tif !x.IsZero() {\n\t\t\txCoin := sdk.NewCoin(coin.Denom, x)\n\t\t\tbva.DelegatedFree = bva.DelegatedFree.Sub(sdk.Coins{xCoin})\n\t\t}\n\n\t\tif !y.IsZero() {\n\t\t\tyCoin := sdk.NewCoin(coin.Denom, y)\n\t\t\tbva.DelegatedVesting = bva.DelegatedVesting.Sub(sdk.Coins{yCoin})\n\t\t}\n\t}\n}", "func (va *ClawbackVestingAccount) updateDelegation(encumbered, toClawBack, bonded, unbonding, unbonded sdk.Coins) sdk.Coins {\n\tdelegated := bonded.Add(unbonding...)\n\toldDelegated := va.DelegatedVesting.Add(va.DelegatedFree...)\n\tslashed := oldDelegated.Sub(coinsMin(delegated, oldDelegated))\n\ttotal := delegated.Add(unbonded...)\n\ttoClawBack = coinsMin(toClawBack, total) // might have been slashed\n\tnewDelegated := coinsMin(delegated, total.Sub(toClawBack)).Add(slashed...)\n\tva.DelegatedVesting = coinsMin(encumbered, newDelegated)\n\tva.DelegatedFree = newDelegated.Sub(va.DelegatedVesting)\n\treturn toClawBack\n}", "func (k msgServer) Delegate(goCtx context.Context, msg *types.MsgDelegate) (*types.MsgDelegateResponse, error) {\n\tctx := sdk.UnwrapSDKContext(goCtx)\n\tvalAddr, valErr := sdk.ValAddressFromBech32(msg.ValidatorAddress)\n\tif valErr != nil {\n\t\treturn nil, valErr\n\t}\n\n\tvalidator, found := k.GetValidator(ctx, valAddr)\n\tif !found {\n\t\treturn nil, types.ErrNoValidatorFound\n\t}\n\n\tdelegatorAddress, err := sdk.AccAddressFromBech32(msg.DelegatorAddress)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbondDenom := k.BondDenom(ctx)\n\tif msg.Amount.Denom != bondDenom {\n\t\treturn nil, sdkerrors.Wrapf(\n\t\t\tsdkerrors.ErrInvalidRequest, \"invalid coin denomination: got %s, expected %s\", msg.Amount.Denom, bondDenom,\n\t\t)\n\t}\n\n\ttokens := msg.Amount.Amount\n\n\t// if this delegation is from a liquid staking provider (identified if the delegator\n\t// is an ICA account), it cannot exceed the global or validator bond cap\n\tif k.DelegatorIsLiquidStaker(delegatorAddress) {\n\t\tshares, err := validator.SharesFromTokens(tokens)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif err := k.SafelyIncreaseTotalLiquidStakedTokens(ctx, tokens, false); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif err := k.SafelyIncreaseValidatorLiquidShares(ctx, &validator, shares); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// NOTE: source funds are always unbonded\n\tnewShares, err := k.Keeper.Delegate(ctx, delegatorAddress, tokens, types.Unbonded, validator, true)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif tokens.IsInt64() {\n\t\tdefer func() {\n\t\t\ttelemetry.IncrCounter(1, types.ModuleName, \"delegate\")\n\t\t\ttelemetry.SetGaugeWithLabels(\n\t\t\t\t[]string{\"tx\", \"msg\", msg.Type()},\n\t\t\t\tfloat32(tokens.Int64()),\n\t\t\t\t[]metrics.Label{telemetry.NewLabel(\"denom\", msg.Amount.Denom)},\n\t\t\t)\n\t\t}()\n\t}\n\n\tctx.EventManager().EmitEvents(sdk.Events{\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeDelegate,\n\t\t\tsdk.NewAttribute(types.AttributeKeyValidator, msg.ValidatorAddress),\n\t\t\tsdk.NewAttribute(sdk.AttributeKeyAmount, msg.Amount.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyNewShares, newShares.String()),\n\t\t),\n\t})\n\n\treturn &types.MsgDelegateResponse{}, nil\n}", "func (k Keeper) TransferDelegation(ctx sdk.Context, valAddr sdk.ValAddress, fromDelegator, toDelegator sdk.AccAddress, shares sdk.Dec) (sdk.Dec, error) {\n\t// Redelegations link a delegation to it's previous validator so slashes are propagated to the new validator.\n\t// If the delegation is transferred to a new owner, the redelegation object must be updated.\n\t// For expediency all transfers with redelegations are blocked.\n\tif k.stakingKeeper.HasReceivingRedelegation(ctx, fromDelegator, valAddr) {\n\t\treturn sdk.Dec{}, types.ErrRedelegationsNotCompleted\n\t}\n\n\tif shares.IsNil() || shares.LT(sdk.ZeroDec()) {\n\t\treturn sdk.Dec{}, errorsmod.Wrap(types.ErrUntransferableShares, \"nil or negative shares\")\n\t}\n\tif shares.Equal(sdk.ZeroDec()) {\n\t\t// Block 0 transfers to reduce edge cases.\n\t\treturn sdk.Dec{}, errorsmod.Wrap(types.ErrUntransferableShares, \"zero shares\")\n\t}\n\n\tfromDelegation, found := k.stakingKeeper.GetDelegation(ctx, fromDelegator, valAddr)\n\tif !found {\n\t\treturn sdk.Dec{}, types.ErrNoDelegatorForAddress\n\t}\n\tvalidator, found := k.stakingKeeper.GetValidator(ctx, valAddr)\n\tif !found {\n\t\treturn sdk.Dec{}, types.ErrNoValidatorFound\n\t}\n\t// Prevent validators from reducing their self delegation below the min.\n\tisValidatorOperator := fromDelegator.Equals(valAddr)\n\tif isValidatorOperator {\n\t\tif isBelowMinSelfDelegation(validator, fromDelegation.Shares.Sub(shares)) {\n\t\t\treturn sdk.Dec{}, types.ErrSelfDelegationBelowMinimum\n\t\t}\n\t}\n\n\treturnAmount, err := k.fastUndelegate(ctx, valAddr, fromDelegator, shares)\n\tif err != nil {\n\t\treturn sdk.Dec{}, err\n\t}\n\treturnCoins := sdk.NewCoins(sdk.NewCoin(k.stakingKeeper.BondDenom(ctx), returnAmount))\n\n\tif err := k.bankKeeper.SendCoins(ctx, fromDelegator, toDelegator, returnCoins); err != nil {\n\t\treturn sdk.Dec{}, err\n\t}\n\treceivedShares, err := k.delegateFromAccount(ctx, valAddr, toDelegator, returnAmount)\n\tif err != nil {\n\t\treturn sdk.Dec{}, err\n\t}\n\n\treturn receivedShares, nil\n}", "func (_DelegationController *DelegationControllerTransactor) Delegate(opts *bind.TransactOpts, validatorId *big.Int, amount *big.Int, delegationPeriod *big.Int, info string) (*types.Transaction, error) {\n\treturn _DelegationController.contract.Transact(opts, \"delegate\", validatorId, amount, delegationPeriod, info)\n}", "func (_DelegationController *DelegationControllerSession) Delegate(validatorId *big.Int, amount *big.Int, delegationPeriod *big.Int, info string) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.Delegate(&_DelegationController.TransactOpts, validatorId, amount, delegationPeriod, info)\n}", "func (_DelegationController *DelegationControllerTransactorSession) Delegate(validatorId *big.Int, amount *big.Int, delegationPeriod *big.Int, info string) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.Delegate(&_DelegationController.TransactOpts, validatorId, amount, delegationPeriod, info)\n}", "func (broadcast *Broadcast) Delegate(ctx context.Context, delegator, voter, amount,\n\tprivKeyHex string, seq int64) (*model.BroadcastResponse, error) {\n\tmsg := model.DelegateMsg{\n\t\tDelegator: delegator,\n\t\tVoter: voter,\n\t\tAmount: amount,\n\t}\n\treturn broadcast.broadcastTransaction(ctx, msg, privKeyHex, seq, \"\", false)\n}", "func (o OfflineNotaryRepository) AddDelegation(data.RoleName, []data.PublicKey, []string) error {\n\treturn nil\n}", "func Delegate(stub shim.ChaincodeStubInterface, args []string) error {\n\tvar vote entities.Vote\n\terr := json.Unmarshal([]byte(args[0]), &vote)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tpoll, err := validateDelegate(stub, vote)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = addVoteToPoll(stub, poll, vote)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Println(\"saving delegate vote\")\n\tutil.UpdateObjectInChain(stub, vote.ID(), util.VotesIndexName, []byte(args[0]))\n\n\tfmt.Println(\"successfully delegated vote to \" + vote.Delegate + \"!\")\n\treturn nil\n}", "func (b *rpcVestingBalance) delegated() (sdk.Coins, sdk.Coins, error) {\n\tdelegatedCoins, err := b.totalDelegated()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tunbondingCoins, err := b.totalUnbondingDelegations()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tdelegated := delegatedCoins.AmountOf(stakingDenom)\n\tunbonding := unbondingCoins.AmountOf(stakingDenom)\n\ttotalStaked := delegated.Add(unbonding)\n\tdelegatedFree := b.vacc.GetDelegatedFree().AmountOf(stakingDenom)\n\n\t// total number of staked and unbonding tokens considered to be liquid\n\ttotalFree := sdk.MinInt(totalStaked, delegatedFree)\n\t// any coins that are not considered liquid, are vesting up to a maximum of delegated\n\tstakedVesting := sdk.MinInt(totalStaked.Sub(totalFree), delegated)\n\t// staked free coins are left over\n\tstakedFree := delegated.Sub(stakedVesting)\n\n\tliquidCoins := sdk.NewCoins(newKavaCoin(stakedFree))\n\tvestingCoins := sdk.NewCoins(newKavaCoin(stakedVesting))\n\treturn liquidCoins, vestingCoins, nil\n}", "func (k Keeper) Delegation(ctx sdk.Context, addrDel sdk.AccAddress, addrVal sdk.ValAddress) exported.DelegationI {\n\treturn nil\n}", "func (del Delegation) AmountDelegated() hexutil.Big {\n\tif del.Delegation.AmountDelegated == nil {\n\t\treturn hexutil.Big{}\n\t}\n\treturn *del.Delegation.AmountDelegated\n}", "func TestCallSimDelegate(t *testing.T) {\n\t// Roll up our sleeves and swear fealty to the witch-king\n\tctx, cancel := context.WithCancel(context.Background())\n\tdefer cancel()\n\tg, ctx := errgroup.WithContext(ctx)\n\n\tdb := dbm.NewMemDB()\n\tst, err := state.MakeGenesisState(db, genesisDoc)\n\trequire.NoError(t, err)\n\n\tfrom := crypto.PrivateKeyFromSecret(\"raaah\", crypto.CurveTypeEd25519)\n\tcontractAddress := crypto.Address{1, 2, 3, 4, 5}\n\tblockchain := &bcm.Blockchain{}\n\tsink := exec.NewNoopEventSink()\n\n\t// Function to set storage value for later\n\tsetDelegate := func(up state.Updatable, value crypto.Address) error {\n\t\tcall, _, err := abi.EncodeFunctionCall(string(solidity.Abi_DelegateProxy), \"setDelegate\", logger, value)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tcache := acmstate.NewCache(st)\n\t\t_, err = evm.Default().Execute(cache, blockchain, sink,\n\t\t\tengine.CallParams{\n\t\t\t\tCallType: exec.CallTypeCall,\n\t\t\t\tOrigin: from.GetAddress(),\n\t\t\t\tCaller: from.GetAddress(),\n\t\t\t\tCallee: contractAddress,\n\t\t\t\tInput: call,\n\t\t\t\tGas: big.NewInt(9999999),\n\t\t\t}, solidity.DeployedBytecode_DelegateProxy)\n\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn cache.Sync(up)\n\t}\n\n\t// Initialise sender smart contract state\n\t_, _, err = st.Update(func(up state.Updatable) error {\n\t\terr = up.UpdateAccount(&acm.Account{\n\t\t\tAddress: from.GetAddress(),\n\t\t\tPublicKey: from.GetPublicKey(),\n\t\t\tBalance: 9999999,\n\t\t\tPermissions: permission.DefaultAccountPermissions,\n\t\t})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn up.UpdateAccount(&acm.Account{\n\t\t\tAddress: contractAddress,\n\t\t\tEVMCode: solidity.DeployedBytecode_DelegateProxy,\n\t\t})\n\t})\n\trequire.NoError(t, err)\n\n\t// Set a series of values of storage slot so we get a deep version tree (which we need to trigger the bug)\n\tdelegate := crypto.Address{0xBE, 0xEF, 0, 0xFA, 0xCE, 0, 0xBA, 0}\n\tfor i := 0; i < 0xBF; i++ {\n\t\tdelegate[7] = byte(i)\n\t\t_, _, err = st.Update(func(up state.Updatable) error {\n\t\t\treturn setDelegate(up, delegate)\n\t\t})\n\t\trequire.NoError(t, err)\n\t}\n\n\t// This is important in order to illicit the former bug - we need a cold LRU tree cache in MutableForest\n\tst, err = state.LoadState(db, st.Version())\n\trequire.NoError(t, err)\n\n\tgetIntCall, _, err := abi.EncodeFunctionCall(string(solidity.Abi_DelegateProxy), \"getDelegate\", logger)\n\trequire.NoError(t, err)\n\tn := 1000\n\n\tfor i := 0; i < n; i++ {\n\t\tg.Go(func() error {\n\t\t\ttxe, err := CallSim(st, blockchain, from.GetAddress(), contractAddress, getIntCall, logger)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\terr = txe.GetException().AsError()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\taddress, err := crypto.AddressFromBytes(txe.GetResult().Return[12:])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif address != delegate {\n\t\t\t\t// The bug for which this test was written will return the zero address here since it is accessing\n\t\t\t\t// an uninitialised tree\n\t\t\t\treturn fmt.Errorf(\"getDelegate returned %v but expected %v\", address, delegate)\n\t\t\t}\n\t\t\treturn nil\n\t\t})\n\t}\n\n\trequire.NoError(t, g.Wait())\n}", "func CalculateDelegateNetPayout(delegatedContracts []DelegatedContract) []DelegatedContract{\n var delegateIndex int\n\n for index, delegate := range delegatedContracts{\n if (delegate.Delegate){\n delegateIndex = index\n }\n }\n\n for _, delegate := range delegatedContracts{\n if (!delegate.Delegate){\n delegatedContracts[delegateIndex].TotalPayout = delegatedContracts[delegateIndex].TotalPayout + delegate.Fee\n }\n }\n return delegatedContracts\n}", "func consolidateDelegations(ctx contract.Context, validator, delegator *types.Address) (*Delegation, []*Delegation, int, error) {\n\t// cycle through all delegations and delete those which are BONDED and\n\t// unlocked while accumulating their amounts\n\tdelegations, err := returnMatchingDelegations(ctx, validator, delegator)\n\tif err != nil {\n\t\treturn nil, nil, -1, err\n\t}\n\n\tunconsolidatedDelegationsCount := 0\n\ttotalDelegationAmount := common.BigZero()\n\tvar consolidatedDelegations []*Delegation\n\tfor _, delegation := range delegations {\n\t\tif delegation.LockTime > uint64(ctx.Now().Unix()) || delegation.State != BONDED {\n\t\t\tunconsolidatedDelegationsCount++\n\t\t\tcontinue\n\t\t}\n\n\t\ttotalDelegationAmount.Add(totalDelegationAmount, &delegation.Amount.Value)\n\t\tconsolidatedDelegations = append(consolidatedDelegations, delegation)\n\n\t\tif err = DeleteDelegation(ctx, delegation); err != nil {\n\t\t\treturn nil, nil, -1, err\n\t\t}\n\t}\n\n\tindex, err := GetNextDelegationIndex(ctx, *validator, *delegator)\n\tif err != nil {\n\t\treturn nil, nil, -1, err\n\t}\n\n\t// create new conolidated delegation\n\tdelegation := &Delegation{\n\t\tValidator: validator,\n\t\tDelegator: delegator,\n\t\tAmount: &types.BigUInt{Value: *totalDelegationAmount},\n\t\tUpdateAmount: loom.BigZeroPB(),\n\t\tLocktimeTier: 0,\n\t\tLockTime: 0,\n\t\tState: BONDED,\n\t\tIndex: index,\n\t}\n\tif err := SetDelegation(ctx, delegation); err != nil {\n\t\treturn nil, nil, -1, err\n\t}\n\treturn delegation, consolidatedDelegations, unconsolidatedDelegationsCount, nil\n}", "func (_TokensNetwork *TokensNetworkTransactor) UpdateBalanceProofDelegate(opts *bind.TransactOpts, token common.Address, partner common.Address, participant common.Address, transferred_amount *big.Int, locksroot [32]byte, nonce uint64, additional_hash [32]byte, partner_signature []byte, participant_signature []byte) (*types.Transaction, error) {\n\treturn _TokensNetwork.contract.Transact(opts, \"updateBalanceProofDelegate\", token, partner, participant, transferred_amount, locksroot, nonce, additional_hash, partner_signature, participant_signature)\n}", "func (k msgServer) CancelUnbondingDelegation(goCtx context.Context, msg *types.MsgCancelUnbondingDelegation) (*types.MsgCancelUnbondingDelegationResponse, error) {\n\tctx := sdk.UnwrapSDKContext(goCtx)\n\n\tvalAddr, err := sdk.ValAddressFromBech32(msg.ValidatorAddress)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdelegatorAddress, err := sdk.AccAddressFromBech32(msg.DelegatorAddress)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbondDenom := k.BondDenom(ctx)\n\tif msg.Amount.Denom != bondDenom {\n\t\treturn nil, sdkerrors.Wrapf(\n\t\t\tsdkerrors.ErrInvalidRequest, \"invalid coin denomination: got %s, expected %s\", msg.Amount.Denom, bondDenom,\n\t\t)\n\t}\n\n\tvalidator, found := k.GetValidator(ctx, valAddr)\n\tif !found {\n\t\treturn nil, types.ErrNoValidatorFound\n\t}\n\n\t// In some situations, the exchange rate becomes invalid, e.g. if\n\t// Validator loses all tokens due to slashing. In this case,\n\t// make all future delegations invalid.\n\tif validator.InvalidExRate() {\n\t\treturn nil, types.ErrDelegatorShareExRateInvalid\n\t}\n\n\tif validator.IsJailed() {\n\t\treturn nil, types.ErrValidatorJailed\n\t}\n\n\tubd, found := k.GetUnbondingDelegation(ctx, delegatorAddress, valAddr)\n\tif !found {\n\t\treturn nil, status.Errorf(\n\t\t\tcodes.NotFound,\n\t\t\t\"unbonding delegation with delegator %s not found for validator %s\",\n\t\t\tmsg.DelegatorAddress, msg.ValidatorAddress,\n\t\t)\n\t}\n\n\t// if this undelegation was from a liquid staking provider (identified if the delegator\n\t// is an ICA account), the global and validator liquid totals should be incremented\n\ttokens := msg.Amount.Amount\n\tshares, err := validator.SharesFromTokens(tokens)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif k.DelegatorIsLiquidStaker(delegatorAddress) {\n\t\tif err := k.SafelyIncreaseTotalLiquidStakedTokens(ctx, tokens, false); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif err := k.SafelyIncreaseValidatorLiquidShares(ctx, &validator, shares); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tvar (\n\t\tunbondEntry types.UnbondingDelegationEntry\n\t\tunbondEntryIndex int64 = -1\n\t)\n\n\tfor i, entry := range ubd.Entries {\n\t\tif entry.CreationHeight == msg.CreationHeight {\n\t\t\tunbondEntry = entry\n\t\t\tunbondEntryIndex = int64(i)\n\t\t\tbreak\n\t\t}\n\t}\n\tif unbondEntryIndex == -1 {\n\t\treturn nil, sdkerrors.ErrNotFound.Wrapf(\"unbonding delegation entry is not found at block height %d\", msg.CreationHeight)\n\t}\n\n\tif unbondEntry.Balance.LT(msg.Amount.Amount) {\n\t\treturn nil, sdkerrors.ErrInvalidRequest.Wrap(\"amount is greater than the unbonding delegation entry balance\")\n\t}\n\n\tif unbondEntry.CompletionTime.Before(ctx.BlockTime()) {\n\t\treturn nil, sdkerrors.ErrInvalidRequest.Wrap(\"unbonding delegation is already processed\")\n\t}\n\n\t// delegate back the unbonding delegation amount to the validator\n\t_, err = k.Keeper.Delegate(ctx, delegatorAddress, msg.Amount.Amount, types.Unbonding, validator, false)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tamount := unbondEntry.Balance.Sub(msg.Amount.Amount)\n\tif amount.IsZero() {\n\t\tubd.RemoveEntry(unbondEntryIndex)\n\t} else {\n\t\t// update the unbondingDelegationEntryBalance and InitialBalance for ubd entry\n\t\tunbondEntry.Balance = amount\n\t\tunbondEntry.InitialBalance = unbondEntry.InitialBalance.Sub(msg.Amount.Amount)\n\t\tubd.Entries[unbondEntryIndex] = unbondEntry\n\t}\n\n\t// set the unbonding delegation or remove it if there are no more entries\n\tif len(ubd.Entries) == 0 {\n\t\tk.RemoveUnbondingDelegation(ctx, ubd)\n\t} else {\n\t\tk.SetUnbondingDelegation(ctx, ubd)\n\t}\n\n\tctx.EventManager().EmitEvent(\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeCancelUnbondingDelegation,\n\t\t\tsdk.NewAttribute(sdk.AttributeKeyAmount, msg.Amount.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyValidator, msg.ValidatorAddress),\n\t\t\tsdk.NewAttribute(types.AttributeKeyDelegator, msg.DelegatorAddress),\n\t\t\tsdk.NewAttribute(types.AttributeKeyCreationHeight, strconv.FormatInt(msg.CreationHeight, 10)),\n\t\t),\n\t)\n\n\treturn &types.MsgCancelUnbondingDelegationResponse{}, nil\n}", "func CalculatePayoutForContract(contract Contract, rate float64, delegate bool) Contract{\n ////-------------JUST FOR TESTING -------------////\n totalNodeRewards := 378 //Amount of rewards for my delegation in cycle 11\n ////--------------END TESTING ------------------////\n\n grossRewards := contract.SharePercentage * float64(totalNodeRewards)\n contract.GrossPayout = grossRewards\n fee := rate * grossRewards\n contract.Fee = fee\n var netRewards float64\n if (delegate){\n netRewards = grossRewards\n contract.NetPayout = netRewards\n contract.Fee = 0\n } else {\n netRewards = grossRewards - fee\n contract.NetPayout = contract.NetPayout + netRewards\n }\n\n return contract\n}", "func (us *DelegationService) AddDelegation(delegation *models.Delegation) (*models.Delegation, error) {\n\t// TODO(tho) add CSR validation against template\n\treturn us.storeInterface.AddDelegation(delegation)\n}", "func (_TokensNetwork *TokensNetworkSession) UpdateBalanceProofDelegate(token common.Address, partner common.Address, participant common.Address, transferred_amount *big.Int, locksroot [32]byte, nonce uint64, additional_hash [32]byte, partner_signature []byte, participant_signature []byte) (*types.Transaction, error) {\n\treturn _TokensNetwork.Contract.UpdateBalanceProofDelegate(&_TokensNetwork.TransactOpts, token, partner, participant, transferred_amount, locksroot, nonce, additional_hash, partner_signature, participant_signature)\n}", "func NewDelegation(d *types.Delegation) *Delegation {\n\treturn &Delegation{Delegation: *d, cg: new(singleflight.Group)}\n}", "func (_TokensNetwork *TokensNetworkTransactorSession) UpdateBalanceProofDelegate(token common.Address, partner common.Address, participant common.Address, transferred_amount *big.Int, locksroot [32]byte, nonce uint64, additional_hash [32]byte, partner_signature []byte, participant_signature []byte) (*types.Transaction, error) {\n\treturn _TokensNetwork.Contract.UpdateBalanceProofDelegate(&_TokensNetwork.TransactOpts, token, partner, participant, transferred_amount, locksroot, nonce, additional_hash, partner_signature, participant_signature)\n}", "func (k Keeper) Delegation(ctx context.Context, addrDel sdk.AccAddress, addrVal sdk.ValAddress) (types.DelegationI, error) {\n\tbond, err := k.Delegations.Get(ctx, collections.Join(addrDel, addrVal))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn bond, nil\n}", "func (_TokensNetwork *TokensNetworkTransactor) UnlockDelegate(opts *bind.TransactOpts, token common.Address, partner common.Address, participant common.Address, transferred_amount *big.Int, expiration *big.Int, amount *big.Int, secret_hash [32]byte, merkle_proof []byte, participant_signature []byte) (*types.Transaction, error) {\n\treturn _TokensNetwork.contract.Transact(opts, \"unlockDelegate\", token, partner, participant, transferred_amount, expiration, amount, secret_hash, merkle_proof, participant_signature)\n}", "func TestDelegatorProxyValidatorConstraints4Steps(t *testing.T) {\n\tcommon.InitConfig()\n\tparams := DefaultParams()\n\n\toriginVaSet := addrVals[1:]\n\tparams.MaxValidators = uint16(len(originVaSet))\n\tparams.Epoch = 2\n\tparams.UnbondingTime = time.Millisecond * 300\n\tstartUpValidator := NewValidator(StartUpValidatorAddr, StartUpValidatorPubkey, Description{}, types.DefaultMinSelfDelegation)\n\tstartUpStatus := baseValidatorStatus{startUpValidator}\n\torgValsLen := len(originVaSet)\n\tfullVaSet := make([]sdk.ValAddress, orgValsLen+1)\n\tcopy(fullVaSet, originVaSet)\n\tcopy(fullVaSet[orgValsLen:], []sdk.ValAddress{startUpStatus.getValidator().GetOperator()})\n\n\tbAction := baseAction{}\n\n\tstep1Actions := IActions{\n\t\tdelegatorRegProxyAction{bAction, ProxiedDelegator, true},\n\t\tdelegatorsAddSharesAction{bAction, false, true, 0, []sdk.AccAddress{ProxiedDelegator}},\n\t\tdelegatorWithdrawAction{bAction, ProxiedDelegator, sdk.OneDec(), sdk.DefaultBondDenom},\n\t\tproxyBindAction{bAction, ProxiedDelegator, ProxiedDelegator},\n\t\tproxyUnBindAction{bAction, ProxiedDelegator},\n\t}\n\n\tstep2Actions := IActions{\n\t\tdelegatorDepositAction{bAction, ValidDelegator1, DelegatedToken1, sdk.DefaultBondDenom},\n\t\tproxyBindAction{bAction, ValidDelegator1, ProxiedDelegator},\n\t\tdelegatorsAddSharesAction{bAction, false, true, 0, []sdk.AccAddress{ValidDelegator1}},\n\t\tproxyUnBindAction{bAction, ValidDelegator1},\n\t\tdelegatorWithdrawAction{bAction, ValidDelegator1, sdk.OneDec(), sdk.DefaultBondDenom},\n\t}\n\n\tstep3Actions := IActions{\n\t\tdelegatorDepositAction{bAction, ValidDelegator1, DelegatedToken1, sdk.DefaultBondDenom},\n\t\tproxyBindAction{bAction, ValidDelegator1, ProxiedDelegator},\n\t\tproxyUnBindAction{bAction, ValidDelegator1},\n\t\tdelegatorWithdrawAction{bAction, ValidDelegator1, sdk.OneDec(), sdk.DefaultBondDenom},\n\t}\n\n\tstep4Actions := IActions{\n\t\tdelegatorRegProxyAction{bAction, ProxiedDelegator, true},\n\t\tdelegatorsAddSharesAction{bAction, false, true, 0, []sdk.AccAddress{ProxiedDelegator}},\n\t\tproxyBindAction{bAction, ProxiedDelegator, ProxiedDelegator},\n\t\tproxyUnBindAction{bAction, ProxiedDelegator},\n\t\tdelegatorWithdrawAction{bAction, ProxiedDelegator, sdk.OneDec(), sdk.DefaultBondDenom},\n\t}\n\n\tfor s1 := 0; s1 < len(step1Actions); s1++ {\n\t\tfor s2 := 0; s2 < len(step2Actions); s2++ {\n\t\t\tfor s3 := 0; s3 < len(step3Actions); s3++ {\n\t\t\t\tfor s4 := 0; s4 < len(step4Actions); s4++ {\n\t\t\t\t\tinputActions := []IAction{\n\t\t\t\t\t\tcreateValidatorAction{bAction, nil},\n\t\t\t\t\t\tdelegatorsAddSharesAction{bAction, false, true, 0, []sdk.AccAddress{ValidDelegator2}},\n\t\t\t\t\t\tdelegatorDepositAction{bAction, ProxiedDelegator, MaxDelegatedToken, sdk.DefaultBondDenom},\n\t\t\t\t\t\tstep1Actions[s1],\n\t\t\t\t\t\tstep2Actions[s2],\n\t\t\t\t\t\tstep3Actions[s3],\n\t\t\t\t\t\tstep4Actions[s4],\n\t\t\t\t\t\tdelegatorRegProxyAction{bAction, ProxiedDelegator, false},\n\t\t\t\t\t\tdestroyValidatorAction{bAction},\n\t\t\t\t\t}\n\n\t\t\t\t\tactionsAndChecker, caseName := generateActionsAndCheckers(inputActions, 3)\n\n\t\t\t\t\tt.Logf(\"============================================== indexes:[%d,%d,%d,%d] %s ==============================================\", s1, s2, s3, s4, caseName)\n\t\t\t\t\t_, _, mk := CreateTestInput(t, false, SufficientInitPower)\n\t\t\t\t\tsmTestCase := newValidatorSMTestCase(mk, params, startUpStatus, inputActions, actionsAndChecker, t)\n\t\t\t\t\tsmTestCase.SetupValidatorSetAndDelegatorSet(int(params.MaxValidators))\n\t\t\t\t\tsmTestCase.printParticipantSnapshot(t)\n\t\t\t\t\tsmTestCase.Run(t)\n\t\t\t\t\tt.Log(\"============================================================================================\")\n\t\t\t\t}\n\n\t\t\t}\n\t\t}\n\t}\n}", "func (k Keeper) fastUndelegate(ctx sdk.Context, valAddr sdk.ValAddress, delegator sdk.AccAddress, shares sdk.Dec) (sdkmath.Int, error) {\n\tvalidator, found := k.stakingKeeper.GetValidator(ctx, valAddr)\n\tif !found {\n\t\treturn sdkmath.Int{}, types.ErrNoDelegatorForAddress\n\t}\n\n\treturnAmount, err := k.stakingKeeper.Unbond(ctx, delegator, valAddr, shares)\n\tif err != nil {\n\t\treturn sdkmath.Int{}, err\n\t}\n\treturnCoins := sdk.NewCoins(sdk.NewCoin(k.stakingKeeper.BondDenom(ctx), returnAmount))\n\n\t// transfer the validator tokens to the not bonded pool\n\tif validator.IsBonded() {\n\t\tif err := k.bankKeeper.SendCoinsFromModuleToModule(ctx, stakingtypes.BondedPoolName, stakingtypes.NotBondedPoolName, returnCoins); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\n\tif err := k.bankKeeper.UndelegateCoinsFromModuleToAccount(ctx, stakingtypes.NotBondedPoolName, delegator, returnCoins); err != nil {\n\t\treturn sdkmath.Int{}, err\n\t}\n\treturn returnAmount, nil\n}", "func (pva *PeriodicVestingAccount) addGrant(ctx sdk.Context, sk StakingKeeper, grantStartTime int64, grantVestingPeriods []Period, grantCoins sdk.Coins) {\n\t// how much is really delegated?\n\tbondedAmt := sk.GetDelegatorBonded(ctx, pva.GetAddress())\n\tunbondingAmt := sk.GetDelegatorUnbonding(ctx, pva.GetAddress())\n\tdelegatedAmt := bondedAmt.Add(unbondingAmt)\n\tdelegated := sdk.NewCoins(sdk.NewCoin(sk.BondDenom(ctx), delegatedAmt))\n\n\t// discover what has been slashed\n\toldDelegated := pva.DelegatedVesting.Add(pva.DelegatedFree...)\n\tslashed := oldDelegated.Sub(coinsMin(oldDelegated, delegated))\n\n\t// rebase the DV+DF by capping slashed at the current unvested amount\n\tunvested := pva.GetVestingCoins(ctx.BlockTime())\n\tnewSlashed := coinsMin(unvested, slashed)\n\tnewTotalDelegated := delegated.Add(newSlashed...)\n\n\t// modify vesting schedule for the new grant\n\tnewStart, newEnd, newPeriods := DisjunctPeriods(pva.StartTime, grantStartTime,\n\t\tpva.GetVestingPeriods(), grantVestingPeriods)\n\tpva.StartTime = newStart\n\tpva.EndTime = newEnd\n\tpva.VestingPeriods = newPeriods\n\tpva.OriginalVesting = pva.OriginalVesting.Add(grantCoins...)\n\n\t// cap DV at the current unvested amount, DF rounds out to newTotalDelegated\n\tunvested2 := pva.GetVestingCoins(ctx.BlockTime())\n\tpva.DelegatedVesting = coinsMin(newTotalDelegated, unvested2)\n\tpva.DelegatedFree = newTotalDelegated.Sub(pva.DelegatedVesting)\n}", "func (k msgServer) Undelegate(goCtx context.Context, msg *types.MsgUndelegate) (*types.MsgUndelegateResponse, error) {\n\tctx := sdk.UnwrapSDKContext(goCtx)\n\n\taddr, err := sdk.ValAddressFromBech32(msg.ValidatorAddress)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdelegatorAddress, err := sdk.AccAddressFromBech32(msg.DelegatorAddress)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttokens := msg.Amount.Amount\n\tshares, err := k.ValidateUnbondAmount(\n\t\tctx, delegatorAddress, addr, tokens,\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvalidator, found := k.GetValidator(ctx, addr)\n\tif !found {\n\t\treturn nil, types.ErrNoValidatorFound\n\t}\n\n\tdelegation, found := k.GetDelegation(ctx, delegatorAddress, addr)\n\tif !found {\n\t\treturn nil, status.Errorf(\n\t\t\tcodes.NotFound,\n\t\t\t\"delegation with delegator %s not found for validator %s\",\n\t\t\tmsg.DelegatorAddress, msg.ValidatorAddress,\n\t\t)\n\t}\n\n\t// if this is a validator self-bond, the new liquid delegation cannot fall below the self-bond * bond factor\n\tif delegation.ValidatorBond {\n\t\tif err := k.SafelyDecreaseValidatorBond(ctx, &validator, shares); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// if this delegation is from a liquid staking provider (identified if the delegator\n\t// is an ICA account), the global and validator liquid totals should be decremented\n\tif k.DelegatorIsLiquidStaker(delegatorAddress) {\n\t\tif err := k.DecreaseTotalLiquidStakedTokens(ctx, tokens); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif err := k.DecreaseValidatorLiquidShares(ctx, &validator, shares); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tbondDenom := k.BondDenom(ctx)\n\tif msg.Amount.Denom != bondDenom {\n\t\treturn nil, sdkerrors.Wrapf(\n\t\t\tsdkerrors.ErrInvalidRequest, \"invalid coin denomination: got %s, expected %s\", msg.Amount.Denom, bondDenom,\n\t\t)\n\t}\n\n\tcompletionTime, err := k.Keeper.Undelegate(ctx, delegatorAddress, addr, shares)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif tokens.IsInt64() {\n\t\tdefer func() {\n\t\t\ttelemetry.IncrCounter(1, types.ModuleName, \"undelegate\")\n\t\t\ttelemetry.SetGaugeWithLabels(\n\t\t\t\t[]string{\"tx\", \"msg\", msg.Type()},\n\t\t\t\tfloat32(tokens.Int64()),\n\t\t\t\t[]metrics.Label{telemetry.NewLabel(\"denom\", msg.Amount.Denom)},\n\t\t\t)\n\t\t}()\n\t}\n\n\tctx.EventManager().EmitEvents(sdk.Events{\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeUnbond,\n\t\t\tsdk.NewAttribute(types.AttributeKeyValidator, msg.ValidatorAddress),\n\t\t\tsdk.NewAttribute(sdk.AttributeKeyAmount, msg.Amount.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyCompletionTime, completionTime.Format(time.RFC3339)),\n\t\t),\n\t})\n\n\treturn &types.MsgUndelegateResponse{\n\t\tCompletionTime: completionTime,\n\t}, nil\n}", "func (p *Ledger) RecordPayment(destination types.NodeAddress, amount int64, confirmed chan bool) {\n\tok := <-confirmed\n\tif ok {\n\t\tp.l.Lock()\n\t\tp.incoming_debt[p.id] -= amount\n\t\tp.outgoing_debt[destination] -= amount\n\t\tp.l.Unlock()\n\t}\n}", "func (a *account) managedTrackDeposit(amount types.Currency) {\n\ta.mu.Lock()\n\tdefer a.mu.Unlock()\n\ta.pendingDeposits = a.pendingDeposits.Add(amount)\n}", "func NewDelegation(d *types.Delegation, repo repository.Repository) *Delegation {\n\treturn &Delegation{\n\t\tDelegation: *d,\n\t\trepo: repo,\n\t}\n}", "func (p *Protocol) NumDelegates() uint64 {\n\treturn p.numDelegates\n}", "func (rs *rootResolver) Delegation(args *struct {\n\tAddress common.Address\n\tStaker hexutil.Big\n}) (*Delegation, error) {\n\t// get the delegator detail from backend\n\td, err := repository.R().Delegation(&args.Address, &args.Staker)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn NewDelegation(d), nil\n}", "func (o OfflineNotaryRepository) AddDelegationPaths(data.RoleName, []string) error {\n\treturn nil\n}", "func (_TokensNetwork *TokensNetworkSession) UnlockDelegate(token common.Address, partner common.Address, participant common.Address, transferred_amount *big.Int, expiration *big.Int, amount *big.Int, secret_hash [32]byte, merkle_proof []byte, participant_signature []byte) (*types.Transaction, error) {\n\treturn _TokensNetwork.Contract.UnlockDelegate(&_TokensNetwork.TransactOpts, token, partner, participant, transferred_amount, expiration, amount, secret_hash, merkle_proof, participant_signature)\n}", "func (tracker *PeerTracker) Track(ci *types.ChainInfo) {\n\ttracker.mu.Lock()\n\tdefer tracker.mu.Unlock()\n\n\t_, tracking := tracker.peers[ci.Peer]\n\t_, trusted := tracker.trusted[ci.Peer]\n\ttracker.peers[ci.Peer] = ci\n\tlogPeerTracker.Infof(\"Tracking %s, new=%t, count=%d trusted=%t\", ci, !tracking, len(tracker.peers), trusted)\n}", "func TestSlashWithRedelegation(t *testing.T) {\n\tapp, ctx, addrDels, addrVals := bootstrapSlashTest(t, 10)\n\tconsAddr := sdk.ConsAddress(PKs[0].Address())\n\tfraction := sdk.NewDecWithPrec(5, 1)\n\tbondDenom := app.StakingKeeper.BondDenom(ctx)\n\n\t// set a redelegation\n\trdTokens := app.StakingKeeper.TokensFromConsensusPower(ctx, 6)\n\trd := types.NewRedelegation(addrDels[0], addrVals[0], addrVals[1], 11,\n\t\ttime.Unix(0, 0), rdTokens, rdTokens.ToDec())\n\tapp.StakingKeeper.SetRedelegation(ctx, rd)\n\n\t// set the associated delegation\n\tdel := types.NewDelegation(addrDels[0], addrVals[1], rdTokens.ToDec())\n\tapp.StakingKeeper.SetDelegation(ctx, del)\n\n\t// update bonded tokens\n\tbondedPool := app.StakingKeeper.GetBondedPool(ctx)\n\tnotBondedPool := app.StakingKeeper.GetNotBondedPool(ctx)\n\trdCoins := sdk.NewCoins(sdk.NewCoin(bondDenom, rdTokens.MulRaw(2)))\n\n\trequire.NoError(t, simapp.FundModuleAccount(app.BankKeeper, ctx, bondedPool.GetName(), rdCoins))\n\n\tapp.AccountKeeper.SetModuleAccount(ctx, bondedPool)\n\n\toldBonded := app.BankKeeper.GetBalance(ctx, bondedPool.GetAddress(), bondDenom).Amount\n\toldNotBonded := app.BankKeeper.GetBalance(ctx, notBondedPool.GetAddress(), bondDenom).Amount\n\n\t// slash validator\n\tctx = ctx.WithBlockHeight(12)\n\tvalidator, found := app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)\n\trequire.True(t, found)\n\n\trequire.NotPanics(t, func() { app.StakingKeeper.Slash(ctx, consAddr, 10, 10, fraction) })\n\tburnAmount := app.StakingKeeper.TokensFromConsensusPower(ctx, 10).ToDec().Mul(fraction).TruncateInt()\n\n\tbondedPool = app.StakingKeeper.GetBondedPool(ctx)\n\tnotBondedPool = app.StakingKeeper.GetNotBondedPool(ctx)\n\n\t// burn bonded tokens from only from delegations\n\tbondedPoolBalance := app.BankKeeper.GetBalance(ctx, bondedPool.GetAddress(), bondDenom).Amount\n\trequire.True(sdk.IntEq(t, oldBonded.Sub(burnAmount), bondedPoolBalance))\n\n\tnotBondedPoolBalance := app.BankKeeper.GetBalance(ctx, notBondedPool.GetAddress(), bondDenom).Amount\n\trequire.True(sdk.IntEq(t, oldNotBonded, notBondedPoolBalance))\n\toldBonded = app.BankKeeper.GetBalance(ctx, bondedPool.GetAddress(), bondDenom).Amount\n\n\t// read updating redelegation\n\trd, found = app.StakingKeeper.GetRedelegation(ctx, addrDels[0], addrVals[0], addrVals[1])\n\trequire.True(t, found)\n\trequire.Len(t, rd.Entries, 1)\n\t// read updated validator\n\tvalidator, found = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)\n\trequire.True(t, found)\n\t// power decreased by 2 - 4 stake originally bonded at the time of infraction\n\t// was still bonded at the time of discovery and was slashed by half, 4 stake\n\t// bonded at the time of discovery hadn't been bonded at the time of infraction\n\t// and wasn't slashed\n\trequire.Equal(t, int64(8), validator.GetConsensusPower(app.StakingKeeper.PowerReduction(ctx)))\n\n\t// slash the validator again\n\tvalidator, found = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)\n\trequire.True(t, found)\n\n\trequire.NotPanics(t, func() { app.StakingKeeper.Slash(ctx, consAddr, 10, 10, sdk.OneDec()) })\n\tburnAmount = app.StakingKeeper.TokensFromConsensusPower(ctx, 7)\n\n\t// read updated pool\n\tbondedPool = app.StakingKeeper.GetBondedPool(ctx)\n\tnotBondedPool = app.StakingKeeper.GetNotBondedPool(ctx)\n\n\t// seven bonded tokens burned\n\tbondedPoolBalance = app.BankKeeper.GetBalance(ctx, bondedPool.GetAddress(), bondDenom).Amount\n\trequire.True(sdk.IntEq(t, oldBonded.Sub(burnAmount), bondedPoolBalance))\n\trequire.True(sdk.IntEq(t, oldNotBonded, notBondedPoolBalance))\n\n\tbondedPoolBalance = app.BankKeeper.GetBalance(ctx, bondedPool.GetAddress(), bondDenom).Amount\n\trequire.True(sdk.IntEq(t, oldBonded.Sub(burnAmount), bondedPoolBalance))\n\n\tnotBondedPoolBalance = app.BankKeeper.GetBalance(ctx, notBondedPool.GetAddress(), bondDenom).Amount\n\trequire.True(sdk.IntEq(t, oldNotBonded, notBondedPoolBalance))\n\toldBonded = app.BankKeeper.GetBalance(ctx, bondedPool.GetAddress(), bondDenom).Amount\n\n\t// read updating redelegation\n\trd, found = app.StakingKeeper.GetRedelegation(ctx, addrDels[0], addrVals[0], addrVals[1])\n\trequire.True(t, found)\n\trequire.Len(t, rd.Entries, 1)\n\t// read updated validator\n\tvalidator, found = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)\n\trequire.True(t, found)\n\t// power decreased by 4\n\trequire.Equal(t, int64(4), validator.GetConsensusPower(app.StakingKeeper.PowerReduction(ctx)))\n\n\t// slash the validator again, by 100%\n\tctx = ctx.WithBlockHeight(12)\n\tvalidator, found = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)\n\trequire.True(t, found)\n\n\trequire.NotPanics(t, func() { app.StakingKeeper.Slash(ctx, consAddr, 10, 10, sdk.OneDec()) })\n\n\tburnAmount = app.StakingKeeper.TokensFromConsensusPower(ctx, 10).ToDec().Mul(sdk.OneDec()).TruncateInt()\n\tburnAmount = burnAmount.Sub(sdk.OneDec().MulInt(rdTokens).TruncateInt())\n\n\t// read updated pool\n\tbondedPool = app.StakingKeeper.GetBondedPool(ctx)\n\tnotBondedPool = app.StakingKeeper.GetNotBondedPool(ctx)\n\n\tbondedPoolBalance = app.BankKeeper.GetBalance(ctx, bondedPool.GetAddress(), bondDenom).Amount\n\trequire.True(sdk.IntEq(t, oldBonded.Sub(burnAmount), bondedPoolBalance))\n\tnotBondedPoolBalance = app.BankKeeper.GetBalance(ctx, notBondedPool.GetAddress(), bondDenom).Amount\n\trequire.True(sdk.IntEq(t, oldNotBonded, notBondedPoolBalance))\n\toldBonded = app.BankKeeper.GetBalance(ctx, bondedPool.GetAddress(), bondDenom).Amount\n\n\t// read updating redelegation\n\trd, found = app.StakingKeeper.GetRedelegation(ctx, addrDels[0], addrVals[0], addrVals[1])\n\trequire.True(t, found)\n\trequire.Len(t, rd.Entries, 1)\n\t// apply TM updates\n\tapplyValidatorSetUpdates(t, ctx, app.StakingKeeper, -1)\n\t// read updated validator\n\t// validator decreased to zero power, should be in unbonding period\n\tvalidator, _ = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)\n\trequire.Equal(t, validator.GetStatus(), types.Unbonding)\n\n\t// slash the validator again, by 100%\n\t// no stake remains to be slashed\n\tctx = ctx.WithBlockHeight(12)\n\t// validator still in unbonding period\n\tvalidator, _ = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)\n\trequire.Equal(t, validator.GetStatus(), types.Unbonding)\n\n\trequire.NotPanics(t, func() { app.StakingKeeper.Slash(ctx, consAddr, 10, 10, sdk.OneDec()) })\n\n\t// read updated pool\n\tbondedPool = app.StakingKeeper.GetBondedPool(ctx)\n\tnotBondedPool = app.StakingKeeper.GetNotBondedPool(ctx)\n\n\tbondedPoolBalance = app.BankKeeper.GetBalance(ctx, bondedPool.GetAddress(), bondDenom).Amount\n\trequire.True(sdk.IntEq(t, oldBonded, bondedPoolBalance))\n\tnotBondedPoolBalance = app.BankKeeper.GetBalance(ctx, notBondedPool.GetAddress(), bondDenom).Amount\n\trequire.True(sdk.IntEq(t, oldNotBonded, notBondedPoolBalance))\n\n\t// read updating redelegation\n\trd, found = app.StakingKeeper.GetRedelegation(ctx, addrDels[0], addrVals[0], addrVals[1])\n\trequire.True(t, found)\n\trequire.Len(t, rd.Entries, 1)\n\t// read updated validator\n\t// power still zero, still in unbonding period\n\tvalidator, _ = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)\n\trequire.Equal(t, validator.GetStatus(), types.Unbonding)\n}", "func (m *MetricsProvider) SignerAddLinkedDataProof(value time.Duration) {\n}", "func (*CardanoSignTransactionRequest_Certificate_StakeDelegation) Descriptor() ([]byte, []int) {\n\treturn file_cardano_proto_rawDescGZIP(), []int{4, 3, 0}\n}", "func (_TokensNetwork *TokensNetworkTransactorSession) UnlockDelegate(token common.Address, partner common.Address, participant common.Address, transferred_amount *big.Int, expiration *big.Int, amount *big.Int, secret_hash [32]byte, merkle_proof []byte, participant_signature []byte) (*types.Transaction, error) {\n\treturn _TokensNetwork.Contract.UnlockDelegate(&_TokensNetwork.TransactOpts, token, partner, participant, transferred_amount, expiration, amount, secret_hash, merkle_proof, participant_signature)\n}", "func (_Bep20 *Bep20Transactor) DelegateBySig(opts *bind.TransactOpts, delegatee common.Address, nonce *big.Int, expiry *big.Int, v uint8, r [32]byte, s [32]byte) (*types.Transaction, error) {\n\treturn _Bep20.contract.Transact(opts, \"delegateBySig\", delegatee, nonce, expiry, v, r, s)\n}", "func (va *ClawbackVestingAccount) addGrant(ctx sdk.Context, sk StakingKeeper, grantStartTime int64, grantLockupPeriods, grantVestingPeriods []Period, grantCoins sdk.Coins) {\n\t// how much is really delegated?\n\tbondedAmt := sk.GetDelegatorBonded(ctx, va.GetAddress())\n\tunbondingAmt := sk.GetDelegatorUnbonding(ctx, va.GetAddress())\n\tdelegatedAmt := bondedAmt.Add(unbondingAmt)\n\tdelegated := sdk.NewCoins(sdk.NewCoin(sk.BondDenom(ctx), delegatedAmt))\n\n\t// discover what has been slashed\n\toldDelegated := va.DelegatedVesting.Add(va.DelegatedFree...)\n\tslashed := oldDelegated.Sub(coinsMin(oldDelegated, delegated))\n\n\t// rebase the DV + DF by capping slashed at the current unvested amount\n\tunvested := va.OriginalVesting.Sub(va.GetVestedOnly(ctx.BlockTime()))\n\tnewSlashed := coinsMin(slashed, unvested)\n\tnewDelegated := delegated.Add(newSlashed...)\n\n\t// modify schedules for the new grant\n\tnewLockupStart, newLockupEnd, newLockupPeriods := DisjunctPeriods(va.StartTime, grantStartTime, va.LockupPeriods, grantLockupPeriods)\n\tnewVestingStart, newVestingEnd, newVestingPeriods := DisjunctPeriods(va.StartTime, grantStartTime,\n\t\tva.GetVestingPeriods(), grantVestingPeriods)\n\tif newLockupStart != newVestingStart {\n\t\tpanic(\"bad start time calculation\")\n\t}\n\tva.StartTime = newLockupStart\n\tva.EndTime = max64(newLockupEnd, newVestingEnd)\n\tva.LockupPeriods = newLockupPeriods\n\tva.VestingPeriods = newVestingPeriods\n\tva.OriginalVesting = va.OriginalVesting.Add(grantCoins...)\n\n\t// cap DV at the current unvested amount, DF rounds out to newDelegated\n\tunvested2 := va.GetVestingCoins(ctx.BlockTime())\n\tva.DelegatedVesting = coinsMin(newDelegated, unvested2)\n\tva.DelegatedFree = newDelegated.Sub(va.DelegatedVesting)\n}", "func CalculatePercentageSharesForCycle(delegatedContracts []DelegatedContract, cycle int, rate float64, spillage bool, delegateAddr string) ([]DelegatedContract, error){\n var stakingBalance float64\n //var balance float64\n var err error\n\n spillAlert := false\n\n stakingBalance, err = GetDelegateStakingBalance(delegateAddr, cycle)\n if (err != nil){\n return delegatedContracts, errors.New(\"func CalculateRollSpillage(delegatedContracts []DelegatedContract, delegateAddr string) failed: \" + err.Error())\n }\n\n mod := math.Mod(stakingBalance, 10000)\n sum := stakingBalance - mod\n balanceCheck := stakingBalance - mod\n\n for index, delegation := range delegatedContracts{\n counter := 0\n for i, _ := range delegation.Contracts {\n if (delegatedContracts[index].Contracts[i].Cycle == cycle){\n break\n }\n counter = counter + 1\n }\n balanceCheck = balanceCheck - delegatedContracts[index].Contracts[counter].Amount\n //fmt.Println(stakingBalance)\n if (spillAlert){\n delegatedContracts[index].Contracts[counter].SharePercentage = 0\n delegatedContracts[index].Contracts[counter].RollInclusion = 0\n } else if (balanceCheck < 0 && spillage){\n spillAlert = true\n delegatedContracts[index].Contracts[counter].SharePercentage = (delegatedContracts[index].Contracts[counter].Amount + stakingBalance) / sum\n delegatedContracts[index].Contracts[counter].RollInclusion = delegatedContracts[index].Contracts[counter].Amount + stakingBalance\n } else{\n delegatedContracts[index].Contracts[counter].SharePercentage = delegatedContracts[index].Contracts[counter].Amount / stakingBalance\n delegatedContracts[index].Contracts[counter].RollInclusion = delegatedContracts[index].Contracts[counter].Amount\n }\n delegatedContracts[index].Contracts[counter] = CalculatePayoutForContract(delegatedContracts[index].Contracts[counter], rate, delegatedContracts[index].Delegate)\n delegatedContracts[index].Fee = delegatedContracts[index].Fee + delegatedContracts[index].Contracts[counter].Fee\n }\n\n return delegatedContracts, nil\n}", "func (a *account) managedTrackWithdrawal(amount types.Currency) {\n\ta.mu.Lock()\n\tdefer a.mu.Unlock()\n\ta.pendingWithdrawals = a.pendingWithdrawals.Add(amount)\n}", "func (_OwnerProxyRegistry *OwnerProxyRegistryCaller) CountDelegates(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _OwnerProxyRegistry.contract.Call(opts, &out, \"countDelegates\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (_OwnerProxyRegistry *OwnerProxyRegistryTransactor) AddDelegate(opts *bind.TransactOpts, from common.Address) (*types.Transaction, error) {\n\treturn _OwnerProxyRegistry.contract.Transact(opts, \"addDelegate\", from)\n}", "func TestSlashWithUnbondingDelegation(t *testing.T) {\n\tapp, ctx, addrDels, addrVals := bootstrapSlashTest(t, 10)\n\n\tconsAddr := sdk.ConsAddress(PKs[0].Address())\n\tfraction := sdk.NewDecWithPrec(5, 1)\n\n\t// set an unbonding delegation with expiration timestamp beyond which the\n\t// unbonding delegation shouldn't be slashed\n\tubdTokens := app.StakingKeeper.TokensFromConsensusPower(ctx, 4)\n\tubd := types.NewUnbondingDelegation(addrDels[0], addrVals[0], 11, time.Unix(0, 0), ubdTokens)\n\tapp.StakingKeeper.SetUnbondingDelegation(ctx, ubd)\n\n\t// slash validator for the first time\n\tctx = ctx.WithBlockHeight(12)\n\tbondedPool := app.StakingKeeper.GetBondedPool(ctx)\n\toldBondedPoolBalances := app.BankKeeper.GetAllBalances(ctx, bondedPool.GetAddress())\n\n\tvalidator, found := app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)\n\trequire.True(t, found)\n\tapp.StakingKeeper.Slash(ctx, consAddr, 10, 10, fraction)\n\n\t// end block\n\tapplyValidatorSetUpdates(t, ctx, app.StakingKeeper, 1)\n\n\t// read updating unbonding delegation\n\tubd, found = app.StakingKeeper.GetUnbondingDelegation(ctx, addrDels[0], addrVals[0])\n\trequire.True(t, found)\n\trequire.Len(t, ubd.Entries, 1)\n\n\t// balance decreased\n\trequire.Equal(t, app.StakingKeeper.TokensFromConsensusPower(ctx, 2), ubd.Entries[0].Balance)\n\n\t// bonded tokens burned\n\tnewBondedPoolBalances := app.BankKeeper.GetAllBalances(ctx, bondedPool.GetAddress())\n\tdiffTokens := oldBondedPoolBalances.Sub(newBondedPoolBalances).AmountOf(app.StakingKeeper.BondDenom(ctx))\n\trequire.Equal(t, app.StakingKeeper.TokensFromConsensusPower(ctx, 3), diffTokens)\n\n\t// read updated validator\n\tvalidator, found = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)\n\trequire.True(t, found)\n\n\t// power decreased by 3 - 6 stake originally bonded at the time of infraction\n\t// was still bonded at the time of discovery and was slashed by half, 4 stake\n\t// bonded at the time of discovery hadn't been bonded at the time of infraction\n\t// and wasn't slashed\n\trequire.Equal(t, int64(7), validator.GetConsensusPower(app.StakingKeeper.PowerReduction(ctx)))\n\n\t// slash validator again\n\tctx = ctx.WithBlockHeight(13)\n\tapp.StakingKeeper.Slash(ctx, consAddr, 9, 10, fraction)\n\n\tubd, found = app.StakingKeeper.GetUnbondingDelegation(ctx, addrDels[0], addrVals[0])\n\trequire.True(t, found)\n\trequire.Len(t, ubd.Entries, 1)\n\n\t// balance decreased again\n\trequire.Equal(t, sdk.NewInt(0), ubd.Entries[0].Balance)\n\n\t// bonded tokens burned again\n\tnewBondedPoolBalances = app.BankKeeper.GetAllBalances(ctx, bondedPool.GetAddress())\n\tdiffTokens = oldBondedPoolBalances.Sub(newBondedPoolBalances).AmountOf(app.StakingKeeper.BondDenom(ctx))\n\trequire.Equal(t, app.StakingKeeper.TokensFromConsensusPower(ctx, 6), diffTokens)\n\n\t// read updated validator\n\tvalidator, found = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)\n\trequire.True(t, found)\n\n\t// power decreased by 3 again\n\trequire.Equal(t, int64(4), validator.GetConsensusPower(app.StakingKeeper.PowerReduction(ctx)))\n\n\t// slash validator again\n\t// all originally bonded stake has been slashed, so this will have no effect\n\t// on the unbonding delegation, but it will slash stake bonded since the infraction\n\t// this may not be the desirable behaviour, ref https://github.com/cosmos/cosmos-sdk/issues/1440\n\tctx = ctx.WithBlockHeight(13)\n\tapp.StakingKeeper.Slash(ctx, consAddr, 9, 10, fraction)\n\n\tubd, found = app.StakingKeeper.GetUnbondingDelegation(ctx, addrDels[0], addrVals[0])\n\trequire.True(t, found)\n\trequire.Len(t, ubd.Entries, 1)\n\n\t// balance unchanged\n\trequire.Equal(t, sdk.NewInt(0), ubd.Entries[0].Balance)\n\n\t// bonded tokens burned again\n\tnewBondedPoolBalances = app.BankKeeper.GetAllBalances(ctx, bondedPool.GetAddress())\n\tdiffTokens = oldBondedPoolBalances.Sub(newBondedPoolBalances).AmountOf(app.StakingKeeper.BondDenom(ctx))\n\trequire.Equal(t, app.StakingKeeper.TokensFromConsensusPower(ctx, 9), diffTokens)\n\n\t// read updated validator\n\tvalidator, found = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)\n\trequire.True(t, found)\n\n\t// power decreased by 3 again\n\trequire.Equal(t, int64(1), validator.GetConsensusPower(app.StakingKeeper.PowerReduction(ctx)))\n\n\t// slash validator again\n\t// all originally bonded stake has been slashed, so this will have no effect\n\t// on the unbonding delegation, but it will slash stake bonded since the infraction\n\t// this may not be the desirable behaviour, ref https://github.com/cosmos/cosmos-sdk/issues/1440\n\tctx = ctx.WithBlockHeight(13)\n\tapp.StakingKeeper.Slash(ctx, consAddr, 9, 10, fraction)\n\n\tubd, found = app.StakingKeeper.GetUnbondingDelegation(ctx, addrDels[0], addrVals[0])\n\trequire.True(t, found)\n\trequire.Len(t, ubd.Entries, 1)\n\n\t// balance unchanged\n\trequire.Equal(t, sdk.NewInt(0), ubd.Entries[0].Balance)\n\n\t// just 1 bonded token burned again since that's all the validator now has\n\tnewBondedPoolBalances = app.BankKeeper.GetAllBalances(ctx, bondedPool.GetAddress())\n\tdiffTokens = oldBondedPoolBalances.Sub(newBondedPoolBalances).AmountOf(app.StakingKeeper.BondDenom(ctx))\n\trequire.Equal(t, app.StakingKeeper.TokensFromConsensusPower(ctx, 10), diffTokens)\n\n\t// apply TM updates\n\tapplyValidatorSetUpdates(t, ctx, app.StakingKeeper, -1)\n\n\t// read updated validator\n\t// power decreased by 1 again, validator is out of stake\n\t// validator should be in unbonding period\n\tvalidator, _ = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)\n\trequire.Equal(t, validator.GetStatus(), types.Unbonding)\n}", "func (_DelegationController *DelegationControllerTransactor) AcceptPendingDelegation(opts *bind.TransactOpts, delegationId *big.Int) (*types.Transaction, error) {\n\treturn _DelegationController.contract.Transact(opts, \"acceptPendingDelegation\", delegationId)\n}", "func (rs *rootResolver) Delegation(args *struct {\n\tAddress common.Address\n\tStaker hexutil.Uint64\n}) (*Delegation, error) {\n\t// get the delegator detail from backend\n\td, err := rs.repo.Delegation(args.Address, args.Staker)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn NewDelegation(d, rs.repo), nil\n}", "func (acc *Account) delegationsTotal() (amount *big.Int, inWithdraw *big.Int, rewards *big.Int, err error) {\n\t// pull all the delegations of the account\n\tlist, err := repository.R().DelegationsByAddressAll(&acc.Address)\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\n\t// prep containers for calculation and loop all delegations found\n\tamount = new(big.Int)\n\trewards = new(big.Int)\n\tinWithdraw = new(big.Int)\n\tfor _, dlg := range list {\n\t\t// any active delegated amount?\n\t\tif 0 < dlg.AmountDelegated.ToInt().Uint64() {\n\t\t\tamount = new(big.Int).Add(amount, dlg.AmountDelegated.ToInt())\n\t\t}\n\n\t\t// get pending rewards for this delegation (can be stashed)\n\t\trw, err := repository.R().PendingRewards(&acc.Address, dlg.ToStakerId)\n\t\tif err != nil {\n\t\t\treturn nil, nil, nil, err\n\t\t}\n\n\t\t// any rewards?\n\t\tif 0 < rw.Amount.ToInt().Uint64() {\n\t\t\trewards = new(big.Int).Add(rewards, rw.Amount.ToInt())\n\t\t}\n\n\t\t// get pending withdrawals\n\t\twd, err := repository.R().WithdrawRequestsPendingTotal(&acc.Address, dlg.ToStakerId)\n\t\tif err != nil {\n\t\t\treturn nil, nil, nil, err\n\t\t}\n\n\t\t// add pending withdrawals value\n\t\tif 0 < wd.Uint64() {\n\t\t\tinWithdraw = new(big.Int).Add(inWithdraw, wd)\n\t\t}\n\t}\n\n\treturn amount, rewards, inWithdraw, nil\n}", "func (_DelegationController *DelegationControllerTransactor) GetAndUpdateDelegatedAmount(opts *bind.TransactOpts, holder common.Address) (*types.Transaction, error) {\n\treturn _DelegationController.contract.Transact(opts, \"getAndUpdateDelegatedAmount\", holder)\n}", "func (del Delegation) Amount() (hexutil.Big, error) {\n\t// get the base amount delegated\n\tbase, err := repository.R().DelegationAmountStaked(&del.Address, del.Delegation.ToStakerId)\n\tif err != nil {\n\t\treturn hexutil.Big{}, err\n\t}\n\n\t// get the sum of all pending withdrawals\n\twd, err := del.pendingWithdrawalsValue()\n\tif err != nil {\n\t\treturn hexutil.Big{}, err\n\t}\n\tval := new(big.Int).Add(base, wd)\n\treturn (hexutil.Big)(*val), nil\n}", "func distributeDelegatorRewards(ctx contract.Context, cachedDelegations *CachedDposStorage, formerValidatorTotals map[string]loom.BigUInt, delegatorRewards map[string]*loom.BigUInt, distributedRewards *loom.BigUInt) (map[string]*loom.BigUInt, error) {\n\tnewDelegationTotals := make(map[string]*loom.BigUInt)\n\n\tcandidates, err := LoadCandidateList(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Initialize delegation totals with whitelist amounts\n\tfor _, candidate := range candidates {\n\t\tstatistic, _ := GetStatistic(ctx, loom.UnmarshalAddressPB(candidate.Address))\n\n\t\tif statistic != nil && statistic.WhitelistAmount != nil && !common.IsZero(statistic.WhitelistAmount.Value) {\n\t\t\tvalidatorKey := loom.UnmarshalAddressPB(statistic.Address).String()\n\t\t\tamount := calculateWeightedWhitelistAmount(*statistic)\n\t\t\tnewDelegationTotals[validatorKey] = &amount\n\t\t}\n\t}\n\n\tdelegations, err := cachedDelegations.loadDelegationList(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar currentDelegations = make(DelegationList, len(delegations))\n\tcopy(currentDelegations, delegations)\n\tfor _, d := range currentDelegations {\n\t\tdelegation, err := GetDelegation(ctx, d.Index, *d.Validator, *d.Delegator)\n\t\tif err == contract.ErrNotFound {\n\t\t\tcontinue\n\t\t} else if err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tvalidatorKey := loom.UnmarshalAddressPB(delegation.Validator).String()\n\n\t\t// Do not distribute rewards to delegators of the Limbo validator\n\t\t// NOTE: because all delegations are sorted in reverse index order, the\n\t\t// 0-index delegation (for rewards) is handled last. Therefore, all\n\t\t// increases to reward delegations will be reflected in newDelegation\n\t\t// totals that are computed at the end of this for loop. (We do this to\n\t\t// avoid looping over all delegations twice)\n\t\tif loom.UnmarshalAddressPB(delegation.Validator).Compare(LimboValidatorAddress(ctx)) != 0 {\n\t\t\t// allocating validator distributions to delegators\n\t\t\t// based on former validator delegation totals\n\t\t\tdelegationTotal := formerValidatorTotals[validatorKey]\n\t\t\trewardsTotal := delegatorRewards[validatorKey]\n\t\t\tif rewardsTotal != nil {\n\t\t\t\tweightedDelegation := calculateWeightedDelegationAmount(*delegation)\n\t\t\t\tdelegatorDistribution := calculateShare(weightedDelegation, delegationTotal, *rewardsTotal)\n\t\t\t\t// increase a delegator's distribution\n\t\t\t\tdistributedRewards.Add(distributedRewards, &delegatorDistribution)\n\t\t\t\tcachedDelegations.IncreaseRewardDelegation(ctx, delegation.Validator, delegation.Delegator, delegatorDistribution)\n\n\t\t\t\t// If the reward delegation is updated by the\n\t\t\t\t// IncreaseRewardDelegation command, we must be sure to use this\n\t\t\t\t// updated version in the rest of the loop. No other delegations\n\t\t\t\t// (non-rewards) have the possibility of being updated outside\n\t\t\t\t// of this loop.\n\t\t\t\tif ctx.FeatureEnabled(features.DPOSVersion3_1, false) && d.Index == REWARD_DELEGATION_INDEX {\n\t\t\t\t\tdelegation, err = GetDelegation(ctx, d.Index, *d.Validator, *d.Delegator)\n\t\t\t\t\tif err == contract.ErrNotFound {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t} else if err != nil {\n\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tupdatedAmount := common.BigZero()\n\t\tif delegation.State == BONDING {\n\t\t\tupdatedAmount.Add(&delegation.Amount.Value, &delegation.UpdateAmount.Value)\n\t\t\tdelegation.Amount = &types.BigUInt{Value: *updatedAmount}\n\t\t} else if delegation.State == UNBONDING {\n\t\t\tupdatedAmount.Sub(&delegation.Amount.Value, &delegation.UpdateAmount.Value)\n\t\t\tdelegation.Amount = &types.BigUInt{Value: *updatedAmount}\n\t\t\tcoin, err := loadCoin(ctx)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\terr = coin.Transfer(loom.UnmarshalAddressPB(delegation.Delegator), &delegation.UpdateAmount.Value)\n\t\t\tif err != nil {\n\t\t\t\ttransferFromErr := fmt.Sprintf(\"Failed coin Transfer - distributeDelegatorRewards, %v, %s\", delegation.Delegator.String(), delegation.UpdateAmount.Value.String())\n\t\t\t\treturn nil, logDposError(ctx, err, transferFromErr)\n\t\t\t}\n\t\t} else if delegation.State == REDELEGATING {\n\t\t\tif err = cachedDelegations.DeleteDelegation(ctx, delegation); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tdelegation.Validator = delegation.UpdateValidator\n\t\t\tdelegation.Amount = delegation.UpdateAmount\n\t\t\tdelegation.LocktimeTier = delegation.UpdateLocktimeTier\n\n\t\t\tindex, err := GetNextDelegationIndex(ctx, *delegation.Validator, *delegation.Delegator)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tdelegation.Index = index\n\n\t\t\tvalidatorKey = loom.UnmarshalAddressPB(delegation.Validator).String()\n\t\t}\n\n\t\t// Delete any delegation whose full amount has been unbonded. In all\n\t\t// other cases, update the delegation state to BONDED and reset its\n\t\t// UpdateAmount\n\t\tif common.IsZero(delegation.Amount.Value) && delegation.State == UNBONDING {\n\t\t\tif err := cachedDelegations.DeleteDelegation(ctx, delegation); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t} else {\n\t\t\t// After a delegation update, zero out UpdateAmount\n\t\t\tdelegation.UpdateAmount = loom.BigZeroPB()\n\t\t\tdelegation.State = BONDED\n\n\t\t\tresetDelegationIfExpired(ctx, delegation)\n\t\t\tif err := cachedDelegations.SetDelegation(ctx, delegation); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\n\t\t// Calculate delegation totals for all validators except the Limbo\n\t\t// validator\n\t\tif loom.UnmarshalAddressPB(delegation.Validator).Compare(LimboValidatorAddress(ctx)) != 0 {\n\t\t\tnewTotal := common.BigZero()\n\t\t\tweightedDelegation := calculateWeightedDelegationAmount(*delegation)\n\t\t\tnewTotal.Add(newTotal, &weightedDelegation)\n\t\t\tif newDelegationTotals[validatorKey] != nil {\n\t\t\t\tnewTotal.Add(newTotal, newDelegationTotals[validatorKey])\n\t\t\t}\n\t\t\tnewDelegationTotals[validatorKey] = newTotal\n\t\t}\n\t}\n\n\treturn newDelegationTotals, nil\n}", "func (a *Account) Track() {\n\t// Request notifications for transactions sending to all wallet\n\t// addresses.\n\taddrs := a.ActiveAddresses()\n\taddrstrs := make([]string, len(addrs))\n\ti := 0\n\tfor addr := range addrs {\n\t\taddrstrs[i] = addr.EncodeAddress()\n\t\ti++\n\t}\n\n\terr := NotifyNewTXs(CurrentServerConn(), addrstrs)\n\tif err != nil {\n\t\tlog.Error(\"Unable to request transaction updates for address.\")\n\t}\n\n\tfor _, txout := range a.TxStore.UnspentOutputs() {\n\t\tReqSpentUtxoNtfn(txout)\n\t}\n}", "func (m *mParcelMockDelegationToken) Set(f func() (r insolar.DelegationToken)) *ParcelMock {\n\tm.mainExpectation = nil\n\tm.expectationSeries = nil\n\n\tm.mock.DelegationTokenFunc = f\n\treturn m.mock\n}", "func (bva BaseVestingAccount) GetDelegatedVesting() sdk.Coins {\n\treturn bva.DelegatedVesting\n}", "func (n *Node) BecomeDelegator(genesisAmount uint64, seedAmount uint64, delegatorAmount uint64, txFee uint64, stakerNodeID string) *Node {\n\n\t// exports AVAX from the X Chain\n\texportTxID, err := n.client.XChainAPI().ExportAVAX(\n\t\tn.UserPass,\n\t\tnil, // from addrs\n\t\t\"\", // change addr\n\t\tseedAmount+txFee,\n\t\tn.PAddress,\n\t)\n\tif err != nil {\n\t\tpanic(stacktrace.Propagate(err, \"Failed to export AVAX to pchainAddress %s\", n.PAddress))\n\t\treturn n\n\t}\n\n\t// waits Tx acceptance in the XChain\n\terr = chainhelper.XChain().AwaitTransactionAcceptance(n.client, exportTxID, constants.TimeoutDuration)\n\tif err != nil {\n\t\tpanic(err)\n\t\treturn n\n\t}\n\n\t// imports the amount to the P Chain\n\timportTxID, err := n.client.PChainAPI().ImportAVAX(\n\t\tn.UserPass,\n\t\tnil, // from addrs\n\t\t\"\", // change addr\n\t\tn.PAddress,\n\t\tconstants.XChainID.String(),\n\t)\n\tif err != nil {\n\t\tpanic(stacktrace.Propagate(err, \"Failed import AVAX to pchainAddress %s\", n.PAddress))\n\t\treturn n\n\t}\n\n\t// waits Tx acceptance in the PChain\n\terr = chainhelper.PChain().AwaitTransactionAcceptance(n.client, importTxID, constants.TimeoutDuration)\n\tif err != nil {\n\t\tpanic(err)\n\t\treturn n\n\t}\n\n\t// verify the PChain balance (seedAmount+txFee-txFee)\n\terr = chainhelper.PChain().CheckBalance(n.client, n.PAddress, seedAmount)\n\tif err != nil {\n\t\tpanic(stacktrace.Propagate(err, \"expected balance of seedAmount exists in the PChain\"))\n\t\treturn n\n\t}\n\n\t// verify the XChain balance of genesisAmount - seedAmount - txFee - txFee (import PChain)\n\terr = chainhelper.XChain().CheckBalance(n.client, n.XAddress, \"AVAX\", genesisAmount-seedAmount-2*txFee)\n\tif err != nil {\n\t\tpanic(stacktrace.Propagate(err, \"expected balance XChain balance of genesisAmount-seedAmount-txFee\"))\n\t\treturn n\n\t}\n\n\tdelegatorStartTime := time.Now().Add(20 * time.Second)\n\tstartTime := uint64(delegatorStartTime.Unix())\n\tendTime := uint64(delegatorStartTime.Add(36 * time.Hour).Unix())\n\taddDelegatorTxID, err := n.client.PChainAPI().AddDelegator(\n\t\tn.UserPass,\n\t\tnil, // from addrs\n\t\t\"\", // change addr\n\t\tn.PAddress,\n\t\tstakerNodeID,\n\t\tdelegatorAmount,\n\t\tstartTime,\n\t\tendTime,\n\t)\n\tif err != nil {\n\t\tpanic(stacktrace.Propagate(err, \"Failed to add delegator %s\", n.PAddress))\n\t\treturn n\n\t}\n\n\terr = chainhelper.PChain().AwaitTransactionAcceptance(n.client, addDelegatorTxID, constants.TimeoutDuration)\n\tif err != nil {\n\t\tpanic(stacktrace.Propagate(err, \"Failed to accept AddDelegator tx: %s\", addDelegatorTxID))\n\t\treturn n\n\t}\n\n\t// Sleep until delegator starts validating\n\ttime.Sleep(time.Until(delegatorStartTime) + 3*time.Second)\n\n\texpectedDelegatorBalance := seedAmount - delegatorAmount\n\terr = chainhelper.PChain().CheckBalance(n.client, n.PAddress, expectedDelegatorBalance)\n\tif err != nil {\n\t\tpanic(stacktrace.Propagate(err, \"Unexpected P Chain Balance after adding a new delegator to the network.\"))\n\t\treturn n\n\t}\n\tlogrus.Infof(\"Added delegator to subnet and verified the expected P Chain balance.\")\n\n\treturn n\n}", "func (_DelegationController *DelegationControllerSession) Delegations(arg0 *big.Int) (struct {\n\tHolder common.Address\n\tValidatorId *big.Int\n\tAmount *big.Int\n\tDelegationPeriod *big.Int\n\tCreated *big.Int\n\tStarted *big.Int\n\tFinished *big.Int\n\tInfo string\n}, error) {\n\treturn _DelegationController.Contract.Delegations(&_DelegationController.CallOpts, arg0)\n}", "func (_TransferProxyRegistry *TransferProxyRegistryCaller) CountDelegates(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _TransferProxyRegistry.contract.Call(opts, &out, \"countDelegates\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (_DelegationController *DelegationControllerCallerSession) Delegations(arg0 *big.Int) (struct {\n\tHolder common.Address\n\tValidatorId *big.Int\n\tAmount *big.Int\n\tDelegationPeriod *big.Int\n\tCreated *big.Int\n\tStarted *big.Int\n\tFinished *big.Int\n\tInfo string\n}, error) {\n\treturn _DelegationController.Contract.Delegations(&_DelegationController.CallOpts, arg0)\n}", "func (a *Account) Track() {\n\trpcc, err := accessClient()\n\tif err != nil {\n\t\tlog.Errorf(\"No chain server client to track addresses.\")\n\t\treturn\n\t}\n\n\t// Request notifications for transactions sending to all wallet\n\t// addresses.\n\t//\n\t// TODO: return as slice? (doesn't have to be ordered, or\n\t// SortedActiveAddresses would be fine.)\n\taddrMap := a.KeyStore.ActiveAddresses()\n\taddrs := make([]btcutil.Address, 0, len(addrMap))\n\tfor addr := range addrMap {\n\t\taddrs = append(addrs, addr)\n\t}\n\n\tif err := rpcc.NotifyReceived(addrs); err != nil {\n\t\tlog.Error(\"Unable to request transaction updates for address.\")\n\t}\n\n\tunspent, err := a.TxStore.UnspentOutputs()\n\tif err != nil {\n\t\tlog.Errorf(\"Unable to access unspent outputs: %v\", err)\n\t\treturn\n\t}\n\tReqSpentUtxoNtfns(unspent)\n}", "func (_DelegationController *DelegationControllerCaller) Delegations(opts *bind.CallOpts, arg0 *big.Int) (struct {\n\tHolder common.Address\n\tValidatorId *big.Int\n\tAmount *big.Int\n\tDelegationPeriod *big.Int\n\tCreated *big.Int\n\tStarted *big.Int\n\tFinished *big.Int\n\tInfo string\n}, error) {\n\tret := new(struct {\n\t\tHolder common.Address\n\t\tValidatorId *big.Int\n\t\tAmount *big.Int\n\t\tDelegationPeriod *big.Int\n\t\tCreated *big.Int\n\t\tStarted *big.Int\n\t\tFinished *big.Int\n\t\tInfo string\n\t})\n\tout := ret\n\terr := _DelegationController.contract.Call(opts, out, \"delegations\", arg0)\n\treturn *ret, err\n}", "func (pm *DPoSProtocolManager) syncDelegatedNodeSafely() {\n\tif !pm.isDelegatedNode() {\n\t\t// only candidate node is able to participant to this process.\n\t\treturn;\n\t}\n\tpm.lock.Lock()\n\tdefer pm.lock.Unlock()\n\tlog.Info(\"Preparing for next big period...\");\n\t// pull the newest delegators from voting contract.\n\ta, b, err0 := VotingAccessor.Refresh()\n\tif err0 != nil {\n\t\tlog.Error(err0.Error())\n\t\treturn;\n\t}\n\tDelegatorsTable = a\n\tDelegatorNodeInfo = b\n\tif uint8(len(GigPeriodHistory)) >= BigPeriodHistorySize {\n\t\tGigPeriodHistory = GigPeriodHistory[1:] //remove the first old one.\n\t}\n\tif len(DelegatorsTable) == 0 || pm.ethManager.peers.Len() == 0 {\n\t\tlog.Info(\"Sorry, could not detect any delegator!\");\n\t\treturn;\n\t}\n\tround := uint64(1)\n\tactiveTime := uint64(time.Now().Unix() + int64(GigPeriodInterval))\n\tif NextGigPeriodInstance != nil {\n\t\tif !TestMode {\n\t\t\tgap := int64(NextGigPeriodInstance.activeTime) - time.Now().Unix()\n\t\t\tif gap > 2 || gap < -2 {\n\t\t\t\tlog.Warn(fmt.Sprintf(\"Scheduling of the new electing round is improper! current gap: %v seconds\", gap))\n\t\t\t\t//restart the scheduler\n\t\t\t\tNextElectionInfo = nil;\n\t\t\t\tgo pm.syncDelegatedNodeSafely();\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\tround = NextGigPeriodInstance.round + 1\n\t\tactiveTime = GigPeriodInstance.activeTime + uint64(GigPeriodInterval)\n\t\t// keep the big period history for block validation.\n\t\tGigPeriodHistory[len(GigPeriodHistory)-1] = *NextGigPeriodInstance;\n\n\t\tGigPeriodInstance = &GigPeriodTable{\n\t\t\tNextGigPeriodInstance.round,\n\t\t\tNextGigPeriodInstance.state,\n\t\t\tNextGigPeriodInstance.delegatedNodes,\n\t\t\tNextGigPeriodInstance.delegatedNodesSign,\n\t\t\tNextGigPeriodInstance.confirmedTickets,\n\t\t\tNextGigPeriodInstance.confirmedBestNode,\n\t\t\tNextGigPeriodInstance.activeTime,\n\t\t};\n\t\tlog.Info(fmt.Sprintf(\"Switched the new big period round. %d \", GigPeriodInstance.round));\n\t}\n\n\t// make sure all delegators are synced at this round.\n\tNextGigPeriodInstance = &GigPeriodTable{\n\t\tround,\n\t\tSTATE_LOOKING,\n\t\tDelegatorsTable,\n\t\tSignCandidates(DelegatorsTable),\n\t\tmake(map[string]uint32),\n\t\tmake(map[string]*GigPeriodTable),\n\t\tactiveTime,\n\t};\n\tpm.trySyncAllDelegators()\n}", "func (k Querier) Delegation(ctx context.Context, req *types.QueryDelegationRequest) (*types.QueryDelegationResponse, error) {\n\tif req == nil {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"empty request\")\n\t}\n\n\tif req.DelegatorAddr == \"\" {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"delegator address cannot be empty\")\n\t}\n\tif req.ValidatorAddr == \"\" {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"validator address cannot be empty\")\n\t}\n\n\tdelAddr, err := k.authKeeper.AddressCodec().StringToBytes(req.DelegatorAddr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvalAddr, err := k.validatorAddressCodec.StringToBytes(req.ValidatorAddr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdelegation, err := k.Delegations.Get(ctx, collections.Join(sdk.AccAddress(delAddr), sdk.ValAddress(valAddr)))\n\tif err != nil {\n\t\tif errors.Is(err, collections.ErrNotFound) {\n\t\t\treturn nil, status.Errorf(\n\t\t\t\tcodes.NotFound,\n\t\t\t\t\"delegation with delegator %s not found for validator %s\",\n\t\t\t\treq.DelegatorAddr, req.ValidatorAddr)\n\t\t}\n\t\treturn nil, status.Error(codes.Internal, err.Error())\n\t}\n\n\tdelResponse, err := delegationToDelegationResponse(ctx, k.Keeper, delegation)\n\tif err != nil {\n\t\treturn nil, status.Error(codes.Internal, err.Error())\n\t}\n\n\treturn &types.QueryDelegationResponse{DelegationResponse: &delResponse}, nil\n}", "func (_DelegationController *DelegationControllerCaller) DelegationsByHolder(opts *bind.CallOpts, arg0 common.Address, arg1 *big.Int) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _DelegationController.contract.Call(opts, out, \"delegationsByHolder\", arg0, arg1)\n\treturn *ret0, err\n}", "func (ac *Accumulator) WithTracking(max int) telegraf.TrackingAccumulator {\n\treturn &TrackingAccumulator{\n\t\tAccumulator: ac,\n\t\tdone: make(chan telegraf.DeliveryInfo, max),\n\t}\n}", "func (_DelegationController *DelegationControllerTransactorSession) AcceptPendingDelegation(delegationId *big.Int) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.AcceptPendingDelegation(&_DelegationController.TransactOpts, delegationId)\n}", "func TestApplyChangelistCreatesDelegation(t *testing.T) {\n\trepo, cs, err := testutils.EmptyRepo(\"docker.com/notary\")\n\trequire.NoError(t, err)\n\n\tnewKey, err := cs.Create(\"targets/level1\", \"docker.com/notary\", data.ED25519Key)\n\trequire.NoError(t, err)\n\n\terr = repo.UpdateDelegationKeys(\"targets/level1\", []data.PublicKey{newKey}, []string{}, 1)\n\trequire.NoError(t, err)\n\terr = repo.UpdateDelegationPaths(\"targets/level1\", []string{\"\"}, []string{}, false)\n\trequire.NoError(t, err)\n\tdelete(repo.Targets, \"targets/level1\")\n\n\thash := sha256.Sum256([]byte{})\n\tf := &data.FileMeta{\n\t\tLength: 1,\n\t\tHashes: map[string][]byte{\n\t\t\t\"sha256\": hash[:],\n\t\t},\n\t}\n\tfjson, err := json.Marshal(f)\n\trequire.NoError(t, err)\n\n\tcl := changelist.NewMemChangelist()\n\trequire.NoError(t, cl.Add(&changelist.TUFChange{\n\t\tActn: changelist.ActionCreate,\n\t\tRole: \"targets/level1\",\n\t\tChangeType: \"target\",\n\t\tChangePath: \"latest\",\n\t\tData: fjson,\n\t}))\n\n\trequire.NoError(t, applyChangelist(repo, nil, cl))\n\t_, ok := repo.Targets[\"targets/level1\"]\n\trequire.True(t, ok, \"Failed to create the delegation target\")\n\t_, ok = repo.Targets[\"targets/level1\"].Signed.Targets[\"latest\"]\n\trequire.True(t, ok, \"Failed to write change to delegation target\")\n}", "func CalculateRollSpillage(delegatedContracts []DelegatedContract, delegateAddr string, cycle int) ([]DelegatedContract, error) {\n stakingBalance, err := GetDelegateStakingBalance(delegateAddr, cycle)\n if (err != nil){\n return delegatedContracts, errors.New(\"func CalculateRollSpillage(delegatedContracts []DelegatedContract, delegateAddr string) failed: \" + err.Error())\n }\n\n mod := math.Mod(stakingBalance, 10000)\n sum := mod * 10000\n\n for index, delegatedContract := range delegatedContracts{\n for i, contract := range delegatedContract.Contracts{\n if (contract.Cycle == cycle){\n stakingBalance = stakingBalance - contract.Amount\n if (stakingBalance < 0){\n delegatedContracts[index].Contracts[i].SharePercentage = (contract.Amount - stakingBalance) / sum\n }\n }\n }\n }\n\n return delegatedContracts, nil\n}", "func (_Bep20 *Bep20Transactor) Delegate(opts *bind.TransactOpts, delegatee common.Address) (*types.Transaction, error) {\n\treturn _Bep20.contract.Transact(opts, \"delegate\", delegatee)\n}", "func (_Bep20 *Bep20Session) DelegateBySig(delegatee common.Address, nonce *big.Int, expiry *big.Int, v uint8, r [32]byte, s [32]byte) (*types.Transaction, error) {\n\treturn _Bep20.Contract.DelegateBySig(&_Bep20.TransactOpts, delegatee, nonce, expiry, v, r, s)\n}", "func (_DelegationController *DelegationControllerSession) AcceptPendingDelegation(delegationId *big.Int) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.AcceptPendingDelegation(&_DelegationController.TransactOpts, delegationId)\n}", "func UnmarshalDelegation(cdc *codec.Codec, key, value []byte) (delegation Delegation, err error) {\n\tvar storeValue delegationValue\n\terr = cdc.UnmarshalBinaryLengthPrefixed(value, &storeValue)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"%v: %v\", ErrNoDelegation(DefaultCodespace).Data(), err)\n\t\treturn\n\t}\n\n\taddrs := key[1:] // remove prefix bytes\n\tif len(addrs) != 2*sdk.AddrLen {\n\t\terr = fmt.Errorf(\"%v\", ErrBadDelegationAddr(DefaultCodespace).Data())\n\t\treturn\n\t}\n\n\tdelAddr := sdk.AccAddress(addrs[:sdk.AddrLen])\n\tvalAddr := sdk.ValAddress(addrs[sdk.AddrLen:])\n\n\treturn Delegation{\n\t\tDelegatorAddr: delAddr,\n\t\tValidatorAddr: valAddr,\n\t\tShares: storeValue.Shares,\n\t}, nil\n}", "func (_DelegationController *DelegationControllerSession) DelegationsByHolder(arg0 common.Address, arg1 *big.Int) (*big.Int, error) {\n\treturn _DelegationController.Contract.DelegationsByHolder(&_DelegationController.CallOpts, arg0, arg1)\n}", "func SendPayments() {\n\tif !checkConfigSharingRatio() {\n\t\tlogger.Fatal(\"Unable to calculcate.\")\n\t}\n\n\tpubKey := viper.GetString(\"delegate.pubkey\")\n\tif core.EnvironmentParams.Network.Type == core.DEVNET {\n\t\tpubKey = viper.GetString(\"delegate.Dpubkey\")\n\t}\n\n\tparams := core.DelegateQueryParams{PublicKey: pubKey}\n\tvar payload core.TransactionPayload\n\n\tvotersEarnings := arkclient.CalculateVotersProfit(params, viper.GetFloat64(\"voters.shareratio\"))\n\n\tsumEarned := 0.0\n\tsumRatio := 0.0\n\tsumShareEarned := 0.0\n\n\tp1, p2 := \"\", \"\"\n\tif _, err := os.Stat(\"/path/to/whatever\"); err == nil {\n\t\t// path/to/whatever exists\n\t} else {\n\t\tp1, p2 = readAccountData()\n\t}\n\n\tclearScreen()\n\n\tfor _, element := range votersEarnings {\n\t\tsumEarned += element.EarnedAmount100\n\t\tsumShareEarned += element.EarnedAmountXX\n\t\tsumRatio += element.VoteWeightShare\n\n\t\t//transaction parameters\n\t\ttxAmount2Send := int64(element.EarnedAmountXX*core.SATOSHI) - core.EnvironmentParams.Fees.Send\n\t\ttx := core.CreateTransaction(element.Address, txAmount2Send, viper.GetString(\"voters.txdescription\"), p1, p2)\n\n\t\tpayload.Transactions = append(payload.Transactions, tx)\n\t}\n\n\t//Cost & reserve fund calculation\n\tcostAmount := sumEarned * viper.GetFloat64(\"costs.shareratio\")\n\treserveAmount := sumEarned * viper.GetFloat64(\"reserve.shareratio\")\n\n\t//summary and conversion checks\n\tif (costAmount + reserveAmount + sumShareEarned) != sumEarned {\n\t\tcolor.Set(color.FgHiRed)\n\t\tlog.Println(\"Calculation of ratios NOT OK - overall summary failing\")\n\t\tlogger.Println(\"Calculation of ratios NOT OK - overall summary failing\")\n\t}\n\n\tcostAmount2Send := int64(costAmount*core.SATOSHI) - core.EnvironmentParams.Fees.Send\n\tcostAddress := viper.GetString(\"costs.address\")\n\tif core.EnvironmentParams.Network.Type == core.DEVNET {\n\t\tcostAddress = viper.GetString(\"costs.Daddress\")\n\t}\n\ttxCosts := core.CreateTransaction(costAddress, costAmount2Send, viper.GetString(\"costs.txdescription\"), p1, p2)\n\tpayload.Transactions = append(payload.Transactions, txCosts)\n\n\treserveAddress := viper.GetString(\"reserve.address\")\n\tif core.EnvironmentParams.Network.Type == core.DEVNET {\n\t\treserveAddress = viper.GetString(\"reserve.Daddress\")\n\t}\n\treserveAmount2Send := int64(reserveAmount*core.SATOSHI) - core.EnvironmentParams.Fees.Send\n\n\ttxReserve := core.CreateTransaction(reserveAddress, reserveAmount2Send, viper.GetString(\"reserve.txdescription\"), p1, p2)\n\tpayload.Transactions = append(payload.Transactions, txReserve)\n\n\tcolor.Set(color.FgHiGreen)\n\tfmt.Println(\"--------------------------------------------------------------------------------------------------------------\")\n\tfmt.Println(\"Transactions to be sent:\")\n\tfmt.Println(\"--------------------------------------------------------------------------------------------------------------\")\n\tcolor.Set(color.FgHiCyan)\n\tfor _, el := range payload.Transactions {\n\t\ts := fmt.Sprintf(\"|%s|%15d| %-40s|\", el.RecipientID, el.Amount, el.VendorField)\n\t\tfmt.Println(s)\n\t\tlogger.Println(s)\n\t}\n\n\tcolor.Set(color.FgHiYellow)\n\tfmt.Println(\"\")\n\tfmt.Println(\"--------------------------------------------------------------------------------------------------------------\")\n\tfmt.Print(\"Send transactions and complete reward payments [Y/N]: \")\n\n\tc, _ := reader.ReadByte()\n\n\tif c == []byte(\"Y\")[0] || c == []byte(\"y\")[0] {\n\t\tfmt.Println(\"Sending rewards to voters and sharing accounts.............\")\n\n\t\tres, httpresponse, err := arkclient.PostTransaction(payload)\n\t\tif res.Success {\n\t\t\tcolor.Set(color.FgHiGreen)\n\t\t\tlogger.Println(\"Transactions sent with Success,\", httpresponse.Status, res.TransactionIDs)\n\t\t\tlog.Println(\"Transactions sent with Success,\", httpresponse.Status)\n\t\t\tlog.Println(\"Audit log of sent transactions is in file paymentLog.csv!\")\n\t\t\tlog2csv(payload, res.TransactionIDs, votersEarnings)\n\t\t} else {\n\t\t\tcolor.Set(color.FgHiRed)\n\t\t\tlogger.Println(res.Message, res.Error, httpresponse.Status, err.Error())\n\t\t\tfmt.Println()\n\t\t\tfmt.Println(\"Failed\", res.Error)\n\t\t}\n\t\treader.ReadString('\\n')\n\t\tpause()\n\t}\n}", "func (_DelegationController *DelegationControllerRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.DelegationControllerTransactor.contract.Transfer(opts)\n}", "func (p *Protocol) NumCandidateDelegates() uint64 {\n\treturn p.numCandidateDelegates\n}", "func MustMarshalDelegation(cdc *codec.Codec, delegation Delegation) []byte {\n\tval := delegationValue{\n\t\tdelegation.Shares,\n\t}\n\treturn cdc.MustMarshalBinaryLengthPrefixed(val)\n}", "func StoreDelegationFromMessage(\n\theight int64, msg *stakingtypes.MsgDelegate, stakingClient stakingtypes.QueryClient, db *database.Db,\n) error {\n\theader := client.GetHeightRequestHeader(height)\n\tres, err := stakingClient.Delegation(\n\t\tcontext.Background(),\n\t\t&stakingtypes.QueryDelegationRequest{\n\t\t\tDelegatorAddr: msg.DelegatorAddress,\n\t\t\tValidatorAddr: msg.ValidatorAddress,\n\t\t},\n\t\theader,\n\t)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdelegation := ConvertDelegationResponse(height, *res.DelegationResponse)\n\treturn db.SaveDelegations([]types.Delegation{delegation})\n}", "func (_DelegationController *DelegationControllerTransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.contract.Transfer(opts)\n}", "func (_DelegationController *DelegationControllerTransactor) Confiscate(opts *bind.TransactOpts, validatorId *big.Int, amount *big.Int) (*types.Transaction, error) {\n\treturn _DelegationController.contract.Transact(opts, \"confiscate\", validatorId, amount)\n}", "func (m *ParcelMock) DelegationTokenMinimockCounter() uint64 {\n\treturn atomic.LoadUint64(&m.DelegationTokenCounter)\n}", "func (s *ArkClient) GetDelegateVoteWeight(params DelegateQueryParams) (int, *http.Response, error) {\n\trespData := new(DelegateVoters)\n\trespError := new(ArkApiResponseError)\n\tresp, err := s.sling.New().Get(\"api/delegates/voters\").QueryStruct(&params).Receive(respData, respError)\n\tif err == nil {\n\t\terr = respError\n\t}\n\n\t//calculating vote weight\n\tbalance := 0\n\tif respData.Success {\n\t\tfor _, element := range respData.Accounts {\n\t\t\tintBalance, _ := strconv.Atoi(element.Balance)\n\t\t\tbalance += intBalance\n\t\t}\n\t}\n\n\treturn balance, resp, err\n}", "func (_Bep20 *Bep20TransactorSession) DelegateBySig(delegatee common.Address, nonce *big.Int, expiry *big.Int, v uint8, r [32]byte, s [32]byte) (*types.Transaction, error) {\n\treturn _Bep20.Contract.DelegateBySig(&_Bep20.TransactOpts, delegatee, nonce, expiry, v, r, s)\n}", "func Transfer(\n\tctx *vm.Context, db vm.StateDB, sender, recipient types.AddressHash, amount *big.Int,\n) {\n\t// NOTE: amount is a re-used pointer varaible\n\tdb.SubBalance(sender, amount)\n\tdb.AddBalance(recipient, amount)\n\tif db.IsContractAddr(sender) && amount.Uint64() > 0 {\n\t\ttransferInfo := vm.NewTransferInfo(sender, recipient, amount.Uint64())\n\t\tlogger.Debugf(\"new transfer info: sender: %x, recipient: %x, amount: %d\",\n\t\t\tsender[:], recipient[:], amount)\n\t\tif v, ok := ctx.Transfers[sender]; ok {\n\t\t\t// if sender and recipient already exists in Transfers, update it instead\n\t\t\t// of append to it\n\t\t\tfor _, w := range v {\n\t\t\t\tif w.To == recipient {\n\t\t\t\t\t// NOTE: cannot miss 'w.value = '\n\t\t\t\t\tw.Value += amount.Uint64()\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tctx.Transfers[sender] = append(ctx.Transfers[sender], transferInfo)\n\t}\n}", "func (o *Member) SetDelegateCur(v int32) {\n\to.DelegateCur = &v\n}", "func (_DelegationController *DelegationControllerCallerSession) DelegationsByHolder(arg0 common.Address, arg1 *big.Int) (*big.Int, error) {\n\treturn _DelegationController.Contract.DelegationsByHolder(&_DelegationController.CallOpts, arg0, arg1)\n}", "func (vi *votedInfo) CalculateReward(multiplier, divider *big.Int, period int) {\n\tif multiplier.Sign() == 0 || period == 0 {\n\t\treturn\n\t}\n\tif divider.Sign() == 0 || vi.totalBondedDelegation.Sign() == 0 {\n\t\treturn\n\t}\n\t// reward = multiplier * period * bondedDelegation / (divider * totalBondedDelegation)\n\tbase := new(big.Int).Mul(multiplier, big.NewInt(int64(period)))\n\treward := new(big.Int)\n\tfor i, addrKey := range vi.rank {\n\t\tif i == vi.maxRankForReward {\n\t\t\tbreak\n\t\t}\n\t\tprep := vi.preps[addrKey]\n\t\tif prep.Enable() == false {\n\t\t\tcontinue\n\t\t}\n\n\t\treward.Mul(base, prep.GetBondedDelegation())\n\t\treward.Div(reward, divider)\n\t\treward.Div(reward, vi.totalBondedDelegation)\n\n\t\tlog.Tracef(\"VOTED REWARD %d = %d * %d * %d / (%d * %d)\",\n\t\t\treward, multiplier, period, prep.GetBondedDelegation(), divider, vi.totalBondedDelegation)\n\n\t\tprep.SetIScore(new(big.Int).Add(prep.IScore(), reward))\n\t}\n}", "func TestDonationCase1(t *testing.T) {\n\tassert := assert.New(t)\n\tstore := newReputationStoreOnMock()\n\trep := NewTestReputationImpl(store)\n\tt1 := time.Date(1995, time.February, 5, 11, 11, 0, 0, time.UTC)\n\tt3 := time.Date(1995, time.February, 6, 12, 11, 0, 0, time.UTC)\n\tt4 := time.Date(1995, time.February, 7, 13, 11, 1, 0, time.UTC)\n\tuser1 := \"user1\"\n\tpost1 := \"post1\"\n\tpost2 := \"post2\"\n\n\t// round 2\n\trep.Update(t1.Unix())\n\trep.DonateAt(user1, post1, big.NewInt(100*OneLinoCoin))\n\tassert.Equal(big.NewInt(100*OneLinoCoin), rep.store.GetRoundPostSumStake(2, post1))\n\tassert.Equal(rep.GetReputation(user1), big.NewInt(InitialCustomerScore))\n\tassert.Equal(big.NewInt(OneLinoCoin), rep.store.GetRoundSumDp(2)) // bounded by this user's dp\n\n\t// round 3\n\trep.Update(t3.Unix())\n\t// (1 * 9 + 100) / 10\n\tassert.Equal(big.NewInt(1090000), rep.GetReputation(user1))\n\tassert.Equal(big.NewInt(OneLinoCoin), rep.GetSumRep(post1))\n\trep.DonateAt(user1, post1, big.NewInt(1*OneLinoCoin)) // does not count\n\trep.DonateAt(user1, post2, big.NewInt(900*OneLinoCoin))\n\trep.Update(t4.Unix())\n\t// (10.9 * 9 + 900) / 10\n\tassert.Equal(big.NewInt(9981000), rep.GetReputation(user1))\n\tassert.Equal([]Pid{post2}, rep.store.GetRoundResult(3))\n\t// round 4\n}", "func (s *Streams) Delegate(data interface{}) {\n\tlisteners := s.Size()\n\n\tif listeners <= 0 {\n\t\treturn\n\t}\n\n\tif s.reverse {\n\t\ts.RevMunch(data)\n\t} else {\n\t\ts.Munch(data)\n\t}\n\n}", "func bindDelegationController(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) {\n\tparsed, err := abi.JSON(strings.NewReader(DelegationControllerABI))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn bind.NewBoundContract(address, parsed, caller, transactor, filterer), nil\n}", "func (_DelegationController *DelegationControllerSession) GetAndUpdateDelegatedAmount(holder common.Address) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.GetAndUpdateDelegatedAmount(&_DelegationController.TransactOpts, holder)\n}", "func CheckPercentageSumForCycle(cycle int, delegatedContracts []DelegatedContract) float64{\n var sum float64\n sum = 0\n for x := 0; x < len(delegatedContracts); x++{\n counter := 0\n for y := 0; y < len(delegatedContracts[x].Contracts); y++{\n if (delegatedContracts[x].Contracts[y].Cycle == cycle){\n break\n }\n counter = counter + 1\n }\n\n sum = sum + delegatedContracts[x].Contracts[counter].SharePercentage\n }\n return sum\n}" ]
[ "0.8189158", "0.7900897", "0.7828547", "0.77607775", "0.7717838", "0.76603925", "0.68343955", "0.6128288", "0.57620025", "0.57456696", "0.554199", "0.5495294", "0.537466", "0.5257036", "0.51831824", "0.5128013", "0.5006918", "0.49731857", "0.4874176", "0.47647288", "0.47589478", "0.47454292", "0.47441489", "0.4718513", "0.4716137", "0.467889", "0.4668559", "0.4642659", "0.46384996", "0.46295005", "0.46215397", "0.46166396", "0.45724845", "0.4557419", "0.45420632", "0.4506051", "0.44967487", "0.4474724", "0.44473198", "0.4442386", "0.44172534", "0.4416488", "0.4412622", "0.44095674", "0.438854", "0.43876827", "0.43857458", "0.4385538", "0.43734056", "0.435699", "0.4353001", "0.43468872", "0.43451804", "0.433373", "0.43273973", "0.43140766", "0.43094248", "0.4305179", "0.43007654", "0.42843542", "0.42667982", "0.42646396", "0.42601877", "0.42560664", "0.42351413", "0.42273742", "0.4213433", "0.42131627", "0.42038164", "0.4203092", "0.41972843", "0.4194368", "0.41926175", "0.4185976", "0.41709363", "0.41632536", "0.41456902", "0.41333213", "0.41228718", "0.4118166", "0.41118613", "0.4099873", "0.4096442", "0.40961382", "0.4083597", "0.40829402", "0.40755302", "0.40704092", "0.40686855", "0.40677524", "0.4060628", "0.40600932", "0.40519482", "0.40508538", "0.40463898", "0.4046198", "0.4042665", "0.4032792", "0.40311256", "0.40252843" ]
0.7722133
4
GetStartTime returns the time when vesting starts for a continuous vesting account.
func (cva ContinuousVestingAccount) GetStartTime() int64 { return cva.StartTime }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (va ClawbackVestingAccount) GetStartTime() int64 {\n\treturn va.StartTime\n}", "func (dva DelayedVestingAccount) GetStartTime() int64 {\n\treturn 0\n}", "func (pva PeriodicVestingAccount) GetStartTime() int64 {\n\treturn pva.StartTime\n}", "func GetStartTime() time.Time {\n\treturn startAtTime\n}", "func (txn TxnProbe) GetStartTime() time.Time {\n\treturn txn.startTime\n}", "func (req *StartWFSRequest) GetStartTime() time.Time {\n\treturn req.StartTime\n}", "func (this *SyncFlightInfo) GetStartTime() time.Time {\n\tthis.lock.RLock()\n\tdefer this.lock.RUnlock()\n\treturn this.startTime\n}", "func (o *ApplianceSetupInfoAllOf) GetStartTime() time.Time {\n\tif o == nil || o.StartTime == nil {\n\t\tvar ret time.Time\n\t\treturn ret\n\t}\n\treturn *o.StartTime\n}", "func (plva PermanentLockedAccount) GetStartTime() int64 {\n\treturn 0\n}", "func (o *VirtualizationIweVirtualMachine) GetStartTime() string {\n\tif o == nil || o.StartTime == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.StartTime\n}", "func (o *ApplianceClusterInstallPhase) GetStartTime() time.Time {\n\tif o == nil || o.StartTime == nil {\n\t\tvar ret time.Time\n\t\treturn ret\n\t}\n\treturn *o.StartTime\n}", "func (o *UcsdBackupInfoAllOf) GetStartTime() time.Time {\n\tif o == nil || o.StartTime == nil {\n\t\tvar ret time.Time\n\t\treturn ret\n\t}\n\treturn *o.StartTime\n}", "func (c *Container) GetStartTime() time.Time {\n\treturn c.start\n}", "func (s *Session) GetStartTime() time.Time {\n\treturn s.started\n}", "func (gm GlobalManager) GetChainStartTime(ctx sdk.Context) (int64, sdk.Error) {\n\tglobalTime, err := gm.storage.GetGlobalTime(ctx)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn globalTime.ChainStartTime, nil\n}", "func (c *Context) StartTime() *time.Time {\n\treturn &c.startTime\n}", "func (o ReservedInstanceOutput) StartTime() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *ReservedInstance) pulumi.StringOutput { return v.StartTime }).(pulumi.StringOutput)\n}", "func (v *Validator) StartTime() time.Time {\n\treturn time.Unix(int64(v.Start), 0)\n}", "func (o *OnpremUpgradePhase) GetStartTime() time.Time {\n\tif o == nil || o.StartTime == nil {\n\t\tvar ret time.Time\n\t\treturn ret\n\t}\n\treturn *o.StartTime\n}", "func StartTime() time.Time {\n\treturn processStartTime\n}", "func (o *Job) GetStartTime(ctx context.Context) (startTime uint64, err error) {\n\terr = o.object.CallWithContext(ctx, \"org.freedesktop.DBus.Properties.Get\", 0, InterfaceJob, \"StartTime\").Store(&startTime)\n\treturn\n}", "func (f *Filler) StartTime() time.Time {\n\treturn f.tp\n}", "func (o *WorkflowServiceItemActionInstance) GetStartTime() time.Time {\n\tif o == nil || o.StartTime == nil {\n\t\tvar ret time.Time\n\t\treturn ret\n\t}\n\treturn *o.StartTime\n}", "func (_LvRecording *LvRecordingCaller) StartTime(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _LvRecording.contract.Call(opts, &out, \"startTime\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (p *SASQueryParameters) StartTime() time.Time {\n\treturn p.startTime\n}", "func (r Reservation) StartTime() string {\n\thr := r.Start / 60\n\tmin := r.Start % 60\n\tvar ampm string\n\tif ampm = \"AM\"; hr >= 12 {\n\t\tampm = \"PM\"\n\t}\n\tif hr > 12 {\n\t\thr = hr - 12\n\t}\n\tif hr == 0 {\n\t\thr = 12\n\t}\n\treturn fmt.Sprintf(\"%02d:%02d %s\", hr, min, ampm)\n}", "func (o GoogleCloudRetailV2alphaConditionTimeRangeOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v GoogleCloudRetailV2alphaConditionTimeRange) *string { return v.StartTime }).(pulumi.StringPtrOutput)\n}", "func (r *ScheduledAction) StartTime() pulumi.StringOutput {\n\treturn (pulumi.StringOutput)(r.s.State[\"startTime\"])\n}", "func (instance *Instance) StartTime() time.Time {\n\tuptimeDuration := time.Duration(instance.Uptime) * time.Second\n\n\treturn time.Now().Add(-uptimeDuration)\n}", "func (o BeanstalkScheduledTaskOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v BeanstalkScheduledTask) *string { return v.StartTime }).(pulumi.StringPtrOutput)\n}", "func (c *PurchasesVoidedpurchasesListCall) StartTime(startTime int64) *PurchasesVoidedpurchasesListCall {\n\tc.urlParams_.Set(\"startTime\", fmt.Sprint(startTime))\n\treturn c\n}", "func (a *Auction) StartTime() time.Time {\n\treturn a.startTime\n}", "func (mgr *Manager) StartTime() time.Time {\n\treturn mgr.startTime\n}", "func (o ResourcePolicyDailyCycleOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ResourcePolicyDailyCycle) *string { return v.StartTime }).(pulumi.StringPtrOutput)\n}", "func (m *UserExperienceAnalyticsDeviceStartupHistory) GetStartTime()(*i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time) {\n val, err := m.GetBackingStore().Get(\"startTime\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time)\n }\n return nil\n}", "func (m *RequestSchedule) GetStartDateTime()(*i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time) {\n val, err := m.GetBackingStore().Get(\"startDateTime\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time)\n }\n return nil\n}", "func (m *SimulationAutomationRun) GetStartDateTime()(*i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time) {\n val, err := m.GetBackingStore().Get(\"startDateTime\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time)\n }\n return nil\n}", "func (b *fixedResolutionValues) StartTime() xtime.UnixNano {\n\treturn b.startTime\n}", "func (req *ServerHTTPRequest) StartTime() time.Time {\n\treturn req.startTime\n}", "func (o *KubernetesPodStatus) GetStartTime() string {\n\tif o == nil || o.StartTime == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.StartTime\n}", "func (m *GetSchedulePostRequestBody) GetStartTime()(iadcd81124412c61e647227ecfc4449d8bba17de0380ddda76f641a29edf2b242.DateTimeTimeZoneable) {\n return m.startTime\n}", "func (o ElastigroupScheduledTaskOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ElastigroupScheduledTask) *string { return v.StartTime }).(pulumi.StringPtrOutput)\n}", "func (o TriggerBuildArtifactsObjectsTimingOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v TriggerBuildArtifactsObjectsTiming) *string { return v.StartTime }).(pulumi.StringPtrOutput)\n}", "func (o *ProjectDeploymentRuleResponse) GetStartTime() time.Time {\n\tif o == nil || o.StartTime.Get() == nil {\n\t\tvar ret time.Time\n\t\treturn ret\n\t}\n\treturn *o.StartTime.Get()\n}", "func (o BaselineStrategyOutput) StartTime() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *BaselineStrategy) pulumi.StringOutput { return v.StartTime }).(pulumi.StringOutput)\n}", "func (o LicenseOutput) StartTime() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *License) pulumi.StringOutput { return v.StartTime }).(pulumi.StringOutput)\n}", "func (o InstanceMaintenanceScheduleOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v InstanceMaintenanceSchedule) *string { return v.StartTime }).(pulumi.StringPtrOutput)\n}", "func (o InstanceMaintenanceScheduleOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v InstanceMaintenanceSchedule) *string { return v.StartTime }).(pulumi.StringPtrOutput)\n}", "func (n *ssvNode) getSlotStartTime(slot uint64) time.Time {\n\ttimeSinceGenesisStart := slot * uint64(n.ethNetwork.SlotDurationSec().Seconds())\n\tstart := time.Unix(int64(n.ethNetwork.MinGenesisTime()+timeSinceGenesisStart), 0)\n\treturn start\n}", "func (o GoogleCloudRetailV2alphaConditionTimeRangeResponseOutput) StartTime() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GoogleCloudRetailV2alphaConditionTimeRangeResponse) string { return v.StartTime }).(pulumi.StringOutput)\n}", "func (o ScanRunOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ScanRun) *string { return v.StartTime }).(pulumi.StringPtrOutput)\n}", "func (o ScanRunOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ScanRun) *string { return v.StartTime }).(pulumi.StringPtrOutput)\n}", "func (o InstanceMaintenanceWindowOutput) StartTime() InstanceMaintenanceWindowStartTimeOutput {\n\treturn o.ApplyT(func(v InstanceMaintenanceWindow) InstanceMaintenanceWindowStartTime { return v.StartTime }).(InstanceMaintenanceWindowStartTimeOutput)\n}", "func (o ScanRunResponseOutput) StartTime() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ScanRunResponse) string { return v.StartTime }).(pulumi.StringOutput)\n}", "func (o ScanRunResponseOutput) StartTime() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ScanRunResponse) string { return v.StartTime }).(pulumi.StringOutput)\n}", "func (o ResourcePolicyHourlyCycleOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ResourcePolicyHourlyCycle) *string { return v.StartTime }).(pulumi.StringPtrOutput)\n}", "func determineStepStartTime(index int, running *corev1.ContainerStateRunning, terminated *corev1.ContainerStateTerminated, stageSteps []v1.CoreActivityStep) metav1.Time {\n\tvar startedAt metav1.Time\n\tif len(stageSteps) > 0 {\n\t\tpreviousStep := stageSteps[index-1]\n\t\tif previousStep.CompletedTimestamp != nil {\n\t\t\tstartedAt = *previousStep.CompletedTimestamp\n\t\t}\n\t} else {\n\t\tif running != nil {\n\t\t\tstartedAt = running.StartedAt\n\t\t} else if terminated != nil {\n\t\t\tstartedAt = terminated.StartedAt\n\t\t}\n\t}\n\treturn startedAt\n}", "func (o ResourcePolicyWeeklyCycleDayOfWeekOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ResourcePolicyWeeklyCycleDayOfWeek) *string { return v.StartTime }).(pulumi.StringPtrOutput)\n}", "func (_LvRecordableStream *LvRecordableStreamCaller) StartTime(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _LvRecordableStream.contract.Call(opts, &out, \"startTime\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (o JobStatusOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v JobStatus) *string { return v.StartTime }).(pulumi.StringPtrOutput)\n}", "func (_Casper *CasperSession) BeginTime() (*big.Int, error) {\n\treturn _Casper.Contract.BeginTime(&_Casper.CallOpts)\n}", "func (o NodeGroupMaintenanceWindowOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v NodeGroupMaintenanceWindow) *string { return v.StartTime }).(pulumi.StringPtrOutput)\n}", "func (_Casper *CasperCallerSession) BeginTime() (*big.Int, error) {\n\treturn _Casper.Contract.BeginTime(&_Casper.CallOpts)\n}", "func (o JobStatusPtrOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v JobStatus) *string { return v.StartTime }).(pulumi.StringPtrOutput)\n}", "func (o DataTransferConfigScheduleOptionsOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v DataTransferConfigScheduleOptions) *string { return v.StartTime }).(pulumi.StringPtrOutput)\n}", "func StartTime() {\n\tstart = time.Now()\n}", "func (pb *Bar) StartTime() time.Time {\n\tpb.mu.RLock()\n\tdefer pb.mu.RUnlock()\n\treturn pb.startTime\n}", "func (o StorageCapacityUnitOutput) StartTime() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *StorageCapacityUnit) pulumi.StringOutput { return v.StartTime }).(pulumi.StringOutput)\n}", "func (o NodeGroupMaintenanceWindowResponseOutput) StartTime() pulumi.StringOutput {\n\treturn o.ApplyT(func(v NodeGroupMaintenanceWindowResponse) string { return v.StartTime }).(pulumi.StringOutput)\n}", "func (sc *TraceScope) BeginTime() time.Time {\n\treturn sc.begin\n}", "func (c *ProjectsTracesListCall) StartTime(startTime string) *ProjectsTracesListCall {\n\tc.urlParams_.Set(\"startTime\", startTime)\n\treturn c\n}", "func (m *ExternalActivity) GetStartDateTime()(*i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time) {\n val, err := m.GetBackingStore().Get(\"startDateTime\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time)\n }\n return nil\n}", "func (s *Storage) StartTime() (int64, error) {\n\treturn int64(model.Latest), nil\n}", "func (o ResourcePolicyDailyCycleResponseOutput) StartTime() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ResourcePolicyDailyCycleResponse) string { return v.StartTime }).(pulumi.StringOutput)\n}", "func (o BuildRunStatusOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v BuildRunStatus) *string { return v.StartTime }).(pulumi.StringPtrOutput)\n}", "func (o ResourcePolicyInstanceSchedulePolicyOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ResourcePolicyInstanceSchedulePolicy) *string { return v.StartTime }).(pulumi.StringPtrOutput)\n}", "func (o LookupJobResultOutput) StartTime() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupJobResult) string { return v.StartTime }).(pulumi.StringOutput)\n}", "func (q *Queries) EventStartTime(ctx context.Context, id models.EventID) (time.Time, error) {\n\tdefer daoSpan(&ctx)()\n\treturn q.dbc.EventStartTime(ctx, id)\n}", "func (c deploymentChecker) BeginTime() uint64 {\n\treturn c.deployment.StartTime\n}", "func (o TimelineOutput) StartTime() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v *Timeline) pulumi.IntPtrOutput { return v.StartTime }).(pulumi.IntPtrOutput)\n}", "func (o TriggerBuildArtifactsObjectsTimingPtrOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *TriggerBuildArtifactsObjectsTiming) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.StartTime\n\t}).(pulumi.StringPtrOutput)\n}", "func (o *Run) GetStartedAt() time.Time {\n\tif o == nil || o.StartedAt == nil {\n\t\tvar ret time.Time\n\t\treturn ret\n\t}\n\treturn *o.StartedAt\n}", "func (o JobScheduleOutput) StartTime() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *JobSchedule) pulumi.StringOutput { return v.StartTime }).(pulumi.StringOutput)\n}", "func (s JobStr) StartTime() (time.Time, error) {\n\tvar (\n\t\terr error\n\t\tres time.Time\n\t)\n\n\tif !strings.Contains(string(s), \"expect_cost:\") {\n\t\treturn res, nil\n\t}\n\n\titems := strings.Split(string(s), \" \")\n\tres, err = time.Parse(\"2006-01-02 15:04:05.999\", items[0]+\" \"+items[1])\n\tif err != nil {\n\t\tlogrus.Errorf(\"time.Parse err:%v\", err)\n\t\treturn res, err\n\t}\n\n\treturn res, err\n}", "func (m *BookingWorkTimeSlot) GetStart()(*i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.TimeOnly) {\n val, err := m.GetBackingStore().Get(\"start\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.TimeOnly)\n }\n return nil\n}", "func (e *Event) StartTime() Time {\n\treturn e.start\n}", "func (o InstanceMaintenancePolicyWeeklyMaintenanceWindowOutput) StartTime() InstanceMaintenancePolicyWeeklyMaintenanceWindowStartTimeOutput {\n\treturn o.ApplyT(func(v InstanceMaintenancePolicyWeeklyMaintenanceWindow) InstanceMaintenancePolicyWeeklyMaintenanceWindowStartTime {\n\t\treturn v.StartTime\n\t}).(InstanceMaintenancePolicyWeeklyMaintenanceWindowStartTimeOutput)\n}", "func (o InstanceMaintenancePolicyWeeklyMaintenanceWindowOutput) StartTime() InstanceMaintenancePolicyWeeklyMaintenanceWindowStartTimeOutput {\n\treturn o.ApplyT(func(v InstanceMaintenancePolicyWeeklyMaintenanceWindow) InstanceMaintenancePolicyWeeklyMaintenanceWindowStartTime {\n\t\treturn v.StartTime\n\t}).(InstanceMaintenancePolicyWeeklyMaintenanceWindowStartTimeOutput)\n}", "func (o DataTransferConfigScheduleOptionsPtrOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *DataTransferConfigScheduleOptions) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.StartTime\n\t}).(pulumi.StringPtrOutput)\n}", "func (o ScanRunPtrOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ScanRun) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.StartTime\n\t}).(pulumi.StringPtrOutput)\n}", "func (o ScanRunPtrOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ScanRun) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.StartTime\n\t}).(pulumi.StringPtrOutput)\n}", "func (o ResourcePolicyDailyCyclePtrOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ResourcePolicyDailyCycle) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.StartTime\n\t}).(pulumi.StringPtrOutput)\n}", "func (f FakeContainerImpl) GetContainerStartTime(containerID string) (int64, error) {\n\tpanic(\"implement me\")\n}", "func (o ResourcePolicyWeeklyCycleDayOfWeekResponseOutput) StartTime() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ResourcePolicyWeeklyCycleDayOfWeekResponse) string { return v.StartTime }).(pulumi.StringOutput)\n}", "func (_Casper *CasperCaller) BeginTime(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _Casper.contract.Call(opts, out, \"beginTime\")\n\treturn *ret0, err\n}", "func (o NodeGroupMaintenanceWindowPtrOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *NodeGroupMaintenanceWindow) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.StartTime\n\t}).(pulumi.StringPtrOutput)\n}", "func (o ResourcePolicyInstanceSchedulePolicyResponseOutput) StartTime() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ResourcePolicyInstanceSchedulePolicyResponse) string { return v.StartTime }).(pulumi.StringOutput)\n}", "func (o KubernetesClusterMaintenanceWindowNodeOsOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v KubernetesClusterMaintenanceWindowNodeOs) *string { return v.StartTime }).(pulumi.StringPtrOutput)\n}", "func (o *ModelsBackupJobStatusResponse) GetStartTime() string {\n\tif o == nil || o.StartTime == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.StartTime\n}", "func (m *TermsExpiration) GetStartDateTime()(*i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time) {\n return m.startDateTime\n}" ]
[ "0.7933969", "0.7929926", "0.7785165", "0.73669004", "0.726981", "0.69838774", "0.69761086", "0.694269", "0.6927703", "0.6854483", "0.6815522", "0.6800892", "0.67183834", "0.67104137", "0.6657018", "0.6623324", "0.6598904", "0.6566596", "0.6558677", "0.6532096", "0.6420241", "0.6413002", "0.6410379", "0.63977444", "0.6384441", "0.6372348", "0.63710326", "0.6353858", "0.63084364", "0.6301016", "0.6279709", "0.6270131", "0.62617517", "0.6258907", "0.62391937", "0.6234576", "0.6234011", "0.62327754", "0.6229195", "0.6227511", "0.6226323", "0.6226308", "0.62210727", "0.6212613", "0.61914754", "0.61911637", "0.618462", "0.618462", "0.61841255", "0.6161347", "0.6157362", "0.6157362", "0.6144203", "0.6132362", "0.6132362", "0.61263657", "0.6111723", "0.60955095", "0.60891074", "0.60863817", "0.6081372", "0.6080586", "0.6077756", "0.6067205", "0.6065588", "0.6060024", "0.6058092", "0.60564154", "0.6047657", "0.60403234", "0.60247684", "0.60234255", "0.6020531", "0.60112816", "0.6006133", "0.600115", "0.6000844", "0.59968597", "0.5994036", "0.59918386", "0.59802645", "0.59793043", "0.5968008", "0.5956629", "0.59549314", "0.59496087", "0.5939626", "0.5939626", "0.59299713", "0.5926451", "0.5926451", "0.59157974", "0.5914877", "0.59133655", "0.59086066", "0.5904549", "0.5901255", "0.5896193", "0.5894082", "0.5876576" ]
0.82052857
0
Validate checks for errors on the account fields
func (cva ContinuousVestingAccount) Validate() error { if cva.GetStartTime() >= cva.GetEndTime() { return errors.New("vesting start-time cannot be before end-time") } return cva.BaseVestingAccount.Validate() }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (account *Account) Validate() (map[string]interface{}, bool) {\n\n\tif !strings.Contains(account.Phone, \"+\") {\n\t\treturn u.Message(false, \"Phone Number address is required\"), false\n\t}\n\n\tif len(account.UserName) < 3 {\n\t\treturn u.Message(false, \"Username is required\"), false\n\t}\n\n\t//PhoneNumber must be unique\n\ttemp := &Account{}\n\n\t//check for errors and duplicate phones\n\terr := GetDB().Table(\"accounts\").Where(\"phone = ?\", account.Phone).First(temp).Error\n\tif err != nil && err != gorm.ErrRecordNotFound {\n\t\treturn u.Message(false, \"Connection error. Please retry\"+err.Error()), false\n\t}\n\tif temp.Phone != \"\" {\n\t\treturn u.Message(false, \"Phone Number address already in use by another user.\"), false\n\t}\n\n\t//check for errors and duplicate username\n\terr = GetDB().Table(\"accounts\").Where(\"user_name = ?\", account.UserName).First(temp).Error\n\tif err != nil && err != gorm.ErrRecordNotFound {\n\t\treturn u.Message(false, \"Connection error. Please retry\"+err.Error()), false\n\t}\n\tif temp.UserName != \"\" {\n\t\tresponse := fmt.Sprintf(\"Username: %d is already in use by another user.\", account.UserName)\n\t\treturn u.Message(false, response), false\n\t}\n\n\treturn u.Message(false, \"Requirement passed\"), true\n}", "func (account Account) Validate() (map[string]interface{}, bool) {\n\n\tif !strings.Contains(account.Email, \"@\") {\n\t\treturn u.Message(false, ERROR_EMAIL), false\n\t}\n\n\tif len(account.Password) < 6 {\n\t\treturn u.Message(false, ERROR_PASSWORD_LENTH), false\n\t}\n\n\t// Email must be unique\n\ttemp := &Account{}\n\n\t// 数据类型合法时,查询数据表,GetDB return the configed db\n\terr := GetDB().Table(\"accounts\").Where(\"email = ?\", account.Email).First(temp).Error\n\tif err != nil && err != gorm.ErrRecordNotFound {\n\t\treturn u.Message(false, ERROR_CONNECTION), false\n\t}\n\t// 存在该email\n\tif temp.Email != \"\" {\n\t\treturn u.Message(false, ERROR_EMAIL_USED), false\n\t}\n\n\treturn u.Message(false, GET_SUCCESS), true\n}", "func (a Account) Validate() error {\n\treturn validation.ValidateStruct(&a,\n\t\tvalidation.Field(&a.Name, validation.Required, validation.Length(3, 75)),\n\t)\n}", "func (m *Account) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateAccountID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateAuditLogs(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateCurrency(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateParentAccountID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validatePaymentMethodID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateReferenceTime(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (account *Account) Validate() (map[string]interface{}, bool) {\n\n\tif !strings.Contains(account.Email, \"@\") {\n\t\treturn u.Message(false, \"Email address is required\"), false\n\t}\n\n\tif len(account.Password) < 6 {\n\t\treturn u.Message(false, \"Password is required\"), false\n\t}\n\n\t//Email must be unique\n\ttemp := &Account{}\n\t//check for errors and duplicate emails\n\terr := GetDB().Table(\"accounts\").Where(\"email = ?\", account.Email).First(temp).Error\n\tif err != nil && err != gorm.ErrRecordNotFound {\n\t\treturn u.Message(false, \"Connection error. Please retry\"), false\n\t}\n\tif temp.Email != \"\" {\n\t\treturn u.Message(false, \"Email address already in use by another user.\"), false\n\t}\n\treturn u.Message(false, \"Requirement passed\"), true\n}", "func (a *Account) Validate() error {\n\treturn nil\n}", "func (mt *Account) Validate() (err error) {\n\tif mt.ID == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`response`, \"id\"))\n\t}\n\tif mt.Password == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`response`, \"password\"))\n\t}\n\n\treturn\n}", "func (accountInfo *AccountInfo) Validate() error {\n\taccountSchema, _ := GetAccountSchema(accountInfo.Domain)\n\tif accountSchema == nil {\n\t\treturn errors.New(\"schema undefined for domain \" + accountInfo.Domain)\n\t}\n\n\t// Group\n\tif !accountSchema.IsGroupExist(accountInfo.Group) {\n\t\treturn errors.New(\"unknown group \" + accountInfo.Group)\n\t}\n\n\t// UserID\n\tif accountInfo.Uid == \"\" {\n\t\treturn errors.New(\"uid can not be empty\")\n\t}\n\n\t// LoginIDs\n\tif len(accountInfo.LoginIDs) == 0 {\n\t\treturn errors.New(\"should have at least one login id\")\n\t}\n\trequiredIDs := accountSchema.getRequiredLogIDs()\n\tfor _, requiredID := range requiredIDs {\n\t\tif _, ok := accountInfo.LoginIDs[requiredID]; !ok {\n\t\t\treturn errors.New(\"login id:\" + requiredID + \" is required but not specified\")\n\t\t}\n\t}\n\tfor k, v := range accountInfo.LoginIDs {\n\t\tloginIDSchema, _ := accountSchema.GetLoginIDSchema(k)\n\t\tif loginIDSchema == nil {\n\t\t\treturn errors.New(\"login id schema for \" + k + \" is not defined\")\n\t\t} else {\n\t\t\tif !loginIDSchema.NeedVerified {\n\t\t\t\tv.Verified = true\n\t\t\t\t// accountInfo.LoginIDs[k] = v\n\t\t\t}\n\t\t\tif !loginIDSchema.Validator.Validate(v.ID) {\n\t\t\t\treturn errors.New(\"invalid format of login id \" + k + \":\" + v.ID)\n\t\t\t}\n\t\t}\n\t}\n\n\t// options\n\toptionsMap := mergeMaps(accountInfo.Profiles, accountInfo.Others)\n\trequiredOptions := accountSchema.getRequiredOptions()\n\tfor _, requiredOption := range requiredOptions {\n\t\tif _, ok := optionsMap[requiredOption]; !ok {\n\t\t\treturn errors.New(\"option:\" + requiredOption + \" is required but not specified\")\n\t\t}\n\t}\n\n\tfor k, v := range optionsMap {\n\t\toptionSchema, _ := accountSchema.GetOptionSchema(k)\n\t\tif optionSchema == nil {\n\t\t\treturn errors.New(\"option schema for \" + k + \" is not defined\")\n\t\t} else {\n\t\t\tif !optionSchema.Validator.Validate(v) {\n\t\t\t\treturn errors.New(\"invalid format of option \" + k)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func (mt *Account) Validate() (err error) {\n\n\tif mt.Href == \"\" {\n\t\terr = goa.MissingAttributeError(`response`, \"href\", err)\n\t}\n\tif mt.Name == \"\" {\n\t\terr = goa.MissingAttributeError(`response`, \"name\", err)\n\t}\n\n\tif mt.CreatedAt != nil {\n\t\tif err2 := goa.ValidateFormat(goa.FormatDateTime, *mt.CreatedAt); err2 != nil {\n\t\t\terr = goa.InvalidFormatError(`response.created_at`, *mt.CreatedAt, goa.FormatDateTime, err2, err)\n\t\t}\n\t}\n\tif mt.CreatedBy != nil {\n\t\tif err2 := goa.ValidateFormat(goa.FormatEmail, *mt.CreatedBy); err2 != nil {\n\t\t\terr = goa.InvalidFormatError(`response.created_by`, *mt.CreatedBy, goa.FormatEmail, err2, err)\n\t\t}\n\t}\n\treturn\n}", "func (c *modAccountRun) validate(args []string) error {\n\tif len(args) < 2 {\n\t\treturn errors.New(\"not enough arguments\")\n\t}\n\n\tif len(args) > 2 {\n\t\treturn errors.New(\"too many arguments\")\n\t}\n\n\treturn nil\n}", "func (m *LedgerAccount) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateAccount(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateCurrency(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validatePostings(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (b *OGame) ValidateAccount(code string) error {\n\treturn b.validateAccount(code)\n}", "func (ut *accountInputPayload) Validate() (err error) {\n\tif ut.Email != nil {\n\t\tif err2 := goa.ValidateFormat(goa.FormatEmail, *ut.Email); err2 != nil {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidFormatError(`response.email`, *ut.Email, goa.FormatEmail, err2))\n\t\t}\n\t}\n\tif ut.Name != nil {\n\t\tif utf8.RuneCountInString(*ut.Name) < 1 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`response.name`, *ut.Name, utf8.RuneCountInString(*ut.Name), 1, true))\n\t\t}\n\t}\n\tif ut.Name != nil {\n\t\tif utf8.RuneCountInString(*ut.Name) > 30 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`response.name`, *ut.Name, utf8.RuneCountInString(*ut.Name), 30, false))\n\t\t}\n\t}\n\tif ut.Surname != nil {\n\t\tif utf8.RuneCountInString(*ut.Surname) < 1 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`response.surname`, *ut.Surname, utf8.RuneCountInString(*ut.Surname), 1, true))\n\t\t}\n\t}\n\tif ut.Surname != nil {\n\t\tif utf8.RuneCountInString(*ut.Surname) > 30 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`response.surname`, *ut.Surname, utf8.RuneCountInString(*ut.Surname), 30, false))\n\t\t}\n\t}\n\treturn\n}", "func (account *Account) ValidateUpdate() (map[string]interface{}, bool) {\n\n\tif !strings.Contains(account.Email, \"@\") {\n\t\treturn u.Message(false, \"Email address is required\"), false\n\t}\n\n\tif len(account.Password) < 6 {\n\t\treturn u.Message(false, \"Password is required\"), false\n\t}\n\n\t//Email must be unique\n\ttemp := &Account{}\n\t//check for errors and duplicate emails\n\terr := GetDB().Table(\"accounts\").Where(\"email = ?\", account.Email).First(temp).Error\n\tif err != nil && err != gorm.ErrRecordNotFound {\n\t\treturn u.Message(false, \"Connection error. Please retry\"), false\n\t}\n\tif temp.Email == \"\" {\n\t\treturn u.Message(false, \"Email address not found in database.\"), false\n\t}\n\treturn u.Message(true, \"Requirement passed\"), true\n}", "func (ut *AccountInputPayload) Validate() (err error) {\n\tif ut.Email != nil {\n\t\tif err2 := goa.ValidateFormat(goa.FormatEmail, *ut.Email); err2 != nil {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidFormatError(`response.email`, *ut.Email, goa.FormatEmail, err2))\n\t\t}\n\t}\n\tif ut.Name != nil {\n\t\tif utf8.RuneCountInString(*ut.Name) < 1 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`response.name`, *ut.Name, utf8.RuneCountInString(*ut.Name), 1, true))\n\t\t}\n\t}\n\tif ut.Name != nil {\n\t\tif utf8.RuneCountInString(*ut.Name) > 30 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`response.name`, *ut.Name, utf8.RuneCountInString(*ut.Name), 30, false))\n\t\t}\n\t}\n\tif ut.Surname != nil {\n\t\tif utf8.RuneCountInString(*ut.Surname) < 1 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`response.surname`, *ut.Surname, utf8.RuneCountInString(*ut.Surname), 1, true))\n\t\t}\n\t}\n\tif ut.Surname != nil {\n\t\tif utf8.RuneCountInString(*ut.Surname) > 30 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`response.surname`, *ut.Surname, utf8.RuneCountInString(*ut.Surname), 30, false))\n\t\t}\n\t}\n\treturn\n}", "func ValidateAccount(client httpclient.IHttpClient, ctx context.Context, lobby, code string) error {\n\tif len(code) != 36 {\n\t\treturn errors.New(\"invalid validation code\")\n\t}\n\treq, err := http.NewRequest(http.MethodPut, \"https://\"+lobby+\".ogame.gameforge.com/api/users/validate/\"+code, strings.NewReader(`{\"language\":\"en\"}`))\n\tif err != nil {\n\t\treturn err\n\t}\n\treq.WithContext(ctx)\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\treturn nil\n}", "func (b *Builder) Validate() (*Account, error) {\n\tb.validate.SetTagName(b.essential.Country)\n\tif err := validateStruct(b.validate, b.essential); err != nil {\n\t\treturn nil, err\n\t}\n\tb.validate.SetTagName(\"validate\")\n\tif err := validateStruct(b.validate, b.essential); err != nil {\n\t\treturn nil, err\n\t}\n\tif err := validateStruct(b.validate, b.optional); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Account{\n\t\tid: b.essential.ID,\n\t\torganizationID: b.essential.OrganizationID,\n\t\tversionIndex: b.optional.VersionIndex,\n\t\tcountry: b.essential.Country,\n\t\tbankIDCode: b.essential.BankIDCode,\n\t\tbankID: b.essential.BankID,\n\t\tbic: b.essential.Bic,\n\t\tiban: b.essential.Iban,\n\t\tbaseCurrency: b.optional.BaseCurrency,\n\t\taccountNumber: b.optional.AccountNumber,\n\t\tcustomerID: b.optional.CustomerID,\n\t\ttitle: b.optional.Title,\n\t\tfirstName: b.optional.FirstName,\n\t\tbankAccountName: b.optional.BankAccountName,\n\t\taltBankAccountNames: b.optional.AltBankAccountNames,\n\t\taccountClassification: b.optional.AccountClassification,\n\t\tjointAccount: b.optional.JointAccount,\n\t\taccountMatchingOptOut: b.optional.AccountMatchingOptOut,\n\t\tsecondaryIdentification: b.optional.SecondaryIdentification,\n\t}, nil\n}", "func (a *Account) Validate() error {\n\tvalidate := validator.New()\n\treturn validate.Struct(a)\n}", "func (ga GenesisAccount) Validate() error {\n\tif ethermint.IsZeroAddress(ga.Address) {\n\t\treturn fmt.Errorf(\"address cannot be the zero address %s\", ga.Address)\n\t}\n\tif len(ethcmn.Hex2Bytes(ga.Code)) == 0 {\n\t\treturn errors.New(\"code cannot be empty\")\n\t}\n\n\treturn ga.Storage.Validate()\n}", "func validate(user *customer_api.DbUser, allowEmpty bool) error {\n\tconst minNameLength, maxNameLength = 3, 20\n\tconst emailRegexString = \"^[a-zA-Z0-9+_.-]+@[a-zA-Z0-9.-]+$\"\n\tvar emailRegex = regexp.MustCompile(emailRegexString)\n\n\tif !(allowEmpty && user.Email == \"\") {\n\t\tif len(user.Email) < 5 || !emailRegex.MatchString(user.Email) {\n\t\t\treturn errors.New(\"invalid email\")\n\t\t}\n\t}\n\n\tif !(allowEmpty && user.FirstName == \"\") {\n\t\tif len(user.FirstName) < minNameLength || len(user.FirstName) > maxNameLength {\n\t\t\treturn errors.New(\"first_name should be between 3 and 20 characters\")\n\t\t}\n\t}\n\n\tif !(allowEmpty && user.LastName == \"\") {\n\t\tif len(user.LastName) < minNameLength || len(user.LastName) > maxNameLength {\n\t\t\treturn errors.New(\"last_name should be between 3 and 20 characters\")\n\t\t}\n\t}\n\n\tif !(allowEmpty && user.Phone == 0) {\n\t\tif user.Phone < 1000000000 || user.Phone > 9999999999 {\n\t\t\treturn errors.New(\"invalid phone no\")\n\t\t}\n\t}\n\n\tif !(allowEmpty && user.Id == \"\") {\n\t\tif user.Id == \"\" {\n\t\t\treturn errors.New(\"id cannot be empty\")\n\t\t}\n\t}\n\treturn nil\n}", "func (server *Server) checkValidAccount(ctx *gin.Context, id int64, curr string) (bool, db.Account) {\n\tacc, err := server.repository.GetAccount(ctx, id)\n\tif err != nil {\n\t\tctx.JSON(http.StatusNotFound, errorResponse(err))\n\t\treturn false, db.Account{}\n\t}\n\tif acc.Currency != curr {\n\t\terr = fmt.Errorf(\"invalid currency for account [%d]: expected %s received %s\", acc.ID, acc.Currency, curr)\n\t\tctx.JSON(http.StatusBadRequest, errorResponse(err))\n\t\treturn false, db.Account{}\n\t}\n\n\treturn true, acc\n}", "func (mt *EasypostCarrierAccounts) Validate() (err error) {\n\tif mt.ID == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`response`, \"id\"))\n\t}\n\tif mt.Object == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`response`, \"object\"))\n\t}\n\n\tif ok := goa.ValidatePattern(`^CarrierAccount$`, mt.Object); !ok {\n\t\terr = goa.MergeErrors(err, goa.InvalidPatternError(`response.object`, mt.Object, `^CarrierAccount$`))\n\t}\n\treturn\n}", "func (m *InfrastructureAccount) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateCostCenter(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateCriticalityLevel(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateEnvironment(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateExternalID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateLifecycleStatus(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateName(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateOwner(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateType(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (m *CloudAccountExtended) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\t// validation for a type composition with CloudAccount\n\tif err := m.CloudAccount.Validate(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateState(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateType(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (a *Account) Validate() error {\n\terr := validation.ValidateStruct(a,\n\t\tvalidation.Field(&a.AdminRoleArn, validateAdminRoleArn...),\n\t\tvalidation.Field(&a.ID, validateID...),\n\t\tvalidation.Field(&a.LastModifiedOn, validateInt64...),\n\t\tvalidation.Field(&a.Status, validateStatus...),\n\t\tvalidation.Field(&a.CreatedOn, validateInt64...),\n\t\tvalidation.Field(&a.PrincipalRoleArn, validatePrincipalRoleArn...),\n\t\tvalidation.Field(&a.PrincipalPolicyHash, validatePrincipalPolicyHash...),\n\t)\n\tif err != nil {\n\t\treturn errors.NewValidation(\"account\", err)\n\t}\n\treturn nil\n}", "func validRawAccount(accountName string) error {\n\t// param absence check\n\tif accountName == \"\" {\n\t\treturn fmt.Errorf(\"invoke NewAccount failed, account name is empty\")\n\t}\n\n\t// account naming rule check\n\tif len(accountName) != accountSize {\n\t\treturn fmt.Errorf(\"invoke NewAccount failed, account name length expect %d, actual: %d\", accountSize, len(accountName))\n\t}\n\n\tfor i := 0; i < accountSize; i++ {\n\t\tif accountName[i] >= '0' && accountName[i] <= '9' {\n\t\t\tcontinue\n\t\t} else {\n\t\t\treturn fmt.Errorf(\"invoke NewAccount failed, account name expect continuous %d number\", accountSize)\n\t\t}\n\t}\n\n\treturn nil\n}", "func (o *CloudSnapshotAccount) Validate() error {\n\n\terrors := elemental.Errors{}\n\trequiredErrors := elemental.Errors{}\n\n\tif err := ValidateTagsWithoutReservedPrefixes(\"associatedTags\", o.AssociatedTags); err != nil {\n\t\terrors = errors.Append(err)\n\t}\n\n\tif err := elemental.ValidateStringInList(\"cloudType\", string(o.CloudType), []string{\"AWS\", \"GCP\"}, false); err != nil {\n\t\terrors = errors.Append(err)\n\t}\n\n\tif len(requiredErrors) > 0 {\n\t\treturn requiredErrors\n\t}\n\n\tif len(errors) > 0 {\n\t\treturn errors\n\t}\n\n\treturn nil\n}", "func (m *ProviderAccountRequest) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateDataset(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateDatasetName(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateField(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validatePreferences(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (uu *UserUpdate) check() error {\n\tif v, ok := uu.mutation.AccountName(); ok {\n\t\tif err := user.AccountNameValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"account_name\", err: fmt.Errorf(\"ent: validator failed for field \\\"account_name\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.StaffType(); ok {\n\t\tif err := user.StaffTypeValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"staff_type\", err: fmt.Errorf(\"ent: validator failed for field \\\"staff_type\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.FamilyName(); ok {\n\t\tif err := user.FamilyNameValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"family_name\", err: fmt.Errorf(\"ent: validator failed for field \\\"family_name\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.GivenName(); ok {\n\t\tif err := user.GivenNameValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"given_name\", err: fmt.Errorf(\"ent: validator failed for field \\\"given_name\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.DisplayName(); ok {\n\t\tif err := user.DisplayNameValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"display_name\", err: fmt.Errorf(\"ent: validator failed for field \\\"display_name\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.IDNumber(); ok {\n\t\tif err := user.IDNumberValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"id_number\", err: fmt.Errorf(\"ent: validator failed for field \\\"id_number\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.Sex(); ok {\n\t\tif err := user.SexValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"sex\", err: fmt.Errorf(\"ent: validator failed for field \\\"sex\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.PhoneNumber(); ok {\n\t\tif err := user.PhoneNumberValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"phone_number\", err: fmt.Errorf(\"ent: validator failed for field \\\"phone_number\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.Address(); ok {\n\t\tif err := user.AddressValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"address\", err: fmt.Errorf(\"ent: validator failed for field \\\"address\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.StaffID(); ok {\n\t\tif err := user.StaffIDValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"staff_id\", err: fmt.Errorf(\"ent: validator failed for field \\\"staff_id\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.PersonalEmail(); ok {\n\t\tif err := user.PersonalEmailValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"personal_email\", err: fmt.Errorf(\"ent: validator failed for field \\\"personal_email\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.IntranetWorkEmail(); ok {\n\t\tif err := user.IntranetWorkEmailValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"intranet_work_email\", err: fmt.Errorf(\"ent: validator failed for field \\\"intranet_work_email\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.ExtranetWorkEmail(); ok {\n\t\tif err := user.ExtranetWorkEmailValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"extranet_work_email\", err: fmt.Errorf(\"ent: validator failed for field \\\"extranet_work_email\\\": %w\", err)}\n\t\t}\n\t}\n\treturn nil\n}", "func (profileImport *ProfileImportRequest) Validate(tx *sql.Tx) error {\n\n\tprofile := profileImport.Profile\n\n\t// Profile fields are valid\n\terrs := tovalidate.ToErrors(validation.Errors{\n\t\t\"name\": validation.Validate(profile.Name, validation.By(\n\t\t\tfunc(value interface{}) error {\n\t\t\t\tname, ok := value.(*string)\n\t\t\t\tif !ok {\n\t\t\t\t\treturn fmt.Errorf(\"wrong type, need: string, got: %T\", value)\n\t\t\t\t}\n\t\t\t\tif name == nil || *name == \"\" {\n\t\t\t\t\treturn errors.New(\"required and cannot be blank\")\n\t\t\t\t}\n\t\t\t\tif strings.Contains(*name, \" \") {\n\t\t\t\t\treturn errors.New(\"cannot contain spaces\")\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t},\n\t\t)),\n\t\t\"description\": validation.Validate(profile.Description, validation.Required),\n\t\t\"cdnName\": validation.Validate(profile.CDNName, validation.Required),\n\t\t\"type\": validation.Validate(profile.Type, validation.Required),\n\t})\n\n\t// Validate CDN exist\n\tif profile.CDNName != nil {\n\t\tif ok, err := CDNExistsByName(*profile.CDNName, tx); err != nil {\n\t\t\terrString := fmt.Sprintf(\"checking cdn name %v existence\", *profile.CDNName)\n\t\t\tlog.Errorf(\"%v: %v\", errString, err.Error())\n\t\t\terrs = append(errs, errors.New(errString))\n\t\t} else if !ok {\n\t\t\terrs = append(errs, fmt.Errorf(\"%v CDN does not exist\", *profile.CDNName))\n\t\t}\n\t}\n\n\t// Validate profile does not already exist\n\tif profile.Name != nil {\n\t\tif ok, err := ProfileExistsByName(*profile.Name, tx); err != nil {\n\t\t\terrString := fmt.Sprintf(\"checking profile name %v existence\", *profile.Name)\n\t\t\tlog.Errorf(\"%v: %v\", errString, err.Error())\n\t\t\terrs = append(errs, errors.New(errString))\n\t\t} else if ok {\n\t\t\terrs = append(errs, fmt.Errorf(\"a profile with the name \\\"%s\\\" already exists\", *profile.Name))\n\t\t}\n\t}\n\n\t// Validate all parameters\n\t// export/import does not include secure flag\n\t// default value to not flag on validation\n\tsecure := 1\n\tfor i, pp := range profileImport.Parameters {\n\t\tif ppErrs := validateProfileParamPostFields(pp.ConfigFile, pp.Name, pp.Value, &secure); len(ppErrs) > 0 {\n\t\t\tfor _, err := range ppErrs {\n\t\t\t\terrs = append(errs, errors.New(\"parameter \"+strconv.Itoa(i)+\": \"+err.Error()))\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(errs) > 0 {\n\t\treturn util.JoinErrs(errs)\n\t}\n\n\treturn nil\n}", "func (u *Usecase) validFields(d *Device) error {\n\tif d.Name == \"\" {\n\t\treturn &InvalidError{\"attribute `Name` must not be empty\"}\n\t}\n\n\tif d.User == 0 {\n\t\treturn &InvalidError{\"invalid user\"}\n\t}\n\n\treturn nil\n}", "func (t *TokenAccount) Validate() error {\n\tv := validator.New()\n\terr := v.RegisterValidation(\"notblank\", validators.NotBlank)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = v.RegisterValidation(\"notall\", validation.NotAll)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn v.Struct(t)\n}", "func (v *Reg) Validate(ctx context.Context, f *reg.Form) error {\n\tvar es Errors\n\n\tif err := validation.Validate(f.Email, validation.Required, is.Email); err != nil {\n\t\tes = append(es, Error{\n\t\t\tField: \"email\",\n\t\t\tMessage: err.Error(),\n\t\t})\n\t}\n\n\tif err := validation.Validate(f.AccountID, validation.Required); err != nil {\n\t\tes = append(es, Error{\n\t\t\tField: \"account_id\",\n\t\t\tMessage: err.Error(),\n\t\t})\n\t}\n\n\tif err := v.Uniquer.Unique(ctx, f.Email); err != nil {\n\t\tswitch errors.Cause(err) {\n\t\tcase reg.ErrEmailExists:\n\t\t\tes = append(es, Error{\n\t\t\t\tField: \"email\",\n\t\t\t\tMessage: err.Error(),\n\t\t\t})\n\t\tdefault:\n\t\t\treturn errors.Wrap(err, \"unique\")\n\t\t}\n\t}\n\n\tfmt.Println(f.Password, f.PasswordConfirmation)\n\n\tif err := validation.Validate(f.Password, validation.Required, validation.Length(6, 32)); err != nil {\n\t\tes = append(es, Error{\n\t\t\tField: \"password\",\n\t\t\tMessage: err.Error(),\n\t\t})\n\t}\n\n\tif err := validation.Validate(f.PasswordConfirmation, validation.Required, validation.Length(6, 32)); err != nil {\n\t\tes = append(es, Error{\n\t\t\tField: \"password_confirmation\",\n\t\t\tMessage: err.Error(),\n\t\t})\n\t}\n\n\tif f.Password != f.PasswordConfirmation {\n\t\tes = append(es, Error{\n\t\t\tField: \"password_confirmation\",\n\t\t\tMessage: \"mismatch\",\n\t\t}, Error{\n\t\t\tField: \"password\",\n\t\t\tMessage: \"mismatch\",\n\t\t})\n\t}\n\n\tif len(es) > 0 {\n\t\treturn es\n\t}\n\n\treturn nil\n}", "func validateAccountName(accountName string) (string, error) {\n\treturn accountName, nil\n}", "func (rcv *controller) validate() error {\n\n\tif err := rcv.read(); err != nil {\n\t\treturn err\n\t}\n\n\t// If account does not exists\n\tif rcv.store.Email == \"\" {\n\t\treturn errors.New(rcv.Translate(\"text11\"))\n\t}\n\n\t// If time for activating account is expired\n\tif time.Now().Unix() > rcv.store.Expired {\n\t\t// Delete registered user from neo4j\n\t\tmaccount.Delete(rcv.store.Email, rcv.Local)\n\t\treturn &expiredError{rcv.Controller}\n\t}\n\n\treturn nil\n}", "func (acc *AccessControlCreate) check() error {\n\tif _, ok := acc.mutation.ServiceID(); !ok {\n\t\treturn &ValidationError{Name: \"service_id\", err: errors.New(\"ent: missing required field \\\"service_id\\\"\")}\n\t}\n\tif _, ok := acc.mutation.OpenAuth(); !ok {\n\t\treturn &ValidationError{Name: \"open_auth\", err: errors.New(\"ent: missing required field \\\"open_auth\\\"\")}\n\t}\n\tif _, ok := acc.mutation.BlackList(); !ok {\n\t\treturn &ValidationError{Name: \"black_list\", err: errors.New(\"ent: missing required field \\\"black_list\\\"\")}\n\t}\n\tif _, ok := acc.mutation.WhiteList(); !ok {\n\t\treturn &ValidationError{Name: \"white_list\", err: errors.New(\"ent: missing required field \\\"white_list\\\"\")}\n\t}\n\tif _, ok := acc.mutation.WhiteHostName(); !ok {\n\t\treturn &ValidationError{Name: \"white_host_name\", err: errors.New(\"ent: missing required field \\\"white_host_name\\\"\")}\n\t}\n\tif _, ok := acc.mutation.ClientipFlowLimit(); !ok {\n\t\treturn &ValidationError{Name: \"clientip_flow_limit\", err: errors.New(\"ent: missing required field \\\"clientip_flow_limit\\\"\")}\n\t}\n\tif _, ok := acc.mutation.ServiceFlowLimit(); !ok {\n\t\treturn &ValidationError{Name: \"service_flow_limit\", err: errors.New(\"ent: missing required field \\\"service_flow_limit\\\"\")}\n\t}\n\treturn nil\n}", "func (u *User) Validate(tx *pop.Connection) (*validate.Errors, error) {\n\tvar err error\n\t//validate based on is agent\n\tif !u.IsAgent { //is not an agent\n\t\treturn validate.Validate(\n\t\t\t&validators.StringIsPresent{Field: u.Email, Name: \"Email\"},\n\t\t\t&validators.StringIsPresent{Field: u.PasswordHash, Name: \"PasswordHash\"},\n\t\t\t&validators.StringIsPresent{Field: u.LastName, Name: \"LastName\"},\n\t\t\t&validators.StringIsPresent{Field: u.FirstName, Name: \"FirstName\"},\n\t\t\t&validators.StringIsPresent{Field: u.Phone, Name: \"Phone\"},\n\t\t\t// check to see if the email address is already taken:\n\t\t\t&validators.FuncValidator{\n\t\t\t\tField: u.Email,\n\t\t\t\tName: \"Email\",\n\t\t\t\tMessage: \"%s is already taken\",\n\t\t\t\tFn: func() bool {\n\t\t\t\t\tvar b bool\n\t\t\t\t\tq := tx.Where(\"email = ?\", u.Email)\n\t\t\t\t\tif u.ID != uuid.Nil {\n\t\t\t\t\t\tq = q.Where(\"id != ?\", u.ID)\n\t\t\t\t\t}\n\t\t\t\t\tb, err = q.Exists(u)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn false\n\t\t\t\t\t}\n\t\t\t\t\treturn !b\n\t\t\t\t},\n\t\t\t},\n\t\t), err\n\n\t} else { // trying to save agent\n\t\treturn validate.Validate(\n\t\t\t&validators.StringIsPresent{Field: u.Email, Name: \"Email\"},\n\t\t\t&validators.StringIsPresent{Field: u.PasswordHash, Name: \"PasswordHash\"},\n\t\t\t&validators.StringIsPresent{Field: u.LastName, Name: \"LastName\"},\n\t\t\t&validators.StringIsPresent{Field: u.FirstName, Name: \"FirstName\"},\n\t\t\t&validators.StringIsPresent{Field: u.Phone, Name: \"Phone\"},\n\t\t\t&validators.StringIsPresent{Field: u.PublicEmail.String, Name: \"PublicEmail\"},\n\t\t\t&validators.StringIsPresent{Field: u.Company.String, Name: \"Company\"},\n\t\t\t&validators.StringIsPresent{Field: u.Address1.String, Name: \"Address1\"},\n\t\t\t&validators.StringIsPresent{Field: u.City.String, Name: \"City\"},\n\t\t\t&validators.StringIsPresent{Field: u.State.String, Name: \"State\"},\n\t\t\t&validators.StringIsPresent{Field: u.Zipcode.String, Name: \"Zipcode\"},\n\t\t\t// check to see if the email address is already taken:\n\t\t\t&validators.FuncValidator{\n\t\t\t\tField: u.Email,\n\t\t\t\tName: \"Email\",\n\t\t\t\tMessage: \"%s is already taken\",\n\t\t\t\tFn: func() bool {\n\t\t\t\t\tvar b bool\n\t\t\t\t\tq := tx.Where(\"email = ?\", u.Email)\n\t\t\t\t\tif u.ID != uuid.Nil {\n\t\t\t\t\t\tq = q.Where(\"id != ?\", u.ID)\n\t\t\t\t\t}\n\t\t\t\t\tb, err = q.Exists(u)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn false\n\t\t\t\t\t}\n\t\t\t\t\treturn !b\n\t\t\t\t},\n\t\t\t},\n\t\t), err\n\n\t}\n}", "func IsValidAccount(a string) bool {\n\t_, err := NewAccount(a)\n\treturn err == nil\n}", "func (u User) IsValid() []error{\n\tvar errs []error\n\tfirstname := strings.Trim(u.FirstName, \" \")\n\tlastname := strings.Trim(u.LastName, \" \")\n\n\tif firstname != \"\" {\n\t\tif strings.Contains(firstname, \" \"){\n\t\t\terrs = append(errs, errors.New(\"FirstName can't have spaces\"))\n\t\t}\n\t\tif len(firstname) < 2 {\n\t\t\terrs = append(errs, errors.New(\"FirstName must be at least 2 characters\"))\n\t\t}\n\t\tif !helper.IsLetter(firstname) {\n\t\t\terrs = append(errs, errors.New(\"Firstname contains a number\"))\n\t\t}\n\t}\n\n\tif lastname != \"\"{\n\t\tif strings.Contains(lastname, \" \"){\n\t\t\terrs = append(errs, errors.New(\"LastName can't have spaces\"))\n\t\t}\n\n\t\tif len(lastname) < 2 {\n\t\t\terrs = append(errs, errors.New(\"LastName must be at least 2 characters\"))\n\t\t}\n\n\t\tif !helper.IsLetter(lastname) {\n\t\t\terrs = append(errs, errors.New(\"Lastname contains a number\"))\n\t\t}\n\t}\n\n\tif u.Email != \"\" {\n\t\tre := regexp.MustCompile(\"^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$\")\n\n\t\tif !re.MatchString(u.Email) {\n\t\t\terrs = append(errs, errors.New(\"Email address is not valid\"))\n\t\t}\n\t}\n\n\n\tyear, _, _, _, _, _ := helper.DateDiff(u.DateOfBirth, time.Now())\n\tif year < 18 {\n\t\terrs = append(errs, errors.New(\"You must be 18 or more\"))\n\t}\n\tif len(errs) > 0 {\n\t\treturn errs\n\t}\n\treturn nil\n}", "func (m *BillingProfiles2) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateAdviceOfCharge(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateCurrency(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateFraudDailyLimit(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateFraudDailyLock(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateFraudDailyNotify(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateFraudIntervalLimit(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateFraudIntervalLock(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateFraudIntervalNotify(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateFraudUseResellerRates(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateHandle(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateIntervalCharge(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateIntervalFreeCash(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateIntervalFreeTime(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateName(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validatePeaktimeSpecial(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validatePeaktimeWeekdays(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validatePrepaid(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validatePrepaidLibrary(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateResellerID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (o *conversionOptions) validate() error {\r\n\tif o.goalID == 0 && len(o.goalName) == 0 {\r\n\t\treturn fmt.Errorf(\"missing required attribute(s): %s or %s\", fieldID, fieldName)\r\n\t} else if o.goalID == 0 && o.tonicPowUserID > 0 {\r\n\t\treturn fmt.Errorf(\"missing required attribute: %s\", fieldID)\r\n\t} else if o.tonicPowUserID == 0 && len(o.tncpwSession) == 0 {\r\n\t\treturn fmt.Errorf(\"missing required attribute(s): %s or %s\", fieldVisitorSessionGUID, fieldUserID)\r\n\t}\r\n\treturn nil\r\n}", "func (m *CustomerTripletexAccount2) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateAccountType(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateAdministrator(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateChartOfAccountsType(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateModules(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateType(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateVatStatusType(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (bva BaseVestingAccount) Validate() error {\n\tif !(bva.DelegatedVesting.IsAllLTE(bva.OriginalVesting)) {\n\t\treturn errors.New(\"delegated vesting amount cannot be greater than original vesting amount\")\n\t}\n\treturn bva.BaseAccount.Validate()\n}", "func (uuo *UserUpdateOne) check() error {\n\tif v, ok := uuo.mutation.AccountName(); ok {\n\t\tif err := user.AccountNameValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"account_name\", err: fmt.Errorf(\"ent: validator failed for field \\\"account_name\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.StaffType(); ok {\n\t\tif err := user.StaffTypeValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"staff_type\", err: fmt.Errorf(\"ent: validator failed for field \\\"staff_type\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.FamilyName(); ok {\n\t\tif err := user.FamilyNameValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"family_name\", err: fmt.Errorf(\"ent: validator failed for field \\\"family_name\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.GivenName(); ok {\n\t\tif err := user.GivenNameValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"given_name\", err: fmt.Errorf(\"ent: validator failed for field \\\"given_name\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.DisplayName(); ok {\n\t\tif err := user.DisplayNameValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"display_name\", err: fmt.Errorf(\"ent: validator failed for field \\\"display_name\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.IDNumber(); ok {\n\t\tif err := user.IDNumberValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"id_number\", err: fmt.Errorf(\"ent: validator failed for field \\\"id_number\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.Sex(); ok {\n\t\tif err := user.SexValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"sex\", err: fmt.Errorf(\"ent: validator failed for field \\\"sex\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.PhoneNumber(); ok {\n\t\tif err := user.PhoneNumberValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"phone_number\", err: fmt.Errorf(\"ent: validator failed for field \\\"phone_number\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.Address(); ok {\n\t\tif err := user.AddressValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"address\", err: fmt.Errorf(\"ent: validator failed for field \\\"address\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.StaffID(); ok {\n\t\tif err := user.StaffIDValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"staff_id\", err: fmt.Errorf(\"ent: validator failed for field \\\"staff_id\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.PersonalEmail(); ok {\n\t\tif err := user.PersonalEmailValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"personal_email\", err: fmt.Errorf(\"ent: validator failed for field \\\"personal_email\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.IntranetWorkEmail(); ok {\n\t\tif err := user.IntranetWorkEmailValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"intranet_work_email\", err: fmt.Errorf(\"ent: validator failed for field \\\"intranet_work_email\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.ExtranetWorkEmail(); ok {\n\t\tif err := user.ExtranetWorkEmailValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"extranet_work_email\", err: fmt.Errorf(\"ent: validator failed for field \\\"extranet_work_email\\\": %w\", err)}\n\t\t}\n\t}\n\treturn nil\n}", "func (m *DomainDiscoverAPIAccount) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateCid(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (msg MsgAddAdminAccount) ValidateBasic() sdk.Error {\n if msg.AdminAddress.Empty() {\n return sdk.ErrInvalidAddress(msg.AdminAddress.String())\n }\n if msg.Owner.Empty() {\n return sdk.ErrInvalidAddress(msg.Owner.String())\n }\n return nil\n}", "func init() {\n\taccountFields := schema.Account{}.Fields()\n\t_ = accountFields\n\t// accountDescProvider is the schema descriptor for provider field.\n\taccountDescProvider := accountFields[1].Descriptor()\n\t// account.ProviderValidator is a validator for the \"provider\" field. It is called by the builders before save.\n\taccount.ProviderValidator = accountDescProvider.Validators[0].(func(string) error)\n\t// accountDescEmail is the schema descriptor for email field.\n\taccountDescEmail := accountFields[2].Descriptor()\n\t// account.EmailValidator is a validator for the \"email\" field. It is called by the builders before save.\n\taccount.EmailValidator = accountDescEmail.Validators[0].(func(string) error)\n\t// accountDescPassword is the schema descriptor for password field.\n\taccountDescPassword := accountFields[3].Descriptor()\n\t// account.PasswordValidator is a validator for the \"password\" field. It is called by the builders before save.\n\taccount.PasswordValidator = func() func(string) error {\n\t\tvalidators := accountDescPassword.Validators\n\t\tfns := [...]func(string) error{\n\t\t\tvalidators[0].(func(string) error),\n\t\t\tvalidators[1].(func(string) error),\n\t\t}\n\t\treturn func(password string) error {\n\t\t\tfor _, fn := range fns {\n\t\t\t\tif err := fn(password); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\t}()\n\t// accountDescLocked is the schema descriptor for locked field.\n\taccountDescLocked := accountFields[4].Descriptor()\n\t// account.DefaultLocked holds the default value on creation for the locked field.\n\taccount.DefaultLocked = accountDescLocked.Default.(bool)\n\t// accountDescConfirmed is the schema descriptor for confirmed field.\n\taccountDescConfirmed := accountFields[5].Descriptor()\n\t// account.DefaultConfirmed holds the default value on creation for the confirmed field.\n\taccount.DefaultConfirmed = accountDescConfirmed.Default.(bool)\n\t// accountDescConfirmationToken is the schema descriptor for confirmation_token field.\n\taccountDescConfirmationToken := accountFields[7].Descriptor()\n\t// account.ConfirmationTokenValidator is a validator for the \"confirmation_token\" field. It is called by the builders before save.\n\taccount.ConfirmationTokenValidator = accountDescConfirmationToken.Validators[0].(func(string) error)\n\t// accountDescRecoveryToken is the schema descriptor for recovery_token field.\n\taccountDescRecoveryToken := accountFields[9].Descriptor()\n\t// account.RecoveryTokenValidator is a validator for the \"recovery_token\" field. It is called by the builders before save.\n\taccount.RecoveryTokenValidator = accountDescRecoveryToken.Validators[0].(func(string) error)\n\t// accountDescOtp is the schema descriptor for otp field.\n\taccountDescOtp := accountFields[11].Descriptor()\n\t// account.OtpValidator is a validator for the \"otp\" field. It is called by the builders before save.\n\taccount.OtpValidator = accountDescOtp.Validators[0].(func(string) error)\n\t// accountDescEmailChange is the schema descriptor for email_change field.\n\taccountDescEmailChange := accountFields[12].Descriptor()\n\t// account.EmailChangeValidator is a validator for the \"email_change\" field. It is called by the builders before save.\n\taccount.EmailChangeValidator = accountDescEmailChange.Validators[0].(func(string) error)\n\t// accountDescEmailChangeToken is the schema descriptor for email_change_token field.\n\taccountDescEmailChangeToken := accountFields[14].Descriptor()\n\t// account.EmailChangeTokenValidator is a validator for the \"email_change_token\" field. It is called by the builders before save.\n\taccount.EmailChangeTokenValidator = accountDescEmailChangeToken.Validators[0].(func(string) error)\n\t// accountDescCreatedAt is the schema descriptor for created_at field.\n\taccountDescCreatedAt := accountFields[18].Descriptor()\n\t// account.DefaultCreatedAt holds the default value on creation for the created_at field.\n\taccount.DefaultCreatedAt = accountDescCreatedAt.Default.(func() time.Time)\n\t// accountDescUpdatedAt is the schema descriptor for updated_at field.\n\taccountDescUpdatedAt := accountFields[19].Descriptor()\n\t// account.DefaultUpdatedAt holds the default value on creation for the updated_at field.\n\taccount.DefaultUpdatedAt = accountDescUpdatedAt.Default.(func() time.Time)\n\t// account.UpdateDefaultUpdatedAt holds the default value on update for the updated_at field.\n\taccount.UpdateDefaultUpdatedAt = accountDescUpdatedAt.UpdateDefault.(func() time.Time)\n\t// accountDescID is the schema descriptor for id field.\n\taccountDescID := accountFields[0].Descriptor()\n\t// account.DefaultID holds the default value on creation for the id field.\n\taccount.DefaultID = accountDescID.Default.(func() uuid.UUID)\n\tsessionFields := schema.Session{}.Fields()\n\t_ = sessionFields\n\t// sessionDescCreatedAt is the schema descriptor for created_at field.\n\tsessionDescCreatedAt := sessionFields[2].Descriptor()\n\t// session.DefaultCreatedAt holds the default value on creation for the created_at field.\n\tsession.DefaultCreatedAt = sessionDescCreatedAt.Default.(func() time.Time)\n\t// sessionDescUpdatedAt is the schema descriptor for updated_at field.\n\tsessionDescUpdatedAt := sessionFields[3].Descriptor()\n\t// session.DefaultUpdatedAt holds the default value on creation for the updated_at field.\n\tsession.DefaultUpdatedAt = sessionDescUpdatedAt.Default.(func() time.Time)\n\t// session.UpdateDefaultUpdatedAt holds the default value on update for the updated_at field.\n\tsession.UpdateDefaultUpdatedAt = sessionDescUpdatedAt.UpdateDefault.(func() time.Time)\n}", "func (mt AccountCollection) Validate() (err error) {\n\tfor _, e := range mt {\n\t\tif e != nil {\n\t\t\tif err2 := e.Validate(); err2 != nil {\n\t\t\t\terr = goa.MergeErrors(err, err2)\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}", "func (frm entryForm) Validate() (map[string]string, bool) {\n\terrs := map[string]string{}\n\tg1 := frm.Department != \"\"\n\tif !g1 {\n\t\terrs[\"department\"] = \"Missing department\"\n\t}\n\tg2 := frm.CheckThis\n\tif !g2 {\n\t\terrs[\"check_this\"] = \"You need to comply\"\n\t}\n\tg3 := frm.Items != \"\"\n\tif !g3 {\n\t\terrs[\"items\"] = \"No items\"\n\t}\n\treturn errs, g1 && g2 && g3\n}", "func (vva ValidatorVestingAccount) Validate() error {\n\tif vva.SigningThreshold > 100 || vva.SigningThreshold < 0 {\n\t\treturn errors.New(\"signing threshold must be between 0 and 100\")\n\t}\n\tif vva.ReturnAddress.Equals(vva.Address) {\n\t\treturn errors.New(\"return address cannot be the same as the account address\")\n\t}\n\treturn vva.PeriodicVestingAccount.Validate()\n}", "func (dva DelayedVestingAccount) Validate() error {\n\treturn dva.BaseVestingAccount.Validate()\n}", "func validate(msgs []*LogMsg) {\n\tif !validatePRAMRegistration(msgs) {\n\t\tlog.Fatalf(\"validatePRAMRegistration\\n\")\n\t}\n}", "func (_PermInterface *PermInterfaceCaller) ValidateAccount(opts *bind.CallOpts, _account common.Address, _orgId string) (bool, error) {\n\tvar out []interface{}\n\terr := _PermInterface.contract.Call(opts, &out, \"validateAccount\", _account, _orgId)\n\n\tif err != nil {\n\t\treturn *new(bool), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(bool)).(*bool)\n\n\treturn out0, err\n\n}", "func (ut *RegisterPayload) Validate() (err error) {\n\tif ut.Email == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`type`, \"email\"))\n\t}\n\tif ut.Password == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`type`, \"password\"))\n\t}\n\tif ut.FirstName == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`type`, \"first_name\"))\n\t}\n\tif ut.LastName == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`type`, \"last_name\"))\n\t}\n\tif err2 := goa.ValidateFormat(goa.FormatEmail, ut.Email); err2 != nil {\n\t\terr = goa.MergeErrors(err, goa.InvalidFormatError(`type.email`, ut.Email, goa.FormatEmail, err2))\n\t}\n\tif utf8.RuneCountInString(ut.Email) < 6 {\n\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`type.email`, ut.Email, utf8.RuneCountInString(ut.Email), 6, true))\n\t}\n\tif utf8.RuneCountInString(ut.Email) > 150 {\n\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`type.email`, ut.Email, utf8.RuneCountInString(ut.Email), 150, false))\n\t}\n\tif utf8.RuneCountInString(ut.FirstName) < 1 {\n\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`type.first_name`, ut.FirstName, utf8.RuneCountInString(ut.FirstName), 1, true))\n\t}\n\tif utf8.RuneCountInString(ut.FirstName) > 200 {\n\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`type.first_name`, ut.FirstName, utf8.RuneCountInString(ut.FirstName), 200, false))\n\t}\n\tif utf8.RuneCountInString(ut.LastName) < 1 {\n\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`type.last_name`, ut.LastName, utf8.RuneCountInString(ut.LastName), 1, true))\n\t}\n\tif utf8.RuneCountInString(ut.LastName) > 200 {\n\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`type.last_name`, ut.LastName, utf8.RuneCountInString(ut.LastName), 200, false))\n\t}\n\tif utf8.RuneCountInString(ut.Password) < 5 {\n\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`type.password`, ut.Password, utf8.RuneCountInString(ut.Password), 5, true))\n\t}\n\tif utf8.RuneCountInString(ut.Password) > 100 {\n\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`type.password`, ut.Password, utf8.RuneCountInString(ut.Password), 100, false))\n\t}\n\treturn\n}", "func (a *Api) validateError() (err error) {\n\tif a.UserID == 0 {\n\t\treturn a.Errors(ErrorMissingValue, \"user_id\")\n\t}\n\n\tif a.Token == \"\" {\n\t\treturn a.Errors(ErrorMissingValue, \"token\")\n\t}\n\n\treturn\n}", "func (uc *UserCreate) check() error {\n\tif _, ok := uc.mutation.Firstname(); !ok {\n\t\treturn &ValidationError{Name: \"firstname\", err: errors.New(\"ent: missing required field \\\"firstname\\\"\")}\n\t}\n\tif _, ok := uc.mutation.Lastname(); !ok {\n\t\treturn &ValidationError{Name: \"lastname\", err: errors.New(\"ent: missing required field \\\"lastname\\\"\")}\n\t}\n\tif _, ok := uc.mutation.Username(); !ok {\n\t\treturn &ValidationError{Name: \"username\", err: errors.New(\"ent: missing required field \\\"username\\\"\")}\n\t}\n\tif _, ok := uc.mutation.Password(); !ok {\n\t\treturn &ValidationError{Name: \"password\", err: errors.New(\"ent: missing required field \\\"password\\\"\")}\n\t}\n\treturn nil\n}", "func (ac *AreahistoryCreate) check() error {\n\tif _, ok := ac.mutation.WalletID(); !ok {\n\t\treturn &ValidationError{Name: \"WalletID\", err: errors.New(\"ent: missing required field \\\"WalletID\\\"\")}\n\t}\n\tif v, ok := ac.mutation.WalletID(); ok {\n\t\tif err := areahistory.WalletIDValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"WalletID\", err: fmt.Errorf(\"ent: validator failed for field \\\"WalletID\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := ac.mutation.ProvinceNameTH(); ok {\n\t\tif err := areahistory.ProvinceNameTHValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"ProvinceNameTH\", err: fmt.Errorf(\"ent: validator failed for field \\\"ProvinceNameTH\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := ac.mutation.DistrictNameTH(); ok {\n\t\tif err := areahistory.DistrictNameTHValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"DistrictNameTH\", err: fmt.Errorf(\"ent: validator failed for field \\\"DistrictNameTH\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := ac.mutation.SubDistrict(); ok {\n\t\tif err := areahistory.SubDistrictValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"SubDistrict\", err: fmt.Errorf(\"ent: validator failed for field \\\"SubDistrict\\\": %w\", err)}\n\t\t}\n\t}\n\treturn nil\n}", "func (_PermInterface *PermInterfaceSession) ValidateAccount(_account common.Address, _orgId string) (bool, error) {\n\treturn _PermInterface.Contract.ValidateAccount(&_PermInterface.CallOpts, _account, _orgId)\n}", "func (uu *UserUpdate) check() error {\n\tif v, ok := uu.mutation.Username(); ok {\n\t\tif err := user.UsernameValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"username\", err: fmt.Errorf(\"ent: validator failed for field \\\"username\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.Fullname(); ok {\n\t\tif err := user.FullnameValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"fullname\", err: fmt.Errorf(\"ent: validator failed for field \\\"fullname\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.Password(); ok {\n\t\tif err := user.PasswordValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"password\", err: fmt.Errorf(\"ent: validator failed for field \\\"password\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.Email(); ok {\n\t\tif err := user.EmailValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"email\", err: fmt.Errorf(\"ent: validator failed for field \\\"email\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.Phone(); ok {\n\t\tif err := user.PhoneValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"phone\", err: fmt.Errorf(\"ent: validator failed for field \\\"phone\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.Bio(); ok {\n\t\tif err := user.BioValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"bio\", err: fmt.Errorf(\"ent: validator failed for field \\\"bio\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.Intro(); ok {\n\t\tif err := user.IntroValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"intro\", err: fmt.Errorf(\"ent: validator failed for field \\\"intro\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.GithubProfile(); ok {\n\t\tif err := user.GithubProfileValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"github_profile\", err: fmt.Errorf(\"ent: validator failed for field \\\"github_profile\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.ProfilePictureURL(); ok {\n\t\tif err := user.ProfilePictureURLValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"profile_picture_url\", err: fmt.Errorf(\"ent: validator failed for field \\\"profile_picture_url\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.Status(); ok {\n\t\tif err := user.StatusValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"status\", err: fmt.Errorf(\"ent: validator failed for field \\\"status\\\": %w\", err)}\n\t\t}\n\t}\n\treturn nil\n}", "func (uc *UserCreate) check() error {\n\tif _, ok := uc.mutation.Age(); !ok {\n\t\treturn &ValidationError{Name: \"age\", err: errors.New(\"ent: missing required field \\\"age\\\"\")}\n\t}\n\tif v, ok := uc.mutation.Age(); ok {\n\t\tif err := user.AgeValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"age\", err: fmt.Errorf(\"ent: validator failed for field \\\"age\\\": %w\", err)}\n\t\t}\n\t}\n\tif _, ok := uc.mutation.Name(); !ok {\n\t\treturn &ValidationError{Name: \"name\", err: errors.New(\"ent: missing required field \\\"name\\\"\")}\n\t}\n\tif v, ok := uc.mutation.ID(); ok {\n\t\tif err := user.IDValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"id\", err: fmt.Errorf(\"ent: validator failed for field \\\"id\\\": %w\", err)}\n\t\t}\n\t}\n\treturn nil\n}", "func (p *PaymentNeed) validate() error {\n\tif p.BeneficiaryID == 0 {\n\t\treturn fmt.Errorf(\"beneficiary ID nul\")\n\t}\n\tif p.Value == 0 {\n\t\treturn fmt.Errorf(\"value nul\")\n\t}\n\treturn nil\n}", "func (r *Result) validate(errMsg *[]string, parentField string) {\n\tjn := resultJsonMap\n\taddErrMessage(errMsg, len(r.Key) > 0 && hasNonEmptyKV(r.Key), \"field '%s' must be non-empty and must not have empty keys or values\", parentField+\".\"+jn[\"Key\"])\n\taddErrMessage(errMsg, hasNonEmptyKV(r.Options), \"field '%s' must not have empty keys or values\", parentField+\".\"+jn[\"Options\"])\n\taddErrMessage(errMsg, regExHexadecimal.MatchString(string(r.Digest)), \"field '%s' must be hexadecimal\", parentField+\".\"+jn[\"Digest\"])\n}", "func CheckAccountResponse(t *testing.T, resp *models.Account, expectedAccount *models.Account) {\n\tif resp.ID != expectedAccount.ID {\n\t\tt.Errorf(\"Response contains wrong ID, got %v expected %v\", resp.ID, expectedAccount.ID)\n\t}\n\tif resp.Type != expectedAccount.Type {\n\t\tt.Errorf(\"Response contains wrong Type, got %v expected %v\", resp.Type, expectedAccount.Type)\n\t}\n\tif resp.OrganisationID != expectedAccount.OrganisationID {\n\t\tt.Errorf(\"Response contains wrong OrganisationID, got %v expected %v\", resp.OrganisationID, expectedAccount.OrganisationID)\n\t}\n\tif resp.Version != expectedAccount.Version {\n\t\tt.Errorf(\"Response contains wrong Version, got %v expected %v\", resp.Version, expectedAccount.Version)\n\t}\n\tif resp.Attributes.Country != expectedAccount.Attributes.Country {\n\t\tt.Errorf(\"Response contains wrong Country, got %v expected %v\", resp.Attributes.Country, expectedAccount.Attributes.Country)\n\t}\n\tif resp.Attributes.BaseCurrency != expectedAccount.Attributes.BaseCurrency {\n\t\tt.Errorf(\"Response contains wrong BaseCurrency, got %v expected %v\", resp.Attributes.BaseCurrency, expectedAccount.Attributes.BaseCurrency)\n\t}\n\tif resp.Attributes.BankID != expectedAccount.Attributes.BankID {\n\t\tt.Errorf(\"Response contains wrong BankID, got %v expected %v\", resp.Attributes.BankID, expectedAccount.Attributes.BankID)\n\t}\n\tif resp.Attributes.BankIDCode != expectedAccount.Attributes.BankIDCode {\n\t\tt.Errorf(\"Response contains wrong BankIDCode, got %v expected %v\", resp.Attributes.BankIDCode, expectedAccount.Attributes.BankIDCode)\n\t}\n\tif resp.Attributes.Bic != expectedAccount.Attributes.Bic {\n\t\tt.Errorf(\"Response contains wrong Bic, got %v expected %v\", resp.Attributes.Bic, expectedAccount.Attributes.Bic)\n\t}\n\tif resp.Attributes.AccountNumber != expectedAccount.Attributes.AccountNumber {\n\t\tt.Errorf(\"Response contains wrong AccountNumber, got %v expected %v\", resp.Attributes.AccountNumber, expectedAccount.Attributes.AccountNumber)\n\t}\n\tif resp.Attributes.CustomerID != expectedAccount.Attributes.CustomerID {\n\t\tt.Errorf(\"Response contains wrong CustomerID, got %v expected %v\", resp.Attributes.CustomerID, expectedAccount.Attributes.CustomerID)\n\t}\n\tif resp.Attributes.FirstName != expectedAccount.Attributes.FirstName {\n\t\tt.Errorf(\"Response contains wrong FirstName, got %v expected %v\", resp.Attributes.FirstName, expectedAccount.Attributes.FirstName)\n\t}\n\tif resp.Attributes.BankAccountName != expectedAccount.Attributes.BankAccountName {\n\t\tt.Errorf(\"Response contains wrong BankAccountName, got %v expected %v\", resp.Attributes.BankAccountName, expectedAccount.Attributes.BankAccountName)\n\t}\n\n\tresponseLength := len(resp.Attributes.AlternativeBankAccountNames)\n\texpectedLength := len(expectedAccount.Attributes.AlternativeBankAccountNames)\n\n\tif responseLength != expectedLength {\n\t\tt.Errorf(\"AlternativeBankAccountNames array is wrong, got %v expected %v\", responseLength, expectedLength)\n\t} else {\n\t\ti := 0\n\t\tfor i < responseLength {\n\t\t\tif resp.Attributes.AlternativeBankAccountNames[i] != expectedAccount.Attributes.AlternativeBankAccountNames[i] {\n\t\t\t\tt.Errorf(\"Response contains wrong AlternativeBankAccountNames, got %v expected %v\", resp.Attributes.AlternativeBankAccountNames[i], expectedAccount.Attributes.AlternativeBankAccountNames[i])\n\t\t\t}\n\t\t\ti = i + 1\n\t\t}\n\t}\n\n\tif resp.Attributes.AlternativeBankAccountNames[0] != expectedAccount.Attributes.AlternativeBankAccountNames[0] {\n\t\tt.Errorf(\"Response contains wrong AlternativeBankAccountNames, got %v expected %v\", resp.Attributes.AlternativeBankAccountNames[0], expectedAccount.Attributes.AlternativeBankAccountNames[0])\n\t}\n\tif resp.Attributes.AccountClassification != expectedAccount.Attributes.AccountClassification {\n\t\tt.Errorf(\"Response contains wrong AccountClassification, got %v expected %v\", resp.Attributes.AccountClassification, expectedAccount.Attributes.AccountClassification)\n\t}\n\tif resp.Attributes.JointAccount != expectedAccount.Attributes.JointAccount {\n\t\tt.Errorf(\"Response contains wrong JointAccount, got %v expected %v\", resp.Attributes.JointAccount, expectedAccount.Attributes.JointAccount)\n\t}\n\tif resp.Attributes.Switched != expectedAccount.Attributes.Switched {\n\t\tt.Errorf(\"Response contains wrong Switched, got %v expected %v\", resp.Attributes.Switched, expectedAccount.Attributes.Switched)\n\t}\n\tif resp.Attributes.AccountMatchingOptOut != expectedAccount.Attributes.AccountMatchingOptOut {\n\t\tt.Errorf(\"Response contains wrong AccountMatchingOptOut, got %v expected %v\", resp.Attributes.AccountMatchingOptOut, expectedAccount.Attributes.AccountMatchingOptOut)\n\t}\n\tif resp.Attributes.Status != expectedAccount.Attributes.Status {\n\t\tt.Errorf(\"Response contains wrong Status, got %v expected %v\", resp.Attributes.Status, expectedAccount.Attributes.Status)\n\t}\n\tif resp.Attributes.SecondaryIdentification != expectedAccount.Attributes.SecondaryIdentification {\n\t\tt.Errorf(\"Response contains wrong SecondaryIdentification, got %v expected %v\", resp.Attributes.SecondaryIdentification, expectedAccount.Attributes.SecondaryIdentification)\n\t}\n}", "func (_PermInterface *PermInterfaceCallerSession) ValidateAccount(_account common.Address, _orgId string) (bool, error) {\n\treturn _PermInterface.Contract.ValidateAccount(&_PermInterface.CallOpts, _account, _orgId)\n}", "func (cfg fromCFN) validate() error {\n\tif cfg.isEmpty() {\n\t\treturn nil\n\t}\n\tif len(aws.StringValue(cfg.Name)) == 0 {\n\t\treturn errors.New(\"name cannot be an empty string\")\n\t}\n\treturn nil\n}", "func isAccountFlagsValid(accountId string) bool {\n\taccount := GetStellarAccount(accountId)\n\treturn account.Flags.AuthRequired && account.Flags.AuthRevocable\n}", "func validate(name, gender string) error {\n\tif name == \"\" {\n\t\treturn &inputError{message: \"name is missing\", missingField: \"name\"}\n\t}\n\tif gender == \"\" {\n\t\treturn &inputError{message: \"gender is missing\", missingField: \"gender\"}\n\t}\n\treturn nil\n}", "func (user *User) Validate() *errors.RestErr {\n\t// Delete spaces at first_name, last_name and email before saving\n\tuser.FirstName = strings.TrimSpace(user.FirstName)\n\tuser.LastName = strings.TrimSpace(user.LastName)\n\tuser.Email = strings.TrimSpace(strings.ToLower(user.Email))\n\n\tif user.Email == \"\"{\n\t\treturn errors.NewBadRequestError(\"Email addres is required\")\n\t}\n\tif !ValidateEmail(user.Email){\n\t\treturn errors.NewBadRequestError(\"Wrong email format\")\n\t}\n\tif strings.TrimSpace(user.Password)== \"\" || len(strings.TrimSpace(user.Password)) < 8{\n\t\treturn errors.NewBadRequestError(\"Password is required and password length must be higher than 8 characters\")\n\t}\n\n\n\treturn nil\n}", "func checkAccount(t *testing.T, tree *avl.Tree, id AccountID, expectedBalance, expectedReward, expectedStake *uint64) {\n\tvar balance, reward, stake uint64\n\tvar exist bool\n\n\tbalance, exist = ReadAccountBalance(tree, id)\n\tassert.Equal(t, expectedBalance != nil, exist, \"account ID: %x\", id)\n\treward, exist = ReadAccountReward(tree, id)\n\tassert.Equal(t, expectedReward != nil, exist, \"account ID: %x\", id)\n\tstake, exist = ReadAccountStake(tree, id)\n\tassert.Equal(t, expectedStake != nil, exist, \"account ID: %x\", id)\n\n\tif expectedBalance != nil {\n\t\tassert.Equal(t, balance, *expectedBalance, \"account ID: %x\", id)\n\t}\n\n\tif expectedReward != nil {\n\t\tassert.Equal(t, reward, *expectedReward, \"account ID: %x\", id)\n\t}\n\n\tif expectedStake != nil {\n\t\tassert.Equal(t, stake, *expectedStake, \"account ID: %x\", id)\n\t}\n}", "func ValidBaseInfo(ctx *gin.Context) {\n\tres := helper.Res{}\n\n\tvar baseInfo BaseInfo\n\tif err := ctx.Bind(&baseInfo); err != nil {\n\t\tres.Status(http.StatusBadRequest).Error(err).Send(ctx)\n\t\treturn\n\t}\n\n\t// user does exist\n\tif _, err := models.FindOneByUsername(baseInfo.Username); err != nil {\n\t\tres.Status(http.StatusBadRequest).Error(err).Send(ctx)\n\t\treturn\n\t}\n\n\t// the email of user does exist\n\tif _, err := models.FindOneByEmail(baseInfo.Email); err != nil {\n\t\tres.Status(http.StatusBadRequest).Error(err).Send(ctx)\n\t\treturn\n\t}\n\n\tres.Success(gin.H{\n\t\t\"isValid\": true,\n\t}).Send(ctx)\n}", "func (w Warrant) Validate() error {\n\tif len(w.FirstName) == 0 {\n\t\treturn errors.New(\"missing first name element\")\n\t}\n\tif len(w.LastName) == 0 {\n\t\treturn errors.New(\"missing last name element\")\n\t}\n\tif len(w.Civility) == 0 {\n\t\treturn errors.New(\"missing civility element\")\n\t}\n\treturn nil\n}", "func (va ClawbackVestingAccount) Validate() error {\n\tif va.GetStartTime() >= va.GetEndTime() {\n\t\treturn errors.New(\"vesting start-time must be before end-time\")\n\t}\n\n\tlockupEnd := va.StartTime\n\tlockupCoins := sdk.NewCoins()\n\tfor _, p := range va.LockupPeriods {\n\t\tlockupEnd += p.Length\n\t\tlockupCoins = lockupCoins.Add(p.Amount...)\n\t}\n\tif lockupEnd > va.EndTime {\n\t\treturn errors.New(\"lockup schedule extends beyond account end time\")\n\t}\n\tif !coinEq(lockupCoins, va.OriginalVesting) {\n\t\treturn errors.New(\"original vesting coins does not match the sum of all coins in lockup periods\")\n\t}\n\n\tvestingEnd := va.StartTime\n\tvestingCoins := sdk.NewCoins()\n\tfor _, p := range va.VestingPeriods {\n\t\tvestingEnd += p.Length\n\t\tvestingCoins = vestingCoins.Add(p.Amount...)\n\t}\n\tif vestingEnd > va.EndTime {\n\t\treturn errors.New(\"vesting schedule exteds beyond account end time\")\n\t}\n\tif !coinEq(vestingCoins, va.OriginalVesting) {\n\t\treturn errors.New(\"original vesting coins does not match the sum of all coins in vesting periods\")\n\t}\n\n\treturn va.BaseVestingAccount.Validate()\n}", "func (ut *registerPayload) Validate() (err error) {\n\tif ut.Email == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`request`, \"email\"))\n\t}\n\tif ut.Password == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`request`, \"password\"))\n\t}\n\tif ut.FirstName == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`request`, \"first_name\"))\n\t}\n\tif ut.LastName == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`request`, \"last_name\"))\n\t}\n\tif ut.Email != nil {\n\t\tif err2 := goa.ValidateFormat(goa.FormatEmail, *ut.Email); err2 != nil {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidFormatError(`request.email`, *ut.Email, goa.FormatEmail, err2))\n\t\t}\n\t}\n\tif ut.Email != nil {\n\t\tif utf8.RuneCountInString(*ut.Email) < 6 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`request.email`, *ut.Email, utf8.RuneCountInString(*ut.Email), 6, true))\n\t\t}\n\t}\n\tif ut.Email != nil {\n\t\tif utf8.RuneCountInString(*ut.Email) > 150 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`request.email`, *ut.Email, utf8.RuneCountInString(*ut.Email), 150, false))\n\t\t}\n\t}\n\tif ut.FirstName != nil {\n\t\tif utf8.RuneCountInString(*ut.FirstName) < 1 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`request.first_name`, *ut.FirstName, utf8.RuneCountInString(*ut.FirstName), 1, true))\n\t\t}\n\t}\n\tif ut.FirstName != nil {\n\t\tif utf8.RuneCountInString(*ut.FirstName) > 200 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`request.first_name`, *ut.FirstName, utf8.RuneCountInString(*ut.FirstName), 200, false))\n\t\t}\n\t}\n\tif ut.LastName != nil {\n\t\tif utf8.RuneCountInString(*ut.LastName) < 1 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`request.last_name`, *ut.LastName, utf8.RuneCountInString(*ut.LastName), 1, true))\n\t\t}\n\t}\n\tif ut.LastName != nil {\n\t\tif utf8.RuneCountInString(*ut.LastName) > 200 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`request.last_name`, *ut.LastName, utf8.RuneCountInString(*ut.LastName), 200, false))\n\t\t}\n\t}\n\tif ut.Password != nil {\n\t\tif utf8.RuneCountInString(*ut.Password) < 5 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`request.password`, *ut.Password, utf8.RuneCountInString(*ut.Password), 5, true))\n\t\t}\n\t}\n\tif ut.Password != nil {\n\t\tif utf8.RuneCountInString(*ut.Password) > 100 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`request.password`, *ut.Password, utf8.RuneCountInString(*ut.Password), 100, false))\n\t\t}\n\t}\n\treturn\n}", "func ValidateWarriorAccount(name string, email string, pwd1 string, pwd2 string) (WarriorName string, WarriorEmail string, WarriorPassword string, validateErr error) {\n\tv := validator.New()\n\ta := warriorAccount{\n\t\tName: name,\n\t\tEmail: email,\n\t\tPassword1: pwd1,\n\t\tPassword2: pwd2,\n\t}\n\terr := v.Struct(a)\n\n\treturn name, email, pwd1, err\n}", "func validateAttributes(attrs map[string]models.ValueType, allAttrs bool) error {\n\t// TBD: to finalize the attributes specifics\n\tattrsOK := false\n\tif vt, ok := attrs[AttrCred]; ok && vt.Kind == com.ValueTypeSecret {\n\t\tif !allAttrs {\n\t\t\tattrsOK = true\n\t\t} else if vt, ok := attrs[AttrZone]; ok && vt.Kind == com.ValueTypeString {\n\t\t\tattrsOK = true\n\t\t}\n\t}\n\tif !attrsOK {\n\t\tmsg := \"required domain attributes missing or invalid: need \" + AttrCred + \"[E]\"\n\t\tif allAttrs {\n\t\t\tmsg += \", \" + AttrZone + \"[S]\"\n\t\t}\n\t\treturn fmt.Errorf(msg)\n\t}\n\treturn nil\n}", "func (cc *CompanyCreate) check() error {\n\tif _, ok := cc.mutation.CreatedAt(); !ok {\n\t\treturn &ValidationError{Name: \"created_at\", err: errors.New(`ent: missing required field \"created_at\"`)}\n\t}\n\tif _, ok := cc.mutation.UpdatedAt(); !ok {\n\t\treturn &ValidationError{Name: \"updated_at\", err: errors.New(`ent: missing required field \"updated_at\"`)}\n\t}\n\tif _, ok := cc.mutation.Name(); !ok {\n\t\treturn &ValidationError{Name: \"name\", err: errors.New(`ent: missing required field \"name\"`)}\n\t}\n\tif v, ok := cc.mutation.Name(); ok {\n\t\tif err := company.NameValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"name\", err: fmt.Errorf(`ent: validator failed for field \"name\": %w`, err)}\n\t\t}\n\t}\n\tif _, ok := cc.mutation.Overview(); !ok {\n\t\treturn &ValidationError{Name: \"overview\", err: errors.New(`ent: missing required field \"overview\"`)}\n\t}\n\tif v, ok := cc.mutation.Overview(); ok {\n\t\tif err := company.OverviewValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"overview\", err: fmt.Errorf(`ent: validator failed for field \"overview\": %w`, err)}\n\t\t}\n\t}\n\tif _, ok := cc.mutation.Website(); !ok {\n\t\treturn &ValidationError{Name: \"website\", err: errors.New(`ent: missing required field \"website\"`)}\n\t}\n\tif v, ok := cc.mutation.Website(); ok {\n\t\tif err := company.WebsiteValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"website\", err: fmt.Errorf(`ent: validator failed for field \"website\": %w`, err)}\n\t\t}\n\t}\n\tif _, ok := cc.mutation.LogoURL(); !ok {\n\t\treturn &ValidationError{Name: \"logo_url\", err: errors.New(`ent: missing required field \"logo_url\"`)}\n\t}\n\tif v, ok := cc.mutation.LogoURL(); ok {\n\t\tif err := company.LogoURLValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"logo_url\", err: fmt.Errorf(`ent: validator failed for field \"logo_url\": %w`, err)}\n\t\t}\n\t}\n\tif _, ok := cc.mutation.Size(); !ok {\n\t\treturn &ValidationError{Name: \"size\", err: errors.New(`ent: missing required field \"size\"`)}\n\t}\n\tif v, ok := cc.mutation.Size(); ok {\n\t\tif err := company.SizeValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"size\", err: fmt.Errorf(`ent: validator failed for field \"size\": %w`, err)}\n\t\t}\n\t}\n\tif _, ok := cc.mutation.FoundedAt(); !ok {\n\t\treturn &ValidationError{Name: \"founded_at\", err: errors.New(`ent: missing required field \"founded_at\"`)}\n\t}\n\tif v, ok := cc.mutation.FoundedAt(); ok {\n\t\tif err := company.FoundedAtValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"founded_at\", err: fmt.Errorf(`ent: validator failed for field \"founded_at\": %w`, err)}\n\t\t}\n\t}\n\treturn nil\n}", "func (m *ProviderAccountPreferences) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func ValidateGetAccountInternalResponseBody(body *GetAccountInternalResponseBody) (err error) {\n\tif body.Name == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"name\", \"body\"))\n\t}\n\tif body.ID == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"id\", \"body\"))\n\t}\n\tif body.Message == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"message\", \"body\"))\n\t}\n\tif body.Temporary == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"temporary\", \"body\"))\n\t}\n\tif body.Timeout == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"timeout\", \"body\"))\n\t}\n\tif body.Fault == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"fault\", \"body\"))\n\t}\n\treturn\n}", "func (o *Virtualserver) validate(dbRecord *common.DbRecord) (ok bool, err error) {\n\t////////////////////////////////////////////////////////////////////////////\n\t// Marshal data interface.\n\t////////////////////////////////////////////////////////////////////////////\n\tvar data virtualserver.Data\n\terr = shared.MarshalInterface(dbRecord.Data, &data)\n\tif err != nil {\n\t\treturn\n\t}\n\t////////////////////////////////////////////////////////////////////////////\n\t// Test required fields.\n\t////////////////////////////////////////////////////////////////////////////\n\tok = true\n\trequired := make(map[string]bool)\n\trequired[\"ProductCode\"] = false\n\trequired[\"IP\"] = false\n\trequired[\"Port\"] = false\n\trequired[\"LoadBalancerIP\"] = false\n\trequired[\"Name\"] = false\n\t////////////////////////////////////////////////////////////////////////////\n\tif data.ProductCode != 0 {\n\t\trequired[\"ProductCode\"] = true\n\t}\n\tif len(dbRecord.LoadBalancerIP) > 0 {\n\t\trequired[\"LoadBalancerIP\"] = true\n\t}\n\tif len(data.Ports) != 0 {\n\t\trequired[\"Port\"] = true\n\t}\n\tif data.IP != \"\" {\n\t\trequired[\"IP\"] = true\n\t}\n\tif data.Name != \"\" {\n\t\trequired[\"Name\"] = true\n\t}\n\tfor _, val := range required {\n\t\tif val == false {\n\t\t\tok = false\n\t\t}\n\t}\n\tif !ok {\n\t\terr = fmt.Errorf(\"missing required fields - %+v\", required)\n\t}\n\treturn\n}", "func (user *User) Validate(action string) map[string]string {\n\tvar errMessages = make(map[string]string)\n\tvar err error\n\n\tswitch strings.ToLower(action) {\n\tcase \"update\":\n\t\tif user.Email == \"\" {\n\t\t\terrMessages[\"email_required\"] = \"email required\"\n\t\t}\n\n\t\tif user.Email != \"\" {\n\t\t\tif err = checkmail.ValidateFormat(user.Email); err != nil {\n\t\t\t\terrMessages[\"invalid_email\"] = \"invalid email\"\n\t\t\t}\n\t\t}\n\tcase \"login\":\n\t\tif user.Password == \"\" {\n\t\t\terrMessages[\"password_required\"] = \"password is required\"\n\t\t}\n\n\t\tif user.Email == \"\" {\n\t\t\terrMessages[\"email_required\"] = \"email required\"\n\t\t}\n\n\t\tif user.Email != \"\" {\n\t\t\tif err = checkmail.ValidateFormat(user.Email); err != nil {\n\t\t\t\terrMessages[\"invalid_email\"] = \"invalid email\"\n\t\t\t}\n\t\t}\n\tcase \"forgotpassword\":\n\t\tif user.Email == \"\" {\n\t\t\terrMessages[\"email_required\"] = \"email required\"\n\t\t}\n\t\tif user.Email != \"\" {\n\t\t\tif err = checkmail.ValidateFormat(user.Email); err != nil {\n\t\t\t\terrMessages[\"invalid_email\"] = \"please provide a valid email\"\n\t\t\t}\n\t\t}\n\tdefault:\n\t\tif user.FirstName == \"\" {\n\t\t\terrMessages[\"firstname_required\"] = \"first name is required\"\n\t\t}\n\n\t\tif user.LastName == \"\" {\n\t\t\terrMessages[\"lastname_required\"] = \"last name is required\"\n\t\t}\n\n\t\tif user.Password == \"\" {\n\t\t\terrMessages[\"password_required\"] = \"password is required\"\n\t\t}\n\n\t\tif user.Password != \"\" && len(user.Password) < 6 {\n\t\t\terrMessages[\"invalid_password\"] = \"password should be at least 6 characters\"\n\t\t}\n\n\t\tif user.Email == \"\" {\n\t\t\terrMessages[\"email_required\"] = \"email is required\"\n\t\t}\n\n\t\tif user.Email != \"\" {\n\t\t\tif err = checkmail.ValidateFormat(user.Email); err != nil {\n\t\t\t\terrMessages[\"invalid_email\"] = \"please provide a valid email\"\n\t\t\t}\n\t\t}\n\t}\n\n\treturn errMessages\n}", "func (a *Application) Validate(tx *pop.Connection) (*validate.Errors, error) {\n\treturn validate.Validate(\n\t\t&validators.StringIsPresent{Field: a.FirstName, Name: \"FirstName\"},\n\t\t&validators.StringIsPresent{Field: a.LastName, Name: \"LastName\"},\n\t), nil\n}", "func (uuo *UserUpdateOne) check() error {\n\tif v, ok := uuo.mutation.Username(); ok {\n\t\tif err := user.UsernameValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"username\", err: fmt.Errorf(\"ent: validator failed for field \\\"username\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.Fullname(); ok {\n\t\tif err := user.FullnameValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"fullname\", err: fmt.Errorf(\"ent: validator failed for field \\\"fullname\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.Password(); ok {\n\t\tif err := user.PasswordValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"password\", err: fmt.Errorf(\"ent: validator failed for field \\\"password\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.Email(); ok {\n\t\tif err := user.EmailValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"email\", err: fmt.Errorf(\"ent: validator failed for field \\\"email\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.Phone(); ok {\n\t\tif err := user.PhoneValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"phone\", err: fmt.Errorf(\"ent: validator failed for field \\\"phone\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.Bio(); ok {\n\t\tif err := user.BioValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"bio\", err: fmt.Errorf(\"ent: validator failed for field \\\"bio\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.Intro(); ok {\n\t\tif err := user.IntroValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"intro\", err: fmt.Errorf(\"ent: validator failed for field \\\"intro\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.GithubProfile(); ok {\n\t\tif err := user.GithubProfileValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"github_profile\", err: fmt.Errorf(\"ent: validator failed for field \\\"github_profile\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.ProfilePictureURL(); ok {\n\t\tif err := user.ProfilePictureURLValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"profile_picture_url\", err: fmt.Errorf(\"ent: validator failed for field \\\"profile_picture_url\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.Status(); ok {\n\t\tif err := user.StatusValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"status\", err: fmt.Errorf(\"ent: validator failed for field \\\"status\\\": %w\", err)}\n\t\t}\n\t}\n\treturn nil\n}", "func (r updateReq) Validate() error {\n\terr := r.addReq.Validate()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif r.ServiceAccountID != r.Body.ID {\n\t\treturn fmt.Errorf(\"service account ID mismatch, you requested to update ServiceAccount = %s but body contains ServiceAccount = %s\", r.ServiceAccountID, r.Body.ID)\n\t}\n\treturn nil\n}", "func (bu *BankdetailUpdate) check() error {\n\tif v, ok := bu.mutation.BankAccountNo(); ok {\n\t\tif err := bankdetail.BankAccountNoValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"Bank_AccountNo\", err: fmt.Errorf(\"ent: validator failed for field \\\"Bank_AccountNo\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := bu.mutation.BankName(); ok {\n\t\tif err := bankdetail.BankNameValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"Bank_Name\", err: fmt.Errorf(\"ent: validator failed for field \\\"Bank_Name\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := bu.mutation.BankAccountName(); ok {\n\t\tif err := bankdetail.BankAccountNameValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"Bank_AccountName\", err: fmt.Errorf(\"ent: validator failed for field \\\"Bank_AccountName\\\": %w\", err)}\n\t\t}\n\t}\n\treturn nil\n}", "func (rc *RentalCreate) check() error {\n\tif _, ok := rc.mutation.Date(); !ok {\n\t\treturn &ValidationError{Name: \"date\", err: errors.New(`ent: missing required field \"Rental.date\"`)}\n\t}\n\tif _, ok := rc.mutation.UserID(); !ok {\n\t\treturn &ValidationError{Name: \"user_id\", err: errors.New(`ent: missing required field \"Rental.user_id\"`)}\n\t}\n\tif _, ok := rc.mutation.CarID(); !ok {\n\t\treturn &ValidationError{Name: \"car_id\", err: errors.New(`ent: missing required field \"Rental.car_id\"`)}\n\t}\n\tif _, ok := rc.mutation.UserID(); !ok {\n\t\treturn &ValidationError{Name: \"user\", err: errors.New(`ent: missing required edge \"Rental.user\"`)}\n\t}\n\tif _, ok := rc.mutation.CarID(); !ok {\n\t\treturn &ValidationError{Name: \"car\", err: errors.New(`ent: missing required edge \"Rental.car\"`)}\n\t}\n\treturn nil\n}", "func (m *ContactAccountAttributesAccountWith) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (m *Customer) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateAutoCollection(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateBalances(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateBillingAddress(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateBillingDateMode(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateBillingDayOfWeek(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateBillingDayOfWeekMode(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateContacts(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateEntityCode(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateFraudFlag(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validatePaymentMethod(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateReferralUrls(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateTaxability(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (m *OBWriteInternational3DataInitiationDebtorAccount) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateIdentification(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateName(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateSchemeName(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateSecondaryIdentification(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (m *ClusterVcenterAccount) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (e *RetrieveBalance) Validate(\n\tr *http.Request,\n) error {\n\tctx := r.Context()\n\n\t// Validate id.\n\tid, owner, token, err := ValidateID(ctx, pat.Param(r, \"balance\"))\n\tif err != nil {\n\t\treturn errors.Trace(err)\n\t}\n\te.ID = *id\n\te.Token = *token\n\te.Owner = *owner\n\n\treturn nil\n}", "func (u *User) Validate() ([]app.Invalid, error) {\n\tvar inv []app.Invalid\n\n\tif u.UserType == 0 {\n\t\tinv = append(inv, app.Invalid{Fld: \"UserType\", Err: \"The value of UserType cannot be 0.\"})\n\t}\n\n\tif u.FirstName == \"\" {\n\t\tinv = append(inv, app.Invalid{Fld: \"FirstName\", Err: \"A value of FirstName cannot be empty.\"})\n\t}\n\n\tif u.LastName == \"\" {\n\t\tinv = append(inv, app.Invalid{Fld: \"LastName\", Err: \"A value of LastName cannot be empty.\"})\n\t}\n\n\tif u.Email == \"\" {\n\t\tinv = append(inv, app.Invalid{Fld: \"Email\", Err: \"A value of Email cannot be empty.\"})\n\t}\n\n\tif u.Company == \"\" {\n\t\tinv = append(inv, app.Invalid{Fld: \"Company\", Err: \"A value of Company cannot be empty.\"})\n\t}\n\n\tif len(u.Addresses) == 0 {\n\t\tinv = append(inv, app.Invalid{Fld: \"Addresses\", Err: \"There must be at least one address.\"})\n\t} else {\n\t\tfor _, ua := range u.Addresses {\n\t\t\tif va, err := ua.Validate(); err != nil {\n\t\t\t\tinv = append(inv, va...)\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(inv) > 0 {\n\t\treturn inv, errors.New(\"Validation failures identified\")\n\t}\n\n\treturn nil, nil\n}", "func ValidateGetAccountResponseBody(body *GetAccountResponseBody) (err error) {\n\tif body.Account != nil {\n\t\tif err2 := ValidateRelayerAccountResponseBody(body.Account); err2 != nil {\n\t\t\terr = goa.MergeErrors(err, err2)\n\t\t}\n\t}\n\treturn\n}", "func (p *Pass) FieldsValid() bool {\n\tfmt.Printf(\"validating: \")\n\tvalid := true\n\tfor k, v := range *p {\n\t\tfmt.Printf(\"%v...\", k)\n\t\tv := isFieldValid(k, v)\n\t\tvalid = valid && v\n\t\tif v {\n\t\t\tfmt.Printf(\"VALID \")\n\t\t} else {\n\t\t\tfmt.Printf(\"INVALID \")\n\t\t}\n\t}\n\n\tfmt.Println(\"\")\n\treturn valid\n}", "func (t AuthToken) Validate() error {\n\t// Holds names of empty fields\n\tempty := []string{}\n\n\t// Check user id\n\tif len(t.UserID) == 0 {\n\t\tempty = append(empty, \"UserID\")\n\t}\n\n\t// Check device id\n\tif len(t.DeviceID) == 0 {\n\t\tempty = append(empty, \"DeviceID\")\n\t}\n\n\t// Check if any empty fields\n\tif len(empty) != 0 {\n\t\treturn fmt.Errorf(\"the following fields were empty: %s\",\n\t\t\tStrings.join(empty))\n\t}\n\n\t// All good\n\treturn nil\n}", "func (p *Passport) ValidateStrict(input string) {\r\n\tbyr := regexp.MustCompile(`byr:(\\d*)`)\r\n\tif byr.MatchString(input) {\r\n\t\tmatches := byr.FindStringSubmatch(input)\r\n\t\tf, err := NewYearField(matches[1], byrMin, byrMax)\r\n\t\tif err == nil {\r\n\t\t\tp.byr = f\r\n\t\t}\r\n\t}\r\n\r\n\tiyr := regexp.MustCompile(`iyr:(\\d*)`)\r\n\tif iyr.MatchString(input) {\r\n\t\tmatches := iyr.FindStringSubmatch(input)\r\n\t\tf, err := NewYearField(matches[1], iyrMin, iyrMax)\r\n\t\tif err == nil {\r\n\t\t\tp.iyr = f\r\n\t\t}\r\n\t}\r\n\r\n\teyr := regexp.MustCompile(`eyr:(\\d*)`)\r\n\tif eyr.MatchString(input) {\r\n\t\tmatches := eyr.FindStringSubmatch(input)\r\n\t\tf, err := NewYearField(matches[1], eyrMin, eyrMax)\r\n\t\tif err == nil {\r\n\t\t\tp.eyr = f\r\n\t\t}\r\n\t}\r\n\r\n\thgt := regexp.MustCompile(`hgt:(\\d*)(cm|in)?`)\r\n\tif hgt.MatchString(input) {\r\n\t\tmatches := hgt.FindStringSubmatch(input)\r\n\t\tf, err := NewHeightField(matches[1], matches[2])\r\n\t\tif err == nil {\r\n\t\t\tp.hgt = f\r\n\t\t}\r\n\t}\r\n\r\n\thcl := regexp.MustCompile(`hcl:(#[a-f0-9]*)`)\r\n\tif hcl.MatchString(input) {\r\n\t\tmatches := hcl.FindStringSubmatch(input)\r\n\t\tf, err := NewTextField(matches[1], hclExp)\r\n\t\tif err == nil {\r\n\t\t\tp.hcl = f\r\n\t\t}\r\n\t}\r\n\r\n\tecl := regexp.MustCompile(`ecl:(\\w*)`)\r\n\tif ecl.MatchString(input) {\r\n\t\tmatches := ecl.FindStringSubmatch(input)\r\n\t\tf, err := NewTextField(matches[1], eclExp)\r\n\t\tif err == nil {\r\n\t\t\tp.ecl = f\r\n\t\t}\r\n\t}\r\n\r\n\tpid := regexp.MustCompile(`pid:(\\d*)`)\r\n\tif pid.MatchString(input) {\r\n\t\tmatches := pid.FindStringSubmatch(input)\r\n\t\tf, err := NewTextField(matches[1], pidExp)\r\n\t\tif err == nil {\r\n\t\t\tp.pid = f\r\n\t\t}\r\n\t}\r\n}", "func (u *User) Validate(tx *pop.Connection) (*validate.Errors, error) {\n\treturn validate.Validate(\n\t\t&validators.StringIsPresent{Field: u.Email, Name: \"Email\"},\n\t\t&validators.StringIsPresent{Field: u.FirstName, Name: \"FirstName\"},\n\t\t&validators.StringIsPresent{Field: u.LastName, Name: \"LastName\"},\n\t\t&validators.StringIsPresent{Field: u.Nickname, Name: \"Nickname\"},\n\t\t&validators.UUIDIsPresent{Field: u.UUID, Name: \"UUID\"},\n\t\t&NullsStringIsURL{Field: u.AuthPhotoURL, Name: \"AuthPhotoURL\"},\n\t\t&domain.StringIsVisible{Field: u.Nickname, Name: \"Nickname\"},\n\t), nil\n}", "func (r *registrationRequest) isValid() error {\n\n\t//check recaptcha\n\trc := recaptcha.R{Secret: config.CaptchaSecretKey}\n\tif !rc.VerifyResponse(r.Captcha) {\n\t\treturn fmt.Errorf(\"ReCaptcha error: %s\", strings.Join(rc.LastError()[1:], \", \"))\n\t}\n\n\t// check if any of this is empty\n\tif r.Email == \"\" || r.Password == \"\" || r.PasswordConfirmation == \"\" ||\n\t\tr.First == \"\" || r.Last == \"\" {\n\t\treturn fmt.Errorf(\"%s\\n\", \"You entered incomplete data. First and last name, email and \"+\n\t\t\t\"password are mandatory fields.\")\n\t}\n\n\t// check if the password match and that the length is at least 8 chars\n\treturn passwordsAreValid(r.Password, r.PasswordConfirmation)\n}", "func (i *infoOptions) validate() error {\n\t// date-field required\n\tif len(i.DateField) == 0 {\n\t\treturn errors.New(`date-field required`)\n\t}\n\n\t// date-field index value if sep is present\n\tif len(i.Sep) > 0 {\n\t\t// attempt to convert DateField to int\n\t\tvar err error\n\t\t_, err = strconv.Atoi(i.DateField)\n\t\tif err != nil {\n\t\t\treturn errors.New(`date-field must be an integer when using a csv field separator`)\n\t\t}\n\t}\n\n\t// dest-template required\n\tif i.DestTemplate == \"\" {\n\t\treturn errors.New(`dest-template required`)\n\t}\n\n\treturn nil\n}", "func (p paymentJson) Validate() error {\n\tif p.AccountId == \"\" {\n\t\treturn errors.New(\"missing customer id\")\n\t}\n\tif p.Amount == 0 {\n\t\treturn errors.New(\"missing amount\")\n\t}\n\treturn nil\n}", "func Validation(a User) error {\n\tfmt.Println(\"user :: \", a)\n\tvar rxEmail = regexp.MustCompile(\"^[a-zA-Z0-9.!#$%&'*+\\\\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$\")\n\tswitch {\n\tcase len(strings.TrimSpace(a.Password)) == 0:\n\t\treturn ErrPasswordInvalid\n\tcase len(strings.TrimSpace(a.Email)) == 0 || !rxEmail.MatchString(a.Email):\n\t\treturn ErrEmailInvalid\n\tdefault:\n\t\treturn nil\n\t}\n}", "func (account *DatabaseAccount) createValidations() []func() (admission.Warnings, error) {\n\treturn []func() (admission.Warnings, error){account.validateResourceReferences, account.validateSecretDestinations}\n}" ]
[ "0.6950377", "0.6660194", "0.6604518", "0.660115", "0.6589453", "0.6474401", "0.6469365", "0.6463922", "0.64215875", "0.63889915", "0.6362919", "0.63358384", "0.6252108", "0.62329525", "0.6229978", "0.61784095", "0.61675555", "0.61494285", "0.6107046", "0.6084981", "0.6062506", "0.6018709", "0.59835136", "0.5935781", "0.59250987", "0.5920425", "0.5918846", "0.5906061", "0.58879864", "0.5874278", "0.5862281", "0.5844713", "0.5843288", "0.58394945", "0.58318245", "0.58267343", "0.5805197", "0.5782027", "0.577867", "0.5762948", "0.57397187", "0.57109004", "0.567482", "0.5670878", "0.5664908", "0.5659827", "0.56587", "0.5648205", "0.5621579", "0.55948484", "0.55917954", "0.55910474", "0.5587459", "0.55859625", "0.55767894", "0.5549079", "0.5528815", "0.5525437", "0.5523396", "0.551239", "0.55084354", "0.55050844", "0.54942113", "0.54916596", "0.5487635", "0.5478365", "0.54646176", "0.54524314", "0.54512787", "0.5443251", "0.54331243", "0.5430431", "0.54267573", "0.54245096", "0.5422896", "0.54207206", "0.54192007", "0.54148257", "0.540501", "0.5398671", "0.5397307", "0.5396947", "0.5394909", "0.53946984", "0.53905594", "0.53878796", "0.5384738", "0.5380616", "0.53800863", "0.53762895", "0.5367286", "0.5357383", "0.5353596", "0.5347578", "0.5342094", "0.5340789", "0.53367335", "0.5334526", "0.5331692", "0.5330748", "0.532834" ]
0.0
-1
MarshalYAML returns the YAML representation of a ContinuousVestingAccount.
func (cva ContinuousVestingAccount) MarshalYAML() (interface{}, error) { accAddr, err := sdk.AccAddressFromBech32(cva.Address) if err != nil { return nil, err } out := vestingAccountYAML{ Address: accAddr, AccountNumber: cva.AccountNumber, PubKey: getPKString(cva), Sequence: cva.Sequence, OriginalVesting: cva.OriginalVesting, DelegatedFree: cva.DelegatedFree, DelegatedVesting: cva.DelegatedVesting, EndTime: cva.EndTime, StartTime: cva.StartTime, } return marshalYaml(out) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (va ClawbackVestingAccount) MarshalYAML() (interface{}, error) {\n\taccAddr, err := sdk.AccAddressFromBech32(va.Address)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tout := vestingAccountYAML{\n\t\tAddress: accAddr,\n\t\tAccountNumber: va.AccountNumber,\n\t\tPubKey: getPKString(va),\n\t\tSequence: va.Sequence,\n\t\tOriginalVesting: va.OriginalVesting,\n\t\tDelegatedFree: va.DelegatedFree,\n\t\tDelegatedVesting: va.DelegatedVesting,\n\t\tEndTime: va.EndTime,\n\t\tStartTime: va.StartTime,\n\t\tVestingPeriods: va.VestingPeriods,\n\t}\n\treturn marshalYaml(out)\n}", "func (bva BaseVestingAccount) MarshalYAML() (interface{}, error) {\n\taccAddr, err := sdk.AccAddressFromBech32(bva.Address)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tout := vestingAccountYAML{\n\t\tAddress: accAddr,\n\t\tAccountNumber: bva.AccountNumber,\n\t\tPubKey: getPKString(bva),\n\t\tSequence: bva.Sequence,\n\t\tOriginalVesting: bva.OriginalVesting,\n\t\tDelegatedFree: bva.DelegatedFree,\n\t\tDelegatedVesting: bva.DelegatedVesting,\n\t\tEndTime: bva.EndTime,\n\t}\n\treturn marshalYaml(out)\n}", "func (pva PeriodicVestingAccount) MarshalYAML() (interface{}, error) {\n\taccAddr, err := sdk.AccAddressFromBech32(pva.Address)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tout := vestingAccountYAML{\n\t\tAddress: accAddr,\n\t\tAccountNumber: pva.AccountNumber,\n\t\tPubKey: getPKString(pva),\n\t\tSequence: pva.Sequence,\n\t\tOriginalVesting: pva.OriginalVesting,\n\t\tDelegatedFree: pva.DelegatedFree,\n\t\tDelegatedVesting: pva.DelegatedVesting,\n\t\tEndTime: pva.EndTime,\n\t\tStartTime: pva.StartTime,\n\t\tVestingPeriods: pva.VestingPeriods,\n\t}\n\treturn marshalYaml(out)\n}", "func (vva ValidatorVestingAccount) MarshalYAML() (interface{}, error) {\n\tvar bs []byte\n\tvar err error\n\tvar pubkey string\n\n\tif vva.PubKey != nil {\n\t\tpubkey, err = sdk.Bech32ifyAccPub(vva.PubKey)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tbs, err = yaml.Marshal(struct {\n\t\tAddress sdk.AccAddress\n\t\tCoins sdk.Coins\n\t\tPubKey string\n\t\tAccountNumber uint64\n\t\tSequence uint64\n\t\tOriginalVesting sdk.Coins\n\t\tDelegatedFree sdk.Coins\n\t\tDelegatedVesting sdk.Coins\n\t\tEndTime int64\n\t\tStartTime int64\n\t\tVestingPeriods vestingtypes.Periods\n\t\tValidatorAddress sdk.ConsAddress\n\t\tReturnAddress sdk.AccAddress\n\t\tSigningThreshold int64\n\t\tCurrentPeriodProgress CurrentPeriodProgress\n\t\tVestingPeriodProgress []VestingProgress\n\t\tDebtAfterFailedVesting sdk.Coins\n\t}{\n\t\tAddress: vva.Address,\n\t\tCoins: vva.Coins,\n\t\tPubKey: pubkey,\n\t\tAccountNumber: vva.AccountNumber,\n\t\tSequence: vva.Sequence,\n\t\tOriginalVesting: vva.OriginalVesting,\n\t\tDelegatedFree: vva.DelegatedFree,\n\t\tDelegatedVesting: vva.DelegatedVesting,\n\t\tEndTime: vva.EndTime,\n\t\tStartTime: vva.StartTime,\n\t\tVestingPeriods: vva.VestingPeriods,\n\t\tValidatorAddress: vva.ValidatorAddress,\n\t\tReturnAddress: vva.ReturnAddress,\n\t\tSigningThreshold: vva.SigningThreshold,\n\t\tCurrentPeriodProgress: vva.CurrentPeriodProgress,\n\t\tVestingPeriodProgress: vva.VestingPeriodProgress,\n\t\tDebtAfterFailedVesting: vva.DebtAfterFailedVesting,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn string(bs), err\n}", "func (r RetryConfig) MarshalYAML() (interface{}, error) {\n\tdummy := dummyRetryConfig{\n\t\tOutput: r.Output,\n\t\tConfig: r.Config,\n\t}\n\tif r.Output == nil {\n\t\tdummy.Output = struct{}{}\n\t}\n\treturn dummy, nil\n}", "func (o *OAuthFlow) MarshalYAML() (interface{}, error) {\n\tnb := high.NewNodeBuilder(o, o.low)\n\treturn nb.Render(), nil\n}", "func (i Instance) MarshalYAML() (interface{}, error) {\n\treturn i.Vars, nil\n}", "func (v Validator) MarshalYAML() (interface{}, error) {\n\tbs, err := yaml.Marshal(struct {\n\t\tStatus sdk.BondStatus\n\t\tJailed bool\n\t\tUnbondingHeight int64\n\t\tConsPubKey string\n\t\tOperatorAddress sdk.ValAddress\n\t\tTokens sdk.Int\n\t\tDelegatorShares sdk.Dec\n\t\tDescription Description\n\t\tUnbondingCompletionTime time.Time\n\t\tCommission Commission\n\t\tMinSelfDelegation sdk.Dec\n\t}{\n\t\tOperatorAddress: v.OperatorAddress,\n\t\tConsPubKey: MustBech32ifyConsPub(v.ConsPubKey),\n\t\tJailed: v.Jailed,\n\t\tStatus: v.Status,\n\t\tTokens: v.Tokens,\n\t\tDelegatorShares: v.DelegatorShares,\n\t\tDescription: v.Description,\n\t\tUnbondingHeight: v.UnbondingHeight,\n\t\tUnbondingCompletionTime: v.UnbondingCompletionTime,\n\t\tCommission: v.Commission,\n\t\tMinSelfDelegation: v.MinSelfDelegation,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn string(bs), nil\n}", "func (b *Backend) MarshalYAML() (interface{}, error) {\n\tb.mu.RLock()\n\tdefer b.mu.RUnlock()\n\n\tpayload := struct {\n\t\tAddress string\n\t\tDisabledUntil time.Time `yaml:\"disabledUntil\"`\n\t\tForcePromotionsAfter time.Duration `yaml:\"forcePromotionsAfter\"`\n\t\tLatency time.Duration `yaml:\"latency\"`\n\t\tMaxConnections int `yaml:\"maxConnections\"`\n\t\tTier int `yaml:\"tier\"`\n\t}{\n\t\tAddress: b.addr.String(),\n\t\tDisabledUntil: b.mu.disabledUntil,\n\t\tForcePromotionsAfter: b.mu.forcePromotionAfter,\n\t\tLatency: b.mu.lastLatency,\n\t\tMaxConnections: b.mu.maxConnections,\n\t\tTier: b.mu.tier,\n\t}\n\treturn payload, nil\n}", "func (key PrivateKey) MarshalYAML() (interface{}, error) {\n\treturn key.String(), nil\n}", "func (p *Parameter) MarshalYAML() (interface{}, error) {\n\tnb := high.NewNodeBuilder(p, p.low)\n\treturn nb.Render(), nil\n}", "func (c *Components) MarshalYAML() (interface{}, error) {\n\tnb := high.NewNodeBuilder(c, c.low)\n\treturn nb.Render(), nil\n}", "func (key PublicKey) MarshalYAML() (interface{}, error) {\n\treturn key.String(), nil\n}", "func (i UserGroupAccess) MarshalYAML() (interface{}, error) {\n\treturn i.String(), nil\n}", "func (a ApprovalStrategy) MarshalYAML() (interface{}, error) {\n\treturn approvalStrategyToString[a], nil\n\t//buffer := bytes.NewBufferString(`\"`)\n\t//buffer.WriteString(approvalStrategyToString[*s])\n\t//buffer.WriteString(`\"`)\n\t//return buffer.Bytes(), nil\n}", "func (export WebAuthnDeviceExport) MarshalYAML() (any, error) {\n\treturn export.ToData(), nil\n}", "func (i ChannelName) MarshalYAML() (interface{}, error) {\n\treturn i.String(), nil\n}", "func (r ReadUntilConfig) MarshalYAML() (interface{}, error) {\n\tdummy := dummyReadUntilConfig{\n\t\tInput: r.Input,\n\t\tRestart: r.Restart,\n\t\tCheck: r.Check,\n\t}\n\tif r.Input == nil {\n\t\tdummy.Input = struct{}{}\n\t}\n\treturn dummy, nil\n}", "func (d *WebAuthnDevice) MarshalYAML() (any, error) {\n\treturn d.ToData(), nil\n}", "func (r OAuthFlow) MarshalYAML() (interface{}, error) {\n\tobj := make(map[string]interface{})\n\n\tobj[\"authorizationUrl\"] = r.AuthorizationURL\n\n\tobj[\"tokenUrl\"] = r.TokenURL\n\n\tif r.RefreshURL != \"\" {\n\t\tobj[\"refreshUrl\"] = r.RefreshURL\n\t}\n\n\tobj[\"scopes\"] = r.Scopes\n\n\tfor key, val := range r.Extensions {\n\t\tobj[key] = val\n\t}\n\n\treturn obj, nil\n}", "func (d *Discriminator) MarshalYAML() (interface{}, error) {\n\tnb := low2.NewNodeBuilder(d, d.low)\n\treturn nb.Render(), nil\n}", "func (d Rate) MarshalYAML() (interface{}, error) {\n\treturn d.String(), nil\n}", "func (z Z) MarshalYAML() (interface{}, error) {\n\ttype Z struct {\n\t\tS string `json:\"s\"`\n\t\tI int32 `json:\"iVal\"`\n\t\tHash string\n\t\tMultiplyIByTwo int64 `json:\"multipliedByTwo\"`\n\t}\n\tvar enc Z\n\tenc.S = z.S\n\tenc.I = z.I\n\tenc.Hash = z.Hash()\n\tenc.MultiplyIByTwo = int64(z.MultiplyIByTwo())\n\treturn &enc, nil\n}", "func (v *Int8) MarshalYAML() (interface{}, error) {\n\tif v.IsAssigned {\n\t\treturn v.Val, nil\n\t}\n\treturn nil, nil\n}", "func (ec EllipticCurve) MarshalYAML() (interface{}, error) {\n\treturn ec.String(), nil\n}", "func (s GitEvent) MarshalYAML() (interface{}, error) {\n\treturn toString[s], nil\n}", "func (p Params) MarshalYAML() (interface{}, error) {\n\treturn p.String(), nil\n}", "func (b ByteCount) MarshalYAML() (interface{}, error) {\n\treturn uint64(b), nil\n}", "func (v *VersionInfo) MarshalYAML() (interface{}, error) {\n\n\treturn &struct {\n\t\tSemVer string `yaml:\"semver\"`\n\t\tShaLong string `yaml:\"shaLong\"`\n\t\tBuildTimestamp int64 `yaml:\"buildTimestamp\"`\n\t\tBranch string `yaml:\"branch\"`\n\t\tArch string `yaml:\"arch\"`\n\t}{\n\t\tSemVer: v.SemVer,\n\t\tShaLong: v.ShaLong,\n\t\tBuildTimestamp: v.BuildTimestamp.Unix(),\n\t\tBranch: v.Branch,\n\t\tArch: v.Arch,\n\t}, nil\n}", "func (bc *ByteCount) MarshalYAML() (interface{}, error) {\n\treturn uint64(AtomicLoadByteCount(bc)), nil\n}", "func (n Nil) MarshalYAML() (interface{}, error) {\n\treturn nil, nil\n}", "func (m MixinDeclaration) MarshalYAML() (interface{}, error) {\n\tif m.Config == nil {\n\t\treturn m.Name, nil\n\t}\n\n\traw := map[string]interface{}{\n\t\tm.Name: m.Config,\n\t}\n\treturn raw, nil\n}", "func Marshal(v interface{}) ([]byte, error) {\n\tvar buf bytes.Buffer\n\tenc := yaml.NewEncoder(&buf)\n\tenc.SetIndent(2)\n\terr := enc.Encode(v)\n\treturn buf.Bytes(), err\n}", "func (r Discriminator) MarshalYAML() (interface{}, error) {\n\tobj := make(map[string]interface{})\n\n\tobj[\"propertyName\"] = r.PropertyName\n\n\tif len(r.Mapping) > 0 {\n\t\tobj[\"mapping\"] = r.Mapping\n\t}\n\n\treturn obj, nil\n}", "func (f Fixed8) MarshalYAML() (interface{}, error) {\n\treturn f.String(), nil\n}", "func (m *BootstrapMode) MarshalYAML() (interface{}, error) {\n\treturn m.String(), nil\n}", "func (ss StdSignature) MarshalYAML() (interface{}, error) {\n\tpk := \"\"\n\tif ss.PubKey != nil {\n\t\tpk = ss.PubKey.String()\n\t}\n\n\tbz, err := yaml.Marshal(struct {\n\t\tPubKey string `json:\"pub_key\"`\n\t\tSignature string `json:\"signature\"`\n\t}{\n\t\tpk,\n\t\tfmt.Sprintf(\"%X\", ss.Signature),\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn string(bz), err\n}", "func (d LegacyDec) MarshalYAML() (interface{}, error) {\n\treturn d.String(), nil\n}", "func (s Secret) MarshalYAML() (interface{}, error) {\n\tif s != \"\" {\n\t\treturn \"<secret>\", nil\n\t}\n\treturn nil, nil\n}", "func (s Secret) MarshalYAML() (interface{}, error) {\n\tif s != \"\" {\n\t\treturn \"<secret>\", nil\n\t}\n\treturn nil, nil\n}", "func (op OpRetain) MarshalYAML() (interface{}, error) {\n\treturn op.Fields, nil\n}", "func (d *DefaultOptions) MarshalYAML() (interface{}, error) {\n\treturn util.MarshalYAMLWithDescriptions(d)\n}", "func (i Int) MarshalYAML() (interface{}, error) {\n\tif !i.IsPresent() {\n\t\treturn nil, nil\n\t}\n\treturn i.value, nil\n}", "func (cp *CertPool) MarshalYAML() (interface{}, error) {\n\treturn cp.Files, nil\n}", "func (schema SchemaType) MarshalYAML() (interface{}, error) {\n\treturn schema.String(), nil\n}", "func (i UOM) MarshalYAML() (interface{}, error) {\n\treturn i.String(), nil\n}", "func (v *Uint16) MarshalYAML() (interface{}, error) {\n\tif v.IsAssigned {\n\t\treturn v.Val, nil\n\t}\n\treturn nil, nil\n}", "func (ep Endpoint) MarshalYAML() (interface{}, error) {\n\ts, err := ep.toString()\n\treturn s, err\n}", "func (d Document) MarshalYAML() (interface{}, error) {\n\treturn d.raw, nil\n}", "func (r *Regexp) MarshalYAML() (interface{}, error) {\n\treturn r.String(), nil\n}", "func (op OpFlatten) MarshalYAML() (interface{}, error) {\n\treturn op.Field.String(), nil\n}", "func (i Interface) MarshalYAML() (interface{}, error) {\n\treturn i.String(), nil\n}", "func (re Regexp) MarshalYAML() (interface{}, error) {\n\tif re.original != \"\" {\n\t\treturn re.original, nil\n\t}\n\treturn nil, nil\n}", "func (re Regexp) MarshalYAML() (interface{}, error) {\n\tif re.original != \"\" {\n\t\treturn re.original, nil\n\t}\n\treturn nil, nil\n}", "func (f BodyField) MarshalYAML() (interface{}, error) {\n\treturn toJSONDot(f), nil\n}", "func (o *OpenAPI3SchemaExtension) MarshalYAML() (interface{}, error) {\n\treturn util.MarshalYAMLWithDescriptions(o)\n}", "func (c CompressionType) MarshalYAML() (interface{}, error) {\n\treturn compressionTypeID[c], nil\n}", "func (d Duration) MarshalYAML() (interface{}, error) {\n\treturn d.String(), nil\n}", "func (d Duration) MarshalYAML() (interface{}, error) {\n\treturn d.Duration.String(), nil\n}", "func (m OrderedMap[K, V]) MarshalYAML() ([]byte, error) {\n\tvar s yaml.MapSlice\n\tfor _, item := range m.ToSlice() {\n\t\ts = append(s, yaml.MapItem{\n\t\t\tKey: item.Key,\n\t\t\tValue: item.Value,\n\t\t})\n\t}\n\treturn yaml.Marshal(s)\n}", "func (f Flag) MarshalYAML() (interface{}, error) {\n\treturn f.Name, nil\n}", "func (d DurationMillis) MarshalYAML() (interface{}, error) {\n\tif !d.IsPresent() {\n\t\treturn nil, nil\n\t}\n\treturn int(d.value / time.Millisecond), nil\n}", "func (o *OpenAPI3PathExtension) MarshalYAML() (interface{}, error) {\n\treturn util.MarshalYAMLWithDescriptions(o)\n}", "func MarshalToYaml(obj runtime.Object, gv schema.GroupVersion) ([]byte, error) {\n\treturn MarshalToYamlForCodecs(obj, gv, clientsetscheme.Codecs)\n}", "func (s SensitiveString) MarshalYAML() (interface{}, error) {\n\treturn s.String(), nil\n}", "func (b Bool) MarshalYAML() (interface{}, error) {\n\tif !b.IsPresent() {\n\t\treturn nil, nil\n\t}\n\treturn b.value, nil\n}", "func MarshalYAML(v interface{}, extensions map[string]interface{}) (interface{}, error) {\n\tif len(extensions) == 0 {\n\t\treturn v, nil\n\t}\n\tmarshaled, err := yaml.Marshal(v)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar unmarshaled map[string]interface{}\n\tif err := yaml.Unmarshal(marshaled, &unmarshaled); err != nil {\n\t\treturn nil, err\n\t}\n\tfor k, v := range extensions {\n\t\tunmarshaled[k] = v\n\t}\n\treturn unmarshaled, nil\n}", "func (o *OpenAPI3Options) MarshalYAML() (interface{}, error) {\n\treturn util.MarshalYAMLWithDescriptions(o)\n}", "func (k *Kluster) YAML() ([]byte, error) {\n\treturn yaml.Marshal(k)\n}", "func (o *OpenAPI3ResponseExtension) MarshalYAML() (interface{}, error) {\n\treturn util.MarshalYAMLWithDescriptions(o)\n}", "func (d DurationMinutes) MarshalYAML() (interface{}, error) {\n\tif !d.IsPresent() {\n\t\treturn nil, nil\n\t}\n\treturn int(d.value / time.Minute), nil\n}", "func (date Date) MarshalYAML() (interface{}, error) {\n\tvar d = string(date)\n\tif err := checkDateFormat(d); err != nil {\n\t\treturn nil, err\n\t}\n\treturn d, nil\n}", "func (r ParseKind) MarshalYAML() ([]byte, error) {\n\tif s, ok := interface{}(r).(fmt.Stringer); ok {\n\t\treturn yaml.Marshal(s.String())\n\t}\n\ts, ok := _ParseKindValueToName[r]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"invalid ParseKind: %d\", r)\n\t}\n\treturn yaml.Marshal(s)\n}", "func (o *Output) MarshalYAML() (interface{}, error) {\n\tif o.ShowValue {\n\t\treturn withvalue(*o), nil\n\t}\n\to.Value = nil // explicitly make empty\n\to.Sensitive = false // explicitly make empty\n\treturn *o, nil\n}", "func (c Configuration) YAML() ([]byte, error) {\n\treturn yaml.Marshal(c)\n}", "func (t TimeUnixSeconds) MarshalYAML() (interface{}, error) {\n\tif !t.IsPresent() {\n\t\treturn nil, nil\n\t}\n\treturn t.value.Unix(), nil\n}", "func (o Op) MarshalYAML() (interface{}, error) {\n\treturn map[string]interface{}{\n\t\to.Type(): o.OpApplier,\n\t}, nil\n}", "func (c *Config) YAML() ([]byte, error) {\n\treturn yaml.Marshal(c)\n}", "func MarshalMetricsYAML(metrics pmetric.Metrics) ([]byte, error) {\n\tunmarshaler := &pmetric.JSONMarshaler{}\n\tfileBytes, err := unmarshaler.MarshalMetrics(metrics)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar jsonVal map[string]interface{}\n\tif err = json.Unmarshal(fileBytes, &jsonVal); err != nil {\n\t\treturn nil, err\n\t}\n\tb := &bytes.Buffer{}\n\tenc := yaml.NewEncoder(b)\n\tenc.SetIndent(2)\n\tif err := enc.Encode(jsonVal); err != nil {\n\t\treturn nil, err\n\t}\n\treturn b.Bytes(), nil\n}", "func (c *Configmap) AsYAML() []byte {\n\tresult, err := yaml.Marshal(*c)\n\tif err != nil {\n\t\tlog.Printf(\"error marshaling YAML: %s\", err)\n\t}\n\treturn result\n}", "func (s DescribeAccountAuditConfigurationOutput) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.AuditCheckConfigurations != nil {\n\t\tv := s.AuditCheckConfigurations\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"auditCheckConfigurations\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetFields(k1, v1)\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.AuditNotificationTargetConfigurations != nil {\n\t\tv := s.AuditNotificationTargetConfigurations\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"auditNotificationTargetConfigurations\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetFields(k1, v1)\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.RoleArn != nil {\n\t\tv := *s.RoleArn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"roleArn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (u *URL) MarshalYAML() (interface{}, error) {\n\treturn u.String(), nil\n}", "func (d DurationSeconds) MarshalYAML() (interface{}, error) {\n\tif !d.IsPresent() {\n\t\treturn nil, nil\n\t}\n\n\treturn int(d.value / time.Second), nil\n}", "func (a *Account) Marshal() ([]byte, error) {\n\treturn a.account.Bytes()\n}", "func SortYAML(in io.Reader, out io.Writer, indent int) error {\n\n\tincomingYAML, err := ioutil.ReadAll(in)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"can't read input: %v\", err)\n\t}\n\n\tvar hasNoStartingLabel bool\n\trootIndent, err := detectRootIndent(incomingYAML)\n\tif err != nil {\n\t\tif !errors.Is(err, ErrNoStartingLabel) {\n\t\t\tfmt.Fprint(out, string(incomingYAML))\n\t\t\treturn fmt.Errorf(\"can't detect root indentation: %v\", err)\n\t\t}\n\n\t\thasNoStartingLabel = true\n\t}\n\n\tif hasNoStartingLabel {\n\t\tincomingYAML = append([]byte(CustomLabel+\"\\n\"), incomingYAML...)\n\t}\n\n\tvar value map[string]interface{}\n\tif err := yaml.Unmarshal(incomingYAML, &value); err != nil {\n\t\tfmt.Fprint(out, string(incomingYAML))\n\n\t\treturn fmt.Errorf(\"can't decode YAML: %v\", err)\n\t}\n\n\tvar outgoingYAML bytes.Buffer\n\tencoder := yaml.NewEncoder(&outgoingYAML)\n\tencoder.SetIndent(indent)\n\n\tif err := encoder.Encode(&value); err != nil {\n\t\tfmt.Fprint(out, string(incomingYAML))\n\t\treturn fmt.Errorf(\"can't re-encode YAML: %v\", err)\n\t}\n\n\treindentedYAML, err := indentYAML(outgoingYAML.String(), rootIndent, indent, hasNoStartingLabel)\n\tif err != nil {\n\t\tfmt.Fprint(out, string(incomingYAML))\n\t\treturn fmt.Errorf(\"can't re-indent YAML: %v\", err)\n\t}\n\n\tfmt.Fprint(out, reindentedYAML)\n\treturn nil\n}", "func (s String) MarshalYAML() (interface{}, error) {\n\tif !s.IsPresent() {\n\t\treturn nil, nil\n\t}\n\treturn s.value, nil\n}", "func (c Config) ToYAML() string {\n\tdata, _ := yaml.Marshal(c)\n\treturn string(data)\n}", "func FormatAsYAML(obj interface{}, indent int) string {\n\tif obj == nil {\n\t\treturn \"none\"\n\t}\n\tdata, err := yaml.Marshal(obj)\n\tif err != nil {\n\t\treturn fmt.Sprintf(\"Error during yaml serialization: %s\", err.Error())\n\t}\n\t// add an additional newline to properly inline\n\treturn ApplyIdent(\"\\n\"+string(data), indent)\n}", "func (u *URL) MarshalYAML() (interface{}, error) {\n\tif u.url == nil {\n\t\treturn nil, nil\n\t}\n\treturn u.url.String(), nil\n}", "func (vm ValidationMap) AsYAML() (string, error) {\n\tdata, err := yaml.Marshal(vm)\n\treturn string(data), err\n}", "func ToYAML(v interface{}) ([]byte, error) {\n\treturn yaml.Marshal(v)\n}", "func (dd *AccountDoc) Marshal() ([]byte, error) {\n\treturn Marshal(dd)\n}", "func (v Values) YAML() (string, error) {\n\tb, err := yaml.Marshal(v)\n\treturn string(b), err\n}", "func (f Float64) MarshalYAML() (interface{}, error) {\n\tif !f.IsPresent() {\n\t\treturn nil, nil\n\t}\n\treturn f.value, nil\n}", "func (s *spiff) Marshal(node Node) ([]byte, error) {\n\treturn yaml.Marshal(node)\n}", "func (s UpdateAccountAuditConfigurationOutput) MarshalFields(e protocol.FieldEncoder) error {\n\treturn nil\n}", "func (d *DiskConfig) ToYAML() (string, error) {\n\ty, err := yaml.Marshal(d)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"error marshaling to yaml: %v\", err)\n\t}\n\treturn string(y), nil\n}", "func Marshal(o interface{}) ([]byte, error) {\n\tj, err := json.Marshal(o)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error marshaling into JSON: %v\", err)\n\t}\n\n\ty, err := JSONToYAML(j)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error converting JSON to YAML: %v\", err)\n\t}\n\n\treturn y, nil\n}", "func (s String) MarshalYAML() (interface{}, error) {\n\tif len(string(s)) == 0 || string(s) == `\"\"` {\n\t\treturn nil, nil\n\t}\n\treturn string(s), nil\n}", "func (s CreateVPCAssociationAuthorizationOutput) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.HostedZoneId != nil {\n\t\tv := *s.HostedZoneId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"HostedZoneId\", protocol.StringValue(v), metadata)\n\t}\n\tif s.VPC != nil {\n\t\tv := s.VPC\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"VPC\", v, metadata)\n\t}\n\treturn nil\n}" ]
[ "0.8220759", "0.82059807", "0.8032163", "0.7778999", "0.6281917", "0.621351", "0.6205962", "0.6153351", "0.6109899", "0.60921556", "0.6080166", "0.60753334", "0.6061997", "0.60296005", "0.59819895", "0.5949471", "0.5909755", "0.5884785", "0.5871395", "0.58268696", "0.57405597", "0.5719856", "0.5702916", "0.569437", "0.5666459", "0.5638416", "0.56282294", "0.5626733", "0.56203073", "0.56034905", "0.5568187", "0.5537363", "0.55112535", "0.54795647", "0.54742724", "0.54510814", "0.5424426", "0.5382488", "0.5360265", "0.5360265", "0.5346349", "0.53447825", "0.53436506", "0.5314862", "0.52657604", "0.5235251", "0.5231919", "0.5231633", "0.5228933", "0.5208645", "0.5194946", "0.51910025", "0.51589555", "0.51589555", "0.5152739", "0.5135135", "0.51291203", "0.510995", "0.5102446", "0.5096431", "0.50858295", "0.5085575", "0.5067334", "0.5059796", "0.505124", "0.50255865", "0.5022852", "0.501242", "0.5004686", "0.4998994", "0.49926785", "0.49907714", "0.49709934", "0.49646574", "0.49169865", "0.4912482", "0.48760334", "0.48724443", "0.48544312", "0.48348495", "0.48241094", "0.4798129", "0.4791764", "0.47157747", "0.47088987", "0.46925852", "0.46639234", "0.46403596", "0.4628797", "0.4579934", "0.4573811", "0.45222944", "0.45127797", "0.44700179", "0.44445452", "0.4426553", "0.44260177", "0.4417518", "0.439528", "0.4392038" ]
0.8481067
0
NewPeriodicVestingAccountRaw creates a new PeriodicVestingAccount object from BaseVestingAccount
func NewPeriodicVestingAccountRaw(bva *BaseVestingAccount, startTime int64, periods Periods) *PeriodicVestingAccount { return &PeriodicVestingAccount{ BaseVestingAccount: bva, StartTime: startTime, VestingPeriods: periods, } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func newPeriodicVestingAccount(address sdk.AccAddress, periods vestingtypes.Periods, firstPeriodStartTimestamp int64) *vestingtypes.PeriodicVestingAccount {\n\tbaseAccount := authtypes.NewBaseAccount(address, nil, 0, 0)\n\n\toriginalVesting := sdk.NewCoins()\n\tfor _, p := range periods {\n\t\toriginalVesting = originalVesting.Add(p.Amount...)\n\t}\n\n\tvar totalPeriods int64\n\tfor _, p := range periods {\n\t\ttotalPeriods += p.Length\n\t}\n\tendTime := firstPeriodStartTimestamp + totalPeriods\n\n\tbaseVestingAccount := vestingtypes.NewBaseVestingAccount(baseAccount, originalVesting, endTime)\n\treturn vestingtypes.NewPeriodicVestingAccountRaw(baseVestingAccount, firstPeriodStartTimestamp, periods)\n}", "func NewPeriodicVestingAccount(baseAcc *authtypes.BaseAccount, originalVesting sdk.Coins, startTime int64, periods Periods) *PeriodicVestingAccount {\n\tendTime := startTime\n\tfor _, p := range periods {\n\t\tendTime += p.Length\n\t}\n\tbaseVestingAcc := &BaseVestingAccount{\n\t\tBaseAccount: baseAcc,\n\t\tOriginalVesting: originalVesting,\n\t\tEndTime: endTime,\n\t}\n\n\treturn &PeriodicVestingAccount{\n\t\tBaseVestingAccount: baseVestingAcc,\n\t\tStartTime: startTime,\n\t\tVestingPeriods: periods,\n\t}\n}", "func NewValidatorVestingAccountRaw(bva *vestingtypes.BaseVestingAccount,\n\tstartTime int64, periods vestingtypes.Periods, validatorAddress sdk.ConsAddress, returnAddress sdk.AccAddress, signingThreshold int64) *ValidatorVestingAccount {\n\n\tpva := &vestingtypes.PeriodicVestingAccount{\n\t\tBaseVestingAccount: bva,\n\t\tStartTime: startTime,\n\t\tVestingPeriods: periods,\n\t}\n\tvar vestingPeriodProgress []VestingProgress\n\tfor i := 0; i < len(periods); i++ {\n\t\tvestingPeriodProgress = append(vestingPeriodProgress, VestingProgress{false, false})\n\t}\n\n\treturn &ValidatorVestingAccount{\n\t\tPeriodicVestingAccount: pva,\n\t\tValidatorAddress: validatorAddress,\n\t\tReturnAddress: returnAddress,\n\t\tSigningThreshold: signingThreshold,\n\t\tCurrentPeriodProgress: CurrentPeriodProgress{0, 0},\n\t\tVestingPeriodProgress: vestingPeriodProgress,\n\t\tDebtAfterFailedVesting: sdk.NewCoins(),\n\t}\n}", "func NewDelayedVestingAccountRaw(bva *BaseVestingAccount) *DelayedVestingAccount {\n\treturn &DelayedVestingAccount{\n\t\tBaseVestingAccount: bva,\n\t}\n}", "func NewContinuousVestingAccountRaw(bva *BaseVestingAccount, startTime int64) *ContinuousVestingAccount {\n\treturn &ContinuousVestingAccount{\n\t\tBaseVestingAccount: bva,\n\t\tStartTime: startTime,\n\t}\n}", "func NewBaseVestingAccount(baseAccount *authtypes.BaseAccount, originalVesting sdk.Coins, endTime int64) *BaseVestingAccount {\n\treturn &BaseVestingAccount{\n\t\tBaseAccount: baseAccount,\n\t\tOriginalVesting: originalVesting,\n\t\tDelegatedFree: sdk.NewCoins(),\n\t\tDelegatedVesting: sdk.NewCoins(),\n\t\tEndTime: endTime,\n\t}\n}", "func newAccount() *Account {\n\treturn &Account{\n\t\tblocks: make(map[string]uint64),\n\t}\n}", "func NewValidatorVestingAccount(baseAcc *authtypes.BaseAccount, startTime int64, periods vestingtypes.Periods, validatorAddress sdk.ConsAddress, returnAddress sdk.AccAddress, signingThreshold int64) *ValidatorVestingAccount {\n\n\tendTime := startTime\n\tfor _, p := range periods {\n\t\tendTime += p.Length\n\t}\n\tbaseVestingAcc := &vestingtypes.BaseVestingAccount{\n\t\tBaseAccount: baseAcc,\n\t\tOriginalVesting: baseAcc.Coins,\n\t\tEndTime: endTime,\n\t}\n\tpva := &vestingtypes.PeriodicVestingAccount{\n\t\tBaseVestingAccount: baseVestingAcc,\n\t\tStartTime: startTime,\n\t\tVestingPeriods: periods,\n\t}\n\tvar vestingPeriodProgress []VestingProgress\n\tfor i := 0; i < len(periods); i++ {\n\t\tvestingPeriodProgress = append(vestingPeriodProgress, VestingProgress{false, false})\n\t}\n\n\treturn &ValidatorVestingAccount{\n\t\tPeriodicVestingAccount: pva,\n\t\tValidatorAddress: validatorAddress,\n\t\tReturnAddress: returnAddress,\n\t\tSigningThreshold: signingThreshold,\n\t\tCurrentPeriodProgress: CurrentPeriodProgress{0, 0},\n\t\tVestingPeriodProgress: vestingPeriodProgress,\n\t\tDebtAfterFailedVesting: sdk.NewCoins(),\n\t}\n}", "func NewContinuousVestingAccount(baseAcc *authtypes.BaseAccount, originalVesting sdk.Coins, startTime, endTime int64) *ContinuousVestingAccount {\n\tbaseVestingAcc := &BaseVestingAccount{\n\t\tBaseAccount: baseAcc,\n\t\tOriginalVesting: originalVesting,\n\t\tEndTime: endTime,\n\t}\n\n\treturn &ContinuousVestingAccount{\n\t\tStartTime: startTime,\n\t\tBaseVestingAccount: baseVestingAcc,\n\t}\n}", "func (*tenantR) NewStruct() *tenantR {\n\treturn &tenantR{}\n}", "func NewDelayedVestingAccount(baseAcc *authtypes.BaseAccount, originalVesting sdk.Coins, endTime int64) *DelayedVestingAccount {\n\tbaseVestingAcc := &BaseVestingAccount{\n\t\tBaseAccount: baseAcc,\n\t\tOriginalVesting: originalVesting,\n\t\tEndTime: endTime,\n\t}\n\n\treturn &DelayedVestingAccount{baseVestingAcc}\n}", "func NewMsgCreatePeriodicVestingAccount(fromAddr, toAddr sdk.AccAddress, startTime int64, periods []Period) *MsgCreatePeriodicVestingAccount {\n\treturn &MsgCreatePeriodicVestingAccount{\n\t\tFromAddress: fromAddr.String(),\n\t\tToAddress: toAddr.String(),\n\t\tStartTime: startTime,\n\t\tVestingPeriods: periods,\n\t}\n}", "func (account *Account) New() {\n\n\tparams, _ := pbc.NewParamsFromString(crypto.Params)\n\tpairing := params.NewPairing()\n\n\tA := pairing.NewG1()\n\tAT := pairing.NewG1()\n\ta := pairing.NewZr()\n\n\ta.Rand()\n\n\tG := pairing.NewG1()\n\tT := pairing.NewG1()\n\tG.SetString(crypto.G, 10)\n\tT.SetString(crypto.T, 10)\n\n\tA.PowZn(G, a)\n\tAT.PowZn(T, a)\n\n\taccount.a = a.String()\n\taccount.A = A.String()\n\taccount.AT = AT.String()\n}", "func newBase() *base {\n\treturn &base{shared.NewUUID(), time.Now().UTC(), time.Now().UTC(), false/*, shared.NewUUID()*/}\n}", "func NewClawbackVestingAccount(baseAcc *authtypes.BaseAccount, funder sdk.AccAddress, originalVesting sdk.Coins, startTime int64, lockupPeriods, vestingPeriods Periods) *ClawbackVestingAccount {\n\t// copy and align schedules to avoid mutating inputs\n\tlp := make(Periods, len(lockupPeriods))\n\tcopy(lp, lockupPeriods)\n\tvp := make(Periods, len(vestingPeriods))\n\tcopy(vp, vestingPeriods)\n\t_, endTime := AlignSchedules(startTime, startTime, lp, vp)\n\tbaseVestingAcc := &BaseVestingAccount{\n\t\tBaseAccount: baseAcc,\n\t\tOriginalVesting: originalVesting,\n\t\tEndTime: endTime,\n\t}\n\n\treturn &ClawbackVestingAccount{\n\t\tBaseVestingAccount: baseVestingAcc,\n\t\tFunderAddress: funder.String(),\n\t\tStartTime: startTime,\n\t\tLockupPeriods: lp,\n\t\tVestingPeriods: vp,\n\t}\n}", "func (*withdrawalCryptoR) NewStruct() *withdrawalCryptoR {\n\treturn &withdrawalCryptoR{}\n}", "func (*ticketR) NewStruct() *ticketR {\n\treturn &ticketR{}\n}", "func newJWTBase(ctx context.Context, cfg Config) (string, error) {\n\tserviceAccount, project, tokenSource, err := getServiceAccountInfo(ctx, cfg)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"unable to get service account from environment\")\n\t}\n\n\tpayload, err := json.Marshal(map[string]interface{}{\n\t\t\"aud\": \"vault/\" + cfg.Role,\n\t\t\"sub\": serviceAccount,\n\t\t\"exp\": time.Now().UTC().Add(5 * time.Minute).Unix(),\n\t})\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"unable to encode JWT payload\")\n\t}\n\n\thc := getHTTPClient(ctx, cfg)\n\t// reuse base transport and timeout but sprinkle on the token source for IAM access\n\thcIAM := &http.Client{\n\t\tTimeout: hc.Timeout,\n\t\tTransport: &oauth2.Transport{\n\t\t\tSource: tokenSource,\n\t\t\tBase: hc.Transport,\n\t\t},\n\t}\n\tiamClient, err := iam.New(hcIAM)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"unable to init IAM client\")\n\t}\n\n\tif cfg.IAMAddress != \"\" {\n\t\tiamClient.BasePath = cfg.IAMAddress\n\t}\n\n\tresp, err := iamClient.Projects.ServiceAccounts.SignJwt(\n\t\tfmt.Sprintf(\"projects/%s/serviceAccounts/%s\",\n\t\t\tproject, serviceAccount),\n\t\t&iam.SignJwtRequest{Payload: string(payload)}).Context(ctx).Do()\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"unable to sign JWT\")\n\t}\n\treturn resp.SignedJwt, nil\n}", "func (c *CoinTest) newAccount(stub shim.ChaincodeStubInterface, args []string) pb.Response {\r\n\tvar id string\r\n\tvar asset int\r\n\tvar err error\r\n\r\n\tif len(args) == 1{\r\n\t\tid = args[0]\r\n\t\tasset = 0\r\n\t}else if len(args) == 2{\r\n\t\tid = args[0]\r\n\t\t//asset, err = strconv.Atoi(args[1])\r\n\t\t//if err != nil{\r\n\t\t//\treturn shim.Error(\"Invalid asset amount, expecting a integer value\")\r\n\t\t//}\r\n\t\tasset = 0;\r\n\t}else{\r\n\t\treturn shim.Error(\"Incorrect number of arguments.\")\r\n\t}\r\n\r\n\t//deliver 0 number of TolakCoin to user\r\n\ttolakCoin.Token.Deliver(token.Address(id), int(asset))\r\n\r\n\t//write to ledger\r\n\terr = stub.PutState(id, []byte(strconv.Itoa(asset)))\r\n\tif err != nil{\r\n\t\treturn shim.Error(err.Error())\r\n\t}\r\n\r\n\treturn shim.Success(nil)\r\n}", "func NewAccount(val string) AccountField {\n\treturn AccountField{quickfix.FIXString(val)}\n}", "func NewAccount(owner string) *Account {\n\treturn &Account{owner: owner, balance: 0}\n}", "func (*currencyR) NewStruct() *currencyR {\n\treturn &currencyR{}\n}", "func newRawAuthentication(value string) httpAuthentication {\n\treturn &basicAuthentication{\n\t\tauthorizationValue: value,\n\t}\n}", "func NewAccount(txr *repository.Transactioner) repository.Account {\n\treturn &account{txr: txr}\n}", "func (pva PeriodicVestingAccount) Validate() error {\n\tif pva.GetStartTime() >= pva.GetEndTime() {\n\t\treturn errors.New(\"vesting start-time cannot be before end-time\")\n\t}\n\tendTime := pva.StartTime\n\toriginalVesting := sdk.NewCoins()\n\tfor _, p := range pva.VestingPeriods {\n\t\tendTime += p.Length\n\t\toriginalVesting = originalVesting.Add(p.Amount...)\n\t}\n\tif endTime != pva.EndTime {\n\t\treturn errors.New(\"vesting end time does not match length of all vesting periods\")\n\t}\n\tif !originalVesting.IsEqual(pva.OriginalVesting) {\n\t\treturn errors.New(\"original vesting coins does not match the sum of all coins in vesting periods\")\n\t}\n\n\treturn pva.BaseVestingAccount.Validate()\n}", "func (*premiumSlotR) NewStruct() *premiumSlotR {\n\treturn &premiumSlotR{}\n}", "func newServiceAccount(cr *storagev1.CSIPowerMaxRevProxy) *v1.ServiceAccount {\n\treturn &v1.ServiceAccount{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: ReverseProxyName,\n\t\t\tNamespace: cr.Namespace,\n\t\t\tOwnerReferences: getOwnerReferences(cr),\n\t\t},\n\t}\n}", "func NewPeriod(amount sdk.Coins, length int64) vestingtypes.Period {\n\treturn vestingtypes.Period{Amount: amount, Length: length}\n}", "func (e Account) EntNew() ent.Ent { return &Account{} }", "func (e Account) EntNew() ent.Ent { return &Account{} }", "func (pva *PeriodicVestingAccount) UnmarshalJSON(bz []byte) error {\n\tvar alias vestingAccountJSON\n\tif err := legacy.Cdc.UnmarshalJSON(bz, &alias); err != nil {\n\t\treturn err\n\t}\n\n\tpva.BaseVestingAccount = &BaseVestingAccount{\n\t\tBaseAccount: NewBaseAccount(alias.Address, alias.Coins, alias.PubKey, alias.AccountNumber, alias.Sequence),\n\t\tOriginalVesting: alias.OriginalVesting,\n\t\tDelegatedFree: alias.DelegatedFree,\n\t\tDelegatedVesting: alias.DelegatedVesting,\n\t\tEndTime: alias.EndTime,\n\t}\n\tpva.StartTime = alias.StartTime\n\tpva.VestingPeriods = alias.VestingPeriods\n\n\treturn nil\n}", "func NewAccount() *Account {\n\n\tcreatedAccount := Account{}\n\n\tnewPrivateKey, err := generatePrivateKey(4096)\n\tif err != nil {\n\t\tlog.Fatal(\"Error generating rsa private key \", err)\n\t}\n\tnewPublicKey, err := generatePublicKey(&newPrivateKey.PublicKey)\n\tif err != nil {\n\t\tlog.Fatal(\"Error generating rsa public key \", err)\n\t}\n\tcreatedAccount.privateKey = newPrivateKey\n\tcreatedAccount.Address = string(newPublicKey)\n\tcreatedAccount.Amount = 0\n\n\treturn &createdAccount\n}", "func (*btcTXOutputR) NewStruct() *btcTXOutputR {\n\treturn &btcTXOutputR{}\n}", "func New(period int) TokenBucket {\n\tlogger := log.New()\n\treturn &repo{\n\t\tBucket: &sync.Map{},\n\t\tSupplementBucket: make(map[int64][]string),\n\t\tRWMutex: &sync.RWMutex{},\n\t\tLogger: logger,\n\t\tPeriod: period,\n\t}\n}", "func NewFundedAccount() *keypair.Full {\n\tkp, err := keypair.Random()\n\tif err != nil {\n\t\tlog.Fatal(err, \"generating random keypair\")\n\t}\n\terr = FundAccount(kp.Address())\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tlog.Printf(\"successfully funded %s\", kp.Address())\n\treturn kp\n}", "func NewCustomAccounting(h modules.Host, m modules.Miner, r modules.Renter, w modules.Wallet, persistDir string, deps modules.Dependencies) (*Accounting, error) {\n\t// Check that at least the wallet is not nil\n\tif w == nil {\n\t\treturn nil, errNilWallet\n\t}\n\n\t// Check required parameters\n\tif persistDir == \"\" {\n\t\treturn nil, errNilPersistDir\n\t}\n\tif deps == nil {\n\t\treturn nil, errNilDeps\n\t}\n\n\t// Initialize the accounting\n\ta := &Accounting{\n\t\tstaticHost: h,\n\t\tstaticMiner: m,\n\t\tstaticRenter: r,\n\t\tstaticWallet: w,\n\n\t\tstaticPersistDir: persistDir,\n\n\t\tstaticDeps: deps,\n\t}\n\n\t// Initialize the persistence\n\terr := a.initPersist()\n\tif err != nil {\n\t\treturn nil, errors.AddContext(err, \"unable to initialize the persistence\")\n\t}\n\n\t// Launch background thread to persist the accounting information\n\tif !a.staticDeps.Disrupt(\"DisablePersistLoop\") {\n\t\tgo a.callThreadedPersistAccounting()\n\t}\n\treturn a, nil\n}", "func (*oauthClientR) NewStruct() *oauthClientR {\n\treturn &oauthClientR{}\n}", "func NewCoinbase(proof, score, R []byte) *Coinbase {\n\treturn &Coinbase{\n\t\tProof: proof,\n\t\tScore: score,\n\t\tR: R,\n\t}\n}", "func (ba *BankAccount) New() Resource {\n\tvar obj = &BankAccount{}\n\treturn obj\n}", "func (c *Jrpc) CreateRawTransaction(in *pty.ReqCreatePrivacyTx, result *interface{}) error {\n\treply, err := c.cli.CreateRawTransaction(context.Background(), in)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t*result = hex.EncodeToString(types.Encode(reply))\n\treturn err\n}", "func NewAccount(user, apiKey string) *Account {\n\treturn &Account{user: user, apiKey: apiKey}\n}", "func newServiceAccount(cr *argoprojv1a1.ArgoCD) *corev1.ServiceAccount {\n\treturn &corev1.ServiceAccount{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: cr.Name,\n\t\t\tNamespace: cr.Namespace,\n\t\t\tLabels: argoutil.LabelsForCluster(cr),\n\t\t},\n\t}\n}", "func (msg MsgCreatePeriodicVestingAccount) Type() string { return TypeMsgCreatePeriodicVestingAccount }", "func NewAccount(id string, name string, primary bool, type_ string, currency Currency, balance AccountBalance, createdAt time.Time, updatedAt time.Time, resource string, resourcePath string, ready bool) *Account {\n\tthis := Account{}\n\tthis.Id = id\n\tthis.Name = name\n\tthis.Primary = primary\n\tthis.Type = type_\n\tthis.Currency = currency\n\tthis.Balance = balance\n\tthis.CreatedAt = createdAt\n\tthis.UpdatedAt = updatedAt\n\tthis.Resource = resource\n\tthis.ResourcePath = resourcePath\n\tthis.Ready = ready\n\treturn &this\n}", "func (w *Wallet) NewAccount(index *uint32) (a *Account, err error) {\n\tindex2 := w.nextIndex\n\tif index != nil {\n\t\tindex2 = *index\n\t}\n\ta = &Account{w: w, index: index2}\n\tif err = w.impl.deriveAccount(a); err != nil {\n\t\treturn\n\t}\n\tpubkeyToAddress := util.PubkeyToAddress\n\tif w.isBanano {\n\t\tpubkeyToAddress = util.PubkeyToBananoAddress\n\t}\n\tif a.address, err = pubkeyToAddress(a.pubkey); err != nil {\n\t\treturn\n\t}\n\tif index == nil {\n\t\tw.nextIndex++\n\t}\n\tif _, ok := w.accounts[a.address]; !ok {\n\t\tw.accounts[a.address] = a\n\t} else if index == nil {\n\t\treturn w.NewAccount(nil)\n\t}\n\treturn\n}", "func (*premiumCodeR) NewStruct() *premiumCodeR {\n\treturn &premiumCodeR{}\n}", "func (c Client) New(params *stripe.TreasuryOutboundPaymentParams) (*stripe.TreasuryOutboundPayment, error) {\n\toutboundpayment := &stripe.TreasuryOutboundPayment{}\n\terr := c.B.Call(\n\t\thttp.MethodPost,\n\t\t\"/v1/treasury/outbound_payments\",\n\t\tc.Key,\n\t\tparams,\n\t\toutboundpayment,\n\t)\n\treturn outboundpayment, err\n}", "func (*vendorR) NewStruct() *vendorR {\n\treturn &vendorR{}\n}", "func NewRPCCtx(embed Ctx) *RPCCtx {\n\tret := &RPCCtx{\n\t\tembed: embed,\n\t\tServices: finder.New(),\n\t\tLog: &ggt.VoidLog{},\n\t\tSession: &ggt.VoidSession{},\n\t\tUpload: &ggt.FileProvider{},\n\t}\n\tret.Log.Handle(nil, nil, nil, \"constructor\", \"RPCCtx\")\n\treturn ret\n}", "func NewAccount(\n\tconfig *accounts.AccountConfig,\n\taccountCoin *Coin,\n\thttpClient *http.Client,\n\tlog *logrus.Entry,\n) *Account {\n\tlog = log.WithField(\"group\", \"eth\").\n\t\tWithFields(logrus.Fields{\"coin\": accountCoin.String(), \"code\": config.Config.Code, \"name\": config.Config.Name})\n\tlog.Debug(\"Creating new account\")\n\n\taccount := &Account{\n\t\tBaseAccount: accounts.NewBaseAccount(config, accountCoin, log),\n\t\tcoin: accountCoin,\n\t\tdbSubfolder: \"\", // set in Initialize()\n\t\tsigningConfiguration: nil,\n\t\thttpClient: httpClient,\n\t\tbalance: coin.NewAmountFromInt64(0),\n\n\t\tenqueueUpdateCh: make(chan struct{}),\n\t\tquitChan: make(chan struct{}),\n\n\t\tlog: log,\n\t}\n\n\treturn account\n}", "func (*holdenAtR) NewStruct() *holdenAtR {\n\treturn &holdenAtR{}\n}", "func (*exchangeCurrencyR) NewStruct() *exchangeCurrencyR {\n\treturn &exchangeCurrencyR{}\n}", "func newRecordV1(r Record) RecordV1 {\n\treturn RecordV1{\n\t\tType: r.Type,\n\t\tName: r.Name,\n\t\tAppliedAt: r.AppliedAt,\n\t}\n}", "func New() *Prober {\n\treturn newForTest(time.Now, newRealTicker)\n}", "func NewAccount(instanceID uuid.UUID, name, aud string) (*Account, error) {\n\tid, err := uuid.NewV4()\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"Error generating unique id\")\n\t}\n\n\taccount := &Account{\n\t\tInstanceID: instanceID,\n\t\tID: id,\n\t\tAud: aud,\n\t\tName: name,\n\t}\n\treturn account, nil\n}", "func NewMockAVR(quote []byte, nonce string) ([]byte, error) {\n\tmockAVR := &mockAVR{\n\t\tVersion: 4,\n\t\tTimestamp: time.Now().UTC().Format(TimestampFormat),\n\t\tISVEnclaveQuoteStatus: \"OK\",\n\t\tISVEnclaveQuoteBody: quote[:quoteLen],\n\t\tNonce: nonce,\n\t}\n\n\tvar q Quote\n\terr := q.UnmarshalBinary(mockAVR.ISVEnclaveQuoteBody)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif err = q.Verify(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn json.Marshal(mockAVR)\n}", "func New(s string, base int) (v BigNum) {\n\tv.Input(s, base)\n\treturn\n}", "func (r *StatusREST) New() runtime.Object {\n\treturn &api.PersistentVolumeClaim{}\n}", "func (*paymentObjectR) NewStruct() *paymentObjectR {\n\treturn &paymentObjectR{}\n}", "func NewAccount(addr, amount string) *Account {\n\tam := big.NewInt(0)\n\tam.SetString(amount, 0)\n\treturn &Account{Address: addr, Amount: am}\n}", "func ExampleNew() {\n\ttoken := \"0xb64ef51c888972c908cfacf59b47c1afbc0ab8ac\"\n\twallet := \"0x9ea0c535b3eb166454c8ccbaba86850c8df3ee57\"\n\texample, _ = New(token, wallet)\n\tfmt.Printf(\"This wallet has %v %v tokens\", example.BalanceString(), example.Name)\n\t// Output: This wallet has 7.282 StorjToken tokens\n}", "func MakeNewAccount(name string) (*MyAccount, error) {\n\tkeys, err := NewKeypair()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &MyAccount{\n\t\tFields: make(map[string]string),\n\t\tKeys: keys,\n\t\tName: name,\n\t}, nil\n}", "func (g *testGenerator) createCoinbaseTx(blockHeight uint32, numVotes uint16) *wire.MsgTx {\n\t// Calculate the subsidy proportions based on the block height and the\n\t// number of votes the block will include.\n\tfullSubsidy := g.calcFullSubsidy(blockHeight)\n\tdevSubsidy := g.calcDevSubsidy(fullSubsidy, blockHeight, numVotes)\n\tpowSubsidy := g.calcPoWSubsidy(fullSubsidy, blockHeight, numVotes)\n\n\ttx := wire.NewMsgTx()\n\ttx.AddTxIn(&wire.TxIn{\n\t\t// Coinbase transactions have no inputs, so previous outpoint is\n\t\t// zero hash and max index.\n\t\tPreviousOutPoint: *wire.NewOutPoint(&chainhash.Hash{},\n\t\t\twire.MaxPrevOutIndex, wire.TxTreeRegular),\n\t\tSequence: wire.MaxTxInSequenceNum,\n\t\tValueIn: int64(devSubsidy + powSubsidy),\n\t\tBlockHeight: wire.NullBlockHeight,\n\t\tBlockIndex: wire.NullBlockIndex,\n\t\tSignatureScript: coinbaseSigScript,\n\t})\n\n\tg.addCoinbaseTxOutputs(tx, blockHeight, devSubsidy, powSubsidy)\n\n\treturn tx\n}", "func New(raw []byte) (*BytesObj, error) {\n\tbo := new(BytesObj)\n\tif err := bo.UnmarshalJSON(raw); err != nil {\n\t\treturn nil, err\n\t}\n\treturn bo, nil\n}", "func (*utxoR) NewStruct() *utxoR {\n\treturn &utxoR{}\n}", "func GenPrivAccount() *PrivAccount {\n\tprivKeyBytes := new([64]byte)\n\tcopy(privKeyBytes[:32], CRandBytes(32))\n\tpubKeyBytes := ed25519.MakePublicKey(privKeyBytes)\n\tpubKey := PubKeyEd25519(pubKeyBytes[:])\n\tprivKey := PrivKeyEd25519(privKeyBytes[:])\n\treturn &PrivAccount{\n\t\tAddress: pubKey.Address(),\n\t\tPubKey: pubKey,\n\t\tPrivKey: privKey,\n\t}\n}", "func (a API) CreateRawTransaction(cmd *btcjson.CreateRawTransactionCmd) (e error) {\n\tRPCHandlers[\"createrawtransaction\"].Call <-API{a.Ch, cmd, nil}\n\treturn\n}", "func New(raw []byte) *Sample {\n\tnow := time.Now().UTC()\n\ts := &Sample{\n\t\tRecordTime: AsTimestamp(now),\n\t\tSampleTime: AsTimestamp(now),\n\t\tRaw: raw,\n\t\tTags: []string{},\n\t\tValues: map[string]float64{},\n\t}\n\treturn s\n}", "func tNewUser(lbl string) *tUser {\n\tintBytes := make([]byte, 4)\n\tbinary.BigEndian.PutUint32(intBytes, acctCounter)\n\tacctID := account.AccountID{}\n\tcopy(acctID[:], acctTemplate[:])\n\tcopy(acctID[account.HashSize-4:], intBytes)\n\taddr := strconv.Itoa(int(acctCounter))\n\tsig := []byte{0xab} // Just to differentiate from the addr.\n\tsig = append(sig, intBytes...)\n\tsigHex := hex.EncodeToString(sig)\n\tacctCounter++\n\treturn &tUser{\n\t\tsig: sig,\n\t\tsigHex: sigHex,\n\t\tacct: acctID,\n\t\taddr: addr,\n\t\tlbl: lbl,\n\t}\n}", "func (mm *BytesMonitor) MakeBoundAccount() BoundAccount {\n\treturn BoundAccount{mon: mm}\n}", "func NewAccount(id string) esfazz.Aggregate {\n\tacc := AccountModel()\n\tacc.Id = id\n\treturn acc\n}", "func NewAccount() *Account {\n\tpriv, _ := ecdsa.GenerateKey(crypto.S256(), cryptorand.Reader)\n\tpub := base64.URLEncoding.EncodeToString(\n\t\tcrypto.FromECDSAPub(&priv.PublicKey))\n\taddr := hex.EncodeToString(crypto.PubkeyToAddress(priv.PublicKey).Bytes())\n\treturn &Account{\n\t\tID: NewUUID(),\n\t\tEthAddr: addr,\n\t\tPublicKey: pub,\n\t\tPrivateKey: base64.URLEncoding.EncodeToString(crypto.FromECDSA(priv)),\n\t}\n}", "func New(params ...rune) SuperSpin {\n\tsp := SuperSpin{\n\t\topenToken: '{',\n\t\tcloseToken: '}',\n\t\torToken: '|',\n\t}\n\n\tif len(params) == 1 {\n\t\tsp.openToken = params[0]\n\t}\n\n\tif len(params) == 2 {\n\t\tsp.closeToken = params[1]\n\t}\n\n\tif len(params) == 3 {\n\t\tsp.orToken = params[2]\n\t}\n\n\treturn sp\n}", "func New(config Config, root *Account) (*Thereum, error) {\n\t// init the configured db\n\tdb := config.DB()\n\t// delay := config.Delayer()\n\n\t// init the genesis block + any accounts designated in config.Allocaiton\n\tgenesis, accounts, err := config.Genesis()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tgenBlock := genesis.MustCommit(db)\n\n\tif root == nil {\n\t\troot, _ = NewAccount(\"defaultRoot\", big.NewInt(100))\n\t}\n\tchainConfig := params.AllEthashProtocolChanges\n\tchainConfig.ChainID = big.NewInt(1)\n\tbc, _ := core.NewBlockChain(db, nil, chainConfig, ethash.NewFaker(), vm.Config{}, nil)\n\tt := &Thereum{\n\t\ttxPool: txpool.NewLinkedPool(),\n\t\tdatabase: db,\n\t\tblockchain: bc,\n\t\tsigner: types.NewEIP155Signer(big.NewInt(1)),\n\t\troot: root,\n\t\tgasLimit: config.GasLimit, // TODO: config and make more flexible\n\t\tDelay: int(config.Delay),\n\t\tEvents: filters.NewEventSystem(&filterBackend{db: db, bc: bc}, false),\n\t\tAccounts: accounts,\n\t}\n\tt.pendingBlock = genBlock\n\tt.chainConfig = chainConfig\n\treturn t, nil\n}", "func New(wsConnection BitsharesAPIConnection, params Params) BitsharesAPI {\n\tapi := &bitsharesAPI{\n\t\tusername: params.Username,\n\t\tpassword: params.Password,\n\t\tconnection: wsConnection,\n\t\tdatabaseAPIID: InvalidAPIID,\n\t\thistoryAPIID: InvalidAPIID,\n\t\tbroadcastAPIID: InvalidAPIID,\n\t\tcryptoAPIID: InvalidAPIID,\n\t\tnetworkNodeAPIID: InvalidAPIID,\n\t}\n\tapi.connection.RegisterCallback(api.connEventHandler)\n\treturn api\n}", "func (k *kubeclient) CreateRaw(upgradeResultObj *apis.UpgradeResult) ([]byte, error) {\n\tur, err := k.Create(upgradeResultObj)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn json.Marshal(ur)\n}", "func NewBase() Base {\r\n\treturn Base{\r\n\t\tActive: \"\",\r\n\t\tTitle: \"Lemonade Stand Supply\",\r\n\t}\r\n}", "func mkdummytx() *Transaction {\n\ttx := &Transaction{\n\t\tBlockHeight: 42,\n\t\tName: \"dummy\",\n\t\tTimestamp: func() time.Time {\n\t\t\tt, _ := time.Parse(\"2006-Jan-02 15:04\", \"1988-Jan-02 10:00\")\n\t\t\treturn t\n\t\t}(),\n\t\tTotalInputs: 13,\n\t\tTotalOutputs: 12,\n\t\tTotalECOutputs: 1,\n\t}\n\treturn tx\n}", "func New(apiKey string) Interface {\n\tvar (\n\t\tcom communication.Interface\n\t\twbs *impl\n\t\turi string\n\t\tfromAt time.Time\n\t)\n\n\tcom, fromAt = communication.New(), time.Now().Truncate(time.Hour*24)\n\turi = fmt.Sprintf(serviceURNv1, serviceURL)\n\twbs = &impl{\n\t\tapiKey: apiKey,\n\t\tinc: incomes.New(com, uri, apiKey, fromAt),\n\t\tods: orders.New(com, uri, apiKey, fromAt),\n\t\tsle: sales.New(com, uri, apiKey, fromAt),\n\t\tstk: stocks.New(com, uri, apiKey, fromAt),\n\t\tmds: monthSale.New(com, uri, apiKey, fromAt),\n\t\tcom: com,\n\t\tfromAt: fromAt,\n\t}\n\n\treturn wbs\n}", "func MakeStandaloneBudget(capacity int64) BoundAccount {\n\treturn BoundAccount{used: capacity}\n}", "func New(OrganisationID string, BaseURL string) *Client {\n\tconfig := config{\n\t\tURL: BaseURL,\n\t\tOrganisationID: OrganisationID,\n\t\tclient: &http.Client{},\n\t}\n\treturn &Client{\n\t\tAccount: AccountEndpoint{\n\t\t\tconfig: &config,\n\t\t},\n\t}\n}", "func (builder *AuthBankGenesisBuilder) WithSimplePeriodicVestingAccount(address sdk.AccAddress, balance sdk.Coins, periods vestingtypes.Periods, firstPeriodStartTimestamp int64) *AuthBankGenesisBuilder {\n\tvestingAccount := newPeriodicVestingAccount(address, periods, firstPeriodStartTimestamp)\n\n\treturn builder.\n\t\tWithAccounts(vestingAccount).\n\t\tWithBalances(banktypes.Balance{Address: address.String(), Coins: balance})\n}", "func NewBase(path string, hashName string) (*Base, error) {\n\tfor _, p := range []string{\"blobs/\" + hashName, \"state\", \"tmp\"} {\n\t\tif err := os.MkdirAll(filepath.Join(path, p), 0755); err != nil && !os.IsExist(err) {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn &Base{Path: path, HashName: hashName, Hash: cryptomap.DetermineHash(hashName)}, nil\n}", "func NewAccount() *Account {\n\tacc := &Account{}\n\tpriv, pub := newKeyPair()\n\tacc.PriKey = priv\n\tacc.PubKey = pub\n\treturn acc\n}", "func newRandomAccountPersistence() accountPersistence {\n\taid, sk := modules.NewAccountID()\n\treturn accountPersistence{\n\t\tAccountID: aid,\n\t\tBalance: types.NewCurrency64(fastrand.Uint64n(1e3)),\n\t\tHostKey: types.SiaPublicKey{},\n\t\tSecretKey: sk,\n\t}\n}", "func NewAgedAccountsPayable()(*AgedAccountsPayable) {\n m := &AgedAccountsPayable{\n }\n m.backingStore = ie8677ce2c7e1b4c22e9c3827ecd078d41185424dd9eeb92b7d971ed2d49a392e.BackingStoreFactoryInstance();\n m.SetAdditionalData(make(map[string]any))\n return m\n}", "func New() *Accounts {\n\treturn &Accounts{\n\t\tdata: make(map[string]*Account),\n\t}\n}", "func NewAccount(id, entityID string) *Account {\n\treturn &Account{\n\t\tID: id,\n\t\tEntityID: entityID,\n\t\tWallets: make([]Wallet, 0),\n\t}\n}", "func newQuota() *catalogue.Quota {\n\treturn &catalogue.Quota{\n\t\tCores: 99999,\n\t\tFloatingIPs: 99999,\n\t\tInstances: 99999,\n\t\tKeyPairs: 99999,\n\t\tRAM: 99999,\n\t\tTenant: \"test-tenant\",\n\t}\n}", "func NewTrainCar() TrainCar {\n c := TrainCar{name: \"TrainCar\", vehicle: \"TrainCar\", speed: 30, capacity: 30, railway: \"CNR\"}\n return c\n}", "func New(cfg *types.RPC) *RPC {\n\tInitCfg(cfg)\n\tif cfg.EnableTrace {\n\t\tgrpc.EnableTracing = true\n\t}\n\treturn &RPC{cfg: cfg}\n}", "func (*customerR) NewStruct() *customerR {\n\treturn &customerR{}\n}", "func NewAccount(address string) *Account {\n\treturn &Account{\n\t\tAddress: address,\n\t\tHeight: \"0\",\n\t\tGoldTokenBalance: \"0\",\n\t\tTotalLockedGoldBalance: \"0\",\n\t\tNonVotingLockedGoldBalance: \"0\",\n\t\tVotingLockedGoldBalance: \"0\",\n\t\tPendingWithdrawalBalance: \"0\",\n\t\tCeloUSDValue: \"0\",\n\t\tDelegations: []*Delegation{},\n\t}\n\n}", "func newPRSignedBaseLayer(baseLayerIdentity PolicyReferenceMatch) (*prSignedBaseLayer, error) {\n\tif baseLayerIdentity == nil {\n\t\treturn nil, InvalidPolicyFormatError(\"baseLayerIdentity not specified\")\n\t}\n\treturn &prSignedBaseLayer{\n\t\tprCommon: prCommon{Type: prTypeSignedBaseLayer},\n\t\tBaseLayerIdentity: baseLayerIdentity,\n\t}, nil\n}", "func newRPCTransactionFromBlockIndex(b *types.Block, index uint64) *RPCTransaction {\n\ttxs := b.Transactions()\n\tif index >= uint64(len(txs)) {\n\t\treturn nil\n\t}\n\treturn newRPCTransaction(txs[index], b.Hash(), b.NumberU64(), index)\n}", "func New(cfg *types.RPC) *RPC {\r\n\tInitCfg(cfg)\r\n\tif cfg.EnableTrace {\r\n\t\tgrpc.EnableTracing = true\r\n\t}\r\n\treturn &RPC{cfg: cfg}\r\n}", "func (ws *WebServer) NewAccount(c *gin.Context) {\n\tnetwork := ws.nodeConfig.GetNetwork()\n\tif network == \"\" {\n\t\tReturnError(c, 500, ErrorNoNetwork.Error())\n\t\treturn\n\t}\n\tn := sdk.Testnet\n\tif network == \"bitmark\" {\n\t\tn = sdk.Livenet\n\t}\n\tseedFile := filepath.Join(ws.rootPath, \"bitmarkd\", network, \"proof.sign\")\n\tif _, err := os.Stat(seedFile); err == nil {\n\t\tReturnError(c, 500, ErrorNoSeedFile.Error())\n\t\treturn\n\t}\n\n\ta, err := sdk.NewAccount(n)\n\tif err != nil {\n\t\tReturnError(c, 500, ErrorCreateAccount.Error())\n\t\treturn\n\t}\n\tseed := a.Seed()\n\n\tf, err := os.OpenFile(seedFile, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0600)\n\tif err != nil {\n\t\tReturnError(c, 500, ErrorOpenSeedFile.Error())\n\t\treturn\n\t}\n\tdefer f.Close()\n\n\t_, err = f.WriteString(fmt.Sprintf(\"SEED:%s\", seed))\n\tif err != nil {\n\t\tReturnError(c, 500, ErrorToWriteSeedFile.Error())\n\t\treturn\n\t}\n\tws.SetAccount(a.AccountNumber(), seed, network) // Record in AccountInfo in memory\n\terr = ws.saveAcct()\n\tif nil != err {\n\t\tReturnError(c, 500, ErrorAutoSaveAccount.Error())\n\t\treturn\n\n\t}\n\tc.JSON(200, map[string]interface{}{\n\t\t\"ok\": 1,\n\t})\n}", "func NewStorageDataRaw(b []byte) StorageDataRaw {\n\treturn StorageDataRaw(b)\n}", "func NewRawStorage(config *storagebackend.ConfigForResource, newFunc func() runtime.Object) (storage.Interface, factory.DestroyFunc, error) {\n\treturn factory.Create(*config, newFunc)\n}", "func NewAccount(file string) (*AccountRoot, error) {\n\tif file == \"\" {\n\t\treturn nil, errors.New(\"config file should be passed\")\n\t}\n\n\tvar err error\n\tconf, err := loadAccount(file)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// debug\n\t// grok.Value(conf)\n\n\t// validate\n\tif err = conf.validate(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn conf, nil\n}" ]
[ "0.76211107", "0.7578755", "0.69147325", "0.688278", "0.6686776", "0.66709", "0.61405754", "0.6001733", "0.58985585", "0.56478363", "0.5611604", "0.5596392", "0.542728", "0.53417903", "0.52059007", "0.51674855", "0.51130736", "0.507255", "0.5046054", "0.500847", "0.49871668", "0.4967131", "0.4954294", "0.493043", "0.49194923", "0.49049357", "0.49033242", "0.48742548", "0.4863246", "0.4863246", "0.48619077", "0.48546234", "0.4838349", "0.48251778", "0.48216683", "0.48143512", "0.4808872", "0.47964114", "0.4778002", "0.47542387", "0.4752122", "0.47519484", "0.47384796", "0.47326398", "0.47249043", "0.47233188", "0.47209466", "0.47163248", "0.47064754", "0.46796945", "0.46753168", "0.467393", "0.4671212", "0.46699023", "0.4669386", "0.4669263", "0.4646084", "0.46441856", "0.4631082", "0.46233127", "0.46150696", "0.46115738", "0.46085384", "0.46074167", "0.46062094", "0.46017173", "0.45938563", "0.45936206", "0.45908678", "0.4588909", "0.45802385", "0.45774886", "0.45700666", "0.45667744", "0.45462114", "0.45440447", "0.45376295", "0.4535234", "0.45256248", "0.45221525", "0.45202833", "0.4518938", "0.45126554", "0.45022914", "0.45007187", "0.4500572", "0.4500564", "0.4499694", "0.44976833", "0.44949323", "0.44943777", "0.44937816", "0.44927758", "0.44875464", "0.44797504", "0.44768435", "0.44705978", "0.44702035", "0.44686443", "0.44671926" ]
0.82215947
0
NewPeriodicVestingAccount returns a new PeriodicVestingAccount
func NewPeriodicVestingAccount(baseAcc *authtypes.BaseAccount, originalVesting sdk.Coins, startTime int64, periods Periods) *PeriodicVestingAccount { endTime := startTime for _, p := range periods { endTime += p.Length } baseVestingAcc := &BaseVestingAccount{ BaseAccount: baseAcc, OriginalVesting: originalVesting, EndTime: endTime, } return &PeriodicVestingAccount{ BaseVestingAccount: baseVestingAcc, StartTime: startTime, VestingPeriods: periods, } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func newPeriodicVestingAccount(address sdk.AccAddress, periods vestingtypes.Periods, firstPeriodStartTimestamp int64) *vestingtypes.PeriodicVestingAccount {\n\tbaseAccount := authtypes.NewBaseAccount(address, nil, 0, 0)\n\n\toriginalVesting := sdk.NewCoins()\n\tfor _, p := range periods {\n\t\toriginalVesting = originalVesting.Add(p.Amount...)\n\t}\n\n\tvar totalPeriods int64\n\tfor _, p := range periods {\n\t\ttotalPeriods += p.Length\n\t}\n\tendTime := firstPeriodStartTimestamp + totalPeriods\n\n\tbaseVestingAccount := vestingtypes.NewBaseVestingAccount(baseAccount, originalVesting, endTime)\n\treturn vestingtypes.NewPeriodicVestingAccountRaw(baseVestingAccount, firstPeriodStartTimestamp, periods)\n}", "func NewPeriodicVestingAccountRaw(bva *BaseVestingAccount, startTime int64, periods Periods) *PeriodicVestingAccount {\n\treturn &PeriodicVestingAccount{\n\t\tBaseVestingAccount: bva,\n\t\tStartTime: startTime,\n\t\tVestingPeriods: periods,\n\t}\n}", "func NewValidatorVestingAccount(baseAcc *authtypes.BaseAccount, startTime int64, periods vestingtypes.Periods, validatorAddress sdk.ConsAddress, returnAddress sdk.AccAddress, signingThreshold int64) *ValidatorVestingAccount {\n\n\tendTime := startTime\n\tfor _, p := range periods {\n\t\tendTime += p.Length\n\t}\n\tbaseVestingAcc := &vestingtypes.BaseVestingAccount{\n\t\tBaseAccount: baseAcc,\n\t\tOriginalVesting: baseAcc.Coins,\n\t\tEndTime: endTime,\n\t}\n\tpva := &vestingtypes.PeriodicVestingAccount{\n\t\tBaseVestingAccount: baseVestingAcc,\n\t\tStartTime: startTime,\n\t\tVestingPeriods: periods,\n\t}\n\tvar vestingPeriodProgress []VestingProgress\n\tfor i := 0; i < len(periods); i++ {\n\t\tvestingPeriodProgress = append(vestingPeriodProgress, VestingProgress{false, false})\n\t}\n\n\treturn &ValidatorVestingAccount{\n\t\tPeriodicVestingAccount: pva,\n\t\tValidatorAddress: validatorAddress,\n\t\tReturnAddress: returnAddress,\n\t\tSigningThreshold: signingThreshold,\n\t\tCurrentPeriodProgress: CurrentPeriodProgress{0, 0},\n\t\tVestingPeriodProgress: vestingPeriodProgress,\n\t\tDebtAfterFailedVesting: sdk.NewCoins(),\n\t}\n}", "func NewDelayedVestingAccount(baseAcc *authtypes.BaseAccount, originalVesting sdk.Coins, endTime int64) *DelayedVestingAccount {\n\tbaseVestingAcc := &BaseVestingAccount{\n\t\tBaseAccount: baseAcc,\n\t\tOriginalVesting: originalVesting,\n\t\tEndTime: endTime,\n\t}\n\n\treturn &DelayedVestingAccount{baseVestingAcc}\n}", "func newAccount() *Account {\n\treturn &Account{\n\t\tblocks: make(map[string]uint64),\n\t}\n}", "func NewMsgCreatePeriodicVestingAccount(fromAddr, toAddr sdk.AccAddress, startTime int64, periods []Period) *MsgCreatePeriodicVestingAccount {\n\treturn &MsgCreatePeriodicVestingAccount{\n\t\tFromAddress: fromAddr.String(),\n\t\tToAddress: toAddr.String(),\n\t\tStartTime: startTime,\n\t\tVestingPeriods: periods,\n\t}\n}", "func NewBaseVestingAccount(baseAccount *authtypes.BaseAccount, originalVesting sdk.Coins, endTime int64) *BaseVestingAccount {\n\treturn &BaseVestingAccount{\n\t\tBaseAccount: baseAccount,\n\t\tOriginalVesting: originalVesting,\n\t\tDelegatedFree: sdk.NewCoins(),\n\t\tDelegatedVesting: sdk.NewCoins(),\n\t\tEndTime: endTime,\n\t}\n}", "func NewContinuousVestingAccount(baseAcc *authtypes.BaseAccount, originalVesting sdk.Coins, startTime, endTime int64) *ContinuousVestingAccount {\n\tbaseVestingAcc := &BaseVestingAccount{\n\t\tBaseAccount: baseAcc,\n\t\tOriginalVesting: originalVesting,\n\t\tEndTime: endTime,\n\t}\n\n\treturn &ContinuousVestingAccount{\n\t\tStartTime: startTime,\n\t\tBaseVestingAccount: baseVestingAcc,\n\t}\n}", "func newServiceAccount(cr *argoprojv1a1.ArgoCD) *corev1.ServiceAccount {\n\treturn &corev1.ServiceAccount{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: cr.Name,\n\t\t\tNamespace: cr.Namespace,\n\t\t\tLabels: argoutil.LabelsForCluster(cr),\n\t\t},\n\t}\n}", "func newServiceAccount(cr *storagev1.CSIPowerMaxRevProxy) *v1.ServiceAccount {\n\treturn &v1.ServiceAccount{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: ReverseProxyName,\n\t\t\tNamespace: cr.Namespace,\n\t\t\tOwnerReferences: getOwnerReferences(cr),\n\t\t},\n\t}\n}", "func (*tenantR) NewStruct() *tenantR {\n\treturn &tenantR{}\n}", "func NewPeriod(amount sdk.Coins, length int64) vestingtypes.Period {\n\treturn vestingtypes.Period{Amount: amount, Length: length}\n}", "func (account *Account) New() {\n\n\tparams, _ := pbc.NewParamsFromString(crypto.Params)\n\tpairing := params.NewPairing()\n\n\tA := pairing.NewG1()\n\tAT := pairing.NewG1()\n\ta := pairing.NewZr()\n\n\ta.Rand()\n\n\tG := pairing.NewG1()\n\tT := pairing.NewG1()\n\tG.SetString(crypto.G, 10)\n\tT.SetString(crypto.T, 10)\n\n\tA.PowZn(G, a)\n\tAT.PowZn(T, a)\n\n\taccount.a = a.String()\n\taccount.A = A.String()\n\taccount.AT = AT.String()\n}", "func (msg MsgCreatePeriodicVestingAccount) Type() string { return TypeMsgCreatePeriodicVestingAccount }", "func NewValidatorVestingAccountRaw(bva *vestingtypes.BaseVestingAccount,\n\tstartTime int64, periods vestingtypes.Periods, validatorAddress sdk.ConsAddress, returnAddress sdk.AccAddress, signingThreshold int64) *ValidatorVestingAccount {\n\n\tpva := &vestingtypes.PeriodicVestingAccount{\n\t\tBaseVestingAccount: bva,\n\t\tStartTime: startTime,\n\t\tVestingPeriods: periods,\n\t}\n\tvar vestingPeriodProgress []VestingProgress\n\tfor i := 0; i < len(periods); i++ {\n\t\tvestingPeriodProgress = append(vestingPeriodProgress, VestingProgress{false, false})\n\t}\n\n\treturn &ValidatorVestingAccount{\n\t\tPeriodicVestingAccount: pva,\n\t\tValidatorAddress: validatorAddress,\n\t\tReturnAddress: returnAddress,\n\t\tSigningThreshold: signingThreshold,\n\t\tCurrentPeriodProgress: CurrentPeriodProgress{0, 0},\n\t\tVestingPeriodProgress: vestingPeriodProgress,\n\t\tDebtAfterFailedVesting: sdk.NewCoins(),\n\t}\n}", "func NewFundedAccount() *keypair.Full {\n\tkp, err := keypair.Random()\n\tif err != nil {\n\t\tlog.Fatal(err, \"generating random keypair\")\n\t}\n\terr = FundAccount(kp.Address())\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tlog.Printf(\"successfully funded %s\", kp.Address())\n\treturn kp\n}", "func NewAccount(txr *repository.Transactioner) repository.Account {\n\treturn &account{txr: txr}\n}", "func NewDelayedVestingAccountRaw(bva *BaseVestingAccount) *DelayedVestingAccount {\n\treturn &DelayedVestingAccount{\n\t\tBaseVestingAccount: bva,\n\t}\n}", "func (e Account) EntNew() ent.Ent { return &Account{} }", "func (e Account) EntNew() ent.Ent { return &Account{} }", "func NewAccount(user, apiKey string) *Account {\n\treturn &Account{user: user, apiKey: apiKey}\n}", "func NewAccount(owner string) *Account {\n\treturn &Account{owner: owner, balance: 0}\n}", "func newServiceAccountWithName(name string, cr *argoprojv1a1.ArgoCD) *corev1.ServiceAccount {\n\tsa := newServiceAccount(cr)\n\tsa.ObjectMeta.Name = getServiceAccountName(cr.Name, name)\n\n\tlbls := sa.ObjectMeta.Labels\n\tlbls[common.ArgoCDKeyName] = name\n\tsa.ObjectMeta.Labels = lbls\n\n\treturn sa\n}", "func NewServiceAccount(name string, namespace string, operatorVersion string) *corev1.ServiceAccount {\n\treturn &corev1.ServiceAccount{\n\t\tTypeMeta: metav1.TypeMeta{\n\t\t\tAPIVersion: \"v1\",\n\t\t\tKind: \"ServiceAccount\",\n\t\t},\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tNamespace: namespace,\n\t\t\tName: name,\n\t\t\tLabels: map[string]string{\n\t\t\t\tmrv1.SchemeGroupVersion.Group: \"\",\n\t\t\t\tmrv1.SchemeGroupVersion.Group + \"/version\": operatorVersion,\n\t\t\t},\n\t\t},\n\t}\n}", "func NewClawbackVestingAccount(baseAcc *authtypes.BaseAccount, funder sdk.AccAddress, originalVesting sdk.Coins, startTime int64, lockupPeriods, vestingPeriods Periods) *ClawbackVestingAccount {\n\t// copy and align schedules to avoid mutating inputs\n\tlp := make(Periods, len(lockupPeriods))\n\tcopy(lp, lockupPeriods)\n\tvp := make(Periods, len(vestingPeriods))\n\tcopy(vp, vestingPeriods)\n\t_, endTime := AlignSchedules(startTime, startTime, lp, vp)\n\tbaseVestingAcc := &BaseVestingAccount{\n\t\tBaseAccount: baseAcc,\n\t\tOriginalVesting: originalVesting,\n\t\tEndTime: endTime,\n\t}\n\n\treturn &ClawbackVestingAccount{\n\t\tBaseVestingAccount: baseVestingAcc,\n\t\tFunderAddress: funder.String(),\n\t\tStartTime: startTime,\n\t\tLockupPeriods: lp,\n\t\tVestingPeriods: vp,\n\t}\n}", "func NewAdaptivePeriodic(startDate time.Time, waitTime time.Duration,\n\trelVal float64, refSymbol string, priceP priceProvider) Strategy {\n\n\treturn &AdaptivePeriodic{\n\t\twaitTime: waitTime,\n\t\tlastInvested: startDate.Add(-waitTime),\n\t\tWithDrawdown: WithDrawdown{\n\t\t\trelVal: relVal,\n\t\t\trefSymbol: refSymbol,\n\t\t\tpriceP: priceP,\n\t\t},\n\t}\n}", "func (c *CoinTest) newAccount(stub shim.ChaincodeStubInterface, args []string) pb.Response {\r\n\tvar id string\r\n\tvar asset int\r\n\tvar err error\r\n\r\n\tif len(args) == 1{\r\n\t\tid = args[0]\r\n\t\tasset = 0\r\n\t}else if len(args) == 2{\r\n\t\tid = args[0]\r\n\t\t//asset, err = strconv.Atoi(args[1])\r\n\t\t//if err != nil{\r\n\t\t//\treturn shim.Error(\"Invalid asset amount, expecting a integer value\")\r\n\t\t//}\r\n\t\tasset = 0;\r\n\t}else{\r\n\t\treturn shim.Error(\"Incorrect number of arguments.\")\r\n\t}\r\n\r\n\t//deliver 0 number of TolakCoin to user\r\n\ttolakCoin.Token.Deliver(token.Address(id), int(asset))\r\n\r\n\t//write to ledger\r\n\terr = stub.PutState(id, []byte(strconv.Itoa(asset)))\r\n\tif err != nil{\r\n\t\treturn shim.Error(err.Error())\r\n\t}\r\n\r\n\treturn shim.Success(nil)\r\n}", "func NewPeriodical(g Game, s Subject, o Object, name string, routine func(), t InstanceTime) *Periodical {\n\te := &Periodical{\n\t\tUnitPair: MakePair(s, o),\n\t\tname: name,\n\t\troutine: routine,\n\t\texpirationTime: t,\n\t}\n\te.handler = MakeEventHandler(func(p interface{}) { e.handle(g, p) })\n\treturn e\n}", "func NewAccount() *Account {\n\n\tcreatedAccount := Account{}\n\n\tnewPrivateKey, err := generatePrivateKey(4096)\n\tif err != nil {\n\t\tlog.Fatal(\"Error generating rsa private key \", err)\n\t}\n\tnewPublicKey, err := generatePublicKey(&newPrivateKey.PublicKey)\n\tif err != nil {\n\t\tlog.Fatal(\"Error generating rsa public key \", err)\n\t}\n\tcreatedAccount.privateKey = newPrivateKey\n\tcreatedAccount.Address = string(newPublicKey)\n\tcreatedAccount.Amount = 0\n\n\treturn &createdAccount\n}", "func (ws *WebServer) NewAccount(c *gin.Context) {\n\tnetwork := ws.nodeConfig.GetNetwork()\n\tif network == \"\" {\n\t\tReturnError(c, 500, ErrorNoNetwork.Error())\n\t\treturn\n\t}\n\tn := sdk.Testnet\n\tif network == \"bitmark\" {\n\t\tn = sdk.Livenet\n\t}\n\tseedFile := filepath.Join(ws.rootPath, \"bitmarkd\", network, \"proof.sign\")\n\tif _, err := os.Stat(seedFile); err == nil {\n\t\tReturnError(c, 500, ErrorNoSeedFile.Error())\n\t\treturn\n\t}\n\n\ta, err := sdk.NewAccount(n)\n\tif err != nil {\n\t\tReturnError(c, 500, ErrorCreateAccount.Error())\n\t\treturn\n\t}\n\tseed := a.Seed()\n\n\tf, err := os.OpenFile(seedFile, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0600)\n\tif err != nil {\n\t\tReturnError(c, 500, ErrorOpenSeedFile.Error())\n\t\treturn\n\t}\n\tdefer f.Close()\n\n\t_, err = f.WriteString(fmt.Sprintf(\"SEED:%s\", seed))\n\tif err != nil {\n\t\tReturnError(c, 500, ErrorToWriteSeedFile.Error())\n\t\treturn\n\t}\n\tws.SetAccount(a.AccountNumber(), seed, network) // Record in AccountInfo in memory\n\terr = ws.saveAcct()\n\tif nil != err {\n\t\tReturnError(c, 500, ErrorAutoSaveAccount.Error())\n\t\treturn\n\n\t}\n\tc.JSON(200, map[string]interface{}{\n\t\t\"ok\": 1,\n\t})\n}", "func NewAccount(opts ...AccountCreationOption) (*Account, error) {\n\taccount := &Account{\n\t\tBalance: big.NewInt(0),\n\t\tvotingWeight: big.NewInt(0),\n\t\taccountType: 1,\n\t}\n\tfor _, opt := range opts {\n\t\tif err := opt(account); err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"failed to apply account creation option\")\n\t\t}\n\t}\n\treturn account, nil\n}", "func NewAccount(instanceID uuid.UUID, name, aud string) (*Account, error) {\n\tid, err := uuid.NewV4()\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"Error generating unique id\")\n\t}\n\n\taccount := &Account{\n\t\tInstanceID: instanceID,\n\t\tID: id,\n\t\tAud: aud,\n\t\tName: name,\n\t}\n\treturn account, nil\n}", "func NewAccount(val string) AccountField {\n\treturn AccountField{quickfix.FIXString(val)}\n}", "func NewAccount(id string, name string, primary bool, type_ string, currency Currency, balance AccountBalance, createdAt time.Time, updatedAt time.Time, resource string, resourcePath string, ready bool) *Account {\n\tthis := Account{}\n\tthis.Id = id\n\tthis.Name = name\n\tthis.Primary = primary\n\tthis.Type = type_\n\tthis.Currency = currency\n\tthis.Balance = balance\n\tthis.CreatedAt = createdAt\n\tthis.UpdatedAt = updatedAt\n\tthis.Resource = resource\n\tthis.ResourcePath = resourcePath\n\tthis.Ready = ready\n\treturn &this\n}", "func newRandomAccountPersistence() accountPersistence {\n\taid, sk := modules.NewAccountID()\n\treturn accountPersistence{\n\t\tAccountID: aid,\n\t\tBalance: types.NewCurrency64(fastrand.Uint64n(1e3)),\n\t\tHostKey: types.SiaPublicKey{},\n\t\tSecretKey: sk,\n\t}\n}", "func NewAccount() *Account {\n\tacc := &Account{}\n\tpriv, pub := newKeyPair()\n\tacc.PriKey = priv\n\tacc.PubKey = pub\n\treturn acc\n}", "func (w *Wallet) NewAccount(index *uint32) (a *Account, err error) {\n\tindex2 := w.nextIndex\n\tif index != nil {\n\t\tindex2 = *index\n\t}\n\ta = &Account{w: w, index: index2}\n\tif err = w.impl.deriveAccount(a); err != nil {\n\t\treturn\n\t}\n\tpubkeyToAddress := util.PubkeyToAddress\n\tif w.isBanano {\n\t\tpubkeyToAddress = util.PubkeyToBananoAddress\n\t}\n\tif a.address, err = pubkeyToAddress(a.pubkey); err != nil {\n\t\treturn\n\t}\n\tif index == nil {\n\t\tw.nextIndex++\n\t}\n\tif _, ok := w.accounts[a.address]; !ok {\n\t\tw.accounts[a.address] = a\n\t} else if index == nil {\n\t\treturn w.NewAccount(nil)\n\t}\n\treturn\n}", "func (policy *ticketPolicy) OnCreateNewAccount(acc *types.Account) {\n}", "func MakeNewAccount(name string) (*MyAccount, error) {\n\tkeys, err := NewKeypair()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &MyAccount{\n\t\tFields: make(map[string]string),\n\t\tKeys: keys,\n\t\tName: name,\n\t}, nil\n}", "func NewContinuousVestingAccountRaw(bva *BaseVestingAccount, startTime int64) *ContinuousVestingAccount {\n\treturn &ContinuousVestingAccount{\n\t\tBaseVestingAccount: bva,\n\t\tStartTime: startTime,\n\t}\n}", "func NewAccount(\n\tconfig *accounts.AccountConfig,\n\taccountCoin *Coin,\n\thttpClient *http.Client,\n\tlog *logrus.Entry,\n) *Account {\n\tlog = log.WithField(\"group\", \"eth\").\n\t\tWithFields(logrus.Fields{\"coin\": accountCoin.String(), \"code\": config.Config.Code, \"name\": config.Config.Name})\n\tlog.Debug(\"Creating new account\")\n\n\taccount := &Account{\n\t\tBaseAccount: accounts.NewBaseAccount(config, accountCoin, log),\n\t\tcoin: accountCoin,\n\t\tdbSubfolder: \"\", // set in Initialize()\n\t\tsigningConfiguration: nil,\n\t\thttpClient: httpClient,\n\t\tbalance: coin.NewAmountFromInt64(0),\n\n\t\tenqueueUpdateCh: make(chan struct{}),\n\t\tquitChan: make(chan struct{}),\n\n\t\tlog: log,\n\t}\n\n\treturn account\n}", "func (va ClawbackVestingAccount) GetVestingPeriods() Periods {\n\treturn va.VestingPeriods\n}", "func newReconciledServiceAccount() *corev1.ServiceAccount {\n\treturn NewServiceAccount(newEventSource())()\n}", "func newQuota() *catalogue.Quota {\n\treturn &catalogue.Quota{\n\t\tCores: 99999,\n\t\tFloatingIPs: 99999,\n\t\tInstances: 99999,\n\t\tKeyPairs: 99999,\n\t\tRAM: 99999,\n\t\tTenant: \"test-tenant\",\n\t}\n}", "func NewPeriodicWorker(call PeriodicWorkerCall, period time.Duration, timerFunc NewTimerFunc) Worker {\n\tw := &periodicWorker{newTimer: timerFunc}\n\tgo func() {\n\t\tdefer w.tomb.Done()\n\t\tw.tomb.Kill(w.run(call, period))\n\t}()\n\treturn w\n}", "func NewPeriod() *Period {\n\tp := &Period{}\n\tp.SetType(\"period\")\n\treturn p\n}", "func NewAccount(addr, amount string) *Account {\n\tam := big.NewInt(0)\n\tam.SetString(amount, 0)\n\treturn &Account{Address: addr, Amount: am}\n}", "func NewAccount(acc *types.Account) *Account {\n\treturn &Account{\n\t\tAccount: *acc,\n\t}\n}", "func (pva PeriodicVestingAccount) GetVestingPeriods() Periods {\n\treturn pva.VestingPeriods\n}", "func NewAccount(id, entityID string) *Account {\n\treturn &Account{\n\t\tID: id,\n\t\tEntityID: entityID,\n\t\tWallets: make([]Wallet, 0),\n\t}\n}", "func NewCustomAccounting(h modules.Host, m modules.Miner, r modules.Renter, w modules.Wallet, persistDir string, deps modules.Dependencies) (*Accounting, error) {\n\t// Check that at least the wallet is not nil\n\tif w == nil {\n\t\treturn nil, errNilWallet\n\t}\n\n\t// Check required parameters\n\tif persistDir == \"\" {\n\t\treturn nil, errNilPersistDir\n\t}\n\tif deps == nil {\n\t\treturn nil, errNilDeps\n\t}\n\n\t// Initialize the accounting\n\ta := &Accounting{\n\t\tstaticHost: h,\n\t\tstaticMiner: m,\n\t\tstaticRenter: r,\n\t\tstaticWallet: w,\n\n\t\tstaticPersistDir: persistDir,\n\n\t\tstaticDeps: deps,\n\t}\n\n\t// Initialize the persistence\n\terr := a.initPersist()\n\tif err != nil {\n\t\treturn nil, errors.AddContext(err, \"unable to initialize the persistence\")\n\t}\n\n\t// Launch background thread to persist the accounting information\n\tif !a.staticDeps.Disrupt(\"DisablePersistLoop\") {\n\t\tgo a.callThreadedPersistAccounting()\n\t}\n\treturn a, nil\n}", "func (ak AccountKeeper) NewAccount(ctx sdk.Context, acc exported.Account) exported.Account {\n\t// FIXME: update account number\n\treturn acc\n}", "func (pga periodicGrantAction) AddToAccount(ctx sdk.Context, rawAccount exported.VestingAccount) error {\n\tpva, ok := rawAccount.(*PeriodicVestingAccount)\n\tif !ok {\n\t\treturn sdkerrors.Wrapf(sdkerrors.ErrNotSupported,\n\t\t\t\"account %s must be a PeriodicVestingAccount, got %T\",\n\t\t\trawAccount.GetAddress(), rawAccount)\n\t}\n\tpva.addGrant(ctx, pga.sk, pga.grantStartTime, pga.grantVestingPeriods, pga.grantCoins)\n\treturn nil\n}", "func NewAccount(id string) esfazz.Aggregate {\n\tacc := AccountModel()\n\tacc.Id = id\n\treturn acc\n}", "func New(period int) TokenBucket {\n\tlogger := log.New()\n\treturn &repo{\n\t\tBucket: &sync.Map{},\n\t\tSupplementBucket: make(map[int64][]string),\n\t\tRWMutex: &sync.RWMutex{},\n\t\tLogger: logger,\n\t\tPeriod: period,\n\t}\n}", "func (pva PeriodicVestingAccount) Validate() error {\n\tif pva.GetStartTime() >= pva.GetEndTime() {\n\t\treturn errors.New(\"vesting start-time cannot be before end-time\")\n\t}\n\tendTime := pva.StartTime\n\toriginalVesting := sdk.NewCoins()\n\tfor _, p := range pva.VestingPeriods {\n\t\tendTime += p.Length\n\t\toriginalVesting = originalVesting.Add(p.Amount...)\n\t}\n\tif endTime != pva.EndTime {\n\t\treturn errors.New(\"vesting end time does not match length of all vesting periods\")\n\t}\n\tif !originalVesting.IsEqual(pva.OriginalVesting) {\n\t\treturn errors.New(\"original vesting coins does not match the sum of all coins in vesting periods\")\n\t}\n\n\treturn pva.BaseVestingAccount.Validate()\n}", "func NewAccount() *Account {\n\tpriv, _ := ecdsa.GenerateKey(crypto.S256(), cryptorand.Reader)\n\tpub := base64.URLEncoding.EncodeToString(\n\t\tcrypto.FromECDSAPub(&priv.PublicKey))\n\taddr := hex.EncodeToString(crypto.PubkeyToAddress(priv.PublicKey).Bytes())\n\treturn &Account{\n\t\tID: NewUUID(),\n\t\tEthAddr: addr,\n\t\tPublicKey: pub,\n\t\tPrivateKey: base64.URLEncoding.EncodeToString(crypto.FromECDSA(priv)),\n\t}\n}", "func New() *Accounts {\n\treturn &Accounts{\n\t\tdata: make(map[string]*Account),\n\t}\n}", "func NewAccount(firstName string) *Account {\n\tthis := Account{}\n\tthis.FirstName = firstName\n\treturn &this\n}", "func NewServiceAccount(name, namespace string, so ...ServiceAccountOption) *corev1.ServiceAccount {\n\tsa := &corev1.ServiceAccount{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: name,\n\t\t\tNamespace: namespace,\n\t\t},\n\t}\n\tfor _, opt := range so {\n\t\topt(sa)\n\t}\n\treturn sa\n}", "func New() *Prober {\n\treturn newForTest(time.Now, newRealTicker)\n}", "func (*ticketR) NewStruct() *ticketR {\n\treturn &ticketR{}\n}", "func (builder *AuthBankGenesisBuilder) WithSimplePeriodicVestingAccount(address sdk.AccAddress, balance sdk.Coins, periods vestingtypes.Periods, firstPeriodStartTimestamp int64) *AuthBankGenesisBuilder {\n\tvestingAccount := newPeriodicVestingAccount(address, periods, firstPeriodStartTimestamp)\n\n\treturn builder.\n\t\tWithAccounts(vestingAccount).\n\t\tWithBalances(banktypes.Balance{Address: address.String(), Coins: balance})\n}", "func New(apiKey string) *Clockwork {\n\treturn &Clockwork{\n\t\tapiKey: apiKey,\n\t}\n}", "func makeAccount(){\n\toperatorSecret, err := hedera.SecretKeyFromString(secret)\n\tif err != nil{\n\t\tpanic(err)\n\t}\n\n\tsecretKey, _ := hedera.GenerateSecretKey()\n\tpublic := secretKey.Public()\n\n\tfmt.Printf(\"secret = %v\\n\", secretKey)\n\tfmt.Printf(\"public = %v\\n\", public)\n\n\tclient, err := hedera.Dial(server)\n\tif err !=nil{\n\t\tpanic(err)\n\t}\n\tdefer client.Close()\n\n\tnodeAccountID := hedera.AccountID{Account: 3}\n\toperatorAccountID := hedera.AccountID{Account: 1001}\n\ttime.Sleep(2* time.Second)\n\tresponse, err := client.CreateAccount().Key(public).InitialBalance(0).Operator(operatorAccountID).Node(nodeAccountID).Memo(\"Test make Account\").Sign(operatorSecret).Execute()\n\tif err != nil{\n\t\tpanic(err)\n\t}\n\n\ttransactionID := response.ID\n\tfmt.Printf(\"Created account; transaction = %v\\n\", transactionID)\n\ttime.Sleep(2* time.Second)\n \n\treceipt,err := client.Transaction(*transactionID).Receipt().Get()\n\tif err != nil{\n\t\tpanic(err)\n\t}\n\tfmt.Printf(\"Account = %v\\n\", *receipt.AccountID)\n\n}", "func NewAccount(address string) *Account {\n\treturn &Account{\n\t\tAddress: address,\n\t\tHeight: \"0\",\n\t\tGoldTokenBalance: \"0\",\n\t\tTotalLockedGoldBalance: \"0\",\n\t\tNonVotingLockedGoldBalance: \"0\",\n\t\tVotingLockedGoldBalance: \"0\",\n\t\tPendingWithdrawalBalance: \"0\",\n\t\tCeloUSDValue: \"0\",\n\t\tDelegations: []*Delegation{},\n\t}\n\n}", "func NewServiceAccount(accountName string, namespace string) *core.ServiceAccount {\n\treturn &core.ServiceAccount{\n\t\tTypeMeta: metav1.TypeMeta{\n\t\t\tKind: \"ServiceAccount\",\n\t\t\tAPIVersion: core.SchemeGroupVersion.String(),\n\t\t},\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: accountName,\n\t\t\tNamespace: namespace,\n\t\t},\n\t}\n}", "func NewAccount(file string) (*AccountRoot, error) {\n\tif file == \"\" {\n\t\treturn nil, errors.New(\"config file should be passed\")\n\t}\n\n\tvar err error\n\tconf, err := loadAccount(file)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// debug\n\t// grok.Value(conf)\n\n\t// validate\n\tif err = conf.validate(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn conf, nil\n}", "func ExampleNew() {\n\ttoken := \"0xb64ef51c888972c908cfacf59b47c1afbc0ab8ac\"\n\twallet := \"0x9ea0c535b3eb166454c8ccbaba86850c8df3ee57\"\n\texample, _ = New(token, wallet)\n\tfmt.Printf(\"This wallet has %v %v tokens\", example.BalanceString(), example.Name)\n\t// Output: This wallet has 7.282 StorjToken tokens\n}", "func New(token string) (*GAB, error) {\n\tbot, err := tapi.NewBotAPI(token)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Could not create new bot with provided token: %v\", err)\n\t}\n\tlog.Printf(\"Authorized on account %s\", bot.Self.UserName)\n\treturn &GAB{\n\t\tTelBot: bot,\n\t}, nil\n}", "func NewPeriod(duration time.Duration) Period {\n\treturn period{\n\t\tduration: duration,\n\t}\n}", "func NewAccount(newid AccountIDType, newemail string) *Account {\n\treturn &Account{\n\t\tid: newid,\n\t\temail: newemail,\n\t}\n}", "func NewPeriodSlot(year int16) PeriodSlot {\n\treturn PeriodSlot{year}\n}", "func NewAccount(email string) *Account {\n\treturn &Account{email: email}\n}", "func NewRBACAccount(accountName string, config *model.Configuration, settings ExportSettings) ([]helm.Node, error) {\n\tvar resources []helm.Node\n\tblock := authModeRBAC(settings)\n\n\taccount, ok := config.Authorization.Accounts[accountName]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"Account %s not found\", accountName)\n\t}\n\n\tif len(account.UsedBy) < 1 {\n\t\t// Nothing uses this account\n\t\t// Possibly, we generated a privileged version instead\n\t\treturn nil, nil\n\t}\n\n\t// If we want to modify the default account, there's no need to create it\n\t// first -- it already exists\n\tif accountName != \"default\" {\n\t\tvar instanceGroupNames []string\n\t\tfor instanceGroupName := range account.UsedBy {\n\t\t\tinstanceGroupNames = append(instanceGroupNames, fmt.Sprintf(\"- %s\", instanceGroupName))\n\t\t}\n\t\tsort.Strings(instanceGroupNames)\n\t\tdescription := fmt.Sprintf(\n\t\t\t\"Service account \\\"%s\\\" is used by the following instance groups:\\n%s\",\n\t\t\taccountName,\n\t\t\tstrings.Join(instanceGroupNames, \"\\n\"))\n\n\t\tcb := NewConfigBuilder().\n\t\t\tSetSettings(&settings).\n\t\t\tSetAPIVersion(\"v1\").\n\t\t\tSetKind(\"ServiceAccount\").\n\t\t\tSetName(accountName).\n\t\t\tAddModifier(block).\n\t\t\tAddModifier(helm.Comment(description))\n\t\tserviceAccount, err := cb.Build()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to build a new kube config: %v\", err)\n\t\t}\n\t\tresources = append(resources, serviceAccount)\n\t}\n\n\t// For each role, create a role binding\n\tfor _, roleName := range account.Roles {\n\t\t// Embed the role first, if it's only used by this binding\n\t\tvar usedByAccounts []string\n\t\tfor accountName := range config.Authorization.RoleUsedBy[roleName] {\n\t\t\tusedByAccounts = append(usedByAccounts, fmt.Sprintf(\"- %s\", accountName))\n\t\t}\n\t\tif len(usedByAccounts) < 2 {\n\t\t\trole, err := NewRBACRole(\n\t\t\t\troleName,\n\t\t\t\tRBACRoleKindRole,\n\t\t\t\tconfig.Authorization.Roles[roleName],\n\t\t\t\tsettings)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\trole.Set(helm.Comment(fmt.Sprintf(`Role \"%s\" only used by account \"%s\"`, roleName, usedByAccounts)))\n\t\t\tresources = append(resources, role)\n\t\t}\n\n\t\tcb := NewConfigBuilder().\n\t\t\tSetSettings(&settings).\n\t\t\tSetAPIVersion(\"rbac.authorization.k8s.io/v1\").\n\t\t\tSetKind(\"RoleBinding\").\n\t\t\tSetName(fmt.Sprintf(\"%s-%s-binding\", accountName, roleName)).\n\t\t\tAddModifier(block).\n\t\t\tAddModifier(helm.Comment(fmt.Sprintf(`Role binding for service account \"%s\" and role \"%s\"`,\n\t\t\t\taccountName,\n\t\t\t\troleName)))\n\t\tbinding, err := cb.Build()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to build a new kube config: %v\", err)\n\t\t}\n\t\tsubjects := helm.NewList(helm.NewMapping(\n\t\t\t\"kind\", \"ServiceAccount\",\n\t\t\t\"name\", accountName))\n\t\tbinding.Add(\"subjects\", subjects)\n\t\tbinding.Add(\"roleRef\", helm.NewMapping(\n\t\t\t\"apiGroup\", \"rbac.authorization.k8s.io\",\n\t\t\t\"kind\", \"Role\",\n\t\t\t\"name\", roleName))\n\t\tresources = append(resources, binding)\n\t}\n\n\t// We have no proper namespace default for kube configuration.\n\tnamespace := \"~\"\n\tif settings.CreateHelmChart {\n\t\tnamespace = \"{{ .Release.Namespace }}\"\n\t}\n\n\t// For each cluster role, create a cluster role binding\n\t// And if the cluster role is only used here, embed that too\n\tfor _, clusterRoleName := range account.ClusterRoles {\n\t\t// Embed the cluster role first, if it's only used by this binding\n\t\tvar accountNames []string\n\t\tfor accountName := range config.Authorization.ClusterRoleUsedBy[clusterRoleName] {\n\t\t\taccountNames = append(accountNames, accountName)\n\t\t}\n\t\tif len(accountNames) < 2 {\n\t\t\trole, err := NewRBACRole(\n\t\t\t\tclusterRoleName,\n\t\t\t\tRBACRoleKindClusterRole,\n\t\t\t\tconfig.Authorization.ClusterRoles[clusterRoleName],\n\t\t\t\tsettings)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\trole.Set(helm.Comment(fmt.Sprintf(`Cluster role \"%s\" only used by account \"%s\"`, clusterRoleName, accountNames)))\n\t\t\tresources = append(resources, role)\n\t\t}\n\n\t\tcb := NewConfigBuilder().\n\t\t\tSetSettings(&settings).\n\t\t\tSetAPIVersion(\"rbac.authorization.k8s.io/v1\").\n\t\t\tSetKind(\"ClusterRoleBinding\").\n\t\t\tAddModifier(block).\n\t\t\tAddModifier(helm.Comment(fmt.Sprintf(`Cluster role binding for service account \"%s\" and cluster role \"%s\"`,\n\t\t\t\taccountName,\n\t\t\t\tclusterRoleName)))\n\t\tif settings.CreateHelmChart {\n\t\t\tcb.SetNameHelmExpression(\n\t\t\t\tfmt.Sprintf(`{{ template \"fissile.SanitizeName\" (printf \"%%s-%s-%s-cluster-binding\" .Release.Namespace) }}`,\n\t\t\t\t\taccountName,\n\t\t\t\t\tclusterRoleName))\n\t\t} else {\n\t\t\tcb.SetName(fmt.Sprintf(\"%s-%s-cluster-binding\", accountName, clusterRoleName))\n\t\t}\n\t\tbinding, err := cb.Build()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to build a new kube config: %v\", err)\n\t\t}\n\t\tsubjects := helm.NewList(helm.NewMapping(\n\t\t\t\"kind\", \"ServiceAccount\",\n\t\t\t\"name\", accountName,\n\t\t\t\"namespace\", namespace))\n\t\tbinding.Add(\"subjects\", subjects)\n\t\troleRef := helm.NewMapping(\n\t\t\t\"kind\", \"ClusterRole\",\n\t\t\t\"apiGroup\", \"rbac.authorization.k8s.io\")\n\t\tif settings.CreateHelmChart {\n\t\t\troleRef.Add(\"name\", fmt.Sprintf(`{{ template \"fissile.SanitizeName\" (printf \"%%s-cluster-role-%s\" .Release.Namespace) }}`, clusterRoleName))\n\t\t} else {\n\t\t\troleRef.Add(\"name\", clusterRoleName)\n\t\t}\n\t\tbinding.Add(\"roleRef\", roleRef)\n\t\tresources = append(resources, binding)\n\t}\n\n\treturn resources, nil\n}", "func tNewUser(lbl string) *tUser {\n\tintBytes := make([]byte, 4)\n\tbinary.BigEndian.PutUint32(intBytes, acctCounter)\n\tacctID := account.AccountID{}\n\tcopy(acctID[:], acctTemplate[:])\n\tcopy(acctID[account.HashSize-4:], intBytes)\n\taddr := strconv.Itoa(int(acctCounter))\n\tsig := []byte{0xab} // Just to differentiate from the addr.\n\tsig = append(sig, intBytes...)\n\tsigHex := hex.EncodeToString(sig)\n\tacctCounter++\n\treturn &tUser{\n\t\tsig: sig,\n\t\tsigHex: sigHex,\n\t\tacct: acctID,\n\t\taddr: addr,\n\t\tlbl: lbl,\n\t}\n}", "func New(ctx context.Context, t *testing.T, cfg Config) *Hospital {\n\tt.Helper()\n\treturn WithTime(ctx, t, cfg, now)\n}", "func MakeStandaloneBudget(capacity int64) BoundAccount {\n\treturn BoundAccount{used: capacity}\n}", "func New(policy *Policy) *RateLimiter {\n\trl := &RateLimiter{\n\t\tpolicy: policy,\n\t\tstartTime: nowFunc(),\n\t}\n\treturn rl\n}", "func (pva *PeriodicVestingAccount) UnmarshalJSON(bz []byte) error {\n\tvar alias vestingAccountJSON\n\tif err := legacy.Cdc.UnmarshalJSON(bz, &alias); err != nil {\n\t\treturn err\n\t}\n\n\tpva.BaseVestingAccount = &BaseVestingAccount{\n\t\tBaseAccount: NewBaseAccount(alias.Address, alias.Coins, alias.PubKey, alias.AccountNumber, alias.Sequence),\n\t\tOriginalVesting: alias.OriginalVesting,\n\t\tDelegatedFree: alias.DelegatedFree,\n\t\tDelegatedVesting: alias.DelegatedVesting,\n\t\tEndTime: alias.EndTime,\n\t}\n\tpva.StartTime = alias.StartTime\n\tpva.VestingPeriods = alias.VestingPeriods\n\n\treturn nil\n}", "func NewServiceAccount(name string, namespace string) *corev1.ServiceAccount {\n\treturn &corev1.ServiceAccount{\n\n\t\tTypeMeta: metav1.TypeMeta{\n\t\t\tKind: \"ServiceAccount\",\n\t\t\tAPIVersion: \"v1\",\n\t\t},\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: name,\n\t\t\tNamespace: namespace,\n\t\t},\n\t}\n}", "func New(rate int, opts ...Option) Limiter {\n\treturn newAtomicBased(rate, opts...)\n}", "func New() {\n\tfmt.Println(POLICY_TEMPLATE_OBJECT)\n}", "func New(token string) *Service {\n\tlog.Println(\"Initializing accounts service\")\n\treturn &Service{\n\t\thttpClient: client.New(accountServiceBaseURL, token),\n\t}\n}", "func New(rate int, opts ...Option) Limiter {\r\n\treturn newAtomicBased(rate, opts...)\r\n}", "func NewServiceAccount(sc *dcv1alpha1.SparkCluster) *corev1.ServiceAccount {\n\treturn &corev1.ServiceAccount{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: InstanceObjectName(sc.Name, ComponentNone),\n\t\t\tNamespace: sc.Namespace,\n\t\t\tLabels: MetadataLabels(sc),\n\t\t},\n\t\tAutomountServiceAccountToken: pointer.BoolPtr(false),\n\t}\n}", "func NewVppToken()(*VppToken) {\n m := &VppToken{\n Entity: *NewEntity(),\n }\n return m\n}", "func NewFoo() *Foo {\n return &Foo{}\n}", "func NewTrade(symbol string, capacity int) *Trade {\n\tmodel := &Trade{\n\t\tTbk: io.NewTimeBucketKey(TradeBucketKey(symbol)),\n\t}\n\tmodel.make(capacity)\n\treturn model\n}", "func New(apiKey string) Interface {\n\tvar (\n\t\tcom communication.Interface\n\t\twbs *impl\n\t\turi string\n\t\tfromAt time.Time\n\t)\n\n\tcom, fromAt = communication.New(), time.Now().Truncate(time.Hour*24)\n\turi = fmt.Sprintf(serviceURNv1, serviceURL)\n\twbs = &impl{\n\t\tapiKey: apiKey,\n\t\tinc: incomes.New(com, uri, apiKey, fromAt),\n\t\tods: orders.New(com, uri, apiKey, fromAt),\n\t\tsle: sales.New(com, uri, apiKey, fromAt),\n\t\tstk: stocks.New(com, uri, apiKey, fromAt),\n\t\tmds: monthSale.New(com, uri, apiKey, fromAt),\n\t\tcom: com,\n\t\tfromAt: fromAt,\n\t}\n\n\treturn wbs\n}", "func GenPrivAccount() *PrivAccount {\n\tprivKeyBytes := new([64]byte)\n\tcopy(privKeyBytes[:32], CRandBytes(32))\n\tpubKeyBytes := ed25519.MakePublicKey(privKeyBytes)\n\tpubKey := PubKeyEd25519(pubKeyBytes[:])\n\tprivKey := PrivKeyEd25519(privKeyBytes[:])\n\treturn &PrivAccount{\n\t\tAddress: pubKey.Address(),\n\t\tPubKey: pubKey,\n\t\tPrivKey: privKey,\n\t}\n}", "func NewPeriodicGrantAction(\n\tsk StakingKeeper,\n\tgrantStartTime int64,\n\tgrantVestingPeriods []Period,\n\tgrantCoins sdk.Coins,\n) exported.AddGrantAction {\n\treturn periodicGrantAction{\n\t\tsk: sk,\n\t\tgrantStartTime: grantStartTime,\n\t\tgrantVestingPeriods: grantVestingPeriods,\n\t\tgrantCoins: grantCoins,\n\t}\n}", "func (c Client) New(params *stripe.TreasuryOutboundPaymentParams) (*stripe.TreasuryOutboundPayment, error) {\n\toutboundpayment := &stripe.TreasuryOutboundPayment{}\n\terr := c.B.Call(\n\t\thttp.MethodPost,\n\t\t\"/v1/treasury/outbound_payments\",\n\t\tc.Key,\n\t\tparams,\n\t\toutboundpayment,\n\t)\n\treturn outboundpayment, err\n}", "func New(OrganisationID string, BaseURL string) *Client {\n\tconfig := config{\n\t\tURL: BaseURL,\n\t\tOrganisationID: OrganisationID,\n\t\tclient: &http.Client{},\n\t}\n\treturn &Client{\n\t\tAccount: AccountEndpoint{\n\t\t\tconfig: &config,\n\t\t},\n\t}\n}", "func NewMontrealTrip(weight float32, deadline int) *Trip {\n trip := Trip{weight: weight, destination: \"Montreal\", deadline: deadline}\n return &trip\n}", "func NewAccount(addr *Address) *Account {\n\treturn &Account{\n\t\taccount: common.NewAccount(common.BytesToAddress(addr.Bytes())),\n\t}\n}", "func New(key string, org string) (*Api, error) {\n\ta := Api{}\n\ta.key = key\n\ta.org = org\n\ta.timezone = \"UTC\"\n\n\ta.client = pagerduty.NewClient(key)\n\n\t_, err := a.client.ListSchedules(pagerduty.ListSchedulesOptions{})\n\tif err != nil {\n\t\treturn &a, fmt.Errorf(\"Failed to list on-call schedules: %v\", err)\n\t}\n\n\tlog.Info(\"Authenticated with PagerDuty\")\n\n\treturn &a, nil\n}", "func (pva *PeriodicVestingAccount) addGrant(ctx sdk.Context, sk StakingKeeper, grantStartTime int64, grantVestingPeriods []Period, grantCoins sdk.Coins) {\n\t// how much is really delegated?\n\tbondedAmt := sk.GetDelegatorBonded(ctx, pva.GetAddress())\n\tunbondingAmt := sk.GetDelegatorUnbonding(ctx, pva.GetAddress())\n\tdelegatedAmt := bondedAmt.Add(unbondingAmt)\n\tdelegated := sdk.NewCoins(sdk.NewCoin(sk.BondDenom(ctx), delegatedAmt))\n\n\t// discover what has been slashed\n\toldDelegated := pva.DelegatedVesting.Add(pva.DelegatedFree...)\n\tslashed := oldDelegated.Sub(coinsMin(oldDelegated, delegated))\n\n\t// rebase the DV+DF by capping slashed at the current unvested amount\n\tunvested := pva.GetVestingCoins(ctx.BlockTime())\n\tnewSlashed := coinsMin(unvested, slashed)\n\tnewTotalDelegated := delegated.Add(newSlashed...)\n\n\t// modify vesting schedule for the new grant\n\tnewStart, newEnd, newPeriods := DisjunctPeriods(pva.StartTime, grantStartTime,\n\t\tpva.GetVestingPeriods(), grantVestingPeriods)\n\tpva.StartTime = newStart\n\tpva.EndTime = newEnd\n\tpva.VestingPeriods = newPeriods\n\tpva.OriginalVesting = pva.OriginalVesting.Add(grantCoins...)\n\n\t// cap DV at the current unvested amount, DF rounds out to newTotalDelegated\n\tunvested2 := pva.GetVestingCoins(ctx.BlockTime())\n\tpva.DelegatedVesting = coinsMin(newTotalDelegated, unvested2)\n\tpva.DelegatedFree = newTotalDelegated.Sub(pva.DelegatedVesting)\n}", "func NewTrainCar() TrainCar {\n c := TrainCar{name: \"TrainCar\", vehicle: \"TrainCar\", speed: 30, capacity: 30, railway: \"CNR\"}\n return c\n}", "func NewAllocAccount(val string) AllocAccountField {\n\treturn AllocAccountField{quickfix.FIXString(val)}\n}" ]
[ "0.8544836", "0.69821393", "0.6438208", "0.6292526", "0.62608457", "0.6215964", "0.61970264", "0.6108542", "0.5944803", "0.5915925", "0.57264006", "0.5667008", "0.5575679", "0.55671585", "0.5528065", "0.5527509", "0.5518966", "0.54529744", "0.54477406", "0.54477406", "0.54178697", "0.54082716", "0.5405061", "0.54026914", "0.53972805", "0.53817797", "0.53536993", "0.53488684", "0.52914184", "0.5274751", "0.52456355", "0.5243129", "0.52356416", "0.52246964", "0.5192932", "0.51811695", "0.5165033", "0.51552874", "0.5152806", "0.515255", "0.5150487", "0.5150306", "0.51422465", "0.5135041", "0.5117746", "0.5110263", "0.51020557", "0.50873876", "0.5084372", "0.50831515", "0.5077215", "0.50658137", "0.5013381", "0.5009134", "0.4990348", "0.4970368", "0.49653468", "0.49633518", "0.49541065", "0.4952022", "0.49404988", "0.49401477", "0.49306324", "0.48713344", "0.4870057", "0.4864155", "0.48575205", "0.48497757", "0.48410693", "0.4833401", "0.4833065", "0.4825373", "0.4813422", "0.4810344", "0.4808641", "0.48080024", "0.48043773", "0.47985086", "0.47984153", "0.4787007", "0.47696927", "0.4736201", "0.47335237", "0.47287202", "0.47191808", "0.4707441", "0.47057784", "0.4697634", "0.469748", "0.4696087", "0.46957102", "0.46896538", "0.46800354", "0.46782604", "0.46748257", "0.4672914", "0.46708882", "0.46675768", "0.46646297", "0.46380916" ]
0.83124036
1
GetVestedCoins returns the total number of vested coins. If no coins are vested, nil is returned.
func (pva PeriodicVestingAccount) GetVestedCoins(blockTime time.Time) sdk.Coins { coins := ReadSchedule(pva.StartTime, pva.EndTime, pva.VestingPeriods, pva.OriginalVesting, blockTime.Unix()) if coins.IsZero() { return nil } return coins }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (plva PermanentLockedAccount) GetVestedCoins(_ time.Time) sdk.Coins {\n\treturn nil\n}", "func (va ClawbackVestingAccount) GetVestedCoins(blockTime time.Time) sdk.Coins {\n\t// It's likely that one or the other schedule will be nearly trivial,\n\t// so there should be little overhead in recomputing the conjunction each time.\n\tcoins := coinsMin(va.GetUnlockedOnly(blockTime), va.GetVestedOnly(blockTime))\n\tif coins.IsZero() {\n\t\treturn nil\n\t}\n\treturn coins\n}", "func (dva DelayedVestingAccount) GetVestedCoins(blockTime time.Time) sdk.Coins {\n\tif blockTime.Unix() >= dva.EndTime {\n\t\treturn dva.OriginalVesting\n\t}\n\n\treturn nil\n}", "func (cva ContinuousVestingAccount) GetVestedCoins(blockTime time.Time) sdk.Coins {\n\tvar vestedCoins sdk.Coins\n\n\t// We must handle the case where the start time for a vesting account has\n\t// been set into the future or when the start of the chain is not exactly\n\t// known.\n\tif blockTime.Unix() <= cva.StartTime {\n\t\treturn vestedCoins\n\t} else if blockTime.Unix() >= cva.EndTime {\n\t\treturn cva.OriginalVesting\n\t}\n\n\t// calculate the vesting scalar\n\tx := blockTime.Unix() - cva.StartTime\n\ty := cva.EndTime - cva.StartTime\n\ts := sdk.NewDec(x).Quo(sdk.NewDec(y))\n\n\tfor _, ovc := range cva.OriginalVesting {\n\t\tvestedAmt := ovc.Amount.ToDec().Mul(s).RoundInt()\n\t\tvestedCoins = append(vestedCoins, sdk.NewCoin(ovc.Denom, vestedAmt))\n\t}\n\n\treturn vestedCoins\n}", "func (vva ValidatorVestingAccount) GetVestedCoins(blockTime time.Time) sdk.Coins {\n\tvar vestedCoins sdk.Coins\n\tif blockTime.Unix() <= vva.StartTime {\n\t\treturn vestedCoins\n\t}\n\tcurrentPeriodStartTime := vva.StartTime\n\tnumberPeriods := len(vva.VestingPeriods)\n\tfor i := 0; i < numberPeriods; i++ {\n\t\tx := blockTime.Unix() - currentPeriodStartTime\n\t\tif x >= vva.VestingPeriods[i].Length {\n\t\t\tif vva.VestingPeriodProgress[i].PeriodComplete {\n\t\t\t\tvestedCoins = vestedCoins.Add(vva.VestingPeriods[i].Amount)\n\t\t\t}\n\t\t\tcurrentPeriodStartTime += vva.VestingPeriods[i].Length\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn vestedCoins\n\n}", "func (cva ContinuousVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn cva.OriginalVesting.Sub(cva.GetVestedCoins(blockTime))\n}", "func (vva ValidatorVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn vva.OriginalVesting.Sub(vva.GetVestedCoins(blockTime))\n}", "func (va ClawbackVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn va.OriginalVesting.Sub(va.GetVestedCoins(blockTime))\n}", "func (dva DelayedVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn dva.OriginalVesting.Sub(dva.GetVestedCoins(blockTime))\n}", "func (pva PeriodicVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn pva.OriginalVesting.Sub(pva.GetVestedCoins(blockTime))\n}", "func (plva PermanentLockedAccount) GetVestingCoins(_ time.Time) sdk.Coins {\n\treturn plva.OriginalVesting\n}", "func (vva ValidatorVestingAccount) GetFailedVestedCoins() sdk.Coins {\n\tvar failedVestedCoins sdk.Coins\n\tnumberPeriods := len(vva.VestingPeriods)\n\tfor i := 0; i < numberPeriods; i++ {\n\t\tif vva.VestingPeriodProgress[i].PeriodComplete {\n\t\t\tif !vva.VestingPeriodProgress[i].VestingSuccessful {\n\t\t\t\tfailedVestedCoins = failedVestedCoins.Add(vva.VestingPeriods[i].Amount)\n\t\t\t}\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn failedVestedCoins\n}", "func (keeper ViewKeeper) GetCoins(ctx sdk.Context, addr sdk.Address) sdk.Coins {\n\treturn getCoins(ctx, keeper.am, addr)\n}", "func (keeper BaseViewKeeper) GetCoins(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins {\n\treturn getCoins(ctx, keeper.am, addr)\n}", "func GetCoins() (coins []Coin, error error) {\n\tvar c = []Coin{}\n\tvar d struct {\n\t\tCrypto []Coin `json:\"crypto\"`\n\t}\n\tjsonData, err := doTauRequest(1, \"GET\", \"data/coins\", nil)\n\tif err != nil {\n\t\treturn c, err\n\t}\n\tif err := json.Unmarshal(jsonData, &d); err != nil {\n\t\treturn c, err\n\t}\n\treturn d.Crypto, nil\n}", "func (keeper SendKeeper) GetCoins(ctx sdk.Context, addr sdk.Address) sdk.Coins {\n\treturn getCoins(ctx, keeper.am, addr)\n}", "func (cva ContinuousVestingAccount) LockedCoins(ctx sdk.Context) sdk.Coins {\n\treturn cva.BaseVestingAccount.LockedCoinsFromVesting(cva.GetVestingCoins(ctx.BlockTime()))\n}", "func (keeper Keeper) GetCoins(ctx sdk.Context, addr sdk.Address) sdk.Coins {\n\treturn getCoins(ctx, keeper.am, addr)\n}", "func (vva ValidatorVestingAccount) SpendableCoins(blockTime time.Time) sdk.Coins {\n\treturn vva.BaseVestingAccount.SpendableCoinsVestingAccount(vva.GetVestingCoins(blockTime))\n}", "func (va ClawbackVestingAccount) LockedCoins(ctx sdk.Context) sdk.Coins {\n\treturn va.BaseVestingAccount.LockedCoinsFromVesting(va.GetVestingCoins(ctx.BlockTime()))\n}", "func (ck CoinKeeper) GetCoins(ctx sdk.Context, addr sdk.Address, amt sdk.Coins) sdk.Coins {\n\tacc := ck.am.GetAccount(ctx, addr)\n\treturn acc.GetCoins()\n}", "func (t *TauAPI) GetCoins() (coins []Coin, error error) {\n\tvar c = []Coin{}\n\tvar d struct {\n\t\tCrypto []Coin `json:\"cryto\"` //typo from api\n\t\tFiat []Coin `json:\"fiat\"`\n\t}\n\tjsonData, err := t.doTauRequest(&TauReq{\n\t\tVersion: 2,\n\t\tMethod: \"GET\",\n\t\tPath: \"coins\",\n\t})\n\tif err != nil {\n\t\treturn c, err\n\t}\n\tif err := json.Unmarshal(jsonData, &d); err != nil {\n\t\treturn c, err\n\t}\n\tc = append(d.Crypto, d.Fiat...)\n\treturn c, nil\n}", "func (va ClawbackVestingAccount) GetVestedOnly(blockTime time.Time) sdk.Coins {\n\treturn ReadSchedule(va.StartTime, va.EndTime, va.VestingPeriods, va.OriginalVesting, blockTime.Unix())\n}", "func (pva PeriodicVestingAccount) LockedCoins(ctx sdk.Context) sdk.Coins {\n\treturn pva.BaseVestingAccount.LockedCoinsFromVesting(pva.GetVestingCoins(ctx.BlockTime()))\n}", "func (candidate *Candidate) GetTotalBipStake() *big.Int {\n\tcandidate.lock.RLock()\n\tdefer candidate.lock.RUnlock()\n\n\treturn big.NewInt(0).Set(candidate.totalBipStake)\n}", "func (dva DelayedVestingAccount) LockedCoins(ctx sdk.Context) sdk.Coins {\n\treturn dva.BaseVestingAccount.LockedCoinsFromVesting(dva.GetVestingCoins(ctx.BlockTime()))\n}", "func (m *Client) GetCoins() ([]string, error) {\n\tresp, err := m.Service.GetCoins()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error requesting coin list: %s\", err)\n\t}\n\tdefer resp.Body.Close()\n\n\tvar response []string\n\terr = json.NewDecoder(resp.Body).Decode(&response)\n\tif err != nil {\n\t\tmsg, _ := ioutil.ReadAll(resp.Body)\n\t\treturn nil, fmt.Errorf(\"error decoding coin list: %s: %s\", msg, err)\n\t}\n\n\treturn response, nil\n}", "func (k Keeper) GetWinnerIncentives(ctx sdk.Context) float32 {\n\tgames := float32(k.GetGames(ctx))\n\tvotes := float32(k.GetVotes(ctx))\n\tgVR := float32(k.GetParams(ctx).GameVoteRatio) / 100\n\treturn games / (votes*gVR + games)\n}", "func (r *ParseResult) GetVoutAmount(vout int) (*big.Int, error) {\n\tamt := big.NewInt(0)\n\n\tif !(r.TokenType == TokenTypeFungible01 ||\n\t\tr.TokenType == TokenTypeNft1Child41 ||\n\t\tr.TokenType == TokenTypeNft1Group81) {\n\t\treturn nil, errors.New(\"cannot extract amount for not type 1 or NFT1 token\")\n\t}\n\n\tif vout == 0 {\n\t\treturn amt, nil\n\t}\n\n\tif r.TransactionType == TransactionTypeSend {\n\t\tif vout > len(r.Data.(SlpSend).Amounts) {\n\t\t\treturn amt, nil\n\t\t}\n\t\treturn amt.Add(amt, new(big.Int).SetUint64(r.Data.(SlpSend).Amounts[vout-1])), nil\n\t} else if r.TransactionType == TransactionTypeMint {\n\t\tif vout == 1 {\n\t\t\treturn amt.Add(amt, new(big.Int).SetUint64(r.Data.(SlpMint).Qty)), nil\n\t\t}\n\t\treturn amt, nil\n\t} else if r.TransactionType == TransactionTypeGenesis {\n\t\tif vout == 1 {\n\t\t\treturn amt.Add(amt, new(big.Int).SetUint64(r.Data.(SlpGenesis).Qty)), nil\n\t\t}\n\t\treturn amt, nil\n\t}\n\treturn nil, errors.New(\"unknown error getting vout amount\")\n}", "func (_TokenVesting *TokenVestingCaller) VestedAmount(opts *bind.CallOpts, _token common.Address) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _TokenVesting.contract.Call(opts, out, \"vestedAmount\", _token)\n\treturn *ret0, err\n}", "func (_TokenVesting *TokenVestingCallerSession) VestedAmount(_token common.Address) (*big.Int, error) {\n\treturn _TokenVesting.Contract.VestedAmount(&_TokenVesting.CallOpts, _token)\n}", "func (_TokenVesting *TokenVestingSession) VestedAmount(_token common.Address) (*big.Int, error) {\n\treturn _TokenVesting.Contract.VestedAmount(&_TokenVesting.CallOpts, _token)\n}", "func (_Bindings *BindingsCallerSession) TotalReserves() (*big.Int, error) {\n\treturn _Bindings.Contract.TotalReserves(&_Bindings.CallOpts)\n}", "func coins(a int) int {\n\tif a == 0 {\n\t\treturn 0\n\t}\n\treturn doCoins(a, 25)\n}", "func GetCoins(accCoins []types.Coin) AccountCoins {\n\tcoins := make(AccountCoins, 0)\n\tfor _, coin := range accCoins {\n\t\tcoins = append(coins, AccountCoin{Amount: uint64(coin.Amount), Denom: coin.Denom})\n\t}\n\treturn coins\n}", "func (o *LoyaltySubLedger) GetTotalSpentPoints() float32 {\n\tif o == nil {\n\t\tvar ret float32\n\t\treturn ret\n\t}\n\n\treturn o.TotalSpentPoints\n}", "func (bva BaseVestingAccount) LockedCoinsFromVesting(vestingCoins sdk.Coins) sdk.Coins {\n\tlockedCoins := vestingCoins.Sub(vestingCoins.Min(bva.DelegatedVesting))\n\tif lockedCoins == nil {\n\t\treturn sdk.Coins{}\n\t}\n\treturn lockedCoins\n}", "func (_Bindings *BindingsSession) TotalReserves() (*big.Int, error) {\n\treturn _Bindings.Contract.TotalReserves(&_Bindings.CallOpts)\n}", "func (r *Repository) GetAmountsOfManageCandidates(ctx context.Context, companyID string) (int32, int32, error) {\n\tobjCompanyID, err := primitive.ObjectIDFromHex(companyID)\n\tif err != nil {\n\t\treturn 0, 0, errors.New(`wrong_id`)\n\t}\n\n\tamount := struct {\n\t\tSaved int32 `bson:\"saved_candidates\"`\n\t\tSkipped int32 `bson:\"skipped_candidates\"`\n\t\t// Alerts int32 `bson:\"alerts\"`\n\t}{}\n\n\tcursor, err := r.companiesCollection.Aggregate(\n\t\tctx,\n\t\t[]bson.M{\n\t\t\t{\n\t\t\t\t\"$match\": bson.M{\n\t\t\t\t\t\"company_id\": objCompanyID,\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\t\"$addFields\": bson.M{\n\t\t\t\t\t\"saved_candidates\": bson.M{\n\t\t\t\t\t\t\"$size\": \"$saved_candidates\",\n\t\t\t\t\t},\n\t\t\t\t\t\"skipped_candidates\": bson.M{\n\t\t\t\t\t\t\"$size\": \"$skipped_candidates\",\n\t\t\t\t\t},\n\t\t\t\t\t// \"alerts\": bson.M{\n\t\t\t\t\t// \t\"$size\": \"$alerts\", // TODO:\n\t\t\t\t\t// },\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\t\"$project\": bson.M{\n\t\t\t\t\t\"saved_candidates\": 1,\n\t\t\t\t\t\"skipped_candidates\": 1,\n\t\t\t\t\t// \"alerts\": 1,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t)\n\tif err != nil {\n\t\tif err == mongo.ErrNoDocuments {\n\t\t\treturn 0, 0, errors.New(`not_found`)\n\t\t}\n\t\treturn 0, 0, err\n\t}\n\tdefer cursor.Close(ctx)\n\n\tif cursor.Next(ctx) {\n\t\terr = cursor.Decode(&amount)\n\t\tif err != nil {\n\t\t\treturn 0, 0, err\n\t\t}\n\t}\n\n\treturn amount.Saved, amount.Skipped, nil\n}", "func (o *Transaction) GetCounterparties() []TransactionCounterparty {\n\tif o == nil || o.Counterparties == nil {\n\t\tvar ret []TransactionCounterparty\n\t\treturn ret\n\t}\n\treturn *o.Counterparties\n}", "func (_CrToken *CrTokenCallerSession) TotalReserves() (*big.Int, error) {\n\treturn _CrToken.Contract.TotalReserves(&_CrToken.CallOpts)\n}", "func (_Bindings *BindingsCaller) TotalReserves(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _Bindings.contract.Call(opts, out, \"totalReserves\")\n\treturn *ret0, err\n}", "func (c Cart) GetVoucherSavings() domain.Price {\n\tprice := domain.Price{}\n\tvar err error\n\n\tfor _, item := range c.Totalitems {\n\t\tif item.Type == TotalsTypeVoucher {\n\t\t\tprice, err = price.Add(item.Price)\n\t\t\tif err != nil {\n\t\t\t\treturn price\n\t\t\t}\n\t\t}\n\t}\n\n\tif price.IsNegative() {\n\t\treturn domain.Price{}\n\t}\n\n\treturn price\n}", "func (_CrToken *CrTokenCaller) TotalReserves(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _CrToken.contract.Call(opts, &out, \"totalReserves\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (_CrToken *CrTokenSession) TotalReserves() (*big.Int, error) {\n\treturn _CrToken.Contract.TotalReserves(&_CrToken.CallOpts)\n}", "func (p *Player) CashSpentTotal() int {\n\treturn p.AdditionalPlayerInformation.TotalCashSpent\n}", "func (keeper ViewKeeper) HasCoins(ctx sdk.Context, addr sdk.Address, amt sdk.Coins) bool {\n\treturn hasCoins(ctx, keeper.am, addr, amt)\n}", "func (keeper BaseViewKeeper) HasCoins(ctx sdk.Context, addr sdk.AccAddress, amt sdk.Coins) bool {\n\treturn hasCoins(ctx, keeper.am, addr, amt)\n}", "func (keeper Keeper) SubtractCoins(ctx sdk.Context, addr sdk.Address, amt sdk.Coins) (sdk.Coins, sdk.Error) {\n\treturn subtractCoins(ctx, keeper.am, addr, amt)\n}", "func (cm *ConnectionManager) sumDeposits() *big.Int {\n\tchs := cm.openChannels()\n\tvar sum = big.NewInt(0)\n\tfor _, c := range chs {\n\t\tsum.Add(sum, c.OurContractBalance)\n\t}\n\treturn sum\n}", "func (plva PermanentLockedAccount) LockedCoins(_ sdk.Context) sdk.Coins {\n\treturn plva.BaseVestingAccount.LockedCoinsFromVesting(plva.OriginalVesting)\n}", "func (_Vault *VaultCaller) GetDecimals(opts *bind.CallOpts, token common.Address) (uint8, error) {\n\tvar (\n\t\tret0 = new(uint8)\n\t)\n\tout := ret0\n\terr := _Vault.contract.Call(opts, out, \"getDecimals\", token)\n\treturn *ret0, err\n}", "func (o *AllocationList) GetInvested() float64 {\n\tif o == nil {\n\t\tvar ret float64\n\t\treturn ret\n\t}\n\n\treturn o.Invested\n}", "func (e *Election) Votes() int {\n\tcount := 0\n\tfor _, ballot := range e.ballots {\n\t\tif ballot {\n\t\t\tcount++\n\t\t}\n\t}\n\treturn count\n}", "func (_Vault *VaultCallerSession) GetDecimals(token common.Address) (uint8, error) {\n\treturn _Vault.Contract.GetDecimals(&_Vault.CallOpts, token)\n}", "func (_Vault *VaultSession) GetDecimals(token common.Address) (uint8, error) {\n\treturn _Vault.Contract.GetDecimals(&_Vault.CallOpts, token)\n}", "func (dcr *ExchangeWallet) ReturnCoins(unspents asset.Coins) error {\n\tdcr.fundingMtx.Lock()\n\tdefer dcr.fundingMtx.Unlock()\n\treturn dcr.returnCoins(unspents)\n}", "func (b *rpcVestingBalance) delegated() (sdk.Coins, sdk.Coins, error) {\n\tdelegatedCoins, err := b.totalDelegated()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tunbondingCoins, err := b.totalUnbondingDelegations()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tdelegated := delegatedCoins.AmountOf(stakingDenom)\n\tunbonding := unbondingCoins.AmountOf(stakingDenom)\n\ttotalStaked := delegated.Add(unbonding)\n\tdelegatedFree := b.vacc.GetDelegatedFree().AmountOf(stakingDenom)\n\n\t// total number of staked and unbonding tokens considered to be liquid\n\ttotalFree := sdk.MinInt(totalStaked, delegatedFree)\n\t// any coins that are not considered liquid, are vesting up to a maximum of delegated\n\tstakedVesting := sdk.MinInt(totalStaked.Sub(totalFree), delegated)\n\t// staked free coins are left over\n\tstakedFree := delegated.Sub(stakedVesting)\n\n\tliquidCoins := sdk.NewCoins(newKavaCoin(stakedFree))\n\tvestingCoins := sdk.NewCoins(newKavaCoin(stakedVesting))\n\treturn liquidCoins, vestingCoins, nil\n}", "func (_Contracts *ContractsCaller) VotersCount(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _Contracts.contract.Call(opts, out, \"votersCount\")\n\treturn *ret0, err\n}", "func (cs *Coins) CoinSelect(amount uint64, asset string) (unspents []explorer.Utxo, change uint64, err error) {\n\tchange = 0\n\tunspents = []explorer.Utxo{}\n\tavailableSats := uint64(0)\n\n\tfor index, unspent := range cs.Utxos {\n\t\tu := unspent\n\t\tassetHash := u.Asset()\n\t\tamountSatoshis := u.Value()\n\t\tif len(u.AssetCommitment()) > 0 && len(u.ValueCommitment()) > 0 {\n\t\t\tbk := cs.BlindingKey\n\t\t\tif len(cs.BlindingKeys) > 0 {\n\t\t\t\tbk = cs.BlindingKeys[index]\n\t\t\t}\n\t\t\tav, err := unblindUxto(u, bk)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, 0, err\n\t\t\t}\n\t\t\tassetHash = av.asset\n\t\t\tamountSatoshis = av.value\n\t\t}\n\t\tif asset == assetHash {\n\t\t\tunspents = append(unspents, unspent)\n\t\t\tavailableSats += amountSatoshis\n\n\t\t\tif availableSats >= amount {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\tif availableSats < amount {\n\t\treturn nil, 0, errors.New(\"You do not have enough coins\")\n\t}\n\n\tchange = availableSats - amount\n\n\treturn unspents, change, nil\n}", "func (_Cakevault *CakevaultSession) TotalShares() (*big.Int, error) {\n\treturn _Cakevault.Contract.TotalShares(&_Cakevault.CallOpts)\n}", "func (_Contracts *ContractsCaller) VotesCount(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _Contracts.contract.Call(opts, out, \"votesCount\")\n\treturn *ret0, err\n}", "func (_Cakevault *CakevaultCallerSession) TotalShares() (*big.Int, error) {\n\treturn _Cakevault.Contract.TotalShares(&_Cakevault.CallOpts)\n}", "func TotalCoinsInvariant(ak auth.AccountKeeper, totalSupplyFn func() sdk.Coins) sdk.Invariant {\n\treturn func(ctx sdk.Context) error {\n\t\ttotalCoins := sdk.NewCoins()\n\n\t\tchkAccount := func(acc auth.Account) bool {\n\t\t\tcoins := acc.GetCoins()\n\t\t\ttotalCoins = totalCoins.Add(coins)\n\t\t\treturn false\n\t\t}\n\n\t\tak.IterateAccounts(ctx, chkAccount)\n\t\tif !totalSupplyFn().IsEqual(totalCoins) {\n\t\t\treturn errors.New(\"total calculated coins doesn't equal expected coins\")\n\t\t}\n\t\treturn nil\n\t}\n}", "func (keeper Keeper) GetVotes(ctx sdk.Context, proposalID uint64) (votes types.Votes) {\n\tkeeper.IterateVotes(ctx, proposalID, func(vote types.Vote) bool {\n\t\tvotes = append(votes, vote)\n\t\treturn false\n\t})\n\treturn\n}", "func (dcr *ExchangeWallet) FundingCoins(ids []dex.Bytes) (asset.Coins, error) {\n\t// First check if we have the coins in cache.\n\tcoins := make(asset.Coins, 0, len(ids))\n\tnotFound := make(map[outPoint]bool)\n\tdcr.fundingMtx.Lock()\n\tdefer dcr.fundingMtx.Unlock() // stay locked until we update the map and lock them in the wallet\n\tfor _, id := range ids {\n\t\ttxHash, vout, err := decodeCoinID(id)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tpt := newOutPoint(txHash, vout)\n\t\tfundingCoin, found := dcr.fundingCoins[pt]\n\t\tif found {\n\t\t\tcoins = append(coins, fundingCoin.op)\n\t\t\tcontinue\n\t\t}\n\t\tnotFound[pt] = true\n\t}\n\tif len(notFound) == 0 {\n\t\treturn coins, nil\n\t}\n\n\t// Check locked outputs for not found coins.\n\tlockedOutputs, err := dcr.lockedOutputs()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor _, output := range lockedOutputs {\n\t\ttxHash, err := chainhash.NewHashFromStr(output.Txid)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error decoding txid from rpc server %s: %w\", output.Txid, err)\n\t\t}\n\t\tpt := newOutPoint(txHash, output.Vout)\n\t\tif !notFound[pt] {\n\t\t\tcontinue\n\t\t}\n\t\ttxOut, err := dcr.node.GetTxOut(dcr.ctx, txHash, output.Vout, true)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"gettxout error for locked output %v: %w\", pt.String(), translateRPCCancelErr(err))\n\t\t}\n\t\tvar address string\n\t\tif len(txOut.ScriptPubKey.Addresses) > 0 {\n\t\t\taddress = txOut.ScriptPubKey.Addresses[0]\n\t\t}\n\t\tcoin := newOutput(txHash, output.Vout, toAtoms(output.Amount), output.Tree)\n\t\tcoins = append(coins, coin)\n\t\tdcr.fundingCoins[pt] = &fundingCoin{\n\t\t\top: coin,\n\t\t\taddr: address,\n\t\t}\n\t\tdelete(notFound, pt)\n\t\tif len(notFound) == 0 {\n\t\t\treturn coins, nil\n\t\t}\n\t}\n\n\t// Some funding coins still not found after checking locked outputs.\n\t// Check wallet unspent outputs as last resort. Lock the coins if found.\n\tunspents, err := dcr.unspents()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcoinsToLock := make([]*wire.OutPoint, 0, len(notFound))\n\tfor _, txout := range unspents {\n\t\ttxHash, err := chainhash.NewHashFromStr(txout.TxID)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error decoding txid from rpc server %s: %w\", txout.TxID, err)\n\t\t}\n\t\tpt := newOutPoint(txHash, txout.Vout)\n\t\tif !notFound[pt] {\n\t\t\tcontinue\n\t\t}\n\t\tcoinsToLock = append(coinsToLock, wire.NewOutPoint(txHash, txout.Vout, txout.Tree))\n\t\tcoin := newOutput(txHash, txout.Vout, toAtoms(txout.Amount), txout.Tree)\n\t\tcoins = append(coins, coin)\n\t\tdcr.fundingCoins[pt] = &fundingCoin{\n\t\t\top: coin,\n\t\t\taddr: txout.Address,\n\t\t}\n\t\tdelete(notFound, pt)\n\t\tif len(notFound) == 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\tif len(notFound) != 0 {\n\t\tids := make([]string, 0, len(notFound))\n\t\tfor pt := range notFound {\n\t\t\tids = append(ids, pt.String())\n\t\t}\n\t\treturn nil, fmt.Errorf(\"funding coins not found: %s\", strings.Join(ids, \", \"))\n\t}\n\tdcr.log.Debugf(\"Locking funding coins that were unlocked %v\", coinsToLock)\n\terr = dcr.node.LockUnspent(dcr.ctx, false, coinsToLock)\n\tif err != nil {\n\t\treturn nil, translateRPCCancelErr(err)\n\t}\n\n\treturn coins, nil\n}", "func (o *Transaction) GetCounterpartiesOk() (*[]TransactionCounterparty, bool) {\n\tif o == nil || o.Counterparties == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Counterparties, true\n}", "func (_MonsterOwnership *MonsterOwnershipSession) TotalSupply() (*big.Int, error) {\n\treturn _MonsterOwnership.Contract.TotalSupply(&_MonsterOwnership.CallOpts)\n}", "func (gc *GovernanceContract) TotalVotingPower() (hexutil.Big, error) {\n\treturn gc.repo.GovernanceTotalWeight(&gc.Address)\n}", "func (o *AvailableBudget) GetSpentInBudgets() []BudgetSpent {\n\tif o == nil || o.SpentInBudgets == nil {\n\t\tvar ret []BudgetSpent\n\t\treturn ret\n\t}\n\treturn *o.SpentInBudgets\n}", "func (_Gatekeeper *GatekeeperCaller) GetRootsCount(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _Gatekeeper.contract.Call(opts, out, \"GetRootsCount\")\n\treturn *ret0, err\n}", "func (c *CoordinatorHelper) Coins(\n\tctx context.Context,\n\tdbTx storage.DatabaseTransaction,\n\taccountIdentifier *types.AccountIdentifier,\n\tcurrency *types.Currency,\n) ([]*types.Coin, error) {\n\tcoins, _, err := c.coinStorage.GetCoinsTransactional(\n\t\tctx,\n\t\tdbTx,\n\t\taccountIdentifier,\n\t)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"%w: unable to get coins\", err)\n\t}\n\n\tcoinsToReturn := []*types.Coin{}\n\tfor _, coin := range coins {\n\t\tif types.Hash(coin.Amount.Currency) != types.Hash(currency) {\n\t\t\tcontinue\n\t\t}\n\n\t\tcoinsToReturn = append(coinsToReturn, coin)\n\t}\n\n\treturn coinsToReturn, nil\n}", "func (s *Store) GetTotalSupply() *big.Int {\n\tamountBytes, err := s.table.TotalSupply.Get([]byte(\"c\"))\n\tif err != nil {\n\t\ts.Log.Crit(\"Failed to get key-value\", \"err\", err)\n\t}\n\tif amountBytes == nil {\n\t\treturn big.NewInt(0)\n\t}\n\treturn new(big.Int).SetBytes(amountBytes)\n}", "func (a *Account) TotalReceived(confirms int) (float64, error) {\n\tbs, err := GetCurBlock()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tvar totalSatoshis int64\n\tfor _, record := range a.TxStore.SortedRecords() {\n\t\ttxout, ok := record.(*tx.RecvTxOut)\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Ignore change.\n\t\tif txout.Change() {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Tally if the appropiate number of block confirmations have passed.\n\t\tif confirmed(confirms, txout.Height(), bs.Height) {\n\t\t\ttotalSatoshis += txout.Value()\n\t\t}\n\t}\n\n\treturn float64(totalSatoshis) / float64(btcutil.SatoshiPerBitcoin), nil\n}", "func (r SlpSend) GetVoutValue(vout int) (*big.Int, bool) {\n\tif vout == 0 {\n\t\treturn nil, false\n\t}\n\n\tif vout > len(r.Amounts) {\n\t\treturn nil, false\n\t}\n\n\treturn new(big.Int).SetUint64(r.Amounts[vout-1]), false\n}", "func (m *TeamSummary) GetGuestsCount()(*int32) {\n return m.guestsCount\n}", "func (dcr *ExchangeWallet) FundingCoins(ids []dex.Bytes) (asset.Coins, error) {\n\t// First check if we have the coins in cache.\n\tcoins := make(asset.Coins, 0, len(ids))\n\tnotFound := make(map[outPoint]bool)\n\tdcr.fundingMtx.Lock()\n\tdefer dcr.fundingMtx.Unlock() // stay locked until we update the map and lock them in the wallet\n\tfor _, id := range ids {\n\t\ttxHash, vout, err := decodeCoinID(id)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tpt := newOutPoint(txHash, vout)\n\t\tfundingCoin, found := dcr.fundingCoins[pt]\n\t\tif found {\n\t\t\tcoins = append(coins, fundingCoin.op)\n\t\t\tcontinue\n\t\t}\n\t\tnotFound[pt] = true\n\t}\n\tif len(notFound) == 0 {\n\t\treturn coins, nil\n\t}\n\n\t// Check locked outputs for not found coins.\n\tfor _, acct := range dcr.fundingAccounts() {\n\t\tlockedOutputs, err := dcr.wallet.LockedOutputs(dcr.ctx, acct)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfor _, output := range lockedOutputs {\n\t\t\ttxHash, err := chainhash.NewHashFromStr(output.Txid)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"error decoding txid from rpc server %s: %w\", output.Txid, err)\n\t\t\t}\n\t\t\tpt := newOutPoint(txHash, output.Vout)\n\t\t\tif !notFound[pt] {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ttxOut, err := dcr.wallet.UnspentOutput(dcr.ctx, txHash, output.Vout, output.Tree)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"gettxout error for locked output %v: %w\", pt.String(), err)\n\t\t\t}\n\t\t\tvar address string\n\t\t\tif len(txOut.Addresses) > 0 {\n\t\t\t\taddress = txOut.Addresses[0]\n\t\t\t}\n\t\t\tcoin := newOutput(txHash, output.Vout, toAtoms(output.Amount), output.Tree)\n\t\t\tcoins = append(coins, coin)\n\t\t\tdcr.fundingCoins[pt] = &fundingCoin{\n\t\t\t\top: coin,\n\t\t\t\taddr: address,\n\t\t\t}\n\t\t\tdelete(notFound, pt)\n\t\t\tif len(notFound) == 0 {\n\t\t\t\treturn coins, nil\n\t\t\t}\n\t\t}\n\t}\n\n\t// Some funding coins still not found after checking locked outputs.\n\t// Check wallet unspent outputs as last resort. Lock the coins if found.\n\tcoinsToLock := make([]*wire.OutPoint, 0, len(notFound))\n\tfor _, acct := range dcr.fundingAccounts() {\n\t\tunspents, err := dcr.wallet.Unspents(dcr.ctx, acct)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfor _, txout := range unspents {\n\t\t\ttxHash, err := chainhash.NewHashFromStr(txout.TxID)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"error decoding txid from rpc server %s: %w\", txout.TxID, err)\n\t\t\t}\n\t\t\tpt := newOutPoint(txHash, txout.Vout)\n\t\t\tif !notFound[pt] {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tcoinsToLock = append(coinsToLock, wire.NewOutPoint(txHash, txout.Vout, txout.Tree))\n\t\t\tcoin := newOutput(txHash, txout.Vout, toAtoms(txout.Amount), txout.Tree)\n\t\t\tcoins = append(coins, coin)\n\t\t\tdcr.fundingCoins[pt] = &fundingCoin{\n\t\t\t\top: coin,\n\t\t\t\taddr: txout.Address,\n\t\t\t}\n\t\t\tdelete(notFound, pt)\n\t\t\tif len(notFound) == 0 {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\t// Return an error if some coins are still not found.\n\tif len(notFound) != 0 {\n\t\tids := make([]string, 0, len(notFound))\n\t\tfor pt := range notFound {\n\t\t\tids = append(ids, pt.String())\n\t\t}\n\t\treturn nil, fmt.Errorf(\"funding coins not found: %s\", strings.Join(ids, \", \"))\n\t}\n\n\tdcr.log.Debugf(\"Locking funding coins that were unlocked %v\", coinsToLock)\n\terr := dcr.wallet.LockUnspent(dcr.ctx, false, coinsToLock)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn coins, nil\n}", "func (_BtlCoin *BtlCoinSession) TotalSupply() (*big.Int, error) {\n\treturn _BtlCoin.Contract.TotalSupply(&_BtlCoin.CallOpts)\n}", "func (u *User) GetTotalPrivateRepos() int {\n\tif u == nil || u.TotalPrivateRepos == nil {\n\t\treturn 0\n\t}\n\treturn *u.TotalPrivateRepos\n}", "func (k Keeper) GetTotalSupply(ctx sdk.Context, denom string) uint64 {\n\tstore := ctx.KVStore(k.storeKey)\n\tbz := store.Get(types.KeyCollection(denom))\n\tif len(bz) == 0 {\n\t\treturn 0\n\t}\n\n\tvar supply uint64\n\tk.cdc.MustUnmarshalBinaryLengthPrefixed(bz, &supply)\n\treturn supply\n}", "func (keeper Keeper) HasCoins(ctx sdk.Context, addr sdk.Address, amt sdk.Coins) bool {\n\treturn hasCoins(ctx, keeper.am, addr, amt)\n}", "func (c Checkout) Total() int {\n\ttotal := 0\n\tfor code, quantity := range c.basket {\n\t\toffer, exists := offers[code]\n\t\tif exists {\n\t\t\ttotal += calculateOfferPrice(code, quantity, offer)\n\t\t} else {\n\t\t\ttotal += calculatePrice(code, quantity)\n\t\t}\n\t}\n\treturn total\n}", "func (supply Supply) GetTotal() sdk.Coins {\n\treturn supply.Total\n}", "func (k *Keeper) GetVaultTotalShares(\n\tctx sdk.Context,\n\tdenom string,\n) (types.VaultShare, bool) {\n\tvault, found := k.GetVaultRecord(ctx, denom)\n\tif !found {\n\t\treturn types.VaultShare{}, false\n\t}\n\n\treturn vault.TotalShares, true\n}", "func (keeper SendKeeper) HasCoins(ctx sdk.Context, addr sdk.Address, amt sdk.Coins) bool {\n\treturn hasCoins(ctx, keeper.am, addr, amt)\n}", "func (_MonsterOwnership *MonsterOwnershipCaller) TotalSupply(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _MonsterOwnership.contract.Call(opts, out, \"totalSupply\")\n\treturn *ret0, err\n}", "func subtractCoins(ctx sdk.Context, am sdk.AccountMapper, addr sdk.Address, amt sdk.Coins) (sdk.Coins, sdk.Error) {\n\toldCoins := getCoins(ctx, am, addr)\n\tnewCoins := oldCoins.Minus(amt)\n\tif !newCoins.IsNotNegative() {\n\t\treturn amt, sdk.ErrInsufficientCoins(fmt.Sprintf(\"%s < %s\", oldCoins, amt))\n\t}\n\terr := setCoins(ctx, am, addr, newCoins)\n\treturn newCoins, err\n}", "func (k Keeper) GetVotes(ctx sdk.Context) int64 {\n\treturn k.GetRunningAverageTotal(ctx, Votes24ValueKey)\n}", "func (_Cakevault *CakevaultCaller) TotalShares(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _Cakevault.contract.Call(opts, &out, \"totalShares\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (_Bindings *BindingsSession) TotalSupply() (*big.Int, error) {\n\treturn _Bindings.Contract.TotalSupply(&_Bindings.CallOpts)\n}", "func (_MonsterOwnership *MonsterOwnershipCallerSession) TotalSupply() (*big.Int, error) {\n\treturn _MonsterOwnership.Contract.TotalSupply(&_MonsterOwnership.CallOpts)\n}", "func (btc *ExchangeWallet) ReturnCoins(unspents asset.Coins) error {\n\tif len(unspents) == 0 {\n\t\treturn fmt.Errorf(\"cannot return zero coins\")\n\t}\n\tops := make([]*output, 0, len(unspents))\n\tbtc.fundingMtx.Lock()\n\tdefer btc.fundingMtx.Unlock()\n\tfor _, unspent := range unspents {\n\t\top, err := btc.convertCoin(unspent)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error converting coin: %v\", err)\n\t\t}\n\t\tops = append(ops, op)\n\t\tdelete(btc.fundingCoins, outpointID(op.txHash.String(), op.vout))\n\t}\n\treturn btc.wallet.LockUnspent(true, ops)\n}", "func (_Lmc *LmcSession) TotalStaked() (*big.Int, error) {\n\treturn _Lmc.Contract.TotalStaked(&_Lmc.CallOpts)\n}", "func (_Contracts *ContractsCallerSession) VotersCount() (*big.Int, error) {\n\treturn _Contracts.Contract.VotersCount(&_Contracts.CallOpts)\n}", "func (a *Agent) GetPeersCount() uint32 {\n\treturn atomic.LoadUint32(&a.peersCount)\n}", "func (_Bep20 *Bep20Caller) GetCurrentVotes(opts *bind.CallOpts, account common.Address) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _Bep20.contract.Call(opts, &out, \"getCurrentVotes\", account)\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (_Contract *ContractSession) TotalSupply() (*big.Int, error) {\n\treturn _Contract.Contract.TotalSupply(&_Contract.CallOpts)\n}", "func (v *Vending) Get(c echo.Context) error {\n\tif v.chocolate == 0 {\n\t\treturn c.String(http.StatusOK, \"Out of chocolate please refill\")\n\t}\n\treturn c.String(http.StatusOK, fmt.Sprintf(\"There are %v pieces of chocolate left.\", v.chocolate))\n}", "func (p *PostgresDb) GetDueAmount(customerID int) (float64, error) {\n\tvar dueAmount float64\n\tpaymentsQuery := `\n\t\tSELECT COALESCE(SUM(amount), 0) \n\t\tFROM payment \n\t\tWHERE customer_id=$1 \n\t\tGROUP BY customer_id\n\t`\n\tvar sumPayments float64\n\terr := p.dbConn.Get(&sumPayments, paymentsQuery, customerID)\n\tif err != nil {\n\t\tlog.Println(\"Error getting sum payments:\", err)\n\t}\n\n\tcreditsQuery := `\t\n\t\tSELECT COALESCE(SUM(amount), 0) \n\t\tFROM credit \n\t\tWHERE customer_id=$1 \n\t\tGROUP BY customer_id\n\t`\n\tvar sumCredits float64\n\terr = p.dbConn.Get(&sumCredits, creditsQuery, customerID)\n\tif err != nil {\n\t\tlog.Println(\"Error getting sum credits:\", err)\n\t}\n\tdueAmount = sumCredits - sumPayments\n\n\treturn dueAmount, nil\n}", "func (_BtlCoin *BtlCoinCallerSession) TotalSupply() (*big.Int, error) {\n\treturn _BtlCoin.Contract.TotalSupply(&_BtlCoin.CallOpts)\n}" ]
[ "0.7472693", "0.728135", "0.72171086", "0.7067881", "0.6926002", "0.67520267", "0.6718381", "0.6669052", "0.66164577", "0.6606495", "0.64622456", "0.56307656", "0.55714226", "0.55141586", "0.544581", "0.53290683", "0.52700144", "0.5242058", "0.5186966", "0.51671714", "0.51350975", "0.5115714", "0.50330526", "0.5031833", "0.50100225", "0.49435633", "0.4897083", "0.48935035", "0.485593", "0.48001558", "0.4784368", "0.47828186", "0.47610685", "0.47225112", "0.47059807", "0.47008497", "0.46998307", "0.46946743", "0.46945977", "0.46840048", "0.46677846", "0.46660444", "0.46437976", "0.46116233", "0.4595778", "0.4572313", "0.45559812", "0.45538944", "0.4533173", "0.4518986", "0.45004946", "0.44995472", "0.4493483", "0.44924805", "0.4488609", "0.4484768", "0.4477084", "0.44613165", "0.44487226", "0.44392908", "0.4426352", "0.43932426", "0.43473378", "0.43304318", "0.43282044", "0.4284704", "0.4280026", "0.42740014", "0.42708856", "0.42685932", "0.4264247", "0.42575285", "0.4251951", "0.4239212", "0.42269608", "0.4224138", "0.42235056", "0.42228407", "0.42186573", "0.42173547", "0.42083633", "0.4204702", "0.42000416", "0.4197236", "0.41935015", "0.4166067", "0.41655052", "0.4165464", "0.4157894", "0.41553947", "0.41525295", "0.41440606", "0.4142263", "0.41368973", "0.41360098", "0.41337416", "0.41231912", "0.41138485", "0.41080377", "0.4102811" ]
0.7318536
1
GetVestingCoins returns the total number of vesting coins. If no coins are vesting, nil is returned.
func (pva PeriodicVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins { return pva.OriginalVesting.Sub(pva.GetVestedCoins(blockTime)) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (vva ValidatorVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn vva.OriginalVesting.Sub(vva.GetVestedCoins(blockTime))\n}", "func (va ClawbackVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn va.OriginalVesting.Sub(va.GetVestedCoins(blockTime))\n}", "func (cva ContinuousVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn cva.OriginalVesting.Sub(cva.GetVestedCoins(blockTime))\n}", "func (dva DelayedVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn dva.OriginalVesting.Sub(dva.GetVestedCoins(blockTime))\n}", "func (plva PermanentLockedAccount) GetVestingCoins(_ time.Time) sdk.Coins {\n\treturn plva.OriginalVesting\n}", "func (cva ContinuousVestingAccount) GetVestedCoins(blockTime time.Time) sdk.Coins {\n\tvar vestedCoins sdk.Coins\n\n\t// We must handle the case where the start time for a vesting account has\n\t// been set into the future or when the start of the chain is not exactly\n\t// known.\n\tif blockTime.Unix() <= cva.StartTime {\n\t\treturn vestedCoins\n\t} else if blockTime.Unix() >= cva.EndTime {\n\t\treturn cva.OriginalVesting\n\t}\n\n\t// calculate the vesting scalar\n\tx := blockTime.Unix() - cva.StartTime\n\ty := cva.EndTime - cva.StartTime\n\ts := sdk.NewDec(x).Quo(sdk.NewDec(y))\n\n\tfor _, ovc := range cva.OriginalVesting {\n\t\tvestedAmt := ovc.Amount.ToDec().Mul(s).RoundInt()\n\t\tvestedCoins = append(vestedCoins, sdk.NewCoin(ovc.Denom, vestedAmt))\n\t}\n\n\treturn vestedCoins\n}", "func (dva DelayedVestingAccount) GetVestedCoins(blockTime time.Time) sdk.Coins {\n\tif blockTime.Unix() >= dva.EndTime {\n\t\treturn dva.OriginalVesting\n\t}\n\n\treturn nil\n}", "func (vva ValidatorVestingAccount) GetVestedCoins(blockTime time.Time) sdk.Coins {\n\tvar vestedCoins sdk.Coins\n\tif blockTime.Unix() <= vva.StartTime {\n\t\treturn vestedCoins\n\t}\n\tcurrentPeriodStartTime := vva.StartTime\n\tnumberPeriods := len(vva.VestingPeriods)\n\tfor i := 0; i < numberPeriods; i++ {\n\t\tx := blockTime.Unix() - currentPeriodStartTime\n\t\tif x >= vva.VestingPeriods[i].Length {\n\t\t\tif vva.VestingPeriodProgress[i].PeriodComplete {\n\t\t\t\tvestedCoins = vestedCoins.Add(vva.VestingPeriods[i].Amount)\n\t\t\t}\n\t\t\tcurrentPeriodStartTime += vva.VestingPeriods[i].Length\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn vestedCoins\n\n}", "func (pva PeriodicVestingAccount) GetVestedCoins(blockTime time.Time) sdk.Coins {\n\tcoins := ReadSchedule(pva.StartTime, pva.EndTime, pva.VestingPeriods, pva.OriginalVesting, blockTime.Unix())\n\tif coins.IsZero() {\n\t\treturn nil\n\t}\n\treturn coins\n}", "func (va ClawbackVestingAccount) GetVestedCoins(blockTime time.Time) sdk.Coins {\n\t// It's likely that one or the other schedule will be nearly trivial,\n\t// so there should be little overhead in recomputing the conjunction each time.\n\tcoins := coinsMin(va.GetUnlockedOnly(blockTime), va.GetVestedOnly(blockTime))\n\tif coins.IsZero() {\n\t\treturn nil\n\t}\n\treturn coins\n}", "func (plva PermanentLockedAccount) GetVestedCoins(_ time.Time) sdk.Coins {\n\treturn nil\n}", "func GetCoins() (coins []Coin, error error) {\n\tvar c = []Coin{}\n\tvar d struct {\n\t\tCrypto []Coin `json:\"crypto\"`\n\t}\n\tjsonData, err := doTauRequest(1, \"GET\", \"data/coins\", nil)\n\tif err != nil {\n\t\treturn c, err\n\t}\n\tif err := json.Unmarshal(jsonData, &d); err != nil {\n\t\treturn c, err\n\t}\n\treturn d.Crypto, nil\n}", "func (keeper ViewKeeper) GetCoins(ctx sdk.Context, addr sdk.Address) sdk.Coins {\n\treturn getCoins(ctx, keeper.am, addr)\n}", "func (keeper BaseViewKeeper) GetCoins(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins {\n\treturn getCoins(ctx, keeper.am, addr)\n}", "func (bva BaseVestingAccount) LockedCoinsFromVesting(vestingCoins sdk.Coins) sdk.Coins {\n\tlockedCoins := vestingCoins.Sub(vestingCoins.Min(bva.DelegatedVesting))\n\tif lockedCoins == nil {\n\t\treturn sdk.Coins{}\n\t}\n\treturn lockedCoins\n}", "func (keeper SendKeeper) GetCoins(ctx sdk.Context, addr sdk.Address) sdk.Coins {\n\treturn getCoins(ctx, keeper.am, addr)\n}", "func (vva ValidatorVestingAccount) GetFailedVestedCoins() sdk.Coins {\n\tvar failedVestedCoins sdk.Coins\n\tnumberPeriods := len(vva.VestingPeriods)\n\tfor i := 0; i < numberPeriods; i++ {\n\t\tif vva.VestingPeriodProgress[i].PeriodComplete {\n\t\t\tif !vva.VestingPeriodProgress[i].VestingSuccessful {\n\t\t\t\tfailedVestedCoins = failedVestedCoins.Add(vva.VestingPeriods[i].Amount)\n\t\t\t}\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn failedVestedCoins\n}", "func (cva ContinuousVestingAccount) LockedCoins(ctx sdk.Context) sdk.Coins {\n\treturn cva.BaseVestingAccount.LockedCoinsFromVesting(cva.GetVestingCoins(ctx.BlockTime()))\n}", "func (va ClawbackVestingAccount) LockedCoins(ctx sdk.Context) sdk.Coins {\n\treturn va.BaseVestingAccount.LockedCoinsFromVesting(va.GetVestingCoins(ctx.BlockTime()))\n}", "func (t *TauAPI) GetCoins() (coins []Coin, error error) {\n\tvar c = []Coin{}\n\tvar d struct {\n\t\tCrypto []Coin `json:\"cryto\"` //typo from api\n\t\tFiat []Coin `json:\"fiat\"`\n\t}\n\tjsonData, err := t.doTauRequest(&TauReq{\n\t\tVersion: 2,\n\t\tMethod: \"GET\",\n\t\tPath: \"coins\",\n\t})\n\tif err != nil {\n\t\treturn c, err\n\t}\n\tif err := json.Unmarshal(jsonData, &d); err != nil {\n\t\treturn c, err\n\t}\n\tc = append(d.Crypto, d.Fiat...)\n\treturn c, nil\n}", "func (keeper Keeper) GetCoins(ctx sdk.Context, addr sdk.Address) sdk.Coins {\n\treturn getCoins(ctx, keeper.am, addr)\n}", "func coins(a int) int {\n\tif a == 0 {\n\t\treturn 0\n\t}\n\treturn doCoins(a, 25)\n}", "func (vva ValidatorVestingAccount) SpendableCoins(blockTime time.Time) sdk.Coins {\n\treturn vva.BaseVestingAccount.SpendableCoinsVestingAccount(vva.GetVestingCoins(blockTime))\n}", "func (pva PeriodicVestingAccount) LockedCoins(ctx sdk.Context) sdk.Coins {\n\treturn pva.BaseVestingAccount.LockedCoinsFromVesting(pva.GetVestingCoins(ctx.BlockTime()))\n}", "func (dva DelayedVestingAccount) LockedCoins(ctx sdk.Context) sdk.Coins {\n\treturn dva.BaseVestingAccount.LockedCoinsFromVesting(dva.GetVestingCoins(ctx.BlockTime()))\n}", "func GetCoins(accCoins []types.Coin) AccountCoins {\n\tcoins := make(AccountCoins, 0)\n\tfor _, coin := range accCoins {\n\t\tcoins = append(coins, AccountCoin{Amount: uint64(coin.Amount), Denom: coin.Denom})\n\t}\n\treturn coins\n}", "func (m *Client) GetCoins() ([]string, error) {\n\tresp, err := m.Service.GetCoins()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error requesting coin list: %s\", err)\n\t}\n\tdefer resp.Body.Close()\n\n\tvar response []string\n\terr = json.NewDecoder(resp.Body).Decode(&response)\n\tif err != nil {\n\t\tmsg, _ := ioutil.ReadAll(resp.Body)\n\t\treturn nil, fmt.Errorf(\"error decoding coin list: %s: %s\", msg, err)\n\t}\n\n\treturn response, nil\n}", "func (ck CoinKeeper) GetCoins(ctx sdk.Context, addr sdk.Address, amt sdk.Coins) sdk.Coins {\n\tacc := ck.am.GetAccount(ctx, addr)\n\treturn acc.GetCoins()\n}", "func (bva BaseVestingAccount) GetOriginalVesting() sdk.Coins {\n\treturn bva.OriginalVesting\n}", "func (k Keeper) GetWinnerIncentives(ctx sdk.Context) float32 {\n\tgames := float32(k.GetGames(ctx))\n\tvotes := float32(k.GetVotes(ctx))\n\tgVR := float32(k.GetParams(ctx).GameVoteRatio) / 100\n\treturn games / (votes*gVR + games)\n}", "func (o *Transaction) GetCounterparties() []TransactionCounterparty {\n\tif o == nil || o.Counterparties == nil {\n\t\tvar ret []TransactionCounterparty\n\t\treturn ret\n\t}\n\treturn *o.Counterparties\n}", "func (cs *Coins) CoinSelect(amount uint64, asset string) (unspents []explorer.Utxo, change uint64, err error) {\n\tchange = 0\n\tunspents = []explorer.Utxo{}\n\tavailableSats := uint64(0)\n\n\tfor index, unspent := range cs.Utxos {\n\t\tu := unspent\n\t\tassetHash := u.Asset()\n\t\tamountSatoshis := u.Value()\n\t\tif len(u.AssetCommitment()) > 0 && len(u.ValueCommitment()) > 0 {\n\t\t\tbk := cs.BlindingKey\n\t\t\tif len(cs.BlindingKeys) > 0 {\n\t\t\t\tbk = cs.BlindingKeys[index]\n\t\t\t}\n\t\t\tav, err := unblindUxto(u, bk)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, 0, err\n\t\t\t}\n\t\t\tassetHash = av.asset\n\t\t\tamountSatoshis = av.value\n\t\t}\n\t\tif asset == assetHash {\n\t\t\tunspents = append(unspents, unspent)\n\t\t\tavailableSats += amountSatoshis\n\n\t\t\tif availableSats >= amount {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\tif availableSats < amount {\n\t\treturn nil, 0, errors.New(\"You do not have enough coins\")\n\t}\n\n\tchange = availableSats - amount\n\n\treturn unspents, change, nil\n}", "func (candidate *Candidate) GetTotalBipStake() *big.Int {\n\tcandidate.lock.RLock()\n\tdefer candidate.lock.RUnlock()\n\n\treturn big.NewInt(0).Set(candidate.totalBipStake)\n}", "func (_TokenVesting *TokenVestingCaller) VestedAmount(opts *bind.CallOpts, _token common.Address) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _TokenVesting.contract.Call(opts, out, \"vestedAmount\", _token)\n\treturn *ret0, err\n}", "func (m *TeamSummary) GetGuestsCount()(*int32) {\n return m.guestsCount\n}", "func (_TokenVesting *TokenVestingSession) VestedAmount(_token common.Address) (*big.Int, error) {\n\treturn _TokenVesting.Contract.VestedAmount(&_TokenVesting.CallOpts, _token)\n}", "func (_Contracts *ContractsCaller) VotersCount(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _Contracts.contract.Call(opts, out, \"votersCount\")\n\treturn *ret0, err\n}", "func (_TokenVesting *TokenVestingCallerSession) VestedAmount(_token common.Address) (*big.Int, error) {\n\treturn _TokenVesting.Contract.VestedAmount(&_TokenVesting.CallOpts, _token)\n}", "func (gc *GovernanceContract) TotalVotingPower() (hexutil.Big, error) {\n\treturn gc.repo.GovernanceTotalWeight(&gc.Address)\n}", "func (m *TeamSummary) GetOwnersCount()(*int32) {\n return m.ownersCount\n}", "func (o *Transaction) GetCounterpartiesOk() (*[]TransactionCounterparty, bool) {\n\tif o == nil || o.Counterparties == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Counterparties, true\n}", "func (r *ParseResult) GetVoutAmount(vout int) (*big.Int, error) {\n\tamt := big.NewInt(0)\n\n\tif !(r.TokenType == TokenTypeFungible01 ||\n\t\tr.TokenType == TokenTypeNft1Child41 ||\n\t\tr.TokenType == TokenTypeNft1Group81) {\n\t\treturn nil, errors.New(\"cannot extract amount for not type 1 or NFT1 token\")\n\t}\n\n\tif vout == 0 {\n\t\treturn amt, nil\n\t}\n\n\tif r.TransactionType == TransactionTypeSend {\n\t\tif vout > len(r.Data.(SlpSend).Amounts) {\n\t\t\treturn amt, nil\n\t\t}\n\t\treturn amt.Add(amt, new(big.Int).SetUint64(r.Data.(SlpSend).Amounts[vout-1])), nil\n\t} else if r.TransactionType == TransactionTypeMint {\n\t\tif vout == 1 {\n\t\t\treturn amt.Add(amt, new(big.Int).SetUint64(r.Data.(SlpMint).Qty)), nil\n\t\t}\n\t\treturn amt, nil\n\t} else if r.TransactionType == TransactionTypeGenesis {\n\t\tif vout == 1 {\n\t\t\treturn amt.Add(amt, new(big.Int).SetUint64(r.Data.(SlpGenesis).Qty)), nil\n\t\t}\n\t\treturn amt, nil\n\t}\n\treturn nil, errors.New(\"unknown error getting vout amount\")\n}", "func (va ClawbackVestingAccount) GetVestedOnly(blockTime time.Time) sdk.Coins {\n\treturn ReadSchedule(va.StartTime, va.EndTime, va.VestingPeriods, va.OriginalVesting, blockTime.Unix())\n}", "func (b *rpcVestingBalance) delegated() (sdk.Coins, sdk.Coins, error) {\n\tdelegatedCoins, err := b.totalDelegated()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tunbondingCoins, err := b.totalUnbondingDelegations()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tdelegated := delegatedCoins.AmountOf(stakingDenom)\n\tunbonding := unbondingCoins.AmountOf(stakingDenom)\n\ttotalStaked := delegated.Add(unbonding)\n\tdelegatedFree := b.vacc.GetDelegatedFree().AmountOf(stakingDenom)\n\n\t// total number of staked and unbonding tokens considered to be liquid\n\ttotalFree := sdk.MinInt(totalStaked, delegatedFree)\n\t// any coins that are not considered liquid, are vesting up to a maximum of delegated\n\tstakedVesting := sdk.MinInt(totalStaked.Sub(totalFree), delegated)\n\t// staked free coins are left over\n\tstakedFree := delegated.Sub(stakedVesting)\n\n\tliquidCoins := sdk.NewCoins(newKavaCoin(stakedFree))\n\tvestingCoins := sdk.NewCoins(newKavaCoin(stakedVesting))\n\treturn liquidCoins, vestingCoins, nil\n}", "func (r *Repository) GetAmountsOfManageCandidates(ctx context.Context, companyID string) (int32, int32, error) {\n\tobjCompanyID, err := primitive.ObjectIDFromHex(companyID)\n\tif err != nil {\n\t\treturn 0, 0, errors.New(`wrong_id`)\n\t}\n\n\tamount := struct {\n\t\tSaved int32 `bson:\"saved_candidates\"`\n\t\tSkipped int32 `bson:\"skipped_candidates\"`\n\t\t// Alerts int32 `bson:\"alerts\"`\n\t}{}\n\n\tcursor, err := r.companiesCollection.Aggregate(\n\t\tctx,\n\t\t[]bson.M{\n\t\t\t{\n\t\t\t\t\"$match\": bson.M{\n\t\t\t\t\t\"company_id\": objCompanyID,\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\t\"$addFields\": bson.M{\n\t\t\t\t\t\"saved_candidates\": bson.M{\n\t\t\t\t\t\t\"$size\": \"$saved_candidates\",\n\t\t\t\t\t},\n\t\t\t\t\t\"skipped_candidates\": bson.M{\n\t\t\t\t\t\t\"$size\": \"$skipped_candidates\",\n\t\t\t\t\t},\n\t\t\t\t\t// \"alerts\": bson.M{\n\t\t\t\t\t// \t\"$size\": \"$alerts\", // TODO:\n\t\t\t\t\t// },\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\t\"$project\": bson.M{\n\t\t\t\t\t\"saved_candidates\": 1,\n\t\t\t\t\t\"skipped_candidates\": 1,\n\t\t\t\t\t// \"alerts\": 1,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t)\n\tif err != nil {\n\t\tif err == mongo.ErrNoDocuments {\n\t\t\treturn 0, 0, errors.New(`not_found`)\n\t\t}\n\t\treturn 0, 0, err\n\t}\n\tdefer cursor.Close(ctx)\n\n\tif cursor.Next(ctx) {\n\t\terr = cursor.Decode(&amount)\n\t\tif err != nil {\n\t\t\treturn 0, 0, err\n\t\t}\n\t}\n\n\treturn amount.Saved, amount.Skipped, nil\n}", "func distributeCoins(root *TreeNode) int {\n\tres := 0\n\tif root.Left != nil {\n\t\tres += distributeCoins(root.Left)\n\t\troot.Val += root.Left.Val - 1\n\t\tres += int(math.Abs(float64(root.Left.Val - 1)))\n\t}\n\tif root.Right != nil {\n\t\tres += distributeCoins(root.Right)\n\t\troot.Val += root.Right.Val - 1\n\t\tres += int(math.Abs(float64(root.Right.Val - 1)))\n\t}\n\treturn res\n}", "func TestGetSupportCoins(t *testing.T) {\n\tt.Parallel()\n\tif _, err := ok.GetSupportCoins(context.Background()); err != nil {\n\t\tt.Error(\"Okx GetSupportCoins() error\", err)\n\t}\n}", "func (plva PermanentLockedAccount) LockedCoins(_ sdk.Context) sdk.Coins {\n\treturn plva.BaseVestingAccount.LockedCoinsFromVesting(plva.OriginalVesting)\n}", "func (keeper BaseViewKeeper) HasCoins(ctx sdk.Context, addr sdk.AccAddress, amt sdk.Coins) bool {\n\treturn hasCoins(ctx, keeper.am, addr, amt)\n}", "func (c *CoordinatorHelper) Coins(\n\tctx context.Context,\n\tdbTx storage.DatabaseTransaction,\n\taccountIdentifier *types.AccountIdentifier,\n\tcurrency *types.Currency,\n) ([]*types.Coin, error) {\n\tcoins, _, err := c.coinStorage.GetCoinsTransactional(\n\t\tctx,\n\t\tdbTx,\n\t\taccountIdentifier,\n\t)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"%w: unable to get coins\", err)\n\t}\n\n\tcoinsToReturn := []*types.Coin{}\n\tfor _, coin := range coins {\n\t\tif types.Hash(coin.Amount.Currency) != types.Hash(currency) {\n\t\t\tcontinue\n\t\t}\n\n\t\tcoinsToReturn = append(coinsToReturn, coin)\n\t}\n\n\treturn coinsToReturn, nil\n}", "func (n Network) VestingAccounts(ctx context.Context, launchID uint64) (vestingAccs []networktypes.VestingAccount, err error) {\n\tn.ev.Send(events.New(events.StatusOngoing, \"Fetching genesis vesting accounts\"))\n\tres, err := n.launchQuery.\n\t\tVestingAccountAll(ctx,\n\t\t\t&launchtypes.QueryAllVestingAccountRequest{\n\t\t\t\tLaunchID: launchID,\n\t\t\t},\n\t\t)\n\tif err != nil {\n\t\treturn vestingAccs, err\n\t}\n\n\tfor i, acc := range res.VestingAccount {\n\t\tparsedAcc, err := networktypes.ToVestingAccount(acc)\n\t\tif err != nil {\n\t\t\treturn vestingAccs, errors.Wrapf(err, \"error parsing vesting account %d\", i)\n\t\t}\n\n\t\tvestingAccs = append(vestingAccs, parsedAcc)\n\t}\n\n\treturn vestingAccs, nil\n}", "func (c Cart) GetVoucherSavings() domain.Price {\n\tprice := domain.Price{}\n\tvar err error\n\n\tfor _, item := range c.Totalitems {\n\t\tif item.Type == TotalsTypeVoucher {\n\t\t\tprice, err = price.Add(item.Price)\n\t\t\tif err != nil {\n\t\t\t\treturn price\n\t\t\t}\n\t\t}\n\t}\n\n\tif price.IsNegative() {\n\t\treturn domain.Price{}\n\t}\n\n\treturn price\n}", "func (_Contracts *ContractsCaller) VotesCount(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _Contracts.contract.Call(opts, out, \"votesCount\")\n\treturn *ret0, err\n}", "func (keeper ViewKeeper) HasCoins(ctx sdk.Context, addr sdk.Address, amt sdk.Coins) bool {\n\treturn hasCoins(ctx, keeper.am, addr, amt)\n}", "func distributeCoins(root *TreeNode) int {\n\tres := 0\n\tvar dfs func(root *TreeNode) int\n\tabs := func(a int) int {\n\t\tif a < 0 {\n\t\t\treturn -a\n\t\t}\n\t\treturn a\n\t}\n\tdfs = func(root *TreeNode) int {\n\t\tif root == nil {\n\t\t\treturn 0\n\t\t}\n\t\tleft := dfs(root.Left)\n\t\tright := dfs(root.Right)\n\t\tres += abs(left) + abs(right)\n\t\treturn left + right + root.Val - 1\n\t}\n\tdfs(root)\n\treturn res\n}", "func (_Bindings *BindingsCallerSession) TotalReserves() (*big.Int, error) {\n\treturn _Bindings.Contract.TotalReserves(&_Bindings.CallOpts)\n}", "func newCoins() sdk.Coins {\n\treturn sdk.Coins{\n\t\tsdk.NewInt64Coin(\"atom\", 10000000),\n\t}\n}", "func (dcr *ExchangeWallet) FundingCoins(ids []dex.Bytes) (asset.Coins, error) {\n\t// First check if we have the coins in cache.\n\tcoins := make(asset.Coins, 0, len(ids))\n\tnotFound := make(map[outPoint]bool)\n\tdcr.fundingMtx.Lock()\n\tdefer dcr.fundingMtx.Unlock() // stay locked until we update the map and lock them in the wallet\n\tfor _, id := range ids {\n\t\ttxHash, vout, err := decodeCoinID(id)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tpt := newOutPoint(txHash, vout)\n\t\tfundingCoin, found := dcr.fundingCoins[pt]\n\t\tif found {\n\t\t\tcoins = append(coins, fundingCoin.op)\n\t\t\tcontinue\n\t\t}\n\t\tnotFound[pt] = true\n\t}\n\tif len(notFound) == 0 {\n\t\treturn coins, nil\n\t}\n\n\t// Check locked outputs for not found coins.\n\tlockedOutputs, err := dcr.lockedOutputs()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor _, output := range lockedOutputs {\n\t\ttxHash, err := chainhash.NewHashFromStr(output.Txid)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error decoding txid from rpc server %s: %w\", output.Txid, err)\n\t\t}\n\t\tpt := newOutPoint(txHash, output.Vout)\n\t\tif !notFound[pt] {\n\t\t\tcontinue\n\t\t}\n\t\ttxOut, err := dcr.node.GetTxOut(dcr.ctx, txHash, output.Vout, true)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"gettxout error for locked output %v: %w\", pt.String(), translateRPCCancelErr(err))\n\t\t}\n\t\tvar address string\n\t\tif len(txOut.ScriptPubKey.Addresses) > 0 {\n\t\t\taddress = txOut.ScriptPubKey.Addresses[0]\n\t\t}\n\t\tcoin := newOutput(txHash, output.Vout, toAtoms(output.Amount), output.Tree)\n\t\tcoins = append(coins, coin)\n\t\tdcr.fundingCoins[pt] = &fundingCoin{\n\t\t\top: coin,\n\t\t\taddr: address,\n\t\t}\n\t\tdelete(notFound, pt)\n\t\tif len(notFound) == 0 {\n\t\t\treturn coins, nil\n\t\t}\n\t}\n\n\t// Some funding coins still not found after checking locked outputs.\n\t// Check wallet unspent outputs as last resort. Lock the coins if found.\n\tunspents, err := dcr.unspents()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcoinsToLock := make([]*wire.OutPoint, 0, len(notFound))\n\tfor _, txout := range unspents {\n\t\ttxHash, err := chainhash.NewHashFromStr(txout.TxID)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error decoding txid from rpc server %s: %w\", txout.TxID, err)\n\t\t}\n\t\tpt := newOutPoint(txHash, txout.Vout)\n\t\tif !notFound[pt] {\n\t\t\tcontinue\n\t\t}\n\t\tcoinsToLock = append(coinsToLock, wire.NewOutPoint(txHash, txout.Vout, txout.Tree))\n\t\tcoin := newOutput(txHash, txout.Vout, toAtoms(txout.Amount), txout.Tree)\n\t\tcoins = append(coins, coin)\n\t\tdcr.fundingCoins[pt] = &fundingCoin{\n\t\t\top: coin,\n\t\t\taddr: txout.Address,\n\t\t}\n\t\tdelete(notFound, pt)\n\t\tif len(notFound) == 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\tif len(notFound) != 0 {\n\t\tids := make([]string, 0, len(notFound))\n\t\tfor pt := range notFound {\n\t\t\tids = append(ids, pt.String())\n\t\t}\n\t\treturn nil, fmt.Errorf(\"funding coins not found: %s\", strings.Join(ids, \", \"))\n\t}\n\tdcr.log.Debugf(\"Locking funding coins that were unlocked %v\", coinsToLock)\n\terr = dcr.node.LockUnspent(dcr.ctx, false, coinsToLock)\n\tif err != nil {\n\t\treturn nil, translateRPCCancelErr(err)\n\t}\n\n\treturn coins, nil\n}", "func (_Gatekeeper *GatekeeperCaller) GetRootsCount(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _Gatekeeper.contract.Call(opts, out, \"GetRootsCount\")\n\treturn *ret0, err\n}", "func (_Bindings *BindingsSession) TotalReserves() (*big.Int, error) {\n\treturn _Bindings.Contract.TotalReserves(&_Bindings.CallOpts)\n}", "func (cm *ConnectionManager) sumDeposits() *big.Int {\n\tchs := cm.openChannels()\n\tvar sum = big.NewInt(0)\n\tfor _, c := range chs {\n\t\tsum.Add(sum, c.OurContractBalance)\n\t}\n\treturn sum\n}", "func (_Bep20 *Bep20Caller) GetCurrentVotes(opts *bind.CallOpts, account common.Address) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _Bep20.contract.Call(opts, &out, \"getCurrentVotes\", account)\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func drawCoins() int {\n\treturn rand.Intn(maxCoins+1-minCoins) + minCoins\n}", "func (_Contracts *ContractsCallerSession) VotersCount() (*big.Int, error) {\n\treturn _Contracts.Contract.VotersCount(&_Contracts.CallOpts)\n}", "func (_CrToken *CrTokenCallerSession) TotalReserves() (*big.Int, error) {\n\treturn _CrToken.Contract.TotalReserves(&_CrToken.CallOpts)\n}", "func (dcr *ExchangeWallet) FundingCoins(ids []dex.Bytes) (asset.Coins, error) {\n\t// First check if we have the coins in cache.\n\tcoins := make(asset.Coins, 0, len(ids))\n\tnotFound := make(map[outPoint]bool)\n\tdcr.fundingMtx.Lock()\n\tdefer dcr.fundingMtx.Unlock() // stay locked until we update the map and lock them in the wallet\n\tfor _, id := range ids {\n\t\ttxHash, vout, err := decodeCoinID(id)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tpt := newOutPoint(txHash, vout)\n\t\tfundingCoin, found := dcr.fundingCoins[pt]\n\t\tif found {\n\t\t\tcoins = append(coins, fundingCoin.op)\n\t\t\tcontinue\n\t\t}\n\t\tnotFound[pt] = true\n\t}\n\tif len(notFound) == 0 {\n\t\treturn coins, nil\n\t}\n\n\t// Check locked outputs for not found coins.\n\tfor _, acct := range dcr.fundingAccounts() {\n\t\tlockedOutputs, err := dcr.wallet.LockedOutputs(dcr.ctx, acct)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfor _, output := range lockedOutputs {\n\t\t\ttxHash, err := chainhash.NewHashFromStr(output.Txid)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"error decoding txid from rpc server %s: %w\", output.Txid, err)\n\t\t\t}\n\t\t\tpt := newOutPoint(txHash, output.Vout)\n\t\t\tif !notFound[pt] {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ttxOut, err := dcr.wallet.UnspentOutput(dcr.ctx, txHash, output.Vout, output.Tree)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"gettxout error for locked output %v: %w\", pt.String(), err)\n\t\t\t}\n\t\t\tvar address string\n\t\t\tif len(txOut.Addresses) > 0 {\n\t\t\t\taddress = txOut.Addresses[0]\n\t\t\t}\n\t\t\tcoin := newOutput(txHash, output.Vout, toAtoms(output.Amount), output.Tree)\n\t\t\tcoins = append(coins, coin)\n\t\t\tdcr.fundingCoins[pt] = &fundingCoin{\n\t\t\t\top: coin,\n\t\t\t\taddr: address,\n\t\t\t}\n\t\t\tdelete(notFound, pt)\n\t\t\tif len(notFound) == 0 {\n\t\t\t\treturn coins, nil\n\t\t\t}\n\t\t}\n\t}\n\n\t// Some funding coins still not found after checking locked outputs.\n\t// Check wallet unspent outputs as last resort. Lock the coins if found.\n\tcoinsToLock := make([]*wire.OutPoint, 0, len(notFound))\n\tfor _, acct := range dcr.fundingAccounts() {\n\t\tunspents, err := dcr.wallet.Unspents(dcr.ctx, acct)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfor _, txout := range unspents {\n\t\t\ttxHash, err := chainhash.NewHashFromStr(txout.TxID)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"error decoding txid from rpc server %s: %w\", txout.TxID, err)\n\t\t\t}\n\t\t\tpt := newOutPoint(txHash, txout.Vout)\n\t\t\tif !notFound[pt] {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tcoinsToLock = append(coinsToLock, wire.NewOutPoint(txHash, txout.Vout, txout.Tree))\n\t\t\tcoin := newOutput(txHash, txout.Vout, toAtoms(txout.Amount), txout.Tree)\n\t\t\tcoins = append(coins, coin)\n\t\t\tdcr.fundingCoins[pt] = &fundingCoin{\n\t\t\t\top: coin,\n\t\t\t\taddr: txout.Address,\n\t\t\t}\n\t\t\tdelete(notFound, pt)\n\t\t\tif len(notFound) == 0 {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\t// Return an error if some coins are still not found.\n\tif len(notFound) != 0 {\n\t\tids := make([]string, 0, len(notFound))\n\t\tfor pt := range notFound {\n\t\t\tids = append(ids, pt.String())\n\t\t}\n\t\treturn nil, fmt.Errorf(\"funding coins not found: %s\", strings.Join(ids, \", \"))\n\t}\n\n\tdcr.log.Debugf(\"Locking funding coins that were unlocked %v\", coinsToLock)\n\terr := dcr.wallet.LockUnspent(dcr.ctx, false, coinsToLock)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn coins, nil\n}", "func (e *Election) Votes() int {\n\tcount := 0\n\tfor _, ballot := range e.ballots {\n\t\tif ballot {\n\t\t\tcount++\n\t\t}\n\t}\n\treturn count\n}", "func (keeper Keeper) SubtractCoins(ctx sdk.Context, addr sdk.Address, amt sdk.Coins) (sdk.Coins, sdk.Error) {\n\treturn subtractCoins(ctx, keeper.am, addr, amt)\n}", "func (_Contracts *ContractsSession) VotersCount() (*big.Int, error) {\n\treturn _Contracts.Contract.VotersCount(&_Contracts.CallOpts)\n}", "func (bva BaseVestingAccount) GetDelegatedVesting() sdk.Coins {\n\treturn bva.DelegatedVesting\n}", "func getOVMETHTotalSupply(inStateDB *state.StateDB) *big.Int {\n\tposition := common.Big2\n\tkey := common.BytesToHash(common.LeftPadBytes(position.Bytes(), 32))\n\treturn inStateDB.GetState(OVMETHAddress, key).Big()\n}", "func (p *Player) CashSpentTotal() int {\n\treturn p.AdditionalPlayerInformation.TotalCashSpent\n}", "func (_CrToken *CrTokenSession) TotalReserves() (*big.Int, error) {\n\treturn _CrToken.Contract.TotalReserves(&_CrToken.CallOpts)\n}", "func (btc *ExchangeWallet) FundingCoins(ids []dex.Bytes) (asset.Coins, error) {\n\t// First check if we have the coins in cache.\n\tcoins := make(asset.Coins, 0, len(ids))\n\tnotFound := make(map[string]struct{})\n\tbtc.fundingMtx.RLock()\n\tfor _, id := range ids {\n\t\ttxHash, vout, err := decodeCoinID(id)\n\t\tif err != nil {\n\t\t\tbtc.fundingMtx.RUnlock()\n\t\t\treturn nil, err\n\t\t}\n\t\topID := outpointID(txHash.String(), vout)\n\t\tfundingCoin, found := btc.fundingCoins[opID]\n\t\tif found {\n\t\t\tcoins = append(coins, newOutput(btc.node, txHash, vout, fundingCoin.amount, fundingCoin.redeemScript))\n\t\t\tcontinue\n\t\t}\n\t\tnotFound[opID] = struct{}{}\n\t}\n\tbtc.fundingMtx.RUnlock()\n\tif len(notFound) == 0 {\n\t\treturn coins, nil\n\t}\n\t_, utxoMap, _, err := btc.spendableUTXOs(0)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlockers := make([]*output, 0, len(ids))\n\tbtc.fundingMtx.Lock()\n\tdefer btc.fundingMtx.Unlock()\n\tfor _, id := range ids {\n\t\ttxHash, vout, err := decodeCoinID(id)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\topID := outpointID(txHash.String(), vout)\n\t\tutxo, found := utxoMap[opID]\n\t\tif !found {\n\t\t\treturn nil, fmt.Errorf(\"funding coin %s not found\", opID)\n\t\t}\n\t\tbtc.fundingCoins[opID] = utxo\n\t\tcoin := newOutput(btc.node, utxo.txHash, utxo.vout, utxo.amount, utxo.redeemScript)\n\t\tcoins = append(coins, coin)\n\t\tlockers = append(lockers, coin)\n\t\tdelete(notFound, opID)\n\t\tif len(notFound) == 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\tif len(notFound) != 0 {\n\t\tids := make([]string, 0, len(notFound))\n\t\tfor opID := range notFound {\n\t\t\tids = append(ids, opID)\n\t\t}\n\t\treturn nil, fmt.Errorf(\"coins not found: %s\", strings.Join(ids, \", \"))\n\t}\n\terr = btc.wallet.LockUnspent(false, lockers)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn coins, nil\n}", "func (a *Agent) GetPeersCount() uint32 {\n\treturn atomic.LoadUint32(&a.peersCount)\n}", "func (c Checkout) Total() int {\n\ttotal := 0\n\tfor code, quantity := range c.basket {\n\t\toffer, exists := offers[code]\n\t\tif exists {\n\t\t\ttotal += calculateOfferPrice(code, quantity, offer)\n\t\t} else {\n\t\t\ttotal += calculatePrice(code, quantity)\n\t\t}\n\t}\n\treturn total\n}", "func (_Vault *VaultSession) GetDecimals(token common.Address) (uint8, error) {\n\treturn _Vault.Contract.GetDecimals(&_Vault.CallOpts, token)\n}", "func (_Vault *VaultCaller) GetDecimals(opts *bind.CallOpts, token common.Address) (uint8, error) {\n\tvar (\n\t\tret0 = new(uint8)\n\t)\n\tout := ret0\n\terr := _Vault.contract.Call(opts, out, \"getDecimals\", token)\n\treturn *ret0, err\n}", "func arrangeCoins(n int) int {\n\tcount := 1\n\tfor n >= count {\n\t\tn -= count\n\t\tcount++\n\t}\n\treturn count - 1\n}", "func (_Bindings *BindingsCaller) TotalReserves(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _Bindings.contract.Call(opts, out, \"totalReserves\")\n\treturn *ret0, err\n}", "func (dcr *ExchangeWallet) ReturnCoins(unspents asset.Coins) error {\n\tdcr.fundingMtx.Lock()\n\tdefer dcr.fundingMtx.Unlock()\n\treturn dcr.returnCoins(unspents)\n}", "func (_Vault *VaultCallerSession) GetDecimals(token common.Address) (uint8, error) {\n\treturn _Vault.Contract.GetDecimals(&_Vault.CallOpts, token)\n}", "func getMoneyAmount(n int) int {\n \n}", "func (_Cakevault *CakevaultSession) TotalShares() (*big.Int, error) {\n\treturn _Cakevault.Contract.TotalShares(&_Cakevault.CallOpts)\n}", "func (_Bep20 *Bep20CallerSession) GetCurrentVotes(account common.Address) (*big.Int, error) {\n\treturn _Bep20.Contract.GetCurrentVotes(&_Bep20.CallOpts, account)\n}", "func TotalCoinsInvariant(ak auth.AccountKeeper, totalSupplyFn func() sdk.Coins) sdk.Invariant {\n\treturn func(ctx sdk.Context) error {\n\t\ttotalCoins := sdk.NewCoins()\n\n\t\tchkAccount := func(acc auth.Account) bool {\n\t\t\tcoins := acc.GetCoins()\n\t\t\ttotalCoins = totalCoins.Add(coins)\n\t\t\treturn false\n\t\t}\n\n\t\tak.IterateAccounts(ctx, chkAccount)\n\t\tif !totalSupplyFn().IsEqual(totalCoins) {\n\t\t\treturn errors.New(\"total calculated coins doesn't equal expected coins\")\n\t\t}\n\t\treturn nil\n\t}\n}", "func ChooseBestOutCoinsToSpent(utxos []*crypto.InputCoin, amount uint64) (\n\tresultOutputCoins []*crypto.InputCoin,\n\tremainOutputCoins []*crypto.InputCoin,\n\ttotalResultOutputCoinAmount uint64, err error) {\n\n\tresultOutputCoins = make([]*crypto.InputCoin, 0)\n\tremainOutputCoins = make([]*crypto.InputCoin, 0)\n\ttotalResultOutputCoinAmount = uint64(0)\n\n\t// either take the smallest coins, or a single largest one\n\tvar outCoinOverLimit *crypto.InputCoin\n\toutCoinsUnderLimit := make([]*crypto.InputCoin, 0)\n\tfor _, outCoin := range utxos {\n\t\tif outCoin.CoinDetails.GetValue() < amount {\n\t\t\toutCoinsUnderLimit = append(outCoinsUnderLimit, outCoin)\n\t\t} else if outCoinOverLimit == nil {\n\t\t\toutCoinOverLimit = outCoin\n\t\t} else if outCoinOverLimit.CoinDetails.GetValue() > outCoin.CoinDetails.GetValue() {\n\t\t\tremainOutputCoins = append(remainOutputCoins, outCoin)\n\t\t} else {\n\t\t\tremainOutputCoins = append(remainOutputCoins, outCoinOverLimit)\n\t\t\toutCoinOverLimit = outCoin\n\t\t}\n\t}\n\tsort.Slice(outCoinsUnderLimit, func(i, j int) bool {\n\t\treturn outCoinsUnderLimit[i].CoinDetails.GetValue() < outCoinsUnderLimit[j].CoinDetails.GetValue()\n\t})\n\tfor _, outCoin := range outCoinsUnderLimit {\n\t\tif totalResultOutputCoinAmount < amount {\n\t\t\ttotalResultOutputCoinAmount += outCoin.CoinDetails.GetValue()\n\t\t\tresultOutputCoins = append(resultOutputCoins, outCoin)\n\t\t} else {\n\t\t\tremainOutputCoins = append(remainOutputCoins, outCoin)\n\t\t}\n\t}\n\tif outCoinOverLimit != nil && (outCoinOverLimit.CoinDetails.GetValue() > 2*amount || totalResultOutputCoinAmount < amount) {\n\t\tremainOutputCoins = append(remainOutputCoins, resultOutputCoins...)\n\t\tresultOutputCoins = []*crypto.InputCoin{outCoinOverLimit}\n\t\ttotalResultOutputCoinAmount = outCoinOverLimit.CoinDetails.GetValue()\n\t} else if outCoinOverLimit != nil {\n\t\tremainOutputCoins = append(remainOutputCoins, outCoinOverLimit)\n\t}\n\tif totalResultOutputCoinAmount < amount {\n\t\treturn resultOutputCoins, remainOutputCoins, totalResultOutputCoinAmount, errors.New(\"Not enough coin\")\n\t} else {\n\t\treturn resultOutputCoins, remainOutputCoins, totalResultOutputCoinAmount, nil\n\t}\n}", "func (_CrToken *CrTokenCaller) TotalReserves(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _CrToken.contract.Call(opts, &out, \"totalReserves\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func GetTotalVestingPeriodLength(periods vesting.Periods) int64 {\n\tlength := int64(0)\n\tfor _, period := range periods {\n\t\tlength += period.Length\n\t}\n\treturn length\n}", "func (_ReserveSpenderMultiSig *ReserveSpenderMultiSigCaller) GetTransactionCount(opts *bind.CallOpts, pending bool, executed bool) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _ReserveSpenderMultiSig.contract.Call(opts, out, \"getTransactionCount\", pending, executed)\n\treturn *ret0, err\n}", "func (m *Machine) ReturnCoins() {\n\tcoins := m.cashEngine.DropCoins()\n\n\ts := fmt.Sprintf(\"-> \")\n\tfor i, c := range coins {\n\t\tif i == len(coins)-1 {\n\t\t\ts += fmt.Sprintf(\"%s\", c.value.String())\n\t\t\tcontinue\n\t\t}\n\t\ts += fmt.Sprintf(\"%s, \", c.value.String())\n\t}\n\n\tm.logger.Println(s)\n}", "func GetTotalVestingPeriodLength(periods vestingtypes.Periods) int64 {\n\tlength := int64(0)\n\tfor _, period := range periods {\n\t\tlength += period.Length\n\t}\n\treturn length\n}", "func (_Bep20 *Bep20Session) GetCurrentVotes(account common.Address) (*big.Int, error) {\n\treturn _Bep20.Contract.GetCurrentVotes(&_Bep20.CallOpts, account)\n}", "func (keeper SendKeeper) HasCoins(ctx sdk.Context, addr sdk.Address, amt sdk.Coins) bool {\n\treturn hasCoins(ctx, keeper.am, addr, amt)\n}", "func (serv *ExchangeServer) GetSupportCoins() []string {\n\tsymbols := make([]string, len(serv.coins))\n\ti := 0\n\tfor _, coin := range serv.coins {\n\t\tsymbols[i] = coin.Symbol()\n\t\ti++\n\t}\n\treturn symbols\n}", "func (o *AllocationList) GetInvested() float64 {\n\tif o == nil {\n\t\tvar ret float64\n\t\treturn ret\n\t}\n\n\treturn o.Invested\n}", "func ConvertSdkCoinsToWasmCoins(coins []sdk.Coin) wasmvmtypes.Coins {\n\tconverted := make(wasmvmtypes.Coins, len(coins))\n\tfor i, c := range coins {\n\t\tconverted[i] = ConvertSdkCoinToWasmCoin(c)\n\t}\n\treturn converted\n}", "func (t *TezTracker) GetStakingRatio() (float64, error) {\n\tlockedBalanceEstimate, err := t.getLockedBalance()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tar := t.repoProvider.GetAccount()\n\tliquidBalance, err := ar.TotalBalance()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tbr := t.repoProvider.GetBaker()\n\tstakedBalance, err := br.TotalStakingBalance()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tsupply := liquidBalance + lockedBalanceEstimate\n\tif supply == 0 {\n\t\treturn 0, nil\n\t}\n\n\tlastBlock, err := t.repoProvider.GetBlock().Last()\n\tif err != nil {\n\t\treturn 0, nil\n\t}\n\n\tbakingRewards, err := br.TotalBakingRewards(\"\", lastBlock.MetaCycle-PreservedCycles, lastBlock.MetaCycle)\n\tif err != nil {\n\t\treturn 0, nil\n\t}\n\n\tendorsementRewards, err := br.TotalEndorsementRewards(\"\", lastBlock.MetaCycle-PreservedCycles, lastBlock.MetaCycle)\n\tif err != nil {\n\t\treturn 0, nil\n\t}\n\n\tstakedBalance = stakedBalance - bakingRewards - endorsementRewards\n\tratio := float64(stakedBalance) / float64(supply)\n\n\treturn ratio, nil\n}", "func (va ClawbackVestingAccount) GetVestingPeriods() Periods {\n\treturn va.VestingPeriods\n}", "func (n *treeNode) getVisits() uint64 {\n\tif n == nil {\n\t\treturn 0\n\t}\n\treturn n.visits\n}" ]
[ "0.7442845", "0.72723347", "0.7266479", "0.7130243", "0.7013952", "0.6711385", "0.6681812", "0.66395986", "0.6623994", "0.6511514", "0.6415937", "0.56000996", "0.554174", "0.54808176", "0.5400817", "0.53537637", "0.5305921", "0.5294013", "0.52684784", "0.52653897", "0.52420926", "0.52269083", "0.51952934", "0.50877964", "0.5014879", "0.49281168", "0.49243104", "0.4906418", "0.48536986", "0.48483047", "0.48297632", "0.4790019", "0.47647175", "0.46119684", "0.4580252", "0.45748505", "0.45620158", "0.45468825", "0.45267123", "0.45218337", "0.45183918", "0.45116597", "0.44759947", "0.44667637", "0.44548517", "0.44495237", "0.4417633", "0.4417015", "0.44138885", "0.4410933", "0.44056422", "0.4400787", "0.44007498", "0.4384444", "0.4377259", "0.43627372", "0.43442202", "0.43283457", "0.43281037", "0.4320912", "0.43161422", "0.4309387", "0.4294217", "0.42822573", "0.42641565", "0.42557913", "0.42496905", "0.42231998", "0.42189085", "0.42077294", "0.41864446", "0.41842276", "0.41787797", "0.41787696", "0.4177772", "0.417599", "0.41759354", "0.41707346", "0.41701806", "0.4168104", "0.4166591", "0.41660267", "0.41593862", "0.41584596", "0.4154587", "0.41503176", "0.41495946", "0.41340876", "0.41298267", "0.412836", "0.41224635", "0.41218624", "0.41204992", "0.41147107", "0.41095278", "0.4100532", "0.4095131", "0.40941277", "0.40936035", "0.40929845" ]
0.7148229
3
LockedCoins returns the set of coins that are not spendable (i.e. locked), defined as the vesting coins that are not delegated.
func (pva PeriodicVestingAccount) LockedCoins(ctx sdk.Context) sdk.Coins { return pva.BaseVestingAccount.LockedCoinsFromVesting(pva.GetVestingCoins(ctx.BlockTime())) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (dva DelayedVestingAccount) LockedCoins(ctx sdk.Context) sdk.Coins {\n\treturn dva.BaseVestingAccount.LockedCoinsFromVesting(dva.GetVestingCoins(ctx.BlockTime()))\n}", "func (cva ContinuousVestingAccount) LockedCoins(ctx sdk.Context) sdk.Coins {\n\treturn cva.BaseVestingAccount.LockedCoinsFromVesting(cva.GetVestingCoins(ctx.BlockTime()))\n}", "func (va ClawbackVestingAccount) LockedCoins(ctx sdk.Context) sdk.Coins {\n\treturn va.BaseVestingAccount.LockedCoinsFromVesting(va.GetVestingCoins(ctx.BlockTime()))\n}", "func (plva PermanentLockedAccount) LockedCoins(_ sdk.Context) sdk.Coins {\n\treturn plva.BaseVestingAccount.LockedCoinsFromVesting(plva.OriginalVesting)\n}", "func (bva BaseVestingAccount) LockedCoinsFromVesting(vestingCoins sdk.Coins) sdk.Coins {\n\tlockedCoins := vestingCoins.Sub(vestingCoins.Min(bva.DelegatedVesting))\n\tif lockedCoins == nil {\n\t\treturn sdk.Coins{}\n\t}\n\treturn lockedCoins\n}", "func (plva PermanentLockedAccount) GetVestingCoins(_ time.Time) sdk.Coins {\n\treturn plva.OriginalVesting\n}", "func (plva PermanentLockedAccount) GetVestedCoins(_ time.Time) sdk.Coins {\n\treturn nil\n}", "func (dcr *ExchangeWallet) lockedOutputs() ([]chainjson.TransactionInput, error) {\n\tvar locked []chainjson.TransactionInput\n\terr := dcr.nodeRawRequest(methodListLockUnspent, anylist{dcr.acct}, &locked)\n\treturn locked, err\n}", "func (w *rpcWallet) LockedOutputs(ctx context.Context, acctName string) ([]chainjson.TransactionInput, error) {\n\tvar locked []chainjson.TransactionInput\n\terr := w.rpcClientRawRequest(ctx, methodListLockUnspent, anylist{acctName}, &locked)\n\treturn locked, translateRPCCancelErr(err)\n}", "func (w *Wallet) LockedOutpoints() []btcjson.TransactionInput {\n\tlocked := make([]btcjson.TransactionInput, len(w.lockedOutpoints))\n\ti := 0\n\tfor op := range w.lockedOutpoints {\n\t\tlocked[i] = btcjson.TransactionInput{\n\t\t\tTxid: op.Hash.String(),\n\t\t\tVout: op.Index,\n\t\t}\n\t\ti++\n\t}\n\treturn locked\n}", "func (a *Account) LockedOutpoints() []btcjson.TransactionInput {\n\tlocked := make([]btcjson.TransactionInput, len(a.lockedOutpoints))\n\ti := 0\n\tfor op := range a.lockedOutpoints {\n\t\tlocked[i] = btcjson.TransactionInput{\n\t\t\tTxid: op.Hash.String(),\n\t\t\tVout: op.Index,\n\t\t}\n\t\ti++\n\t}\n\treturn locked\n}", "func (b *Bitcoind) ListLockUnspent() (unspendableOutputs []UnspendableOutput, err error) {\n\tr, err := b.client.call(\"listlockunspent\", nil)\n\tif err = handleError(err, &r); err != nil {\n\t\treturn\n\t}\n\n\terr = json.Unmarshal(r.Result, &unspendableOutputs)\n\treturn\n}", "func (btc *ExchangeWallet) lockedSats() (uint64, error) {\n\tlockedOutpoints, err := btc.wallet.ListLockUnspent()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tvar sum uint64\n\tbtc.fundingMtx.Lock()\n\tdefer btc.fundingMtx.Unlock()\n\tfor _, outPoint := range lockedOutpoints {\n\t\topID := outpointID(outPoint.TxID, outPoint.Vout)\n\t\tutxo, found := btc.fundingCoins[opID]\n\t\tif found {\n\t\t\tsum += utxo.amount\n\t\t\tcontinue\n\t\t}\n\t\ttxHash, err := chainhash.NewHashFromStr(outPoint.TxID)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\ttxOut, err := btc.node.GetTxOut(txHash, outPoint.Vout, true)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\tif txOut == nil {\n\t\t\t// Must be spent now?\n\t\t\tbtc.log.Debugf(\"ignoring output from listlockunspent that wasn't found with gettxout. %s\", opID)\n\t\t\tcontinue\n\t\t}\n\t\tsum += toSatoshi(txOut.Value)\n\t}\n\treturn sum, nil\n}", "func (dva DelayedVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn dva.OriginalVesting.Sub(dva.GetVestedCoins(blockTime))\n}", "func (dcr *ExchangeWallet) FundingCoins(ids []dex.Bytes) (asset.Coins, error) {\n\t// First check if we have the coins in cache.\n\tcoins := make(asset.Coins, 0, len(ids))\n\tnotFound := make(map[outPoint]bool)\n\tdcr.fundingMtx.Lock()\n\tdefer dcr.fundingMtx.Unlock() // stay locked until we update the map and lock them in the wallet\n\tfor _, id := range ids {\n\t\ttxHash, vout, err := decodeCoinID(id)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tpt := newOutPoint(txHash, vout)\n\t\tfundingCoin, found := dcr.fundingCoins[pt]\n\t\tif found {\n\t\t\tcoins = append(coins, fundingCoin.op)\n\t\t\tcontinue\n\t\t}\n\t\tnotFound[pt] = true\n\t}\n\tif len(notFound) == 0 {\n\t\treturn coins, nil\n\t}\n\n\t// Check locked outputs for not found coins.\n\tlockedOutputs, err := dcr.lockedOutputs()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor _, output := range lockedOutputs {\n\t\ttxHash, err := chainhash.NewHashFromStr(output.Txid)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error decoding txid from rpc server %s: %w\", output.Txid, err)\n\t\t}\n\t\tpt := newOutPoint(txHash, output.Vout)\n\t\tif !notFound[pt] {\n\t\t\tcontinue\n\t\t}\n\t\ttxOut, err := dcr.node.GetTxOut(dcr.ctx, txHash, output.Vout, true)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"gettxout error for locked output %v: %w\", pt.String(), translateRPCCancelErr(err))\n\t\t}\n\t\tvar address string\n\t\tif len(txOut.ScriptPubKey.Addresses) > 0 {\n\t\t\taddress = txOut.ScriptPubKey.Addresses[0]\n\t\t}\n\t\tcoin := newOutput(txHash, output.Vout, toAtoms(output.Amount), output.Tree)\n\t\tcoins = append(coins, coin)\n\t\tdcr.fundingCoins[pt] = &fundingCoin{\n\t\t\top: coin,\n\t\t\taddr: address,\n\t\t}\n\t\tdelete(notFound, pt)\n\t\tif len(notFound) == 0 {\n\t\t\treturn coins, nil\n\t\t}\n\t}\n\n\t// Some funding coins still not found after checking locked outputs.\n\t// Check wallet unspent outputs as last resort. Lock the coins if found.\n\tunspents, err := dcr.unspents()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcoinsToLock := make([]*wire.OutPoint, 0, len(notFound))\n\tfor _, txout := range unspents {\n\t\ttxHash, err := chainhash.NewHashFromStr(txout.TxID)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error decoding txid from rpc server %s: %w\", txout.TxID, err)\n\t\t}\n\t\tpt := newOutPoint(txHash, txout.Vout)\n\t\tif !notFound[pt] {\n\t\t\tcontinue\n\t\t}\n\t\tcoinsToLock = append(coinsToLock, wire.NewOutPoint(txHash, txout.Vout, txout.Tree))\n\t\tcoin := newOutput(txHash, txout.Vout, toAtoms(txout.Amount), txout.Tree)\n\t\tcoins = append(coins, coin)\n\t\tdcr.fundingCoins[pt] = &fundingCoin{\n\t\t\top: coin,\n\t\t\taddr: txout.Address,\n\t\t}\n\t\tdelete(notFound, pt)\n\t\tif len(notFound) == 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\tif len(notFound) != 0 {\n\t\tids := make([]string, 0, len(notFound))\n\t\tfor pt := range notFound {\n\t\t\tids = append(ids, pt.String())\n\t\t}\n\t\treturn nil, fmt.Errorf(\"funding coins not found: %s\", strings.Join(ids, \", \"))\n\t}\n\tdcr.log.Debugf(\"Locking funding coins that were unlocked %v\", coinsToLock)\n\terr = dcr.node.LockUnspent(dcr.ctx, false, coinsToLock)\n\tif err != nil {\n\t\treturn nil, translateRPCCancelErr(err)\n\t}\n\n\treturn coins, nil\n}", "func (bc *BlockChain) FindUnspentTransactions(addr string) []Transaction {\n\tvar unspentTXs []Transaction\n\tspentTXOutputs := make(map[string][]int)\n\titerator := bc.Iterator()\n\n\tfor {\n\t\t_block := iterator.Next()\n\n\t\tfor _, tx := range _block.Transactions {\n\t\t\ttxID := hex.EncodeToString(tx.ID)\n\n\t\tOutputs:\n\t\t\tfor outIdx, out := range tx.VOut {\n\t\t\t\tif spentTXOutputs[txID] != nil {\n\t\t\t\t\tfor _, spentOut := range spentTXOutputs[txID] {\n\t\t\t\t\t\tif spentOut == outIdx {\n\t\t\t\t\t\t\tcontinue Outputs\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif out.CanBeUnlockedWith(addr) {\n\t\t\t\t\tunspentTXs = append(unspentTXs, *tx)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif !tx.isCoinBaseTx() {\n\t\t\t\tfor _, in := range tx.VIn {\n\t\t\t\t\tif in.CanUnlockOutputWith(addr) {\n\t\t\t\t\t\tinTxID := hex.EncodeToString(in.TxID)\n\t\t\t\t\t\tspentTXOutputs[inTxID] = append(spentTXOutputs[inTxID], in.VOut)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif len(_block.Prev) == 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn unspentTXs\n}", "func (va ClawbackVestingAccount) GetVestedCoins(blockTime time.Time) sdk.Coins {\n\t// It's likely that one or the other schedule will be nearly trivial,\n\t// so there should be little overhead in recomputing the conjunction each time.\n\tcoins := coinsMin(va.GetUnlockedOnly(blockTime), va.GetVestedOnly(blockTime))\n\tif coins.IsZero() {\n\t\treturn nil\n\t}\n\treturn coins\n}", "func (dcr *ExchangeWallet) FundingCoins(ids []dex.Bytes) (asset.Coins, error) {\n\t// First check if we have the coins in cache.\n\tcoins := make(asset.Coins, 0, len(ids))\n\tnotFound := make(map[outPoint]bool)\n\tdcr.fundingMtx.Lock()\n\tdefer dcr.fundingMtx.Unlock() // stay locked until we update the map and lock them in the wallet\n\tfor _, id := range ids {\n\t\ttxHash, vout, err := decodeCoinID(id)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tpt := newOutPoint(txHash, vout)\n\t\tfundingCoin, found := dcr.fundingCoins[pt]\n\t\tif found {\n\t\t\tcoins = append(coins, fundingCoin.op)\n\t\t\tcontinue\n\t\t}\n\t\tnotFound[pt] = true\n\t}\n\tif len(notFound) == 0 {\n\t\treturn coins, nil\n\t}\n\n\t// Check locked outputs for not found coins.\n\tfor _, acct := range dcr.fundingAccounts() {\n\t\tlockedOutputs, err := dcr.wallet.LockedOutputs(dcr.ctx, acct)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfor _, output := range lockedOutputs {\n\t\t\ttxHash, err := chainhash.NewHashFromStr(output.Txid)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"error decoding txid from rpc server %s: %w\", output.Txid, err)\n\t\t\t}\n\t\t\tpt := newOutPoint(txHash, output.Vout)\n\t\t\tif !notFound[pt] {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ttxOut, err := dcr.wallet.UnspentOutput(dcr.ctx, txHash, output.Vout, output.Tree)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"gettxout error for locked output %v: %w\", pt.String(), err)\n\t\t\t}\n\t\t\tvar address string\n\t\t\tif len(txOut.Addresses) > 0 {\n\t\t\t\taddress = txOut.Addresses[0]\n\t\t\t}\n\t\t\tcoin := newOutput(txHash, output.Vout, toAtoms(output.Amount), output.Tree)\n\t\t\tcoins = append(coins, coin)\n\t\t\tdcr.fundingCoins[pt] = &fundingCoin{\n\t\t\t\top: coin,\n\t\t\t\taddr: address,\n\t\t\t}\n\t\t\tdelete(notFound, pt)\n\t\t\tif len(notFound) == 0 {\n\t\t\t\treturn coins, nil\n\t\t\t}\n\t\t}\n\t}\n\n\t// Some funding coins still not found after checking locked outputs.\n\t// Check wallet unspent outputs as last resort. Lock the coins if found.\n\tcoinsToLock := make([]*wire.OutPoint, 0, len(notFound))\n\tfor _, acct := range dcr.fundingAccounts() {\n\t\tunspents, err := dcr.wallet.Unspents(dcr.ctx, acct)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfor _, txout := range unspents {\n\t\t\ttxHash, err := chainhash.NewHashFromStr(txout.TxID)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"error decoding txid from rpc server %s: %w\", txout.TxID, err)\n\t\t\t}\n\t\t\tpt := newOutPoint(txHash, txout.Vout)\n\t\t\tif !notFound[pt] {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tcoinsToLock = append(coinsToLock, wire.NewOutPoint(txHash, txout.Vout, txout.Tree))\n\t\t\tcoin := newOutput(txHash, txout.Vout, toAtoms(txout.Amount), txout.Tree)\n\t\t\tcoins = append(coins, coin)\n\t\t\tdcr.fundingCoins[pt] = &fundingCoin{\n\t\t\t\top: coin,\n\t\t\t\taddr: txout.Address,\n\t\t\t}\n\t\t\tdelete(notFound, pt)\n\t\t\tif len(notFound) == 0 {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\t// Return an error if some coins are still not found.\n\tif len(notFound) != 0 {\n\t\tids := make([]string, 0, len(notFound))\n\t\tfor pt := range notFound {\n\t\t\tids = append(ids, pt.String())\n\t\t}\n\t\treturn nil, fmt.Errorf(\"funding coins not found: %s\", strings.Join(ids, \", \"))\n\t}\n\n\tdcr.log.Debugf(\"Locking funding coins that were unlocked %v\", coinsToLock)\n\terr := dcr.wallet.LockUnspent(dcr.ctx, false, coinsToLock)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn coins, nil\n}", "func (vva ValidatorVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn vva.OriginalVesting.Sub(vva.GetVestedCoins(blockTime))\n}", "func (va ClawbackVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn va.OriginalVesting.Sub(va.GetVestedCoins(blockTime))\n}", "func (dva DelayedVestingAccount) GetVestedCoins(blockTime time.Time) sdk.Coins {\n\tif blockTime.Unix() >= dva.EndTime {\n\t\treturn dva.OriginalVesting\n\t}\n\n\treturn nil\n}", "func (vva ValidatorVestingAccount) SpendableCoins(blockTime time.Time) sdk.Coins {\n\treturn vva.BaseVestingAccount.SpendableCoinsVestingAccount(vva.GetVestingCoins(blockTime))\n}", "func (vva ValidatorVestingAccount) GetVestedCoins(blockTime time.Time) sdk.Coins {\n\tvar vestedCoins sdk.Coins\n\tif blockTime.Unix() <= vva.StartTime {\n\t\treturn vestedCoins\n\t}\n\tcurrentPeriodStartTime := vva.StartTime\n\tnumberPeriods := len(vva.VestingPeriods)\n\tfor i := 0; i < numberPeriods; i++ {\n\t\tx := blockTime.Unix() - currentPeriodStartTime\n\t\tif x >= vva.VestingPeriods[i].Length {\n\t\t\tif vva.VestingPeriodProgress[i].PeriodComplete {\n\t\t\t\tvestedCoins = vestedCoins.Add(vva.VestingPeriods[i].Amount)\n\t\t\t}\n\t\t\tcurrentPeriodStartTime += vva.VestingPeriods[i].Length\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn vestedCoins\n\n}", "func (chain *BlockChain) FindUnspentTransactions(address string) []Transaction {\n\tvar unspentTxs []Transaction\n\n\tspentTxOs := make(map[string][]int)\n\n\titer := chain.Iterator()\n\n\tfor {\n\t\tblock := iter.Next()\n\n\t\tfor _, tx := range block.Transactions {\n\t\t\ttxID := hex.EncodeToString(tx.ID)\n\n\t\tOutputs:\n\t\t\tfor outIdx, out := range tx.Outputs {\n\t\t\t\tif spentTxOs[txID] != nil {\n\t\t\t\t\tfor _, spentOut := range spentTxOs[txID] {\n\t\t\t\t\t\tif spentOut == outIdx {\n\t\t\t\t\t\t\tcontinue Outputs\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif out.CanBeUnlocked(address) {\n\t\t\t\t\tunspentTxs = append(unspentTxs, *tx)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif tx.IsCoinbase() == false {\n\t\t\t\tfor _, in := range tx.Inputs {\n\t\t\t\t\tif in.CanUnlock(address) {\n\t\t\t\t\t\tinTxID := hex.EncodeToString(in.ID)\n\n\t\t\t\t\t\tspentTxOs[inTxID] = append(spentTxOs[inTxID], in.Out)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif len(block.PrevHash) == 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn unspentTxs\n}", "func (cva ContinuousVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn cva.OriginalVesting.Sub(cva.GetVestedCoins(blockTime))\n}", "func (pva PeriodicVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn pva.OriginalVesting.Sub(pva.GetVestedCoins(blockTime))\n}", "func (dcr *ExchangeWallet) lockFundingCoins(fCoins []*fundingCoin) error {\n\twireOPs := make([]*wire.OutPoint, 0, len(fCoins))\n\tfor _, c := range fCoins {\n\t\twireOPs = append(wireOPs, wire.NewOutPoint(c.op.txHash(), c.op.vout(), c.op.tree))\n\t}\n\terr := dcr.wallet.LockUnspent(dcr.ctx, false, wireOPs)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, c := range fCoins {\n\t\tdcr.fundingCoins[c.op.pt] = c\n\t}\n\treturn nil\n}", "func (b *Bitcoind) LockUnspent(lock bool, outputs []UnspendableOutput) (success bool, err error) {\n\tr, err := b.client.call(\"lockunspent\", []interface{}{lock, outputs})\n\tif err = handleError(err, &r); err != nil {\n\t\treturn\n\t}\n\n\terr = json.Unmarshal(r.Result, &success)\n\treturn\n}", "func (va ClawbackVestingAccount) GetUnlockedOnly(blockTime time.Time) sdk.Coins {\n\treturn ReadSchedule(va.StartTime, va.EndTime, va.LockupPeriods, va.OriginalVesting, blockTime.Unix())\n}", "func (dcr *ExchangeWallet) returnCoins(unspents asset.Coins) ([]*fundingCoin, error) {\n\tif len(unspents) == 0 {\n\t\treturn nil, fmt.Errorf(\"cannot return zero coins\")\n\t}\n\n\tops := make([]*wire.OutPoint, 0, len(unspents))\n\tfundingCoins := make([]*fundingCoin, 0, len(unspents))\n\n\tdcr.log.Debugf(\"returning coins %s\", unspents)\n\tfor _, unspent := range unspents {\n\t\top, err := dcr.convertCoin(unspent)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error converting coin: %w\", err)\n\t\t}\n\t\tops = append(ops, op.wireOutPoint()) // op.tree may be wire.TxTreeUnknown, but that's fine since wallet.LockUnspent doesn't rely on it\n\t\tif fCoin, ok := dcr.fundingCoins[op.pt]; ok {\n\t\t\tfundingCoins = append(fundingCoins, fCoin)\n\t\t\tdelete(dcr.fundingCoins, op.pt)\n\t\t} else {\n\t\t\tdcr.log.Warnf(\"returning coin %s that is not cached as a funding coin\", op)\n\t\t\tfundingCoins = append(fundingCoins, &fundingCoin{op: op})\n\t\t}\n\t}\n\n\treturn fundingCoins, dcr.wallet.LockUnspent(dcr.ctx, true, ops)\n}", "func (w *Wallet) Locked() bool {\n\treturn <-w.lockState\n}", "func (dcr *ExchangeWallet) lockFundingCoins(fCoins []*fundingCoin) error {\n\twireOPs := make([]*wire.OutPoint, 0, len(fCoins))\n\tfor _, c := range fCoins {\n\t\twireOPs = append(wireOPs, wire.NewOutPoint(c.op.txHash(), c.op.vout(), c.op.tree))\n\t}\n\terr := dcr.node.LockUnspent(dcr.ctx, false, wireOPs)\n\tif err != nil {\n\t\treturn translateRPCCancelErr(err)\n\t}\n\tfor _, c := range fCoins {\n\t\tdcr.fundingCoins[c.op.pt] = c\n\t}\n\treturn nil\n}", "func (cva ContinuousVestingAccount) GetVestedCoins(blockTime time.Time) sdk.Coins {\n\tvar vestedCoins sdk.Coins\n\n\t// We must handle the case where the start time for a vesting account has\n\t// been set into the future or when the start of the chain is not exactly\n\t// known.\n\tif blockTime.Unix() <= cva.StartTime {\n\t\treturn vestedCoins\n\t} else if blockTime.Unix() >= cva.EndTime {\n\t\treturn cva.OriginalVesting\n\t}\n\n\t// calculate the vesting scalar\n\tx := blockTime.Unix() - cva.StartTime\n\ty := cva.EndTime - cva.StartTime\n\ts := sdk.NewDec(x).Quo(sdk.NewDec(y))\n\n\tfor _, ovc := range cva.OriginalVesting {\n\t\tvestedAmt := ovc.Amount.ToDec().Mul(s).RoundInt()\n\t\tvestedCoins = append(vestedCoins, sdk.NewCoin(ovc.Denom, vestedAmt))\n\t}\n\n\treturn vestedCoins\n}", "func (dcr *ExchangeWallet) returnCoins(unspents asset.Coins) error {\n\tif len(unspents) == 0 {\n\t\treturn fmt.Errorf(\"cannot return zero coins\")\n\t}\n\tops := make([]*wire.OutPoint, 0, len(unspents))\n\n\tdcr.log.Debugf(\"returning coins %s\", unspents)\n\tfor _, unspent := range unspents {\n\t\top, err := dcr.convertCoin(unspent)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error converting coin: %w\", err)\n\t\t}\n\t\tops = append(ops, wire.NewOutPoint(op.txHash(), op.vout(), op.tree))\n\t\tdelete(dcr.fundingCoins, op.pt)\n\t}\n\treturn translateRPCCancelErr(dcr.node.LockUnspent(dcr.ctx, true, ops))\n}", "func (dcr *ExchangeWallet) Locked() bool {\n\tfor _, acct := range dcr.fundingAccounts() {\n\t\tunlocked, err := dcr.wallet.AccountUnlocked(dcr.ctx, acct)\n\t\tif err != nil {\n\t\t\tdcr.log.Errorf(\"error checking account lock status %v\", err)\n\t\t\tunlocked = false // assume wallet is unlocked?\n\t\t}\n\t\tif !unlocked {\n\t\t\treturn true // Locked is true if any of the funding accounts is locked.\n\t\t}\n\t}\n\treturn false\n}", "func (w *Wallet) ListUnspent(minconf, maxconf int32,\n\taddresses map[string]struct{}) ([]*btcjson.ListUnspentResult, er.R) {\n\n\tvar results []*btcjson.ListUnspentResult\n\terr := walletdb.View(w.db, func(tx walletdb.ReadTx) er.R {\n\t\taddrmgrNs := tx.ReadBucket(waddrmgrNamespaceKey)\n\t\ttxmgrNs := tx.ReadBucket(wtxmgrNamespaceKey)\n\n\t\tsyncBlock := w.Manager.SyncedTo()\n\n\t\tfilter := len(addresses) != 0\n\t\tunspent, err := w.TxStore.GetUnspentOutputs(txmgrNs)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tsort.Sort(sort.Reverse(creditSlice(unspent)))\n\n\t\tdefaultAccountName := \"default\"\n\n\t\tresults = make([]*btcjson.ListUnspentResult, 0, len(unspent))\n\t\tfor i := range unspent {\n\t\t\toutput := unspent[i]\n\n\t\t\t// Outputs with fewer confirmations than the minimum or more\n\t\t\t// confs than the maximum are excluded.\n\t\t\tconfs := confirms(output.Height, syncBlock.Height)\n\t\t\tif confs < minconf || confs > maxconf {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// Only mature coinbase outputs are included.\n\t\t\tif output.FromCoinBase {\n\t\t\t\ttarget := int32(w.ChainParams().CoinbaseMaturity)\n\t\t\t\tif !confirmed(target, output.Height, syncBlock.Height) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Exclude locked outputs from the result set.\n\t\t\tif w.LockedOutpoint(output.OutPoint) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// Lookup the associated account for the output. Use the\n\t\t\t// default account name in case there is no associated account\n\t\t\t// for some reason, although this should never happen.\n\t\t\t//\n\t\t\t// This will be unnecessary once transactions and outputs are\n\t\t\t// grouped under the associated account in the db.\n\t\t\tacctName := defaultAccountName\n\t\t\tsc, addrs, _, err := txscript.ExtractPkScriptAddrs(\n\t\t\t\toutput.PkScript, w.chainParams)\n\t\t\tif err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif len(addrs) > 0 {\n\t\t\t\tsmgr, acct, err := w.Manager.AddrAccount(addrmgrNs, addrs[0])\n\t\t\t\tif err == nil {\n\t\t\t\t\ts, err := smgr.AccountName(addrmgrNs, acct)\n\t\t\t\t\tif err == nil {\n\t\t\t\t\t\tacctName = s\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif filter {\n\t\t\t\tfor _, addr := range addrs {\n\t\t\t\t\t_, ok := addresses[addr.EncodeAddress()]\n\t\t\t\t\tif ok {\n\t\t\t\t\t\tgoto include\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\tinclude:\n\t\t\t// At the moment watch-only addresses are not supported, so all\n\t\t\t// recorded outputs that are not multisig are \"spendable\".\n\t\t\t// Multisig outputs are only \"spendable\" if all keys are\n\t\t\t// controlled by this wallet.\n\t\t\t//\n\t\t\t// TODO: Each case will need updates when watch-only addrs\n\t\t\t// is added. For P2PK, P2PKH, and P2SH, the address must be\n\t\t\t// looked up and not be watching-only. For multisig, all\n\t\t\t// pubkeys must belong to the manager with the associated\n\t\t\t// private key (currently it only checks whether the pubkey\n\t\t\t// exists, since the private key is required at the moment).\n\t\t\tvar spendable bool\n\t\tscSwitch:\n\t\t\tswitch sc {\n\t\t\tcase txscript.PubKeyHashTy:\n\t\t\t\tspendable = true\n\t\t\tcase txscript.PubKeyTy:\n\t\t\t\tspendable = true\n\t\t\tcase txscript.WitnessV0ScriptHashTy:\n\t\t\t\tspendable = true\n\t\t\tcase txscript.WitnessV0PubKeyHashTy:\n\t\t\t\tspendable = true\n\t\t\tcase txscript.MultiSigTy:\n\t\t\t\tfor _, a := range addrs {\n\t\t\t\t\t_, err := w.Manager.Address(addrmgrNs, a)\n\t\t\t\t\tif err == nil {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tif waddrmgr.ErrAddressNotFound.Is(err) {\n\t\t\t\t\t\tbreak scSwitch\n\t\t\t\t\t}\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tspendable = true\n\t\t\t}\n\n\t\t\tresult := &btcjson.ListUnspentResult{\n\t\t\t\tTxID: output.OutPoint.Hash.String(),\n\t\t\t\tVout: output.OutPoint.Index,\n\t\t\t\tAccount: acctName,\n\t\t\t\tScriptPubKey: hex.EncodeToString(output.PkScript),\n\t\t\t\tAmount: output.Amount.ToBTC(),\n\t\t\t\tConfirmations: int64(confs),\n\t\t\t\tSpendable: spendable,\n\t\t\t}\n\n\t\t\t// BUG: this should be a JSON array so that all\n\t\t\t// addresses can be included, or removed (and the\n\t\t\t// caller extracts addresses from the pkScript).\n\t\t\tif len(addrs) > 0 {\n\t\t\t\tresult.Address = addrs[0].EncodeAddress()\n\t\t\t}\n\n\t\t\tresults = append(results, result)\n\t\t}\n\t\treturn nil\n\t})\n\treturn results, err\n}", "func (wt *Wallet) Locked() bool {\n\treturn <-wt.lockState\n}", "func NewQueryLockedCoinsParams(accountID types.AccountID) QueryLockedCoinsParams {\n\treturn QueryLockedCoinsParams{\n\t\tAccountID: accountID,\n\t}\n}", "func (pva PeriodicVestingAccount) GetVestedCoins(blockTime time.Time) sdk.Coins {\n\tcoins := ReadSchedule(pva.StartTime, pva.EndTime, pva.VestingPeriods, pva.OriginalVesting, blockTime.Unix())\n\tif coins.IsZero() {\n\t\treturn nil\n\t}\n\treturn coins\n}", "func GetLockedDistributionAddresses() []string {\n\t// TODO -- once we reach 30% distribution, we can hardcode the\n\t// initial timestamp for releasing more coins\n\taddrs := make([]string, DistributionAddressesTotal-InitialUnlockedCount)\n\tfor i := range distributionAddresses[InitialUnlockedCount:] {\n\t\taddrs[i] = distributionAddresses[InitialUnlockedCount+uint64(i)]\n\t}\n\n\treturn addrs\n}", "func (btc *ExchangeWallet) ReturnCoins(unspents asset.Coins) error {\n\tif len(unspents) == 0 {\n\t\treturn fmt.Errorf(\"cannot return zero coins\")\n\t}\n\tops := make([]*output, 0, len(unspents))\n\tbtc.fundingMtx.Lock()\n\tdefer btc.fundingMtx.Unlock()\n\tfor _, unspent := range unspents {\n\t\top, err := btc.convertCoin(unspent)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error converting coin: %v\", err)\n\t\t}\n\t\tops = append(ops, op)\n\t\tdelete(btc.fundingCoins, outpointID(op.txHash.String(), op.vout))\n\t}\n\treturn btc.wallet.LockUnspent(true, ops)\n}", "func (r *Ring) InPot() []Box {\n\treturn r.Where(func(s *Seat) bool {\n\t\treturn s.State == seat.Play || s.State == seat.Bet || s.State == seat.AllIn\n\t})\n}", "func (dcr *ExchangeWallet) ReturnCoins(unspents asset.Coins) error {\n\tdcr.fundingMtx.Lock()\n\tdefer dcr.fundingMtx.Unlock()\n\treturn dcr.returnCoins(unspents)\n}", "func (keeper SendKeeper) GetCoins(ctx sdk.Context, addr sdk.Address) sdk.Coins {\n\treturn getCoins(ctx, keeper.am, addr)\n}", "func (txn TxnProbe) CollectLockedKeys() [][]byte {\n\treturn txn.collectLockedKeys()\n}", "func (keeper ViewKeeper) GetCoins(ctx sdk.Context, addr sdk.Address) sdk.Coins {\n\treturn getCoins(ctx, keeper.am, addr)\n}", "func GetUnspentOutputCoinsExceptSpendingUTXO(rpcClient *rpcclient.HttpClient, keyWallet *wallet.KeyWallet) ([]*crypto.InputCoin, error) {\n\tpublicKey := keyWallet.KeySet.PaymentAddress.Pk\n\n\t// check and remove utxo cache (these utxos in txs that were confirmed)\n\t//CheckAndRemoveUTXOFromCache(keyWallet.KeySet.PaymentAddress.Pk, inputCoins)\n\tCheckAndRemoveUTXOFromCacheV2(keyWallet.KeySet.PaymentAddress.Pk, rpcClient)\n\n\t// get unspent output coins from network\n\tutxos, err := GetUnspentOutputCoins(rpcClient, keyWallet)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tinputCoins := ConvertOutputCoinToInputCoin(utxos)\n\n\t// except spending utxos from unspent output coins\n\tutxosInCache := GetUTXOCacheByPublicKey(publicKey)\n\tfor serialNumberStr, _ := range utxosInCache {\n\t\tfor i, inputCoin := range inputCoins {\n\t\t\tsnStrTmp := base58.Base58Check{}.Encode(inputCoin.CoinDetails.GetSerialNumber().ToBytesS(), common.ZeroByte)\n\t\t\tif snStrTmp == serialNumberStr {\n\t\t\t\tinputCoins = removeElementFromSlice(inputCoins, i)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\treturn inputCoins, nil\n}", "func (btc *ExchangeWallet) FundingCoins(ids []dex.Bytes) (asset.Coins, error) {\n\t// First check if we have the coins in cache.\n\tcoins := make(asset.Coins, 0, len(ids))\n\tnotFound := make(map[string]struct{})\n\tbtc.fundingMtx.RLock()\n\tfor _, id := range ids {\n\t\ttxHash, vout, err := decodeCoinID(id)\n\t\tif err != nil {\n\t\t\tbtc.fundingMtx.RUnlock()\n\t\t\treturn nil, err\n\t\t}\n\t\topID := outpointID(txHash.String(), vout)\n\t\tfundingCoin, found := btc.fundingCoins[opID]\n\t\tif found {\n\t\t\tcoins = append(coins, newOutput(btc.node, txHash, vout, fundingCoin.amount, fundingCoin.redeemScript))\n\t\t\tcontinue\n\t\t}\n\t\tnotFound[opID] = struct{}{}\n\t}\n\tbtc.fundingMtx.RUnlock()\n\tif len(notFound) == 0 {\n\t\treturn coins, nil\n\t}\n\t_, utxoMap, _, err := btc.spendableUTXOs(0)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlockers := make([]*output, 0, len(ids))\n\tbtc.fundingMtx.Lock()\n\tdefer btc.fundingMtx.Unlock()\n\tfor _, id := range ids {\n\t\ttxHash, vout, err := decodeCoinID(id)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\topID := outpointID(txHash.String(), vout)\n\t\tutxo, found := utxoMap[opID]\n\t\tif !found {\n\t\t\treturn nil, fmt.Errorf(\"funding coin %s not found\", opID)\n\t\t}\n\t\tbtc.fundingCoins[opID] = utxo\n\t\tcoin := newOutput(btc.node, utxo.txHash, utxo.vout, utxo.amount, utxo.redeemScript)\n\t\tcoins = append(coins, coin)\n\t\tlockers = append(lockers, coin)\n\t\tdelete(notFound, opID)\n\t\tif len(notFound) == 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\tif len(notFound) != 0 {\n\t\tids := make([]string, 0, len(notFound))\n\t\tfor opID := range notFound {\n\t\t\tids = append(ids, opID)\n\t\t}\n\t\treturn nil, fmt.Errorf(\"coins not found: %s\", strings.Join(ids, \", \"))\n\t}\n\terr = btc.wallet.LockUnspent(false, lockers)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn coins, nil\n}", "func (vva ValidatorVestingAccount) GetFailedVestedCoins() sdk.Coins {\n\tvar failedVestedCoins sdk.Coins\n\tnumberPeriods := len(vva.VestingPeriods)\n\tfor i := 0; i < numberPeriods; i++ {\n\t\tif vva.VestingPeriodProgress[i].PeriodComplete {\n\t\t\tif !vva.VestingPeriodProgress[i].VestingSuccessful {\n\t\t\t\tfailedVestedCoins = failedVestedCoins.Add(vva.VestingPeriods[i].Amount)\n\t\t\t}\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn failedVestedCoins\n}", "func (o *AccountCollectionGetParams) SetLocked(locked *bool) {\n\to.Locked = locked\n}", "func (c *CoordinatorHelper) Coins(\n\tctx context.Context,\n\tdbTx storage.DatabaseTransaction,\n\taccountIdentifier *types.AccountIdentifier,\n\tcurrency *types.Currency,\n) ([]*types.Coin, error) {\n\tcoins, _, err := c.coinStorage.GetCoinsTransactional(\n\t\tctx,\n\t\tdbTx,\n\t\taccountIdentifier,\n\t)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"%w: unable to get coins\", err)\n\t}\n\n\tcoinsToReturn := []*types.Coin{}\n\tfor _, coin := range coins {\n\t\tif types.Hash(coin.Amount.Currency) != types.Hash(currency) {\n\t\t\tcontinue\n\t\t}\n\n\t\tcoinsToReturn = append(coinsToReturn, coin)\n\t}\n\n\treturn coinsToReturn, nil\n}", "func (dcr *ExchangeWallet) ReturnCoins(unspents asset.Coins) error {\n\tdcr.fundingMtx.Lock()\n\treturnedCoins, err := dcr.returnCoins(unspents)\n\tdcr.fundingMtx.Unlock()\n\tif err != nil || dcr.unmixedAccount == \"\" {\n\t\treturn err\n\t}\n\n\t// If any of these coins belong to the trading account, transfer them to the\n\t// unmixed account to be re-mixed into the primary account before being\n\t// re-selected for funding future orders. This doesn't apply to unspent\n\t// split tx outputs, which should remain in the trading account and be\n\t// selected from there for funding future orders.\n\tvar coinsToTransfer []asset.Coin\n\tfor _, coin := range returnedCoins {\n\t\tif coin.addr == \"\" {\n\t\t\ttxOut, err := dcr.wallet.UnspentOutput(dcr.ctx, coin.op.txHash(), coin.op.vout(), coin.op.tree)\n\t\t\tif err != nil {\n\t\t\t\tdcr.log.Errorf(\"wallet.UnspentOutput error for returned coin %s: %v\", coin.op, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif len(txOut.Addresses) == 0 {\n\t\t\t\tdcr.log.Errorf(\"no address in gettxout response for returned coin %s\", coin.op)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tcoin.addr = txOut.Addresses[0]\n\t\t}\n\t\taddrInfo, err := dcr.wallet.AddressInfo(dcr.ctx, coin.addr)\n\t\tif err != nil {\n\t\t\tdcr.log.Errorf(\"wallet.AddressInfo error for returned coin %s: %v\", coin.op, err)\n\t\t\tcontinue\n\t\t}\n\t\t// Move this coin to the unmixed account if it was sent to the internal\n\t\t// branch of the trading account. This excludes unspent split tx outputs\n\t\t// which are sent to the external branch of the trading account.\n\t\tif addrInfo.Branch == acctInternalBranch && addrInfo.Account == dcr.tradingAccount {\n\t\t\tcoinsToTransfer = append(coinsToTransfer, coin.op)\n\t\t}\n\t}\n\n\tif len(coinsToTransfer) > 0 {\n\t\ttx, totalSent, err := dcr.sendAll(coinsToTransfer, dcr.unmixedAccount)\n\t\tif err != nil {\n\t\t\tdcr.log.Errorf(\"unable to transfer unlocked swapped change from temp trading \"+\n\t\t\t\t\"account to unmixed account: %v\", err)\n\t\t} else {\n\t\t\tdcr.log.Infof(\"Transferred %s from temp trading account to unmixed account in tx %s.\",\n\t\t\t\tdcrutil.Amount(totalSent), tx.TxHash())\n\t\t}\n\t}\n\n\treturn nil\n}", "func GetCoins(accCoins []types.Coin) AccountCoins {\n\tcoins := make(AccountCoins, 0)\n\tfor _, coin := range accCoins {\n\t\tcoins = append(coins, AccountCoin{Amount: uint64(coin.Amount), Denom: coin.Denom})\n\t}\n\treturn coins\n}", "func (keeper BaseViewKeeper) GetCoins(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins {\n\treturn getCoins(ctx, keeper.am, addr)\n}", "func (b *BlockChain) GetUnspentTxns(address string) []Transaction {\n\tvar unspentTxns []Transaction\n\tvar spentTxnMap = make(map[string][]int) // map txnID -> output index\n\n\t// go over blocks one by one\n\titer := b.GetIterator()\n\tfor {\n\t\tblck := iter.Next()\n\n\t\t// go over all Transactions in this block\n\t\tfor _, txn := range blck.Transactions {\n\t\t\t// get string identifying this transaction\n\t\t\ttxID := hex.EncodeToString(txn.ID)\n\n\t\tOutputLoop:\n\t\t\t// go over all outputs in this Txn\n\t\t\tfor outIndex, output := range txn.Out {\n\n\t\t\t\t// check if this output is spent.\n\t\t\t\tif spentTxnMap[txID] != nil {\n\t\t\t\t\tfor _, indx := range spentTxnMap[txID] {\n\t\t\t\t\t\tif indx == outIndex {\n\t\t\t\t\t\t\tcontinue OutputLoop\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// check if this output belongs to this address\n\t\t\t\tif output.CheckOutputUnlock(address) {\n\t\t\t\t\tunspentTxns = append(unspentTxns, *txn)\n\t\t\t\t}\n\n\t\t\t\t// if this is not genesis block, go over all inputs\n\t\t\t\t// that refers to output that belongs to this address\n\t\t\t\t// and mark them as unspent\n\t\t\t\tif txn.IsCoinbase() == false {\n\t\t\t\t\tfor _, inp := range txn.In {\n\t\t\t\t\t\tif inp.CheckInputUnlock(address) {\n\t\t\t\t\t\t\tspentTxnMap[txID] = append(spentTxnMap[txID], inp.Out)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif len(blck.PrevBlockHash) == 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn unspentTxns\n}", "func (keeper Keeper) GetCoins(ctx sdk.Context, addr sdk.Address) sdk.Coins {\n\treturn getCoins(ctx, keeper.am, addr)\n}", "func (dcr *ExchangeWallet) Locked() bool {\n\twalletInfo, err := dcr.node.WalletInfo(dcr.ctx)\n\tif err != nil {\n\t\tdcr.log.Errorf(\"walletinfo error: %v\", err)\n\t\treturn false\n\t}\n\treturn !walletInfo.Unlocked\n}", "func GetUnspentOutputCoins(rpcClient *rpcclient.HttpClient, keyWallet *wallet.KeyWallet) ([]*crypto.OutputCoin, error) {\n\tprivateKey := &keyWallet.KeySet.PrivateKey\n\tpaymentAddressStr := keyWallet.Base58CheckSerialize(wallet.PaymentAddressType)\n\tviewingKeyStr := keyWallet.Base58CheckSerialize(wallet.ReadonlyKeyType)\n\n\toutputCoins, err := GetListOutputCoins(rpcClient, paymentAddressStr, viewingKeyStr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tserialNumbers, err := DeriveSerialNumbers(privateKey, outputCoins)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tisExisted, err := CheckExistenceSerialNumber(rpcClient, paymentAddressStr, serialNumbers)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tutxos := make([]*crypto.OutputCoin, 0)\n\tfor i, out := range outputCoins {\n\t\tif !isExisted[i] {\n\t\t\tutxos = append(utxos, out)\n\t\t}\n\t}\n\n\treturn utxos, nil\n}", "func (dcr *ExchangeWallet) lockedAtoms() (uint64, error) {\n\tlockedOutpoints, err := dcr.lockedOutputs()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tvar sum uint64\n\tfor _, op := range lockedOutpoints {\n\t\tsum += toAtoms(op.Amount)\n\t}\n\treturn sum, nil\n}", "func (u UTXOSet) FindUnspentTransactions(pubKeyHash []byte) []TxOutput {\n\tvar UTXOs []TxOutput\n\n\tdb := u.Blockchain.Database\n\n\terr := db.View(func(txn *badger.Txn) error {\n\t\topts := badger.DefaultIteratorOptions\n\n\t\tit := txn.NewIterator(opts)\n\t\tdefer it.Close()\n\n\t\t// iterate through UTXOS prefixes\n\t\tfor it.Seek(utxoPrefix); it.ValidForPrefix(utxoPrefix); it.Next() {\n\t\t\t// get the value of each utxo prefixed item\n\t\t\tv := valueHash(it.Item())\n\t\t\touts := DeserializeOutputs(v)\n\n\t\t\t// iterate through each output, check to see if it is locked by the provided hash address\n\t\t\tfor _, out := range outs.Outputs {\n\t\t\t\tif out.IsLockedWithKey(pubKeyHash) {\n\t\t\t\t\tUTXOs = append(UTXOs, out)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn nil\n\t})\n\thandle(err)\n\n\treturn UTXOs\n}", "func distributeLockedAmount(ctx coretypes.Sandbox, bets []*BetInfo, totalLockedAmount int64) bool {\n\tsumsByPlayers := make(map[coretypes.AgentID]int64)\n\ttotalWinningAmount := int64(0)\n\tfor _, bet := range bets {\n\t\tif _, ok := sumsByPlayers[bet.Player]; !ok {\n\t\t\tsumsByPlayers[bet.Player] = 0\n\t\t}\n\t\tsumsByPlayers[bet.Player] += bet.Sum\n\t\ttotalWinningAmount += bet.Sum\n\t}\n\n\t// NOTE 1: float64 was avoided for determinism reasons\n\t// NOTE 2: beware overflows\n\n\tfor player, sum := range sumsByPlayers {\n\t\tsumsByPlayers[player] = (totalLockedAmount * sum) / totalWinningAmount\n\t}\n\n\t// make deterministic sequence by sorting. Eliminate possible rounding effects\n\tseqPlayers := make([]coretypes.AgentID, 0, len(sumsByPlayers))\n\tresultSum := int64(0)\n\tfor player, sum := range sumsByPlayers {\n\t\tseqPlayers = append(seqPlayers, player)\n\t\tresultSum += sum\n\t}\n\tsort.Slice(seqPlayers, func(i, j int) bool {\n\t\treturn bytes.Compare(seqPlayers[i][:], seqPlayers[j][:]) < 0\n\t})\n\n\t// ensure we distribute not more than totalLockedAmount iotas\n\tif resultSum > totalLockedAmount {\n\t\tsumsByPlayers[seqPlayers[0]] -= resultSum - totalLockedAmount\n\t}\n\n\t// filter out those who proportionally got 0\n\tfinalWinners := seqPlayers[:0]\n\tfor _, player := range seqPlayers {\n\t\tif sumsByPlayers[player] <= 0 {\n\t\t\tcontinue\n\t\t}\n\t\tfinalWinners = append(finalWinners, player)\n\t}\n\t// distribute iotas\n\tfor i := range finalWinners {\n\n\t\tavailable := ctx.Balance(balance.ColorIOTA)\n\t\tctx.Event(fmt.Sprintf(\"sending reward iotas %d to the winner %s. Available iotas: %d\",\n\t\t\tsumsByPlayers[finalWinners[i]], finalWinners[i].String(), available))\n\n\t\t//if !ctx.MoveTokens(finalWinners[i], balance.ColorIOTA, sumsByPlayers[finalWinners[i]]) {\n\t\t//\treturn false\n\t\t//}\n\t}\n\treturn true\n}", "func (w *rpcWallet) LockUnspent(ctx context.Context, unlock bool, ops []*wire.OutPoint) error {\n\treturn translateRPCCancelErr(w.client().LockUnspent(ctx, unlock, ops))\n}", "func (ck CoinKeeper) GetCoins(ctx sdk.Context, addr sdk.Address, amt sdk.Coins) sdk.Coins {\n\tacc := ck.am.GetAccount(ctx, addr)\n\treturn acc.GetCoins()\n}", "func GetUnlockedDistributionAddresses() []string {\n\t// The first InitialUnlockedCount (25) addresses are unlocked by default.\n\t// Subsequent addresses will be unlocked at a rate of UnlockAddressRate (5) per year,\n\t// after the InitialUnlockedCount (25) addresses have no remaining balance.\n\t// The unlock timer will be enabled manually once the\n\t// InitialUnlockedCount (25) addresses are distributed.\n\n\t// NOTE: To have automatic unlocking, transaction verification would have\n\t// to be handled in visor rather than in coin.Transactions.Visor(), because\n\t// the coin package is agnostic to the state of the blockchain and cannot reference it.\n\t// Instead of automatic unlocking, we can hardcode the timestamp at which the first 30%\n\t// is distributed, then compute the unlocked addresses easily here.\n\n\taddrs := make([]string, InitialUnlockedCount)\n\tfor i := range distributionAddresses[:InitialUnlockedCount] {\n\t\taddrs[i] = distributionAddresses[i]\n\t}\n\treturn addrs\n}", "func WithoutBlocking(ctx context.Context) context.Context {\n\treturn context.WithValue(ctx, nonBlockingTxnCtxKey, &nonBlockingTxnOpt{})\n}", "func (b *Bitcoind) ListUnspent(minconf, maxconf uint32) (transactions []Transaction, err error) {\n\tif maxconf > 999999 {\n\t\tmaxconf = 999999\n\t}\n\n\tr, err := b.client.call(\"listunspent\", []interface{}{minconf, maxconf})\n\tif err = handleError(err, &r); err != nil {\n\t\treturn\n\t}\n\n\terr = json.Unmarshal(r.Result, &transactions)\n\treturn\n}", "func (am *AccountManager) ListUnspent(minconf, maxconf int,\n\taddresses map[string]bool) ([]*btcjson.ListUnspentResult, error) {\n\n\tbs, err := GetCurBlock()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfilter := len(addresses) != 0\n\n\tvar results []*btcjson.ListUnspentResult\n\tfor _, a := range am.AllAccounts() {\n\t\tunspent, err := a.TxStore.UnspentOutputs()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfor _, credit := range unspent {\n\t\t\tconfs := credit.Confirmations(bs.Height)\n\t\t\tif int(confs) < minconf || int(confs) > maxconf {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t_, addrs, _, _ := credit.Addresses(cfg.Net())\n\t\t\tif filter {\n\t\t\t\tfor _, addr := range addrs {\n\t\t\t\t\t_, ok := addresses[addr.EncodeAddress()]\n\t\t\t\t\tif ok {\n\t\t\t\t\t\tgoto include\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\t\tinclude:\n\t\t\tresult := &btcjson.ListUnspentResult{\n\t\t\t\tTxId: credit.Tx().Sha().String(),\n\t\t\t\tVout: credit.OutputIndex,\n\t\t\t\tAccount: a.Name(),\n\t\t\t\tScriptPubKey: hex.EncodeToString(credit.TxOut().PkScript),\n\t\t\t\tAmount: credit.Amount().ToUnit(btcutil.AmountBTC),\n\t\t\t\tConfirmations: int64(confs),\n\t\t\t}\n\n\t\t\t// BUG: this should be a JSON array so that all\n\t\t\t// addresses can be included, or removed (and the\n\t\t\t// caller extracts addresses from the pkScript).\n\t\t\tif len(addrs) > 0 {\n\t\t\t\tresult.Address = addrs[0].EncodeAddress()\n\t\t\t}\n\n\t\t\tresults = append(results, result)\n\t\t}\n\t}\n\n\treturn results, nil\n}", "func (w *Wallet) ResetLockedOutpoints() {\n\tw.lockedOutpoints = map[wire.OutPoint]struct{}{}\n}", "func (c *Channel) Locked() *big.Int {\n\treturn c.OurState.AmountLocked()\n}", "func (va ClawbackVestingAccount) GetVestedOnly(blockTime time.Time) sdk.Coins {\n\treturn ReadSchedule(va.StartTime, va.EndTime, va.VestingPeriods, va.OriginalVesting, blockTime.Unix())\n}", "func (c *Channel) Locked() *big.Int {\n\treturn c.OurState.amountLocked()\n}", "func (s *Store) ListLockedOutputs(ns walletdb.ReadBucket) ([]*LockedOutput,\n\terror) {\n\n\tvar outputs []*LockedOutput\n\terr := forEachLockedOutput(\n\t\tns, func(op wire.OutPoint, id LockID, expiration time.Time) {\n\t\t\t// Skip expired leases. They will be cleaned up with the\n\t\t\t// next call to DeleteExpiredLockedOutputs.\n\t\t\tif !s.clock.Now().Before(expiration) {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\toutputs = append(outputs, &LockedOutput{\n\t\t\t\tOutpoint: op,\n\t\t\t\tLockID: id,\n\t\t\t\tExpiration: expiration,\n\t\t\t})\n\t\t},\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn outputs, nil\n}", "func coinSupplyHandler(gateway Gatewayer) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tif r.Method != http.MethodGet {\n\t\t\twh.Error405(w)\n\t\t\treturn\n\t\t}\n\n\t\tallUnspents, err := gateway.GetUnspentOutputsSummary(nil)\n\t\tif err != nil {\n\t\t\terr = fmt.Errorf(\"gateway.GetUnspentOutputsSummary failed: %v\", err)\n\t\t\twh.Error500(w, err.Error())\n\t\t\treturn\n\t\t}\n\n\t\tunlockedAddrs := params.GetUnlockedDistributionAddressesDecoded()\n\t\t// Search map of unlocked addresses, used to filter unspents\n\t\tunlockedAddrSet := newAddrSet(unlockedAddrs)\n\n\t\tvar unlockedSupply uint64\n\t\t// check confirmed unspents only\n\t\tfor _, u := range allUnspents.Confirmed {\n\t\t\t// check if address is an unlocked distribution address\n\t\t\tif _, ok := unlockedAddrSet[u.Body.Address]; ok {\n\t\t\t\tvar err error\n\t\t\t\tunlockedSupply, err = mathutil.AddUint64(unlockedSupply, u.Body.Coins)\n\t\t\t\tif err != nil {\n\t\t\t\t\terr = fmt.Errorf(\"uint64 overflow while adding up unlocked supply coins: %v\", err)\n\t\t\t\t\twh.Error500(w, err.Error())\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// \"total supply\" is the number of coins unlocked.\n\t\t// Each distribution address was allocated params.DistributionAddressInitialBalance coins.\n\t\ttotalSupply := uint64(len(unlockedAddrs)) * params.DistributionAddressInitialBalance\n\t\ttotalSupply *= droplet.Multiplier\n\n\t\t// \"current supply\" is the number of coins distributed from the unlocked pool\n\t\tcurrentSupply := totalSupply - unlockedSupply\n\n\t\tcurrentSupplyStr, err := droplet.ToString(currentSupply)\n\t\tif err != nil {\n\t\t\terr = fmt.Errorf(\"Failed to convert coins to string: %v\", err)\n\t\t\twh.Error500(w, err.Error())\n\t\t\treturn\n\t\t}\n\n\t\ttotalSupplyStr, err := droplet.ToString(totalSupply)\n\t\tif err != nil {\n\t\t\terr = fmt.Errorf(\"Failed to convert coins to string: %v\", err)\n\t\t\twh.Error500(w, err.Error())\n\t\t\treturn\n\t\t}\n\n\t\tmaxSupplyStr, err := droplet.ToString(params.MaxCoinSupply * droplet.Multiplier)\n\t\tif err != nil {\n\t\t\terr = fmt.Errorf(\"Failed to convert coins to string: %v\", err)\n\t\t\twh.Error500(w, err.Error())\n\t\t\treturn\n\t\t}\n\n\t\t// locked distribution addresses\n\t\tlockedAddrs := params.GetLockedDistributionAddressesDecoded()\n\t\tlockedAddrSet := newAddrSet(lockedAddrs)\n\n\t\t// get total coins hours which excludes locked distribution addresses\n\t\tvar totalCoinHours uint64\n\t\tfor _, out := range allUnspents.Confirmed {\n\t\t\tif _, ok := lockedAddrSet[out.Body.Address]; !ok {\n\t\t\t\tvar err error\n\t\t\t\ttotalCoinHours, err = mathutil.AddUint64(totalCoinHours, out.CalculatedHours)\n\t\t\t\tif err != nil {\n\t\t\t\t\terr = fmt.Errorf(\"uint64 overflow while adding up total coin hours: %v\", err)\n\t\t\t\t\twh.Error500(w, err.Error())\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// get current coin hours which excludes all distribution addresses\n\t\tvar currentCoinHours uint64\n\t\tfor _, out := range allUnspents.Confirmed {\n\t\t\t// check if address not in locked distribution addresses\n\t\t\tif _, ok := lockedAddrSet[out.Body.Address]; !ok {\n\t\t\t\t// check if address not in unlocked distribution addresses\n\t\t\t\tif _, ok := unlockedAddrSet[out.Body.Address]; !ok {\n\t\t\t\t\tcurrentCoinHours += out.CalculatedHours\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif err != nil {\n\t\t\terr = fmt.Errorf(\"Failed to get total coinhours: %v\", err)\n\t\t\twh.Error500(w, err.Error())\n\t\t\treturn\n\t\t}\n\n\t\tcs := CoinSupply{\n\t\t\tCurrentSupply: currentSupplyStr,\n\t\t\tTotalSupply: totalSupplyStr,\n\t\t\tMaxSupply: maxSupplyStr,\n\t\t\tCurrentCoinHourSupply: strconv.FormatUint(currentCoinHours, 10),\n\t\t\tTotalCoinHourSupply: strconv.FormatUint(totalCoinHours, 10),\n\t\t\tUnlockedAddresses: params.GetUnlockedDistributionAddresses(),\n\t\t\tLockedAddresses: params.GetLockedDistributionAddresses(),\n\t\t}\n\n\t\twh.SendJSONOr500(logger, w, cs)\n\t}\n}", "func (dcr *ExchangeWallet) spendableUTXOs() ([]*compositeUTXO, error) {\n\tunspents, err := dcr.unspents()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(unspents) == 0 {\n\t\treturn nil, fmt.Errorf(\"insufficient funds. 0 DCR available to spend in %q account\", dcr.acct)\n\t}\n\n\t// Parse utxos to include script size for spending input.\n\t// Returned utxos will be sorted in ascending order by amount (smallest first).\n\tutxos, err := dcr.parseUTXOs(unspents)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error parsing unspent outputs: %w\", err)\n\t}\n\tif len(utxos) == 0 {\n\t\treturn nil, fmt.Errorf(\"no funds available\")\n\t}\n\treturn utxos, nil\n}", "func (s *Store) UnspentOutputs(ns walletdb.ReadBucket) ([]Credit, error) {\n\tvar unspent []Credit\n\n\tvar op wire.OutPoint\n\tvar block Block\n\terr := ns.NestedReadBucket(bucketUnspent).ForEach(func(k, v []byte) error {\n\t\terr := readCanonicalOutPoint(k, &op)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Skip the output if it's locked.\n\t\t_, _, isLocked := isLockedOutput(ns, op, s.clock.Now())\n\t\tif isLocked {\n\t\t\treturn nil\n\t\t}\n\n\t\tif existsRawUnminedInput(ns, k) != nil {\n\t\t\t// Output is spent by an unmined transaction.\n\t\t\t// Skip this k/v pair.\n\t\t\treturn nil\n\t\t}\n\n\t\terr = readUnspentBlock(v, &block)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tblockTime, err := fetchBlockTime(ns, block.Height)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// TODO(jrick): reading the entire transaction should\n\t\t// be avoidable. Creating the credit only requires the\n\t\t// output amount and pkScript.\n\t\trec, err := fetchTxRecord(ns, &op.Hash, &block)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unable to retrieve transaction %v: \"+\n\t\t\t\t\"%v\", op.Hash, err)\n\t\t}\n\t\ttxOut := rec.MsgTx.TxOut[op.Index]\n\t\tcred := Credit{\n\t\t\tOutPoint: op,\n\t\t\tBlockMeta: BlockMeta{\n\t\t\t\tBlock: block,\n\t\t\t\tTime: blockTime,\n\t\t\t},\n\t\t\tAmount: btcutil.Amount(txOut.Value),\n\t\t\tPkScript: txOut.PkScript,\n\t\t\tReceived: rec.Received,\n\t\t\tFromCoinBase: blockchain.IsCoinBaseTx(&rec.MsgTx),\n\t\t}\n\t\tunspent = append(unspent, cred)\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\tif _, ok := err.(Error); ok {\n\t\t\treturn nil, err\n\t\t}\n\t\tstr := \"failed iterating unspent bucket\"\n\t\treturn nil, storeError(ErrDatabase, str, err)\n\t}\n\n\terr = ns.NestedReadBucket(bucketUnminedCredits).ForEach(func(k, v []byte) error {\n\t\tif err := readCanonicalOutPoint(k, &op); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Skip the output if it's locked.\n\t\t_, _, isLocked := isLockedOutput(ns, op, s.clock.Now())\n\t\tif isLocked {\n\t\t\treturn nil\n\t\t}\n\n\t\tif existsRawUnminedInput(ns, k) != nil {\n\t\t\t// Output is spent by an unmined transaction.\n\t\t\t// Skip to next unmined credit.\n\t\t\treturn nil\n\t\t}\n\n\t\t// TODO(jrick): Reading/parsing the entire transaction record\n\t\t// just for the output amount and script can be avoided.\n\t\trecVal := existsRawUnmined(ns, op.Hash[:])\n\t\tvar rec TxRecord\n\t\terr = readRawTxRecord(&op.Hash, recVal, &rec)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unable to retrieve raw transaction \"+\n\t\t\t\t\"%v: %v\", op.Hash, err)\n\t\t}\n\n\t\ttxOut := rec.MsgTx.TxOut[op.Index]\n\t\tcred := Credit{\n\t\t\tOutPoint: op,\n\t\t\tBlockMeta: BlockMeta{\n\t\t\t\tBlock: Block{Height: -1},\n\t\t\t},\n\t\t\tAmount: btcutil.Amount(txOut.Value),\n\t\t\tPkScript: txOut.PkScript,\n\t\t\tReceived: rec.Received,\n\t\t\tFromCoinBase: blockchain.IsCoinBaseTx(&rec.MsgTx),\n\t\t}\n\t\tunspent = append(unspent, cred)\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\tif _, ok := err.(Error); ok {\n\t\t\treturn nil, err\n\t\t}\n\t\tstr := \"failed iterating unmined credits bucket\"\n\t\treturn nil, storeError(ErrDatabase, str, err)\n\t}\n\n\treturn unspent, nil\n}", "func (tx *Transaction) GetNewFromCoins() []FromCoin {\n\tnfcs := make([]FromCoin, 0)\n\tfor index, c := range tx.To.Coins {\n\t\tticket := Ticket{}\n\t\tticket.SetTxid(*tx.GetTxID())\n\t\tticket.SetIndex(uint32(index))\n\n\t\tnfc := FromCoin{}\n\t\tnfc.SetId(c.Id)\n\t\tnfc.AddTicket(&ticket)\n\n\t\tnfcs = append(nfcs, nfc)\n\t}\n\n\treturn nfcs\n}", "func (b *BlockChain) GetUnspentOutputs(address string) []TxOutput {\n\tvar unspentOuts []TxOutput\n\ttxns := b.GetUnspentTxns(address)\n\n\t// go over each txn and each output in it and collect ones which belongs to this address\n\tfor _, txn := range txns {\n\t\t// iterate over all outputs\n\t\tfor _, output := range txn.Out {\n\t\t\tif output.CheckOutputUnlock(address) {\n\t\t\t\tunspentOuts = append(unspentOuts, output)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn unspentOuts\n}", "func (serv *ExchangeServer) GetSupportCoins() []string {\n\tsymbols := make([]string, len(serv.coins))\n\ti := 0\n\tfor _, coin := range serv.coins {\n\t\tsymbols[i] = coin.Symbol()\n\t\ti++\n\t}\n\treturn symbols\n}", "func (o RunnerOutput) Locked() pulumi.BoolOutput {\n\treturn o.ApplyT(func(v *Runner) pulumi.BoolOutput { return v.Locked }).(pulumi.BoolOutput)\n}", "func (cm *coinsMempool) Get(maxTransactions uint64, s state.State) ([]*primitives.Tx, state.State) {\n\tcm.lock.RLock()\n\tdefer cm.lock.RUnlock()\n\tallTransactions := make([]*primitives.Tx, 0, maxTransactions)\n\nouter:\n\tfor _, addr := range cm.mempool {\n\t\tfor _, tx := range addr.transactions {\n\t\t\tif err := s.ApplyTransactionSingle(tx, [20]byte{}, cm.params); err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tallTransactions = append(allTransactions, tx)\n\t\t\tif uint64(len(allTransactions)) >= maxTransactions {\n\t\t\t\tbreak outer\n\t\t\t}\n\t\t}\n\t}\n\n\t// we can prioritize here, but we aren't to keep it simple\n\treturn allTransactions, s\n}", "func (cb CommitteeBits) FilterNonParticipants(committee []ValidatorIndex) []ValidatorIndex {\n\tbitLen := cb.BitLen()\n\tout := committee[:0]\n\tif bitLen != uint64(len(committee)) {\n\t\tpanic(\"committee mismatch, bitfield length does not match\")\n\t}\n\tfor i := uint64(0); i < bitLen; i++ {\n\t\tif !cb.GetBit(i) {\n\t\t\tout = append(out, committee[i])\n\t\t}\n\t}\n\treturn out\n}", "func (k Keeper) MintCoins(ctx sdk.Context, newCoins sdk.Coins) error {\n\tif newCoins.Empty() {\n\t\t// skip as no coins need to be minted\n\t\treturn nil\n\t}\n\treturn k.supplyKeeper.MintCoins(ctx, types.ModuleName, newCoins)\n}", "func (u UTXOSet) FindUnspentTransactionOutputs(pubKeyHash []byte) []TxOutput {\n\tvar UTXOs []TxOutput\n\n\tdb := u.BlockChain.Database\n\n\terr := db.View(func(txn *badger.Txn) error {\n\t\topts := badger.DefaultIteratorOptions\n\n\t\tit := txn.NewIterator(opts)\n\t\tdefer it.Close()\n\n\t\t// iterate through all transactions with UTXOs\n\t\tfor it.Seek(utxoPrefix); it.ValidForPrefix(utxoPrefix); it.Next() {\n\t\t\titem := it.Item()\n\t\t\tv, err := item.Value()\n\t\t\tHandle(err)\n\t\t\touts := DeserializeOutputs(v)\n\t\t\t// go through all outputs of that transaction\n\t\t\tfor _, out := range outs.Outputs {\n\t\t\t\t// check the output was locked with this address (belongs to this receiver and can be unlocked by this address to use as new input)\n\t\t\t\tif out.IsLockedWithKey(pubKeyHash) {\n\t\t\t\t\tUTXOs = append(UTXOs, out)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t})\n\tHandle(err)\n\treturn UTXOs\n}", "func (_TokensNetwork *TokensNetworkCaller) QueryUnlockedLocks(opts *bind.CallOpts, token common.Address, participant common.Address, partner common.Address, lockhash [32]byte) (bool, error) {\n\tvar (\n\t\tret0 = new(bool)\n\t)\n\tout := ret0\n\terr := _TokensNetwork.contract.Call(opts, out, \"queryUnlockedLocks\", token, participant, partner, lockhash)\n\treturn *ret0, err\n}", "func (rt *recvTxOut) SetLocked(locked bool) {\n\trt.locked = locked\n}", "func (rt *recvTxOut) Locked() bool {\n\treturn rt.locked\n}", "func (_TokensNetwork *TokensNetworkCallerSession) QueryUnlockedLocks(token common.Address, participant common.Address, partner common.Address, lockhash [32]byte) (bool, error) {\n\treturn _TokensNetwork.Contract.QueryUnlockedLocks(&_TokensNetwork.CallOpts, token, participant, partner, lockhash)\n}", "func (tp *TXPool) GetUnverifiedTxs(txs []*types.Transaction,\n\theight uint32) *CheckBlkResult {\n\ttp.Lock()\n\tdefer tp.Unlock()\n\tres := &CheckBlkResult{\n\t\tVerifiedTxs: make([]*VerifyTxResult, 0, len(txs)),\n\t\tUnverifiedTxs: make([]*types.Transaction, 0),\n\t\tOldTxs: make([]*types.Transaction, 0),\n\t}\n\tfor _, tx := range txs {\n\t\ttxEntry := tp.txList[tx.Hash()]\n\t\tif txEntry == nil {\n\t\t\tres.UnverifiedTxs = append(res.UnverifiedTxs,\n\t\t\t\ttx)\n\t\t\tcontinue\n\t\t}\n\n\t\tif !tp.compareTxHeight(txEntry, height) {\n\t\t\tdelete(tp.txList, tx.Hash())\n\t\t\tres.OldTxs = append(res.OldTxs, txEntry.Tx)\n\t\t\tcontinue\n\t\t}\n\n\t\tfor _, v := range txEntry.Attrs {\n\t\t\tif v.Type == vt.Stateful {\n\t\t\t\tentry := &VerifyTxResult{\n\t\t\t\t\tTx: tx,\n\t\t\t\t\tHeight: v.Height,\n\t\t\t\t\tErrCode: v.ErrCode,\n\t\t\t\t}\n\t\t\t\tres.VerifiedTxs = append(res.VerifiedTxs,\n\t\t\t\t\tentry)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\treturn res\n}", "func (_TokensNetwork *TokensNetworkSession) QueryUnlockedLocks(token common.Address, participant common.Address, partner common.Address, lockhash [32]byte) (bool, error) {\n\treturn _TokensNetwork.Contract.QueryUnlockedLocks(&_TokensNetwork.CallOpts, token, participant, partner, lockhash)\n}", "func (tb *transactionBuilder) FundCoins(amount types.Currency, refundAddress *types.UnlockHash, reuseRefundAddress bool) error {\n\ttb.wallet.mu.Lock()\n\tdefer tb.wallet.mu.Unlock()\n\n\tif !tb.wallet.unlocked {\n\t\treturn modules.ErrLockedWallet\n\t}\n\n\t// prepare fulfillable context\n\tctx := tb.wallet.getFulfillableContextForLatestBlock()\n\n\t// Collect a value-sorted set of fulfillable coin outputs.\n\tvar so sortedOutputs\n\tfor scoid, sco := range tb.wallet.coinOutputs {\n\t\tif !sco.Condition.Fulfillable(ctx) {\n\t\t\tcontinue\n\t\t}\n\t\tso.ids = append(so.ids, scoid)\n\t\tso.outputs = append(so.outputs, sco)\n\t}\n\t// Add all of the unconfirmed outputs as well.\n\tfor _, upt := range tb.wallet.unconfirmedProcessedTransactions {\n\t\tfor i, sco := range upt.Transaction.CoinOutputs {\n\t\t\tuh := sco.Condition.UnlockHash()\n\t\t\t// Determine if the output belongs to the wallet.\n\t\t\texists, err := tb.wallet.keyExists(uh)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif !exists || !sco.Condition.Fulfillable(ctx) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tso.ids = append(so.ids, upt.Transaction.CoinOutputID(uint64(i)))\n\t\t\tso.outputs = append(so.outputs, sco)\n\t\t}\n\t}\n\tsort.Sort(sort.Reverse(so))\n\n\t// Create a transaction that will add the correct amount of coins to the\n\t// transaction.\n\tvar fund types.Currency\n\t// potentialFund tracks the balance of the wallet including outputs that\n\t// have been spent in other unconfirmed transactions recently. This is to\n\t// provide the user with a more useful error message in the event that they\n\t// are overspending.\n\tvar potentialFund types.Currency\n\tvar spentScoids []types.CoinOutputID\n\tfor i := range so.ids {\n\t\tscoid := so.ids[i]\n\t\tsco := so.outputs[i]\n\t\t// Check that this output has not recently been spent by the wallet.\n\t\tspendHeight := tb.wallet.spentOutputs[types.OutputID(scoid)]\n\t\t// Prevent an underflow error.\n\t\tallowedHeight := tb.wallet.consensusSetHeight - RespendTimeout\n\t\tif tb.wallet.consensusSetHeight < RespendTimeout {\n\t\t\tallowedHeight = 0\n\t\t}\n\t\tif spendHeight > allowedHeight {\n\t\t\tpotentialFund = potentialFund.Add(sco.Value)\n\t\t\tcontinue\n\t\t}\n\n\t\t// prepare fulfillment, matching the output\n\t\tuh := sco.Condition.UnlockHash()\n\t\tvar ff types.MarshalableUnlockFulfillment\n\t\tswitch sco.Condition.ConditionType() {\n\t\tcase types.ConditionTypeUnlockHash, types.ConditionTypeTimeLock:\n\t\t\t// ConditionTypeTimeLock is fine, as we know it's fulfillable,\n\t\t\t// and that can only mean for now that it is using an internal unlockHashCondition or nilCondition\n\t\t\tpk, _, err := tb.wallet.getKey(uh)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tff = types.NewSingleSignatureFulfillment(pk)\n\t\tdefault:\n\t\t\tbuild.Severe(fmt.Errorf(\"unexpected condition type: %[1]v (%[1]T)\", sco.Condition))\n\t\t\treturn types.ErrUnexpectedUnlockCondition\n\t\t}\n\t\t// Add a coin input for this output.\n\t\tsci := types.CoinInput{\n\t\t\tParentID: scoid,\n\t\t\tFulfillment: types.NewFulfillment(ff),\n\t\t}\n\t\ttb.coinInputs = append(tb.coinInputs, inputSignContext{\n\t\t\tInputIndex: len(tb.transaction.CoinInputs),\n\t\t\tUnlockHash: uh,\n\t\t})\n\t\ttb.transaction.CoinInputs = append(tb.transaction.CoinInputs, sci)\n\n\t\tspentScoids = append(spentScoids, scoid)\n\n\t\t// Add the output to the total fund\n\t\tfund = fund.Add(sco.Value)\n\t\tpotentialFund = potentialFund.Add(sco.Value)\n\t\tif fund.Cmp(amount) >= 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\tif potentialFund.Cmp(amount) >= 0 && fund.Cmp(amount) < 0 {\n\t\treturn modules.ErrIncompleteTransactions\n\t}\n\tif fund.Cmp(amount) < 0 {\n\t\treturn modules.ErrLowBalance\n\t}\n\n\t// Create a refund output if needed.\n\tif !amount.Equals(fund) {\n\t\tvar refundUnlockHash types.UnlockHash\n\t\tif refundAddress != nil {\n\t\t\t// use specified refund address\n\t\t\trefundUnlockHash = *refundAddress\n\t\t} else if reuseRefundAddress {\n\t\t\t// use the fist coin input of this tx as refund address\n\t\t\tvar maxCoinAmount types.Currency\n\t\t\tfor _, ci := range tb.transaction.CoinInputs {\n\t\t\t\tco, exists := tb.wallet.coinOutputs[ci.ParentID]\n\t\t\t\tif !exists {\n\t\t\t\t\tco = tb.getCoFromUnconfirmedProcessedTransactions(ci.ParentID)\n\t\t\t\t}\n\t\t\t\tif maxCoinAmount.Cmp(co.Value) < 0 {\n\t\t\t\t\tmaxCoinAmount = co.Value\n\t\t\t\t\trefundUnlockHash = co.Condition.UnlockHash()\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\t// generate a new address\n\t\t\tvar err error\n\t\t\trefundUnlockHash, err = tb.wallet.nextPrimarySeedAddress()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\trefundOutput := types.CoinOutput{\n\t\t\tValue: fund.Sub(amount),\n\t\t\tCondition: types.NewCondition(types.NewUnlockHashCondition(refundUnlockHash)),\n\t\t}\n\t\ttb.transaction.CoinOutputs = append(tb.transaction.CoinOutputs, refundOutput)\n\t}\n\n\t// Mark all outputs that were spent as spent.\n\tfor _, scoid := range spentScoids {\n\t\ttb.wallet.spentOutputs[types.OutputID(scoid)] = tb.wallet.consensusSetHeight\n\t}\n\treturn nil\n}", "func (o AttachedDiskResponseOutput) Locked() pulumi.BoolOutput {\n\treturn o.ApplyT(func(v AttachedDiskResponse) bool { return v.Locked }).(pulumi.BoolOutput)\n}", "func (b *rpcVestingBalance) unbonding() (sdk.Coins, sdk.Coins, error) {\n\tunbondingCoins, err := b.totalUnbondingDelegations()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tunbonding := unbondingCoins.AmountOf(stakingDenom)\n\tdelegatedFree := b.vacc.GetDelegatedFree().AmountOf(stakingDenom)\n\n\tunbondingFree := sdk.MinInt(delegatedFree, unbonding)\n\tunbondingVesting := unbonding.Sub(unbondingFree)\n\n\tliquidCoins := sdk.NewCoins(newKavaCoin(unbondingFree))\n\tvestingCoins := sdk.NewCoins(newKavaCoin(unbondingVesting))\n\treturn liquidCoins, vestingCoins, nil\n}", "func (s *StakingKeeperMock) GetBondedValidatorsByPower(ctx sdk.Context) []stakingtypes.Validator {\n\treturn s.BondedValidators\n}", "func (s *Store) GetUnspentOutputs(ns walletdb.ReadBucket) ([]Credit, er.R) {\n\tvar unspent []Credit\n\terr := s.ForEachUnspentOutput(ns, nil, func(_ []byte, c *Credit) er.R {\n\t\tunspent = append(unspent, *c)\n\t\treturn nil\n\t})\n\treturn unspent, err\n}", "func (w *Wallet) GetUnspentBlockStakeOutputs() (unspent []types.UnspentBlockStakeOutput, err error) {\n\tw.mu.RLock()\n\tdefer w.mu.RUnlock()\n\n\tif !w.unlocked {\n\t\terr = modules.ErrLockedWallet\n\t\treturn\n\t}\n\n\tunspent = make([]types.UnspentBlockStakeOutput, 0)\n\n\t// prepare fulfillable context\n\tctx := w.getFulfillableContextForLatestBlock()\n\n\t// collect all fulfillable block stake outputs\n\tfor usbsoid, output := range w.blockstakeOutputs {\n\t\tif output.Condition.Fulfillable(ctx) {\n\t\t\tunspent = append(unspent, w.unspentblockstakeoutputs[usbsoid])\n\t\t}\n\t}\n\treturn\n}", "func (btc *ExchangeWallet) spendableUTXOs(confs uint32) ([]*compositeUTXO, map[string]*compositeUTXO, uint64, error) {\n\tunspents, err := btc.wallet.ListUnspent()\n\tif err != nil {\n\t\treturn nil, nil, 0, err\n\t}\n\tsort.Slice(unspents, func(i, j int) bool { return unspents[i].Amount < unspents[j].Amount })\n\tvar sum uint64\n\tutxos := make([]*compositeUTXO, 0, len(unspents))\n\tutxoMap := make(map[string]*compositeUTXO, len(unspents))\n\tfor _, txout := range unspents {\n\t\tif txout.Confirmations >= confs && txout.Safe {\n\t\t\tnfo, err := dexbtc.InputInfo(txout.ScriptPubKey, txout.RedeemScript, btc.chainParams)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, nil, 0, fmt.Errorf(\"error reading asset info: %v\", err)\n\t\t\t}\n\t\t\ttxHash, err := chainhash.NewHashFromStr(txout.TxID)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, nil, 0, fmt.Errorf(\"error decoding txid in ListUnspentResult: %v\", err)\n\t\t\t}\n\t\t\tutxo := &compositeUTXO{\n\t\t\t\ttxHash: txHash,\n\t\t\t\tvout: txout.Vout,\n\t\t\t\taddress: txout.Address,\n\t\t\t\tredeemScript: txout.RedeemScript,\n\t\t\t\tamount: toSatoshi(txout.Amount),\n\t\t\t\tinput: nfo,\n\t\t\t}\n\t\t\tutxos = append(utxos, utxo)\n\t\t\tutxoMap[outpointID(txout.TxID, txout.Vout)] = utxo\n\t\t\tsum += toSatoshi(txout.Amount)\n\t\t}\n\t}\n\treturn utxos, utxoMap, sum, nil\n}", "func newCoins() sdk.Coins {\n\treturn sdk.Coins{\n\t\tsdk.NewInt64Coin(\"atom\", 10000000),\n\t}\n}", "func (dcr *ExchangeWallet) spendableUTXOs() ([]*compositeUTXO, error) {\n\tunspents, err := dcr.wallet.Unspents(dcr.ctx, dcr.primaryAcct)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif dcr.tradingAccount != \"\" {\n\t\t// Trading account may contain spendable utxos such as unspent split tx\n\t\t// outputs that are unlocked/returned. TODO: Care should probably be\n\t\t// taken to ensure only unspent split tx outputs are selected and other\n\t\t// unmixed outputs in the trading account are ignored.\n\t\ttradingAcctSpendables, err := dcr.wallet.Unspents(dcr.ctx, dcr.tradingAccount)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tunspents = append(unspents, tradingAcctSpendables...)\n\t}\n\tif len(unspents) == 0 {\n\t\treturn nil, fmt.Errorf(\"insufficient funds. 0 DCR available to spend in account %q\", dcr.primaryAcct)\n\t}\n\n\t// Parse utxos to include script size for spending input. Returned utxos\n\t// will be sorted in ascending order by amount (smallest first).\n\tutxos, err := dcr.parseUTXOs(unspents)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error parsing unspent outputs: %w\", err)\n\t}\n\tif len(utxos) == 0 {\n\t\treturn nil, fmt.Errorf(\"no funds available\")\n\t}\n\treturn utxos, nil\n}", "func (m *Machine) ReturnCoins() {\n\tcoins := m.cashEngine.DropCoins()\n\n\ts := fmt.Sprintf(\"-> \")\n\tfor i, c := range coins {\n\t\tif i == len(coins)-1 {\n\t\t\ts += fmt.Sprintf(\"%s\", c.value.String())\n\t\t\tcontinue\n\t\t}\n\t\ts += fmt.Sprintf(\"%s, \", c.value.String())\n\t}\n\n\tm.logger.Println(s)\n}", "func (_DelegationController *DelegationControllerCaller) GetLockedInPendingDelegations(opts *bind.CallOpts, holder common.Address) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _DelegationController.contract.Call(opts, out, \"getLockedInPendingDelegations\", holder)\n\treturn *ret0, err\n}" ]
[ "0.743822", "0.7427831", "0.7415347", "0.73155016", "0.6838768", "0.6392438", "0.61915195", "0.6113116", "0.5887824", "0.58088565", "0.5682898", "0.5653102", "0.5612937", "0.55591124", "0.55491835", "0.5499366", "0.5479898", "0.54708606", "0.5414742", "0.54000133", "0.5391922", "0.5381455", "0.5366295", "0.53310007", "0.5281678", "0.527682", "0.52673715", "0.5255804", "0.52503407", "0.5227853", "0.5200495", "0.51879275", "0.5175841", "0.5145682", "0.5143227", "0.5107518", "0.50978565", "0.50891787", "0.50752866", "0.5048513", "0.5027409", "0.4995251", "0.4962171", "0.49311852", "0.4891159", "0.4880241", "0.48709798", "0.486914", "0.48483112", "0.48366922", "0.4818395", "0.4812281", "0.4809962", "0.48022002", "0.47951964", "0.47937816", "0.47909018", "0.47555852", "0.4739755", "0.47138813", "0.4711921", "0.4699762", "0.46986675", "0.46966118", "0.46941933", "0.4690534", "0.46793562", "0.46758604", "0.46585345", "0.4657782", "0.46539363", "0.4641091", "0.46118796", "0.45871714", "0.45718923", "0.45666152", "0.45525762", "0.45508417", "0.45399627", "0.45245695", "0.45244202", "0.45207965", "0.45140705", "0.45043382", "0.4503364", "0.44928548", "0.4487691", "0.44839776", "0.44800422", "0.4468056", "0.4453965", "0.4444224", "0.4434911", "0.4432183", "0.44260392", "0.44247302", "0.4424636", "0.4422741", "0.44216043", "0.44128725" ]
0.7512996
0
TrackDelegation tracks a desired delegation amount by setting the appropriate values for the amount of delegated vesting, delegated free, and reducing the overall amount of base coins.
func (pva *PeriodicVestingAccount) TrackDelegation(blockTime time.Time, balance, amount sdk.Coins) { pva.BaseVestingAccount.TrackDelegation(balance, pva.GetVestingCoins(blockTime), amount) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (bva *BaseVestingAccount) TrackDelegation(balance, vestingCoins, amount sdk.Coins) {\n\tfor _, coin := range amount {\n\t\tbaseAmt := balance.AmountOf(coin.Denom)\n\t\tvestingAmt := vestingCoins.AmountOf(coin.Denom)\n\t\tdelVestingAmt := bva.DelegatedVesting.AmountOf(coin.Denom)\n\n\t\t// Panic if the delegation amount is zero or if the base coins does not\n\t\t// exceed the desired delegation amount.\n\t\tif coin.Amount.IsZero() || baseAmt.LT(coin.Amount) {\n\t\t\tpanic(\"delegation attempt with zero coins or insufficient funds\")\n\t\t}\n\n\t\t// compute x and y per the specification, where:\n\t\t// X := min(max(V - DV, 0), D)\n\t\t// Y := D - X\n\t\tx := sdk.MinInt(sdk.MaxInt(vestingAmt.Sub(delVestingAmt), sdk.ZeroInt()), coin.Amount)\n\t\ty := coin.Amount.Sub(x)\n\n\t\tif !x.IsZero() {\n\t\t\txCoin := sdk.NewCoin(coin.Denom, x)\n\t\t\tbva.DelegatedVesting = bva.DelegatedVesting.Add(xCoin)\n\t\t}\n\n\t\tif !y.IsZero() {\n\t\t\tyCoin := sdk.NewCoin(coin.Denom, y)\n\t\t\tbva.DelegatedFree = bva.DelegatedFree.Add(yCoin)\n\t\t}\n\t}\n}", "func (dva *DelayedVestingAccount) TrackDelegation(blockTime time.Time, balance, amount sdk.Coins) {\n\tdva.BaseVestingAccount.TrackDelegation(balance, dva.GetVestingCoins(blockTime), amount)\n}", "func (vva *ValidatorVestingAccount) TrackDelegation(blockTime time.Time, amount sdk.Coins) {\n\tvva.BaseVestingAccount.TrackDelegation(vva.GetVestingCoins(blockTime), amount)\n}", "func (cva *ContinuousVestingAccount) TrackDelegation(blockTime time.Time, balance, amount sdk.Coins) {\n\tcva.BaseVestingAccount.TrackDelegation(balance, cva.GetVestingCoins(blockTime), amount)\n}", "func (va *ClawbackVestingAccount) TrackDelegation(blockTime time.Time, balance, amount sdk.Coins) {\n\tva.BaseVestingAccount.TrackDelegation(balance, va.GetVestingCoins(blockTime), amount)\n}", "func (plva *PermanentLockedAccount) TrackDelegation(blockTime time.Time, balance, amount sdk.Coins) {\n\tplva.BaseVestingAccount.TrackDelegation(balance, plva.OriginalVesting, amount)\n}", "func (bva *BaseVestingAccount) TrackUndelegation(amount sdk.Coins) {\n\tfor _, coin := range amount {\n\t\t// panic if the undelegation amount is zero\n\t\tif coin.Amount.IsZero() {\n\t\t\tpanic(\"undelegation attempt with zero coins\")\n\t\t}\n\t\tdelegatedFree := bva.DelegatedFree.AmountOf(coin.Denom)\n\t\tdelegatedVesting := bva.DelegatedVesting.AmountOf(coin.Denom)\n\n\t\t// compute x and y per the specification, where:\n\t\t// X := min(DF, D)\n\t\t// Y := min(DV, D - X)\n\t\tx := sdk.MinInt(delegatedFree, coin.Amount)\n\t\ty := sdk.MinInt(delegatedVesting, coin.Amount.Sub(x))\n\n\t\tif !x.IsZero() {\n\t\t\txCoin := sdk.NewCoin(coin.Denom, x)\n\t\t\tbva.DelegatedFree = bva.DelegatedFree.Sub(sdk.Coins{xCoin})\n\t\t}\n\n\t\tif !y.IsZero() {\n\t\t\tyCoin := sdk.NewCoin(coin.Denom, y)\n\t\t\tbva.DelegatedVesting = bva.DelegatedVesting.Sub(sdk.Coins{yCoin})\n\t\t}\n\t}\n}", "func (va *ClawbackVestingAccount) updateDelegation(encumbered, toClawBack, bonded, unbonding, unbonded sdk.Coins) sdk.Coins {\n\tdelegated := bonded.Add(unbonding...)\n\toldDelegated := va.DelegatedVesting.Add(va.DelegatedFree...)\n\tslashed := oldDelegated.Sub(coinsMin(delegated, oldDelegated))\n\ttotal := delegated.Add(unbonded...)\n\ttoClawBack = coinsMin(toClawBack, total) // might have been slashed\n\tnewDelegated := coinsMin(delegated, total.Sub(toClawBack)).Add(slashed...)\n\tva.DelegatedVesting = coinsMin(encumbered, newDelegated)\n\tva.DelegatedFree = newDelegated.Sub(va.DelegatedVesting)\n\treturn toClawBack\n}", "func (k msgServer) Delegate(goCtx context.Context, msg *types.MsgDelegate) (*types.MsgDelegateResponse, error) {\n\tctx := sdk.UnwrapSDKContext(goCtx)\n\tvalAddr, valErr := sdk.ValAddressFromBech32(msg.ValidatorAddress)\n\tif valErr != nil {\n\t\treturn nil, valErr\n\t}\n\n\tvalidator, found := k.GetValidator(ctx, valAddr)\n\tif !found {\n\t\treturn nil, types.ErrNoValidatorFound\n\t}\n\n\tdelegatorAddress, err := sdk.AccAddressFromBech32(msg.DelegatorAddress)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbondDenom := k.BondDenom(ctx)\n\tif msg.Amount.Denom != bondDenom {\n\t\treturn nil, sdkerrors.Wrapf(\n\t\t\tsdkerrors.ErrInvalidRequest, \"invalid coin denomination: got %s, expected %s\", msg.Amount.Denom, bondDenom,\n\t\t)\n\t}\n\n\ttokens := msg.Amount.Amount\n\n\t// if this delegation is from a liquid staking provider (identified if the delegator\n\t// is an ICA account), it cannot exceed the global or validator bond cap\n\tif k.DelegatorIsLiquidStaker(delegatorAddress) {\n\t\tshares, err := validator.SharesFromTokens(tokens)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif err := k.SafelyIncreaseTotalLiquidStakedTokens(ctx, tokens, false); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif err := k.SafelyIncreaseValidatorLiquidShares(ctx, &validator, shares); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// NOTE: source funds are always unbonded\n\tnewShares, err := k.Keeper.Delegate(ctx, delegatorAddress, tokens, types.Unbonded, validator, true)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif tokens.IsInt64() {\n\t\tdefer func() {\n\t\t\ttelemetry.IncrCounter(1, types.ModuleName, \"delegate\")\n\t\t\ttelemetry.SetGaugeWithLabels(\n\t\t\t\t[]string{\"tx\", \"msg\", msg.Type()},\n\t\t\t\tfloat32(tokens.Int64()),\n\t\t\t\t[]metrics.Label{telemetry.NewLabel(\"denom\", msg.Amount.Denom)},\n\t\t\t)\n\t\t}()\n\t}\n\n\tctx.EventManager().EmitEvents(sdk.Events{\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeDelegate,\n\t\t\tsdk.NewAttribute(types.AttributeKeyValidator, msg.ValidatorAddress),\n\t\t\tsdk.NewAttribute(sdk.AttributeKeyAmount, msg.Amount.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyNewShares, newShares.String()),\n\t\t),\n\t})\n\n\treturn &types.MsgDelegateResponse{}, nil\n}", "func (k Keeper) TransferDelegation(ctx sdk.Context, valAddr sdk.ValAddress, fromDelegator, toDelegator sdk.AccAddress, shares sdk.Dec) (sdk.Dec, error) {\n\t// Redelegations link a delegation to it's previous validator so slashes are propagated to the new validator.\n\t// If the delegation is transferred to a new owner, the redelegation object must be updated.\n\t// For expediency all transfers with redelegations are blocked.\n\tif k.stakingKeeper.HasReceivingRedelegation(ctx, fromDelegator, valAddr) {\n\t\treturn sdk.Dec{}, types.ErrRedelegationsNotCompleted\n\t}\n\n\tif shares.IsNil() || shares.LT(sdk.ZeroDec()) {\n\t\treturn sdk.Dec{}, errorsmod.Wrap(types.ErrUntransferableShares, \"nil or negative shares\")\n\t}\n\tif shares.Equal(sdk.ZeroDec()) {\n\t\t// Block 0 transfers to reduce edge cases.\n\t\treturn sdk.Dec{}, errorsmod.Wrap(types.ErrUntransferableShares, \"zero shares\")\n\t}\n\n\tfromDelegation, found := k.stakingKeeper.GetDelegation(ctx, fromDelegator, valAddr)\n\tif !found {\n\t\treturn sdk.Dec{}, types.ErrNoDelegatorForAddress\n\t}\n\tvalidator, found := k.stakingKeeper.GetValidator(ctx, valAddr)\n\tif !found {\n\t\treturn sdk.Dec{}, types.ErrNoValidatorFound\n\t}\n\t// Prevent validators from reducing their self delegation below the min.\n\tisValidatorOperator := fromDelegator.Equals(valAddr)\n\tif isValidatorOperator {\n\t\tif isBelowMinSelfDelegation(validator, fromDelegation.Shares.Sub(shares)) {\n\t\t\treturn sdk.Dec{}, types.ErrSelfDelegationBelowMinimum\n\t\t}\n\t}\n\n\treturnAmount, err := k.fastUndelegate(ctx, valAddr, fromDelegator, shares)\n\tif err != nil {\n\t\treturn sdk.Dec{}, err\n\t}\n\treturnCoins := sdk.NewCoins(sdk.NewCoin(k.stakingKeeper.BondDenom(ctx), returnAmount))\n\n\tif err := k.bankKeeper.SendCoins(ctx, fromDelegator, toDelegator, returnCoins); err != nil {\n\t\treturn sdk.Dec{}, err\n\t}\n\treceivedShares, err := k.delegateFromAccount(ctx, valAddr, toDelegator, returnAmount)\n\tif err != nil {\n\t\treturn sdk.Dec{}, err\n\t}\n\n\treturn receivedShares, nil\n}", "func (_DelegationController *DelegationControllerTransactor) Delegate(opts *bind.TransactOpts, validatorId *big.Int, amount *big.Int, delegationPeriod *big.Int, info string) (*types.Transaction, error) {\n\treturn _DelegationController.contract.Transact(opts, \"delegate\", validatorId, amount, delegationPeriod, info)\n}", "func (_DelegationController *DelegationControllerSession) Delegate(validatorId *big.Int, amount *big.Int, delegationPeriod *big.Int, info string) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.Delegate(&_DelegationController.TransactOpts, validatorId, amount, delegationPeriod, info)\n}", "func (_DelegationController *DelegationControllerTransactorSession) Delegate(validatorId *big.Int, amount *big.Int, delegationPeriod *big.Int, info string) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.Delegate(&_DelegationController.TransactOpts, validatorId, amount, delegationPeriod, info)\n}", "func (broadcast *Broadcast) Delegate(ctx context.Context, delegator, voter, amount,\n\tprivKeyHex string, seq int64) (*model.BroadcastResponse, error) {\n\tmsg := model.DelegateMsg{\n\t\tDelegator: delegator,\n\t\tVoter: voter,\n\t\tAmount: amount,\n\t}\n\treturn broadcast.broadcastTransaction(ctx, msg, privKeyHex, seq, \"\", false)\n}", "func (o OfflineNotaryRepository) AddDelegation(data.RoleName, []data.PublicKey, []string) error {\n\treturn nil\n}", "func Delegate(stub shim.ChaincodeStubInterface, args []string) error {\n\tvar vote entities.Vote\n\terr := json.Unmarshal([]byte(args[0]), &vote)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tpoll, err := validateDelegate(stub, vote)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = addVoteToPoll(stub, poll, vote)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Println(\"saving delegate vote\")\n\tutil.UpdateObjectInChain(stub, vote.ID(), util.VotesIndexName, []byte(args[0]))\n\n\tfmt.Println(\"successfully delegated vote to \" + vote.Delegate + \"!\")\n\treturn nil\n}", "func (b *rpcVestingBalance) delegated() (sdk.Coins, sdk.Coins, error) {\n\tdelegatedCoins, err := b.totalDelegated()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tunbondingCoins, err := b.totalUnbondingDelegations()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tdelegated := delegatedCoins.AmountOf(stakingDenom)\n\tunbonding := unbondingCoins.AmountOf(stakingDenom)\n\ttotalStaked := delegated.Add(unbonding)\n\tdelegatedFree := b.vacc.GetDelegatedFree().AmountOf(stakingDenom)\n\n\t// total number of staked and unbonding tokens considered to be liquid\n\ttotalFree := sdk.MinInt(totalStaked, delegatedFree)\n\t// any coins that are not considered liquid, are vesting up to a maximum of delegated\n\tstakedVesting := sdk.MinInt(totalStaked.Sub(totalFree), delegated)\n\t// staked free coins are left over\n\tstakedFree := delegated.Sub(stakedVesting)\n\n\tliquidCoins := sdk.NewCoins(newKavaCoin(stakedFree))\n\tvestingCoins := sdk.NewCoins(newKavaCoin(stakedVesting))\n\treturn liquidCoins, vestingCoins, nil\n}", "func (k Keeper) Delegation(ctx sdk.Context, addrDel sdk.AccAddress, addrVal sdk.ValAddress) exported.DelegationI {\n\treturn nil\n}", "func (del Delegation) AmountDelegated() hexutil.Big {\n\tif del.Delegation.AmountDelegated == nil {\n\t\treturn hexutil.Big{}\n\t}\n\treturn *del.Delegation.AmountDelegated\n}", "func TestCallSimDelegate(t *testing.T) {\n\t// Roll up our sleeves and swear fealty to the witch-king\n\tctx, cancel := context.WithCancel(context.Background())\n\tdefer cancel()\n\tg, ctx := errgroup.WithContext(ctx)\n\n\tdb := dbm.NewMemDB()\n\tst, err := state.MakeGenesisState(db, genesisDoc)\n\trequire.NoError(t, err)\n\n\tfrom := crypto.PrivateKeyFromSecret(\"raaah\", crypto.CurveTypeEd25519)\n\tcontractAddress := crypto.Address{1, 2, 3, 4, 5}\n\tblockchain := &bcm.Blockchain{}\n\tsink := exec.NewNoopEventSink()\n\n\t// Function to set storage value for later\n\tsetDelegate := func(up state.Updatable, value crypto.Address) error {\n\t\tcall, _, err := abi.EncodeFunctionCall(string(solidity.Abi_DelegateProxy), \"setDelegate\", logger, value)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tcache := acmstate.NewCache(st)\n\t\t_, err = evm.Default().Execute(cache, blockchain, sink,\n\t\t\tengine.CallParams{\n\t\t\t\tCallType: exec.CallTypeCall,\n\t\t\t\tOrigin: from.GetAddress(),\n\t\t\t\tCaller: from.GetAddress(),\n\t\t\t\tCallee: contractAddress,\n\t\t\t\tInput: call,\n\t\t\t\tGas: big.NewInt(9999999),\n\t\t\t}, solidity.DeployedBytecode_DelegateProxy)\n\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn cache.Sync(up)\n\t}\n\n\t// Initialise sender smart contract state\n\t_, _, err = st.Update(func(up state.Updatable) error {\n\t\terr = up.UpdateAccount(&acm.Account{\n\t\t\tAddress: from.GetAddress(),\n\t\t\tPublicKey: from.GetPublicKey(),\n\t\t\tBalance: 9999999,\n\t\t\tPermissions: permission.DefaultAccountPermissions,\n\t\t})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn up.UpdateAccount(&acm.Account{\n\t\t\tAddress: contractAddress,\n\t\t\tEVMCode: solidity.DeployedBytecode_DelegateProxy,\n\t\t})\n\t})\n\trequire.NoError(t, err)\n\n\t// Set a series of values of storage slot so we get a deep version tree (which we need to trigger the bug)\n\tdelegate := crypto.Address{0xBE, 0xEF, 0, 0xFA, 0xCE, 0, 0xBA, 0}\n\tfor i := 0; i < 0xBF; i++ {\n\t\tdelegate[7] = byte(i)\n\t\t_, _, err = st.Update(func(up state.Updatable) error {\n\t\t\treturn setDelegate(up, delegate)\n\t\t})\n\t\trequire.NoError(t, err)\n\t}\n\n\t// This is important in order to illicit the former bug - we need a cold LRU tree cache in MutableForest\n\tst, err = state.LoadState(db, st.Version())\n\trequire.NoError(t, err)\n\n\tgetIntCall, _, err := abi.EncodeFunctionCall(string(solidity.Abi_DelegateProxy), \"getDelegate\", logger)\n\trequire.NoError(t, err)\n\tn := 1000\n\n\tfor i := 0; i < n; i++ {\n\t\tg.Go(func() error {\n\t\t\ttxe, err := CallSim(st, blockchain, from.GetAddress(), contractAddress, getIntCall, logger)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\terr = txe.GetException().AsError()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\taddress, err := crypto.AddressFromBytes(txe.GetResult().Return[12:])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif address != delegate {\n\t\t\t\t// The bug for which this test was written will return the zero address here since it is accessing\n\t\t\t\t// an uninitialised tree\n\t\t\t\treturn fmt.Errorf(\"getDelegate returned %v but expected %v\", address, delegate)\n\t\t\t}\n\t\t\treturn nil\n\t\t})\n\t}\n\n\trequire.NoError(t, g.Wait())\n}", "func CalculateDelegateNetPayout(delegatedContracts []DelegatedContract) []DelegatedContract{\n var delegateIndex int\n\n for index, delegate := range delegatedContracts{\n if (delegate.Delegate){\n delegateIndex = index\n }\n }\n\n for _, delegate := range delegatedContracts{\n if (!delegate.Delegate){\n delegatedContracts[delegateIndex].TotalPayout = delegatedContracts[delegateIndex].TotalPayout + delegate.Fee\n }\n }\n return delegatedContracts\n}", "func consolidateDelegations(ctx contract.Context, validator, delegator *types.Address) (*Delegation, []*Delegation, int, error) {\n\t// cycle through all delegations and delete those which are BONDED and\n\t// unlocked while accumulating their amounts\n\tdelegations, err := returnMatchingDelegations(ctx, validator, delegator)\n\tif err != nil {\n\t\treturn nil, nil, -1, err\n\t}\n\n\tunconsolidatedDelegationsCount := 0\n\ttotalDelegationAmount := common.BigZero()\n\tvar consolidatedDelegations []*Delegation\n\tfor _, delegation := range delegations {\n\t\tif delegation.LockTime > uint64(ctx.Now().Unix()) || delegation.State != BONDED {\n\t\t\tunconsolidatedDelegationsCount++\n\t\t\tcontinue\n\t\t}\n\n\t\ttotalDelegationAmount.Add(totalDelegationAmount, &delegation.Amount.Value)\n\t\tconsolidatedDelegations = append(consolidatedDelegations, delegation)\n\n\t\tif err = DeleteDelegation(ctx, delegation); err != nil {\n\t\t\treturn nil, nil, -1, err\n\t\t}\n\t}\n\n\tindex, err := GetNextDelegationIndex(ctx, *validator, *delegator)\n\tif err != nil {\n\t\treturn nil, nil, -1, err\n\t}\n\n\t// create new conolidated delegation\n\tdelegation := &Delegation{\n\t\tValidator: validator,\n\t\tDelegator: delegator,\n\t\tAmount: &types.BigUInt{Value: *totalDelegationAmount},\n\t\tUpdateAmount: loom.BigZeroPB(),\n\t\tLocktimeTier: 0,\n\t\tLockTime: 0,\n\t\tState: BONDED,\n\t\tIndex: index,\n\t}\n\tif err := SetDelegation(ctx, delegation); err != nil {\n\t\treturn nil, nil, -1, err\n\t}\n\treturn delegation, consolidatedDelegations, unconsolidatedDelegationsCount, nil\n}", "func (_TokensNetwork *TokensNetworkTransactor) UpdateBalanceProofDelegate(opts *bind.TransactOpts, token common.Address, partner common.Address, participant common.Address, transferred_amount *big.Int, locksroot [32]byte, nonce uint64, additional_hash [32]byte, partner_signature []byte, participant_signature []byte) (*types.Transaction, error) {\n\treturn _TokensNetwork.contract.Transact(opts, \"updateBalanceProofDelegate\", token, partner, participant, transferred_amount, locksroot, nonce, additional_hash, partner_signature, participant_signature)\n}", "func (k msgServer) CancelUnbondingDelegation(goCtx context.Context, msg *types.MsgCancelUnbondingDelegation) (*types.MsgCancelUnbondingDelegationResponse, error) {\n\tctx := sdk.UnwrapSDKContext(goCtx)\n\n\tvalAddr, err := sdk.ValAddressFromBech32(msg.ValidatorAddress)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdelegatorAddress, err := sdk.AccAddressFromBech32(msg.DelegatorAddress)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbondDenom := k.BondDenom(ctx)\n\tif msg.Amount.Denom != bondDenom {\n\t\treturn nil, sdkerrors.Wrapf(\n\t\t\tsdkerrors.ErrInvalidRequest, \"invalid coin denomination: got %s, expected %s\", msg.Amount.Denom, bondDenom,\n\t\t)\n\t}\n\n\tvalidator, found := k.GetValidator(ctx, valAddr)\n\tif !found {\n\t\treturn nil, types.ErrNoValidatorFound\n\t}\n\n\t// In some situations, the exchange rate becomes invalid, e.g. if\n\t// Validator loses all tokens due to slashing. In this case,\n\t// make all future delegations invalid.\n\tif validator.InvalidExRate() {\n\t\treturn nil, types.ErrDelegatorShareExRateInvalid\n\t}\n\n\tif validator.IsJailed() {\n\t\treturn nil, types.ErrValidatorJailed\n\t}\n\n\tubd, found := k.GetUnbondingDelegation(ctx, delegatorAddress, valAddr)\n\tif !found {\n\t\treturn nil, status.Errorf(\n\t\t\tcodes.NotFound,\n\t\t\t\"unbonding delegation with delegator %s not found for validator %s\",\n\t\t\tmsg.DelegatorAddress, msg.ValidatorAddress,\n\t\t)\n\t}\n\n\t// if this undelegation was from a liquid staking provider (identified if the delegator\n\t// is an ICA account), the global and validator liquid totals should be incremented\n\ttokens := msg.Amount.Amount\n\tshares, err := validator.SharesFromTokens(tokens)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif k.DelegatorIsLiquidStaker(delegatorAddress) {\n\t\tif err := k.SafelyIncreaseTotalLiquidStakedTokens(ctx, tokens, false); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif err := k.SafelyIncreaseValidatorLiquidShares(ctx, &validator, shares); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tvar (\n\t\tunbondEntry types.UnbondingDelegationEntry\n\t\tunbondEntryIndex int64 = -1\n\t)\n\n\tfor i, entry := range ubd.Entries {\n\t\tif entry.CreationHeight == msg.CreationHeight {\n\t\t\tunbondEntry = entry\n\t\t\tunbondEntryIndex = int64(i)\n\t\t\tbreak\n\t\t}\n\t}\n\tif unbondEntryIndex == -1 {\n\t\treturn nil, sdkerrors.ErrNotFound.Wrapf(\"unbonding delegation entry is not found at block height %d\", msg.CreationHeight)\n\t}\n\n\tif unbondEntry.Balance.LT(msg.Amount.Amount) {\n\t\treturn nil, sdkerrors.ErrInvalidRequest.Wrap(\"amount is greater than the unbonding delegation entry balance\")\n\t}\n\n\tif unbondEntry.CompletionTime.Before(ctx.BlockTime()) {\n\t\treturn nil, sdkerrors.ErrInvalidRequest.Wrap(\"unbonding delegation is already processed\")\n\t}\n\n\t// delegate back the unbonding delegation amount to the validator\n\t_, err = k.Keeper.Delegate(ctx, delegatorAddress, msg.Amount.Amount, types.Unbonding, validator, false)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tamount := unbondEntry.Balance.Sub(msg.Amount.Amount)\n\tif amount.IsZero() {\n\t\tubd.RemoveEntry(unbondEntryIndex)\n\t} else {\n\t\t// update the unbondingDelegationEntryBalance and InitialBalance for ubd entry\n\t\tunbondEntry.Balance = amount\n\t\tunbondEntry.InitialBalance = unbondEntry.InitialBalance.Sub(msg.Amount.Amount)\n\t\tubd.Entries[unbondEntryIndex] = unbondEntry\n\t}\n\n\t// set the unbonding delegation or remove it if there are no more entries\n\tif len(ubd.Entries) == 0 {\n\t\tk.RemoveUnbondingDelegation(ctx, ubd)\n\t} else {\n\t\tk.SetUnbondingDelegation(ctx, ubd)\n\t}\n\n\tctx.EventManager().EmitEvent(\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeCancelUnbondingDelegation,\n\t\t\tsdk.NewAttribute(sdk.AttributeKeyAmount, msg.Amount.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyValidator, msg.ValidatorAddress),\n\t\t\tsdk.NewAttribute(types.AttributeKeyDelegator, msg.DelegatorAddress),\n\t\t\tsdk.NewAttribute(types.AttributeKeyCreationHeight, strconv.FormatInt(msg.CreationHeight, 10)),\n\t\t),\n\t)\n\n\treturn &types.MsgCancelUnbondingDelegationResponse{}, nil\n}", "func CalculatePayoutForContract(contract Contract, rate float64, delegate bool) Contract{\n ////-------------JUST FOR TESTING -------------////\n totalNodeRewards := 378 //Amount of rewards for my delegation in cycle 11\n ////--------------END TESTING ------------------////\n\n grossRewards := contract.SharePercentage * float64(totalNodeRewards)\n contract.GrossPayout = grossRewards\n fee := rate * grossRewards\n contract.Fee = fee\n var netRewards float64\n if (delegate){\n netRewards = grossRewards\n contract.NetPayout = netRewards\n contract.Fee = 0\n } else {\n netRewards = grossRewards - fee\n contract.NetPayout = contract.NetPayout + netRewards\n }\n\n return contract\n}", "func (us *DelegationService) AddDelegation(delegation *models.Delegation) (*models.Delegation, error) {\n\t// TODO(tho) add CSR validation against template\n\treturn us.storeInterface.AddDelegation(delegation)\n}", "func (_TokensNetwork *TokensNetworkSession) UpdateBalanceProofDelegate(token common.Address, partner common.Address, participant common.Address, transferred_amount *big.Int, locksroot [32]byte, nonce uint64, additional_hash [32]byte, partner_signature []byte, participant_signature []byte) (*types.Transaction, error) {\n\treturn _TokensNetwork.Contract.UpdateBalanceProofDelegate(&_TokensNetwork.TransactOpts, token, partner, participant, transferred_amount, locksroot, nonce, additional_hash, partner_signature, participant_signature)\n}", "func NewDelegation(d *types.Delegation) *Delegation {\n\treturn &Delegation{Delegation: *d, cg: new(singleflight.Group)}\n}", "func (_TokensNetwork *TokensNetworkTransactorSession) UpdateBalanceProofDelegate(token common.Address, partner common.Address, participant common.Address, transferred_amount *big.Int, locksroot [32]byte, nonce uint64, additional_hash [32]byte, partner_signature []byte, participant_signature []byte) (*types.Transaction, error) {\n\treturn _TokensNetwork.Contract.UpdateBalanceProofDelegate(&_TokensNetwork.TransactOpts, token, partner, participant, transferred_amount, locksroot, nonce, additional_hash, partner_signature, participant_signature)\n}", "func (k Keeper) Delegation(ctx context.Context, addrDel sdk.AccAddress, addrVal sdk.ValAddress) (types.DelegationI, error) {\n\tbond, err := k.Delegations.Get(ctx, collections.Join(addrDel, addrVal))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn bond, nil\n}", "func (_TokensNetwork *TokensNetworkTransactor) UnlockDelegate(opts *bind.TransactOpts, token common.Address, partner common.Address, participant common.Address, transferred_amount *big.Int, expiration *big.Int, amount *big.Int, secret_hash [32]byte, merkle_proof []byte, participant_signature []byte) (*types.Transaction, error) {\n\treturn _TokensNetwork.contract.Transact(opts, \"unlockDelegate\", token, partner, participant, transferred_amount, expiration, amount, secret_hash, merkle_proof, participant_signature)\n}", "func TestDelegatorProxyValidatorConstraints4Steps(t *testing.T) {\n\tcommon.InitConfig()\n\tparams := DefaultParams()\n\n\toriginVaSet := addrVals[1:]\n\tparams.MaxValidators = uint16(len(originVaSet))\n\tparams.Epoch = 2\n\tparams.UnbondingTime = time.Millisecond * 300\n\tstartUpValidator := NewValidator(StartUpValidatorAddr, StartUpValidatorPubkey, Description{}, types.DefaultMinSelfDelegation)\n\tstartUpStatus := baseValidatorStatus{startUpValidator}\n\torgValsLen := len(originVaSet)\n\tfullVaSet := make([]sdk.ValAddress, orgValsLen+1)\n\tcopy(fullVaSet, originVaSet)\n\tcopy(fullVaSet[orgValsLen:], []sdk.ValAddress{startUpStatus.getValidator().GetOperator()})\n\n\tbAction := baseAction{}\n\n\tstep1Actions := IActions{\n\t\tdelegatorRegProxyAction{bAction, ProxiedDelegator, true},\n\t\tdelegatorsAddSharesAction{bAction, false, true, 0, []sdk.AccAddress{ProxiedDelegator}},\n\t\tdelegatorWithdrawAction{bAction, ProxiedDelegator, sdk.OneDec(), sdk.DefaultBondDenom},\n\t\tproxyBindAction{bAction, ProxiedDelegator, ProxiedDelegator},\n\t\tproxyUnBindAction{bAction, ProxiedDelegator},\n\t}\n\n\tstep2Actions := IActions{\n\t\tdelegatorDepositAction{bAction, ValidDelegator1, DelegatedToken1, sdk.DefaultBondDenom},\n\t\tproxyBindAction{bAction, ValidDelegator1, ProxiedDelegator},\n\t\tdelegatorsAddSharesAction{bAction, false, true, 0, []sdk.AccAddress{ValidDelegator1}},\n\t\tproxyUnBindAction{bAction, ValidDelegator1},\n\t\tdelegatorWithdrawAction{bAction, ValidDelegator1, sdk.OneDec(), sdk.DefaultBondDenom},\n\t}\n\n\tstep3Actions := IActions{\n\t\tdelegatorDepositAction{bAction, ValidDelegator1, DelegatedToken1, sdk.DefaultBondDenom},\n\t\tproxyBindAction{bAction, ValidDelegator1, ProxiedDelegator},\n\t\tproxyUnBindAction{bAction, ValidDelegator1},\n\t\tdelegatorWithdrawAction{bAction, ValidDelegator1, sdk.OneDec(), sdk.DefaultBondDenom},\n\t}\n\n\tstep4Actions := IActions{\n\t\tdelegatorRegProxyAction{bAction, ProxiedDelegator, true},\n\t\tdelegatorsAddSharesAction{bAction, false, true, 0, []sdk.AccAddress{ProxiedDelegator}},\n\t\tproxyBindAction{bAction, ProxiedDelegator, ProxiedDelegator},\n\t\tproxyUnBindAction{bAction, ProxiedDelegator},\n\t\tdelegatorWithdrawAction{bAction, ProxiedDelegator, sdk.OneDec(), sdk.DefaultBondDenom},\n\t}\n\n\tfor s1 := 0; s1 < len(step1Actions); s1++ {\n\t\tfor s2 := 0; s2 < len(step2Actions); s2++ {\n\t\t\tfor s3 := 0; s3 < len(step3Actions); s3++ {\n\t\t\t\tfor s4 := 0; s4 < len(step4Actions); s4++ {\n\t\t\t\t\tinputActions := []IAction{\n\t\t\t\t\t\tcreateValidatorAction{bAction, nil},\n\t\t\t\t\t\tdelegatorsAddSharesAction{bAction, false, true, 0, []sdk.AccAddress{ValidDelegator2}},\n\t\t\t\t\t\tdelegatorDepositAction{bAction, ProxiedDelegator, MaxDelegatedToken, sdk.DefaultBondDenom},\n\t\t\t\t\t\tstep1Actions[s1],\n\t\t\t\t\t\tstep2Actions[s2],\n\t\t\t\t\t\tstep3Actions[s3],\n\t\t\t\t\t\tstep4Actions[s4],\n\t\t\t\t\t\tdelegatorRegProxyAction{bAction, ProxiedDelegator, false},\n\t\t\t\t\t\tdestroyValidatorAction{bAction},\n\t\t\t\t\t}\n\n\t\t\t\t\tactionsAndChecker, caseName := generateActionsAndCheckers(inputActions, 3)\n\n\t\t\t\t\tt.Logf(\"============================================== indexes:[%d,%d,%d,%d] %s ==============================================\", s1, s2, s3, s4, caseName)\n\t\t\t\t\t_, _, mk := CreateTestInput(t, false, SufficientInitPower)\n\t\t\t\t\tsmTestCase := newValidatorSMTestCase(mk, params, startUpStatus, inputActions, actionsAndChecker, t)\n\t\t\t\t\tsmTestCase.SetupValidatorSetAndDelegatorSet(int(params.MaxValidators))\n\t\t\t\t\tsmTestCase.printParticipantSnapshot(t)\n\t\t\t\t\tsmTestCase.Run(t)\n\t\t\t\t\tt.Log(\"============================================================================================\")\n\t\t\t\t}\n\n\t\t\t}\n\t\t}\n\t}\n}", "func (k Keeper) fastUndelegate(ctx sdk.Context, valAddr sdk.ValAddress, delegator sdk.AccAddress, shares sdk.Dec) (sdkmath.Int, error) {\n\tvalidator, found := k.stakingKeeper.GetValidator(ctx, valAddr)\n\tif !found {\n\t\treturn sdkmath.Int{}, types.ErrNoDelegatorForAddress\n\t}\n\n\treturnAmount, err := k.stakingKeeper.Unbond(ctx, delegator, valAddr, shares)\n\tif err != nil {\n\t\treturn sdkmath.Int{}, err\n\t}\n\treturnCoins := sdk.NewCoins(sdk.NewCoin(k.stakingKeeper.BondDenom(ctx), returnAmount))\n\n\t// transfer the validator tokens to the not bonded pool\n\tif validator.IsBonded() {\n\t\tif err := k.bankKeeper.SendCoinsFromModuleToModule(ctx, stakingtypes.BondedPoolName, stakingtypes.NotBondedPoolName, returnCoins); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\n\tif err := k.bankKeeper.UndelegateCoinsFromModuleToAccount(ctx, stakingtypes.NotBondedPoolName, delegator, returnCoins); err != nil {\n\t\treturn sdkmath.Int{}, err\n\t}\n\treturn returnAmount, nil\n}", "func (pva *PeriodicVestingAccount) addGrant(ctx sdk.Context, sk StakingKeeper, grantStartTime int64, grantVestingPeriods []Period, grantCoins sdk.Coins) {\n\t// how much is really delegated?\n\tbondedAmt := sk.GetDelegatorBonded(ctx, pva.GetAddress())\n\tunbondingAmt := sk.GetDelegatorUnbonding(ctx, pva.GetAddress())\n\tdelegatedAmt := bondedAmt.Add(unbondingAmt)\n\tdelegated := sdk.NewCoins(sdk.NewCoin(sk.BondDenom(ctx), delegatedAmt))\n\n\t// discover what has been slashed\n\toldDelegated := pva.DelegatedVesting.Add(pva.DelegatedFree...)\n\tslashed := oldDelegated.Sub(coinsMin(oldDelegated, delegated))\n\n\t// rebase the DV+DF by capping slashed at the current unvested amount\n\tunvested := pva.GetVestingCoins(ctx.BlockTime())\n\tnewSlashed := coinsMin(unvested, slashed)\n\tnewTotalDelegated := delegated.Add(newSlashed...)\n\n\t// modify vesting schedule for the new grant\n\tnewStart, newEnd, newPeriods := DisjunctPeriods(pva.StartTime, grantStartTime,\n\t\tpva.GetVestingPeriods(), grantVestingPeriods)\n\tpva.StartTime = newStart\n\tpva.EndTime = newEnd\n\tpva.VestingPeriods = newPeriods\n\tpva.OriginalVesting = pva.OriginalVesting.Add(grantCoins...)\n\n\t// cap DV at the current unvested amount, DF rounds out to newTotalDelegated\n\tunvested2 := pva.GetVestingCoins(ctx.BlockTime())\n\tpva.DelegatedVesting = coinsMin(newTotalDelegated, unvested2)\n\tpva.DelegatedFree = newTotalDelegated.Sub(pva.DelegatedVesting)\n}", "func (k msgServer) Undelegate(goCtx context.Context, msg *types.MsgUndelegate) (*types.MsgUndelegateResponse, error) {\n\tctx := sdk.UnwrapSDKContext(goCtx)\n\n\taddr, err := sdk.ValAddressFromBech32(msg.ValidatorAddress)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdelegatorAddress, err := sdk.AccAddressFromBech32(msg.DelegatorAddress)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttokens := msg.Amount.Amount\n\tshares, err := k.ValidateUnbondAmount(\n\t\tctx, delegatorAddress, addr, tokens,\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvalidator, found := k.GetValidator(ctx, addr)\n\tif !found {\n\t\treturn nil, types.ErrNoValidatorFound\n\t}\n\n\tdelegation, found := k.GetDelegation(ctx, delegatorAddress, addr)\n\tif !found {\n\t\treturn nil, status.Errorf(\n\t\t\tcodes.NotFound,\n\t\t\t\"delegation with delegator %s not found for validator %s\",\n\t\t\tmsg.DelegatorAddress, msg.ValidatorAddress,\n\t\t)\n\t}\n\n\t// if this is a validator self-bond, the new liquid delegation cannot fall below the self-bond * bond factor\n\tif delegation.ValidatorBond {\n\t\tif err := k.SafelyDecreaseValidatorBond(ctx, &validator, shares); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// if this delegation is from a liquid staking provider (identified if the delegator\n\t// is an ICA account), the global and validator liquid totals should be decremented\n\tif k.DelegatorIsLiquidStaker(delegatorAddress) {\n\t\tif err := k.DecreaseTotalLiquidStakedTokens(ctx, tokens); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif err := k.DecreaseValidatorLiquidShares(ctx, &validator, shares); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tbondDenom := k.BondDenom(ctx)\n\tif msg.Amount.Denom != bondDenom {\n\t\treturn nil, sdkerrors.Wrapf(\n\t\t\tsdkerrors.ErrInvalidRequest, \"invalid coin denomination: got %s, expected %s\", msg.Amount.Denom, bondDenom,\n\t\t)\n\t}\n\n\tcompletionTime, err := k.Keeper.Undelegate(ctx, delegatorAddress, addr, shares)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif tokens.IsInt64() {\n\t\tdefer func() {\n\t\t\ttelemetry.IncrCounter(1, types.ModuleName, \"undelegate\")\n\t\t\ttelemetry.SetGaugeWithLabels(\n\t\t\t\t[]string{\"tx\", \"msg\", msg.Type()},\n\t\t\t\tfloat32(tokens.Int64()),\n\t\t\t\t[]metrics.Label{telemetry.NewLabel(\"denom\", msg.Amount.Denom)},\n\t\t\t)\n\t\t}()\n\t}\n\n\tctx.EventManager().EmitEvents(sdk.Events{\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeUnbond,\n\t\t\tsdk.NewAttribute(types.AttributeKeyValidator, msg.ValidatorAddress),\n\t\t\tsdk.NewAttribute(sdk.AttributeKeyAmount, msg.Amount.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyCompletionTime, completionTime.Format(time.RFC3339)),\n\t\t),\n\t})\n\n\treturn &types.MsgUndelegateResponse{\n\t\tCompletionTime: completionTime,\n\t}, nil\n}", "func (p *Ledger) RecordPayment(destination types.NodeAddress, amount int64, confirmed chan bool) {\n\tok := <-confirmed\n\tif ok {\n\t\tp.l.Lock()\n\t\tp.incoming_debt[p.id] -= amount\n\t\tp.outgoing_debt[destination] -= amount\n\t\tp.l.Unlock()\n\t}\n}", "func (a *account) managedTrackDeposit(amount types.Currency) {\n\ta.mu.Lock()\n\tdefer a.mu.Unlock()\n\ta.pendingDeposits = a.pendingDeposits.Add(amount)\n}", "func NewDelegation(d *types.Delegation, repo repository.Repository) *Delegation {\n\treturn &Delegation{\n\t\tDelegation: *d,\n\t\trepo: repo,\n\t}\n}", "func (p *Protocol) NumDelegates() uint64 {\n\treturn p.numDelegates\n}", "func (rs *rootResolver) Delegation(args *struct {\n\tAddress common.Address\n\tStaker hexutil.Big\n}) (*Delegation, error) {\n\t// get the delegator detail from backend\n\td, err := repository.R().Delegation(&args.Address, &args.Staker)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn NewDelegation(d), nil\n}", "func (o OfflineNotaryRepository) AddDelegationPaths(data.RoleName, []string) error {\n\treturn nil\n}", "func (_TokensNetwork *TokensNetworkSession) UnlockDelegate(token common.Address, partner common.Address, participant common.Address, transferred_amount *big.Int, expiration *big.Int, amount *big.Int, secret_hash [32]byte, merkle_proof []byte, participant_signature []byte) (*types.Transaction, error) {\n\treturn _TokensNetwork.Contract.UnlockDelegate(&_TokensNetwork.TransactOpts, token, partner, participant, transferred_amount, expiration, amount, secret_hash, merkle_proof, participant_signature)\n}", "func (tracker *PeerTracker) Track(ci *types.ChainInfo) {\n\ttracker.mu.Lock()\n\tdefer tracker.mu.Unlock()\n\n\t_, tracking := tracker.peers[ci.Peer]\n\t_, trusted := tracker.trusted[ci.Peer]\n\ttracker.peers[ci.Peer] = ci\n\tlogPeerTracker.Infof(\"Tracking %s, new=%t, count=%d trusted=%t\", ci, !tracking, len(tracker.peers), trusted)\n}", "func TestSlashWithRedelegation(t *testing.T) {\n\tapp, ctx, addrDels, addrVals := bootstrapSlashTest(t, 10)\n\tconsAddr := sdk.ConsAddress(PKs[0].Address())\n\tfraction := sdk.NewDecWithPrec(5, 1)\n\tbondDenom := app.StakingKeeper.BondDenom(ctx)\n\n\t// set a redelegation\n\trdTokens := app.StakingKeeper.TokensFromConsensusPower(ctx, 6)\n\trd := types.NewRedelegation(addrDels[0], addrVals[0], addrVals[1], 11,\n\t\ttime.Unix(0, 0), rdTokens, rdTokens.ToDec())\n\tapp.StakingKeeper.SetRedelegation(ctx, rd)\n\n\t// set the associated delegation\n\tdel := types.NewDelegation(addrDels[0], addrVals[1], rdTokens.ToDec())\n\tapp.StakingKeeper.SetDelegation(ctx, del)\n\n\t// update bonded tokens\n\tbondedPool := app.StakingKeeper.GetBondedPool(ctx)\n\tnotBondedPool := app.StakingKeeper.GetNotBondedPool(ctx)\n\trdCoins := sdk.NewCoins(sdk.NewCoin(bondDenom, rdTokens.MulRaw(2)))\n\n\trequire.NoError(t, simapp.FundModuleAccount(app.BankKeeper, ctx, bondedPool.GetName(), rdCoins))\n\n\tapp.AccountKeeper.SetModuleAccount(ctx, bondedPool)\n\n\toldBonded := app.BankKeeper.GetBalance(ctx, bondedPool.GetAddress(), bondDenom).Amount\n\toldNotBonded := app.BankKeeper.GetBalance(ctx, notBondedPool.GetAddress(), bondDenom).Amount\n\n\t// slash validator\n\tctx = ctx.WithBlockHeight(12)\n\tvalidator, found := app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)\n\trequire.True(t, found)\n\n\trequire.NotPanics(t, func() { app.StakingKeeper.Slash(ctx, consAddr, 10, 10, fraction) })\n\tburnAmount := app.StakingKeeper.TokensFromConsensusPower(ctx, 10).ToDec().Mul(fraction).TruncateInt()\n\n\tbondedPool = app.StakingKeeper.GetBondedPool(ctx)\n\tnotBondedPool = app.StakingKeeper.GetNotBondedPool(ctx)\n\n\t// burn bonded tokens from only from delegations\n\tbondedPoolBalance := app.BankKeeper.GetBalance(ctx, bondedPool.GetAddress(), bondDenom).Amount\n\trequire.True(sdk.IntEq(t, oldBonded.Sub(burnAmount), bondedPoolBalance))\n\n\tnotBondedPoolBalance := app.BankKeeper.GetBalance(ctx, notBondedPool.GetAddress(), bondDenom).Amount\n\trequire.True(sdk.IntEq(t, oldNotBonded, notBondedPoolBalance))\n\toldBonded = app.BankKeeper.GetBalance(ctx, bondedPool.GetAddress(), bondDenom).Amount\n\n\t// read updating redelegation\n\trd, found = app.StakingKeeper.GetRedelegation(ctx, addrDels[0], addrVals[0], addrVals[1])\n\trequire.True(t, found)\n\trequire.Len(t, rd.Entries, 1)\n\t// read updated validator\n\tvalidator, found = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)\n\trequire.True(t, found)\n\t// power decreased by 2 - 4 stake originally bonded at the time of infraction\n\t// was still bonded at the time of discovery and was slashed by half, 4 stake\n\t// bonded at the time of discovery hadn't been bonded at the time of infraction\n\t// and wasn't slashed\n\trequire.Equal(t, int64(8), validator.GetConsensusPower(app.StakingKeeper.PowerReduction(ctx)))\n\n\t// slash the validator again\n\tvalidator, found = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)\n\trequire.True(t, found)\n\n\trequire.NotPanics(t, func() { app.StakingKeeper.Slash(ctx, consAddr, 10, 10, sdk.OneDec()) })\n\tburnAmount = app.StakingKeeper.TokensFromConsensusPower(ctx, 7)\n\n\t// read updated pool\n\tbondedPool = app.StakingKeeper.GetBondedPool(ctx)\n\tnotBondedPool = app.StakingKeeper.GetNotBondedPool(ctx)\n\n\t// seven bonded tokens burned\n\tbondedPoolBalance = app.BankKeeper.GetBalance(ctx, bondedPool.GetAddress(), bondDenom).Amount\n\trequire.True(sdk.IntEq(t, oldBonded.Sub(burnAmount), bondedPoolBalance))\n\trequire.True(sdk.IntEq(t, oldNotBonded, notBondedPoolBalance))\n\n\tbondedPoolBalance = app.BankKeeper.GetBalance(ctx, bondedPool.GetAddress(), bondDenom).Amount\n\trequire.True(sdk.IntEq(t, oldBonded.Sub(burnAmount), bondedPoolBalance))\n\n\tnotBondedPoolBalance = app.BankKeeper.GetBalance(ctx, notBondedPool.GetAddress(), bondDenom).Amount\n\trequire.True(sdk.IntEq(t, oldNotBonded, notBondedPoolBalance))\n\toldBonded = app.BankKeeper.GetBalance(ctx, bondedPool.GetAddress(), bondDenom).Amount\n\n\t// read updating redelegation\n\trd, found = app.StakingKeeper.GetRedelegation(ctx, addrDels[0], addrVals[0], addrVals[1])\n\trequire.True(t, found)\n\trequire.Len(t, rd.Entries, 1)\n\t// read updated validator\n\tvalidator, found = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)\n\trequire.True(t, found)\n\t// power decreased by 4\n\trequire.Equal(t, int64(4), validator.GetConsensusPower(app.StakingKeeper.PowerReduction(ctx)))\n\n\t// slash the validator again, by 100%\n\tctx = ctx.WithBlockHeight(12)\n\tvalidator, found = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)\n\trequire.True(t, found)\n\n\trequire.NotPanics(t, func() { app.StakingKeeper.Slash(ctx, consAddr, 10, 10, sdk.OneDec()) })\n\n\tburnAmount = app.StakingKeeper.TokensFromConsensusPower(ctx, 10).ToDec().Mul(sdk.OneDec()).TruncateInt()\n\tburnAmount = burnAmount.Sub(sdk.OneDec().MulInt(rdTokens).TruncateInt())\n\n\t// read updated pool\n\tbondedPool = app.StakingKeeper.GetBondedPool(ctx)\n\tnotBondedPool = app.StakingKeeper.GetNotBondedPool(ctx)\n\n\tbondedPoolBalance = app.BankKeeper.GetBalance(ctx, bondedPool.GetAddress(), bondDenom).Amount\n\trequire.True(sdk.IntEq(t, oldBonded.Sub(burnAmount), bondedPoolBalance))\n\tnotBondedPoolBalance = app.BankKeeper.GetBalance(ctx, notBondedPool.GetAddress(), bondDenom).Amount\n\trequire.True(sdk.IntEq(t, oldNotBonded, notBondedPoolBalance))\n\toldBonded = app.BankKeeper.GetBalance(ctx, bondedPool.GetAddress(), bondDenom).Amount\n\n\t// read updating redelegation\n\trd, found = app.StakingKeeper.GetRedelegation(ctx, addrDels[0], addrVals[0], addrVals[1])\n\trequire.True(t, found)\n\trequire.Len(t, rd.Entries, 1)\n\t// apply TM updates\n\tapplyValidatorSetUpdates(t, ctx, app.StakingKeeper, -1)\n\t// read updated validator\n\t// validator decreased to zero power, should be in unbonding period\n\tvalidator, _ = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)\n\trequire.Equal(t, validator.GetStatus(), types.Unbonding)\n\n\t// slash the validator again, by 100%\n\t// no stake remains to be slashed\n\tctx = ctx.WithBlockHeight(12)\n\t// validator still in unbonding period\n\tvalidator, _ = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)\n\trequire.Equal(t, validator.GetStatus(), types.Unbonding)\n\n\trequire.NotPanics(t, func() { app.StakingKeeper.Slash(ctx, consAddr, 10, 10, sdk.OneDec()) })\n\n\t// read updated pool\n\tbondedPool = app.StakingKeeper.GetBondedPool(ctx)\n\tnotBondedPool = app.StakingKeeper.GetNotBondedPool(ctx)\n\n\tbondedPoolBalance = app.BankKeeper.GetBalance(ctx, bondedPool.GetAddress(), bondDenom).Amount\n\trequire.True(sdk.IntEq(t, oldBonded, bondedPoolBalance))\n\tnotBondedPoolBalance = app.BankKeeper.GetBalance(ctx, notBondedPool.GetAddress(), bondDenom).Amount\n\trequire.True(sdk.IntEq(t, oldNotBonded, notBondedPoolBalance))\n\n\t// read updating redelegation\n\trd, found = app.StakingKeeper.GetRedelegation(ctx, addrDels[0], addrVals[0], addrVals[1])\n\trequire.True(t, found)\n\trequire.Len(t, rd.Entries, 1)\n\t// read updated validator\n\t// power still zero, still in unbonding period\n\tvalidator, _ = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)\n\trequire.Equal(t, validator.GetStatus(), types.Unbonding)\n}", "func (m *MetricsProvider) SignerAddLinkedDataProof(value time.Duration) {\n}", "func (*CardanoSignTransactionRequest_Certificate_StakeDelegation) Descriptor() ([]byte, []int) {\n\treturn file_cardano_proto_rawDescGZIP(), []int{4, 3, 0}\n}", "func (_TokensNetwork *TokensNetworkTransactorSession) UnlockDelegate(token common.Address, partner common.Address, participant common.Address, transferred_amount *big.Int, expiration *big.Int, amount *big.Int, secret_hash [32]byte, merkle_proof []byte, participant_signature []byte) (*types.Transaction, error) {\n\treturn _TokensNetwork.Contract.UnlockDelegate(&_TokensNetwork.TransactOpts, token, partner, participant, transferred_amount, expiration, amount, secret_hash, merkle_proof, participant_signature)\n}", "func (_Bep20 *Bep20Transactor) DelegateBySig(opts *bind.TransactOpts, delegatee common.Address, nonce *big.Int, expiry *big.Int, v uint8, r [32]byte, s [32]byte) (*types.Transaction, error) {\n\treturn _Bep20.contract.Transact(opts, \"delegateBySig\", delegatee, nonce, expiry, v, r, s)\n}", "func (va *ClawbackVestingAccount) addGrant(ctx sdk.Context, sk StakingKeeper, grantStartTime int64, grantLockupPeriods, grantVestingPeriods []Period, grantCoins sdk.Coins) {\n\t// how much is really delegated?\n\tbondedAmt := sk.GetDelegatorBonded(ctx, va.GetAddress())\n\tunbondingAmt := sk.GetDelegatorUnbonding(ctx, va.GetAddress())\n\tdelegatedAmt := bondedAmt.Add(unbondingAmt)\n\tdelegated := sdk.NewCoins(sdk.NewCoin(sk.BondDenom(ctx), delegatedAmt))\n\n\t// discover what has been slashed\n\toldDelegated := va.DelegatedVesting.Add(va.DelegatedFree...)\n\tslashed := oldDelegated.Sub(coinsMin(oldDelegated, delegated))\n\n\t// rebase the DV + DF by capping slashed at the current unvested amount\n\tunvested := va.OriginalVesting.Sub(va.GetVestedOnly(ctx.BlockTime()))\n\tnewSlashed := coinsMin(slashed, unvested)\n\tnewDelegated := delegated.Add(newSlashed...)\n\n\t// modify schedules for the new grant\n\tnewLockupStart, newLockupEnd, newLockupPeriods := DisjunctPeriods(va.StartTime, grantStartTime, va.LockupPeriods, grantLockupPeriods)\n\tnewVestingStart, newVestingEnd, newVestingPeriods := DisjunctPeriods(va.StartTime, grantStartTime,\n\t\tva.GetVestingPeriods(), grantVestingPeriods)\n\tif newLockupStart != newVestingStart {\n\t\tpanic(\"bad start time calculation\")\n\t}\n\tva.StartTime = newLockupStart\n\tva.EndTime = max64(newLockupEnd, newVestingEnd)\n\tva.LockupPeriods = newLockupPeriods\n\tva.VestingPeriods = newVestingPeriods\n\tva.OriginalVesting = va.OriginalVesting.Add(grantCoins...)\n\n\t// cap DV at the current unvested amount, DF rounds out to newDelegated\n\tunvested2 := va.GetVestingCoins(ctx.BlockTime())\n\tva.DelegatedVesting = coinsMin(newDelegated, unvested2)\n\tva.DelegatedFree = newDelegated.Sub(va.DelegatedVesting)\n}", "func CalculatePercentageSharesForCycle(delegatedContracts []DelegatedContract, cycle int, rate float64, spillage bool, delegateAddr string) ([]DelegatedContract, error){\n var stakingBalance float64\n //var balance float64\n var err error\n\n spillAlert := false\n\n stakingBalance, err = GetDelegateStakingBalance(delegateAddr, cycle)\n if (err != nil){\n return delegatedContracts, errors.New(\"func CalculateRollSpillage(delegatedContracts []DelegatedContract, delegateAddr string) failed: \" + err.Error())\n }\n\n mod := math.Mod(stakingBalance, 10000)\n sum := stakingBalance - mod\n balanceCheck := stakingBalance - mod\n\n for index, delegation := range delegatedContracts{\n counter := 0\n for i, _ := range delegation.Contracts {\n if (delegatedContracts[index].Contracts[i].Cycle == cycle){\n break\n }\n counter = counter + 1\n }\n balanceCheck = balanceCheck - delegatedContracts[index].Contracts[counter].Amount\n //fmt.Println(stakingBalance)\n if (spillAlert){\n delegatedContracts[index].Contracts[counter].SharePercentage = 0\n delegatedContracts[index].Contracts[counter].RollInclusion = 0\n } else if (balanceCheck < 0 && spillage){\n spillAlert = true\n delegatedContracts[index].Contracts[counter].SharePercentage = (delegatedContracts[index].Contracts[counter].Amount + stakingBalance) / sum\n delegatedContracts[index].Contracts[counter].RollInclusion = delegatedContracts[index].Contracts[counter].Amount + stakingBalance\n } else{\n delegatedContracts[index].Contracts[counter].SharePercentage = delegatedContracts[index].Contracts[counter].Amount / stakingBalance\n delegatedContracts[index].Contracts[counter].RollInclusion = delegatedContracts[index].Contracts[counter].Amount\n }\n delegatedContracts[index].Contracts[counter] = CalculatePayoutForContract(delegatedContracts[index].Contracts[counter], rate, delegatedContracts[index].Delegate)\n delegatedContracts[index].Fee = delegatedContracts[index].Fee + delegatedContracts[index].Contracts[counter].Fee\n }\n\n return delegatedContracts, nil\n}", "func (a *account) managedTrackWithdrawal(amount types.Currency) {\n\ta.mu.Lock()\n\tdefer a.mu.Unlock()\n\ta.pendingWithdrawals = a.pendingWithdrawals.Add(amount)\n}", "func (_OwnerProxyRegistry *OwnerProxyRegistryCaller) CountDelegates(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _OwnerProxyRegistry.contract.Call(opts, &out, \"countDelegates\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (_OwnerProxyRegistry *OwnerProxyRegistryTransactor) AddDelegate(opts *bind.TransactOpts, from common.Address) (*types.Transaction, error) {\n\treturn _OwnerProxyRegistry.contract.Transact(opts, \"addDelegate\", from)\n}", "func TestSlashWithUnbondingDelegation(t *testing.T) {\n\tapp, ctx, addrDels, addrVals := bootstrapSlashTest(t, 10)\n\n\tconsAddr := sdk.ConsAddress(PKs[0].Address())\n\tfraction := sdk.NewDecWithPrec(5, 1)\n\n\t// set an unbonding delegation with expiration timestamp beyond which the\n\t// unbonding delegation shouldn't be slashed\n\tubdTokens := app.StakingKeeper.TokensFromConsensusPower(ctx, 4)\n\tubd := types.NewUnbondingDelegation(addrDels[0], addrVals[0], 11, time.Unix(0, 0), ubdTokens)\n\tapp.StakingKeeper.SetUnbondingDelegation(ctx, ubd)\n\n\t// slash validator for the first time\n\tctx = ctx.WithBlockHeight(12)\n\tbondedPool := app.StakingKeeper.GetBondedPool(ctx)\n\toldBondedPoolBalances := app.BankKeeper.GetAllBalances(ctx, bondedPool.GetAddress())\n\n\tvalidator, found := app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)\n\trequire.True(t, found)\n\tapp.StakingKeeper.Slash(ctx, consAddr, 10, 10, fraction)\n\n\t// end block\n\tapplyValidatorSetUpdates(t, ctx, app.StakingKeeper, 1)\n\n\t// read updating unbonding delegation\n\tubd, found = app.StakingKeeper.GetUnbondingDelegation(ctx, addrDels[0], addrVals[0])\n\trequire.True(t, found)\n\trequire.Len(t, ubd.Entries, 1)\n\n\t// balance decreased\n\trequire.Equal(t, app.StakingKeeper.TokensFromConsensusPower(ctx, 2), ubd.Entries[0].Balance)\n\n\t// bonded tokens burned\n\tnewBondedPoolBalances := app.BankKeeper.GetAllBalances(ctx, bondedPool.GetAddress())\n\tdiffTokens := oldBondedPoolBalances.Sub(newBondedPoolBalances).AmountOf(app.StakingKeeper.BondDenom(ctx))\n\trequire.Equal(t, app.StakingKeeper.TokensFromConsensusPower(ctx, 3), diffTokens)\n\n\t// read updated validator\n\tvalidator, found = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)\n\trequire.True(t, found)\n\n\t// power decreased by 3 - 6 stake originally bonded at the time of infraction\n\t// was still bonded at the time of discovery and was slashed by half, 4 stake\n\t// bonded at the time of discovery hadn't been bonded at the time of infraction\n\t// and wasn't slashed\n\trequire.Equal(t, int64(7), validator.GetConsensusPower(app.StakingKeeper.PowerReduction(ctx)))\n\n\t// slash validator again\n\tctx = ctx.WithBlockHeight(13)\n\tapp.StakingKeeper.Slash(ctx, consAddr, 9, 10, fraction)\n\n\tubd, found = app.StakingKeeper.GetUnbondingDelegation(ctx, addrDels[0], addrVals[0])\n\trequire.True(t, found)\n\trequire.Len(t, ubd.Entries, 1)\n\n\t// balance decreased again\n\trequire.Equal(t, sdk.NewInt(0), ubd.Entries[0].Balance)\n\n\t// bonded tokens burned again\n\tnewBondedPoolBalances = app.BankKeeper.GetAllBalances(ctx, bondedPool.GetAddress())\n\tdiffTokens = oldBondedPoolBalances.Sub(newBondedPoolBalances).AmountOf(app.StakingKeeper.BondDenom(ctx))\n\trequire.Equal(t, app.StakingKeeper.TokensFromConsensusPower(ctx, 6), diffTokens)\n\n\t// read updated validator\n\tvalidator, found = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)\n\trequire.True(t, found)\n\n\t// power decreased by 3 again\n\trequire.Equal(t, int64(4), validator.GetConsensusPower(app.StakingKeeper.PowerReduction(ctx)))\n\n\t// slash validator again\n\t// all originally bonded stake has been slashed, so this will have no effect\n\t// on the unbonding delegation, but it will slash stake bonded since the infraction\n\t// this may not be the desirable behaviour, ref https://github.com/cosmos/cosmos-sdk/issues/1440\n\tctx = ctx.WithBlockHeight(13)\n\tapp.StakingKeeper.Slash(ctx, consAddr, 9, 10, fraction)\n\n\tubd, found = app.StakingKeeper.GetUnbondingDelegation(ctx, addrDels[0], addrVals[0])\n\trequire.True(t, found)\n\trequire.Len(t, ubd.Entries, 1)\n\n\t// balance unchanged\n\trequire.Equal(t, sdk.NewInt(0), ubd.Entries[0].Balance)\n\n\t// bonded tokens burned again\n\tnewBondedPoolBalances = app.BankKeeper.GetAllBalances(ctx, bondedPool.GetAddress())\n\tdiffTokens = oldBondedPoolBalances.Sub(newBondedPoolBalances).AmountOf(app.StakingKeeper.BondDenom(ctx))\n\trequire.Equal(t, app.StakingKeeper.TokensFromConsensusPower(ctx, 9), diffTokens)\n\n\t// read updated validator\n\tvalidator, found = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)\n\trequire.True(t, found)\n\n\t// power decreased by 3 again\n\trequire.Equal(t, int64(1), validator.GetConsensusPower(app.StakingKeeper.PowerReduction(ctx)))\n\n\t// slash validator again\n\t// all originally bonded stake has been slashed, so this will have no effect\n\t// on the unbonding delegation, but it will slash stake bonded since the infraction\n\t// this may not be the desirable behaviour, ref https://github.com/cosmos/cosmos-sdk/issues/1440\n\tctx = ctx.WithBlockHeight(13)\n\tapp.StakingKeeper.Slash(ctx, consAddr, 9, 10, fraction)\n\n\tubd, found = app.StakingKeeper.GetUnbondingDelegation(ctx, addrDels[0], addrVals[0])\n\trequire.True(t, found)\n\trequire.Len(t, ubd.Entries, 1)\n\n\t// balance unchanged\n\trequire.Equal(t, sdk.NewInt(0), ubd.Entries[0].Balance)\n\n\t// just 1 bonded token burned again since that's all the validator now has\n\tnewBondedPoolBalances = app.BankKeeper.GetAllBalances(ctx, bondedPool.GetAddress())\n\tdiffTokens = oldBondedPoolBalances.Sub(newBondedPoolBalances).AmountOf(app.StakingKeeper.BondDenom(ctx))\n\trequire.Equal(t, app.StakingKeeper.TokensFromConsensusPower(ctx, 10), diffTokens)\n\n\t// apply TM updates\n\tapplyValidatorSetUpdates(t, ctx, app.StakingKeeper, -1)\n\n\t// read updated validator\n\t// power decreased by 1 again, validator is out of stake\n\t// validator should be in unbonding period\n\tvalidator, _ = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)\n\trequire.Equal(t, validator.GetStatus(), types.Unbonding)\n}", "func (_DelegationController *DelegationControllerTransactor) AcceptPendingDelegation(opts *bind.TransactOpts, delegationId *big.Int) (*types.Transaction, error) {\n\treturn _DelegationController.contract.Transact(opts, \"acceptPendingDelegation\", delegationId)\n}", "func (rs *rootResolver) Delegation(args *struct {\n\tAddress common.Address\n\tStaker hexutil.Uint64\n}) (*Delegation, error) {\n\t// get the delegator detail from backend\n\td, err := rs.repo.Delegation(args.Address, args.Staker)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn NewDelegation(d, rs.repo), nil\n}", "func (acc *Account) delegationsTotal() (amount *big.Int, inWithdraw *big.Int, rewards *big.Int, err error) {\n\t// pull all the delegations of the account\n\tlist, err := repository.R().DelegationsByAddressAll(&acc.Address)\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\n\t// prep containers for calculation and loop all delegations found\n\tamount = new(big.Int)\n\trewards = new(big.Int)\n\tinWithdraw = new(big.Int)\n\tfor _, dlg := range list {\n\t\t// any active delegated amount?\n\t\tif 0 < dlg.AmountDelegated.ToInt().Uint64() {\n\t\t\tamount = new(big.Int).Add(amount, dlg.AmountDelegated.ToInt())\n\t\t}\n\n\t\t// get pending rewards for this delegation (can be stashed)\n\t\trw, err := repository.R().PendingRewards(&acc.Address, dlg.ToStakerId)\n\t\tif err != nil {\n\t\t\treturn nil, nil, nil, err\n\t\t}\n\n\t\t// any rewards?\n\t\tif 0 < rw.Amount.ToInt().Uint64() {\n\t\t\trewards = new(big.Int).Add(rewards, rw.Amount.ToInt())\n\t\t}\n\n\t\t// get pending withdrawals\n\t\twd, err := repository.R().WithdrawRequestsPendingTotal(&acc.Address, dlg.ToStakerId)\n\t\tif err != nil {\n\t\t\treturn nil, nil, nil, err\n\t\t}\n\n\t\t// add pending withdrawals value\n\t\tif 0 < wd.Uint64() {\n\t\t\tinWithdraw = new(big.Int).Add(inWithdraw, wd)\n\t\t}\n\t}\n\n\treturn amount, rewards, inWithdraw, nil\n}", "func (_DelegationController *DelegationControllerTransactor) GetAndUpdateDelegatedAmount(opts *bind.TransactOpts, holder common.Address) (*types.Transaction, error) {\n\treturn _DelegationController.contract.Transact(opts, \"getAndUpdateDelegatedAmount\", holder)\n}", "func (del Delegation) Amount() (hexutil.Big, error) {\n\t// get the base amount delegated\n\tbase, err := repository.R().DelegationAmountStaked(&del.Address, del.Delegation.ToStakerId)\n\tif err != nil {\n\t\treturn hexutil.Big{}, err\n\t}\n\n\t// get the sum of all pending withdrawals\n\twd, err := del.pendingWithdrawalsValue()\n\tif err != nil {\n\t\treturn hexutil.Big{}, err\n\t}\n\tval := new(big.Int).Add(base, wd)\n\treturn (hexutil.Big)(*val), nil\n}", "func distributeDelegatorRewards(ctx contract.Context, cachedDelegations *CachedDposStorage, formerValidatorTotals map[string]loom.BigUInt, delegatorRewards map[string]*loom.BigUInt, distributedRewards *loom.BigUInt) (map[string]*loom.BigUInt, error) {\n\tnewDelegationTotals := make(map[string]*loom.BigUInt)\n\n\tcandidates, err := LoadCandidateList(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Initialize delegation totals with whitelist amounts\n\tfor _, candidate := range candidates {\n\t\tstatistic, _ := GetStatistic(ctx, loom.UnmarshalAddressPB(candidate.Address))\n\n\t\tif statistic != nil && statistic.WhitelistAmount != nil && !common.IsZero(statistic.WhitelistAmount.Value) {\n\t\t\tvalidatorKey := loom.UnmarshalAddressPB(statistic.Address).String()\n\t\t\tamount := calculateWeightedWhitelistAmount(*statistic)\n\t\t\tnewDelegationTotals[validatorKey] = &amount\n\t\t}\n\t}\n\n\tdelegations, err := cachedDelegations.loadDelegationList(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar currentDelegations = make(DelegationList, len(delegations))\n\tcopy(currentDelegations, delegations)\n\tfor _, d := range currentDelegations {\n\t\tdelegation, err := GetDelegation(ctx, d.Index, *d.Validator, *d.Delegator)\n\t\tif err == contract.ErrNotFound {\n\t\t\tcontinue\n\t\t} else if err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tvalidatorKey := loom.UnmarshalAddressPB(delegation.Validator).String()\n\n\t\t// Do not distribute rewards to delegators of the Limbo validator\n\t\t// NOTE: because all delegations are sorted in reverse index order, the\n\t\t// 0-index delegation (for rewards) is handled last. Therefore, all\n\t\t// increases to reward delegations will be reflected in newDelegation\n\t\t// totals that are computed at the end of this for loop. (We do this to\n\t\t// avoid looping over all delegations twice)\n\t\tif loom.UnmarshalAddressPB(delegation.Validator).Compare(LimboValidatorAddress(ctx)) != 0 {\n\t\t\t// allocating validator distributions to delegators\n\t\t\t// based on former validator delegation totals\n\t\t\tdelegationTotal := formerValidatorTotals[validatorKey]\n\t\t\trewardsTotal := delegatorRewards[validatorKey]\n\t\t\tif rewardsTotal != nil {\n\t\t\t\tweightedDelegation := calculateWeightedDelegationAmount(*delegation)\n\t\t\t\tdelegatorDistribution := calculateShare(weightedDelegation, delegationTotal, *rewardsTotal)\n\t\t\t\t// increase a delegator's distribution\n\t\t\t\tdistributedRewards.Add(distributedRewards, &delegatorDistribution)\n\t\t\t\tcachedDelegations.IncreaseRewardDelegation(ctx, delegation.Validator, delegation.Delegator, delegatorDistribution)\n\n\t\t\t\t// If the reward delegation is updated by the\n\t\t\t\t// IncreaseRewardDelegation command, we must be sure to use this\n\t\t\t\t// updated version in the rest of the loop. No other delegations\n\t\t\t\t// (non-rewards) have the possibility of being updated outside\n\t\t\t\t// of this loop.\n\t\t\t\tif ctx.FeatureEnabled(features.DPOSVersion3_1, false) && d.Index == REWARD_DELEGATION_INDEX {\n\t\t\t\t\tdelegation, err = GetDelegation(ctx, d.Index, *d.Validator, *d.Delegator)\n\t\t\t\t\tif err == contract.ErrNotFound {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t} else if err != nil {\n\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tupdatedAmount := common.BigZero()\n\t\tif delegation.State == BONDING {\n\t\t\tupdatedAmount.Add(&delegation.Amount.Value, &delegation.UpdateAmount.Value)\n\t\t\tdelegation.Amount = &types.BigUInt{Value: *updatedAmount}\n\t\t} else if delegation.State == UNBONDING {\n\t\t\tupdatedAmount.Sub(&delegation.Amount.Value, &delegation.UpdateAmount.Value)\n\t\t\tdelegation.Amount = &types.BigUInt{Value: *updatedAmount}\n\t\t\tcoin, err := loadCoin(ctx)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\terr = coin.Transfer(loom.UnmarshalAddressPB(delegation.Delegator), &delegation.UpdateAmount.Value)\n\t\t\tif err != nil {\n\t\t\t\ttransferFromErr := fmt.Sprintf(\"Failed coin Transfer - distributeDelegatorRewards, %v, %s\", delegation.Delegator.String(), delegation.UpdateAmount.Value.String())\n\t\t\t\treturn nil, logDposError(ctx, err, transferFromErr)\n\t\t\t}\n\t\t} else if delegation.State == REDELEGATING {\n\t\t\tif err = cachedDelegations.DeleteDelegation(ctx, delegation); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tdelegation.Validator = delegation.UpdateValidator\n\t\t\tdelegation.Amount = delegation.UpdateAmount\n\t\t\tdelegation.LocktimeTier = delegation.UpdateLocktimeTier\n\n\t\t\tindex, err := GetNextDelegationIndex(ctx, *delegation.Validator, *delegation.Delegator)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tdelegation.Index = index\n\n\t\t\tvalidatorKey = loom.UnmarshalAddressPB(delegation.Validator).String()\n\t\t}\n\n\t\t// Delete any delegation whose full amount has been unbonded. In all\n\t\t// other cases, update the delegation state to BONDED and reset its\n\t\t// UpdateAmount\n\t\tif common.IsZero(delegation.Amount.Value) && delegation.State == UNBONDING {\n\t\t\tif err := cachedDelegations.DeleteDelegation(ctx, delegation); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t} else {\n\t\t\t// After a delegation update, zero out UpdateAmount\n\t\t\tdelegation.UpdateAmount = loom.BigZeroPB()\n\t\t\tdelegation.State = BONDED\n\n\t\t\tresetDelegationIfExpired(ctx, delegation)\n\t\t\tif err := cachedDelegations.SetDelegation(ctx, delegation); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\n\t\t// Calculate delegation totals for all validators except the Limbo\n\t\t// validator\n\t\tif loom.UnmarshalAddressPB(delegation.Validator).Compare(LimboValidatorAddress(ctx)) != 0 {\n\t\t\tnewTotal := common.BigZero()\n\t\t\tweightedDelegation := calculateWeightedDelegationAmount(*delegation)\n\t\t\tnewTotal.Add(newTotal, &weightedDelegation)\n\t\t\tif newDelegationTotals[validatorKey] != nil {\n\t\t\t\tnewTotal.Add(newTotal, newDelegationTotals[validatorKey])\n\t\t\t}\n\t\t\tnewDelegationTotals[validatorKey] = newTotal\n\t\t}\n\t}\n\n\treturn newDelegationTotals, nil\n}", "func (a *Account) Track() {\n\t// Request notifications for transactions sending to all wallet\n\t// addresses.\n\taddrs := a.ActiveAddresses()\n\taddrstrs := make([]string, len(addrs))\n\ti := 0\n\tfor addr := range addrs {\n\t\taddrstrs[i] = addr.EncodeAddress()\n\t\ti++\n\t}\n\n\terr := NotifyNewTXs(CurrentServerConn(), addrstrs)\n\tif err != nil {\n\t\tlog.Error(\"Unable to request transaction updates for address.\")\n\t}\n\n\tfor _, txout := range a.TxStore.UnspentOutputs() {\n\t\tReqSpentUtxoNtfn(txout)\n\t}\n}", "func (m *mParcelMockDelegationToken) Set(f func() (r insolar.DelegationToken)) *ParcelMock {\n\tm.mainExpectation = nil\n\tm.expectationSeries = nil\n\n\tm.mock.DelegationTokenFunc = f\n\treturn m.mock\n}", "func (bva BaseVestingAccount) GetDelegatedVesting() sdk.Coins {\n\treturn bva.DelegatedVesting\n}", "func (n *Node) BecomeDelegator(genesisAmount uint64, seedAmount uint64, delegatorAmount uint64, txFee uint64, stakerNodeID string) *Node {\n\n\t// exports AVAX from the X Chain\n\texportTxID, err := n.client.XChainAPI().ExportAVAX(\n\t\tn.UserPass,\n\t\tnil, // from addrs\n\t\t\"\", // change addr\n\t\tseedAmount+txFee,\n\t\tn.PAddress,\n\t)\n\tif err != nil {\n\t\tpanic(stacktrace.Propagate(err, \"Failed to export AVAX to pchainAddress %s\", n.PAddress))\n\t\treturn n\n\t}\n\n\t// waits Tx acceptance in the XChain\n\terr = chainhelper.XChain().AwaitTransactionAcceptance(n.client, exportTxID, constants.TimeoutDuration)\n\tif err != nil {\n\t\tpanic(err)\n\t\treturn n\n\t}\n\n\t// imports the amount to the P Chain\n\timportTxID, err := n.client.PChainAPI().ImportAVAX(\n\t\tn.UserPass,\n\t\tnil, // from addrs\n\t\t\"\", // change addr\n\t\tn.PAddress,\n\t\tconstants.XChainID.String(),\n\t)\n\tif err != nil {\n\t\tpanic(stacktrace.Propagate(err, \"Failed import AVAX to pchainAddress %s\", n.PAddress))\n\t\treturn n\n\t}\n\n\t// waits Tx acceptance in the PChain\n\terr = chainhelper.PChain().AwaitTransactionAcceptance(n.client, importTxID, constants.TimeoutDuration)\n\tif err != nil {\n\t\tpanic(err)\n\t\treturn n\n\t}\n\n\t// verify the PChain balance (seedAmount+txFee-txFee)\n\terr = chainhelper.PChain().CheckBalance(n.client, n.PAddress, seedAmount)\n\tif err != nil {\n\t\tpanic(stacktrace.Propagate(err, \"expected balance of seedAmount exists in the PChain\"))\n\t\treturn n\n\t}\n\n\t// verify the XChain balance of genesisAmount - seedAmount - txFee - txFee (import PChain)\n\terr = chainhelper.XChain().CheckBalance(n.client, n.XAddress, \"AVAX\", genesisAmount-seedAmount-2*txFee)\n\tif err != nil {\n\t\tpanic(stacktrace.Propagate(err, \"expected balance XChain balance of genesisAmount-seedAmount-txFee\"))\n\t\treturn n\n\t}\n\n\tdelegatorStartTime := time.Now().Add(20 * time.Second)\n\tstartTime := uint64(delegatorStartTime.Unix())\n\tendTime := uint64(delegatorStartTime.Add(36 * time.Hour).Unix())\n\taddDelegatorTxID, err := n.client.PChainAPI().AddDelegator(\n\t\tn.UserPass,\n\t\tnil, // from addrs\n\t\t\"\", // change addr\n\t\tn.PAddress,\n\t\tstakerNodeID,\n\t\tdelegatorAmount,\n\t\tstartTime,\n\t\tendTime,\n\t)\n\tif err != nil {\n\t\tpanic(stacktrace.Propagate(err, \"Failed to add delegator %s\", n.PAddress))\n\t\treturn n\n\t}\n\n\terr = chainhelper.PChain().AwaitTransactionAcceptance(n.client, addDelegatorTxID, constants.TimeoutDuration)\n\tif err != nil {\n\t\tpanic(stacktrace.Propagate(err, \"Failed to accept AddDelegator tx: %s\", addDelegatorTxID))\n\t\treturn n\n\t}\n\n\t// Sleep until delegator starts validating\n\ttime.Sleep(time.Until(delegatorStartTime) + 3*time.Second)\n\n\texpectedDelegatorBalance := seedAmount - delegatorAmount\n\terr = chainhelper.PChain().CheckBalance(n.client, n.PAddress, expectedDelegatorBalance)\n\tif err != nil {\n\t\tpanic(stacktrace.Propagate(err, \"Unexpected P Chain Balance after adding a new delegator to the network.\"))\n\t\treturn n\n\t}\n\tlogrus.Infof(\"Added delegator to subnet and verified the expected P Chain balance.\")\n\n\treturn n\n}", "func (_DelegationController *DelegationControllerSession) Delegations(arg0 *big.Int) (struct {\n\tHolder common.Address\n\tValidatorId *big.Int\n\tAmount *big.Int\n\tDelegationPeriod *big.Int\n\tCreated *big.Int\n\tStarted *big.Int\n\tFinished *big.Int\n\tInfo string\n}, error) {\n\treturn _DelegationController.Contract.Delegations(&_DelegationController.CallOpts, arg0)\n}", "func (_TransferProxyRegistry *TransferProxyRegistryCaller) CountDelegates(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _TransferProxyRegistry.contract.Call(opts, &out, \"countDelegates\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (a *Account) Track() {\n\trpcc, err := accessClient()\n\tif err != nil {\n\t\tlog.Errorf(\"No chain server client to track addresses.\")\n\t\treturn\n\t}\n\n\t// Request notifications for transactions sending to all wallet\n\t// addresses.\n\t//\n\t// TODO: return as slice? (doesn't have to be ordered, or\n\t// SortedActiveAddresses would be fine.)\n\taddrMap := a.KeyStore.ActiveAddresses()\n\taddrs := make([]btcutil.Address, 0, len(addrMap))\n\tfor addr := range addrMap {\n\t\taddrs = append(addrs, addr)\n\t}\n\n\tif err := rpcc.NotifyReceived(addrs); err != nil {\n\t\tlog.Error(\"Unable to request transaction updates for address.\")\n\t}\n\n\tunspent, err := a.TxStore.UnspentOutputs()\n\tif err != nil {\n\t\tlog.Errorf(\"Unable to access unspent outputs: %v\", err)\n\t\treturn\n\t}\n\tReqSpentUtxoNtfns(unspent)\n}", "func (_DelegationController *DelegationControllerCallerSession) Delegations(arg0 *big.Int) (struct {\n\tHolder common.Address\n\tValidatorId *big.Int\n\tAmount *big.Int\n\tDelegationPeriod *big.Int\n\tCreated *big.Int\n\tStarted *big.Int\n\tFinished *big.Int\n\tInfo string\n}, error) {\n\treturn _DelegationController.Contract.Delegations(&_DelegationController.CallOpts, arg0)\n}", "func (_DelegationController *DelegationControllerCaller) Delegations(opts *bind.CallOpts, arg0 *big.Int) (struct {\n\tHolder common.Address\n\tValidatorId *big.Int\n\tAmount *big.Int\n\tDelegationPeriod *big.Int\n\tCreated *big.Int\n\tStarted *big.Int\n\tFinished *big.Int\n\tInfo string\n}, error) {\n\tret := new(struct {\n\t\tHolder common.Address\n\t\tValidatorId *big.Int\n\t\tAmount *big.Int\n\t\tDelegationPeriod *big.Int\n\t\tCreated *big.Int\n\t\tStarted *big.Int\n\t\tFinished *big.Int\n\t\tInfo string\n\t})\n\tout := ret\n\terr := _DelegationController.contract.Call(opts, out, \"delegations\", arg0)\n\treturn *ret, err\n}", "func (pm *DPoSProtocolManager) syncDelegatedNodeSafely() {\n\tif !pm.isDelegatedNode() {\n\t\t// only candidate node is able to participant to this process.\n\t\treturn;\n\t}\n\tpm.lock.Lock()\n\tdefer pm.lock.Unlock()\n\tlog.Info(\"Preparing for next big period...\");\n\t// pull the newest delegators from voting contract.\n\ta, b, err0 := VotingAccessor.Refresh()\n\tif err0 != nil {\n\t\tlog.Error(err0.Error())\n\t\treturn;\n\t}\n\tDelegatorsTable = a\n\tDelegatorNodeInfo = b\n\tif uint8(len(GigPeriodHistory)) >= BigPeriodHistorySize {\n\t\tGigPeriodHistory = GigPeriodHistory[1:] //remove the first old one.\n\t}\n\tif len(DelegatorsTable) == 0 || pm.ethManager.peers.Len() == 0 {\n\t\tlog.Info(\"Sorry, could not detect any delegator!\");\n\t\treturn;\n\t}\n\tround := uint64(1)\n\tactiveTime := uint64(time.Now().Unix() + int64(GigPeriodInterval))\n\tif NextGigPeriodInstance != nil {\n\t\tif !TestMode {\n\t\t\tgap := int64(NextGigPeriodInstance.activeTime) - time.Now().Unix()\n\t\t\tif gap > 2 || gap < -2 {\n\t\t\t\tlog.Warn(fmt.Sprintf(\"Scheduling of the new electing round is improper! current gap: %v seconds\", gap))\n\t\t\t\t//restart the scheduler\n\t\t\t\tNextElectionInfo = nil;\n\t\t\t\tgo pm.syncDelegatedNodeSafely();\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\tround = NextGigPeriodInstance.round + 1\n\t\tactiveTime = GigPeriodInstance.activeTime + uint64(GigPeriodInterval)\n\t\t// keep the big period history for block validation.\n\t\tGigPeriodHistory[len(GigPeriodHistory)-1] = *NextGigPeriodInstance;\n\n\t\tGigPeriodInstance = &GigPeriodTable{\n\t\t\tNextGigPeriodInstance.round,\n\t\t\tNextGigPeriodInstance.state,\n\t\t\tNextGigPeriodInstance.delegatedNodes,\n\t\t\tNextGigPeriodInstance.delegatedNodesSign,\n\t\t\tNextGigPeriodInstance.confirmedTickets,\n\t\t\tNextGigPeriodInstance.confirmedBestNode,\n\t\t\tNextGigPeriodInstance.activeTime,\n\t\t};\n\t\tlog.Info(fmt.Sprintf(\"Switched the new big period round. %d \", GigPeriodInstance.round));\n\t}\n\n\t// make sure all delegators are synced at this round.\n\tNextGigPeriodInstance = &GigPeriodTable{\n\t\tround,\n\t\tSTATE_LOOKING,\n\t\tDelegatorsTable,\n\t\tSignCandidates(DelegatorsTable),\n\t\tmake(map[string]uint32),\n\t\tmake(map[string]*GigPeriodTable),\n\t\tactiveTime,\n\t};\n\tpm.trySyncAllDelegators()\n}", "func (k Querier) Delegation(ctx context.Context, req *types.QueryDelegationRequest) (*types.QueryDelegationResponse, error) {\n\tif req == nil {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"empty request\")\n\t}\n\n\tif req.DelegatorAddr == \"\" {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"delegator address cannot be empty\")\n\t}\n\tif req.ValidatorAddr == \"\" {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"validator address cannot be empty\")\n\t}\n\n\tdelAddr, err := k.authKeeper.AddressCodec().StringToBytes(req.DelegatorAddr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvalAddr, err := k.validatorAddressCodec.StringToBytes(req.ValidatorAddr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdelegation, err := k.Delegations.Get(ctx, collections.Join(sdk.AccAddress(delAddr), sdk.ValAddress(valAddr)))\n\tif err != nil {\n\t\tif errors.Is(err, collections.ErrNotFound) {\n\t\t\treturn nil, status.Errorf(\n\t\t\t\tcodes.NotFound,\n\t\t\t\t\"delegation with delegator %s not found for validator %s\",\n\t\t\t\treq.DelegatorAddr, req.ValidatorAddr)\n\t\t}\n\t\treturn nil, status.Error(codes.Internal, err.Error())\n\t}\n\n\tdelResponse, err := delegationToDelegationResponse(ctx, k.Keeper, delegation)\n\tif err != nil {\n\t\treturn nil, status.Error(codes.Internal, err.Error())\n\t}\n\n\treturn &types.QueryDelegationResponse{DelegationResponse: &delResponse}, nil\n}", "func (ac *Accumulator) WithTracking(max int) telegraf.TrackingAccumulator {\n\treturn &TrackingAccumulator{\n\t\tAccumulator: ac,\n\t\tdone: make(chan telegraf.DeliveryInfo, max),\n\t}\n}", "func (_DelegationController *DelegationControllerCaller) DelegationsByHolder(opts *bind.CallOpts, arg0 common.Address, arg1 *big.Int) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _DelegationController.contract.Call(opts, out, \"delegationsByHolder\", arg0, arg1)\n\treturn *ret0, err\n}", "func (_DelegationController *DelegationControllerTransactorSession) AcceptPendingDelegation(delegationId *big.Int) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.AcceptPendingDelegation(&_DelegationController.TransactOpts, delegationId)\n}", "func TestApplyChangelistCreatesDelegation(t *testing.T) {\n\trepo, cs, err := testutils.EmptyRepo(\"docker.com/notary\")\n\trequire.NoError(t, err)\n\n\tnewKey, err := cs.Create(\"targets/level1\", \"docker.com/notary\", data.ED25519Key)\n\trequire.NoError(t, err)\n\n\terr = repo.UpdateDelegationKeys(\"targets/level1\", []data.PublicKey{newKey}, []string{}, 1)\n\trequire.NoError(t, err)\n\terr = repo.UpdateDelegationPaths(\"targets/level1\", []string{\"\"}, []string{}, false)\n\trequire.NoError(t, err)\n\tdelete(repo.Targets, \"targets/level1\")\n\n\thash := sha256.Sum256([]byte{})\n\tf := &data.FileMeta{\n\t\tLength: 1,\n\t\tHashes: map[string][]byte{\n\t\t\t\"sha256\": hash[:],\n\t\t},\n\t}\n\tfjson, err := json.Marshal(f)\n\trequire.NoError(t, err)\n\n\tcl := changelist.NewMemChangelist()\n\trequire.NoError(t, cl.Add(&changelist.TUFChange{\n\t\tActn: changelist.ActionCreate,\n\t\tRole: \"targets/level1\",\n\t\tChangeType: \"target\",\n\t\tChangePath: \"latest\",\n\t\tData: fjson,\n\t}))\n\n\trequire.NoError(t, applyChangelist(repo, nil, cl))\n\t_, ok := repo.Targets[\"targets/level1\"]\n\trequire.True(t, ok, \"Failed to create the delegation target\")\n\t_, ok = repo.Targets[\"targets/level1\"].Signed.Targets[\"latest\"]\n\trequire.True(t, ok, \"Failed to write change to delegation target\")\n}", "func CalculateRollSpillage(delegatedContracts []DelegatedContract, delegateAddr string, cycle int) ([]DelegatedContract, error) {\n stakingBalance, err := GetDelegateStakingBalance(delegateAddr, cycle)\n if (err != nil){\n return delegatedContracts, errors.New(\"func CalculateRollSpillage(delegatedContracts []DelegatedContract, delegateAddr string) failed: \" + err.Error())\n }\n\n mod := math.Mod(stakingBalance, 10000)\n sum := mod * 10000\n\n for index, delegatedContract := range delegatedContracts{\n for i, contract := range delegatedContract.Contracts{\n if (contract.Cycle == cycle){\n stakingBalance = stakingBalance - contract.Amount\n if (stakingBalance < 0){\n delegatedContracts[index].Contracts[i].SharePercentage = (contract.Amount - stakingBalance) / sum\n }\n }\n }\n }\n\n return delegatedContracts, nil\n}", "func (_Bep20 *Bep20Transactor) Delegate(opts *bind.TransactOpts, delegatee common.Address) (*types.Transaction, error) {\n\treturn _Bep20.contract.Transact(opts, \"delegate\", delegatee)\n}", "func (_Bep20 *Bep20Session) DelegateBySig(delegatee common.Address, nonce *big.Int, expiry *big.Int, v uint8, r [32]byte, s [32]byte) (*types.Transaction, error) {\n\treturn _Bep20.Contract.DelegateBySig(&_Bep20.TransactOpts, delegatee, nonce, expiry, v, r, s)\n}", "func (_DelegationController *DelegationControllerSession) AcceptPendingDelegation(delegationId *big.Int) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.AcceptPendingDelegation(&_DelegationController.TransactOpts, delegationId)\n}", "func UnmarshalDelegation(cdc *codec.Codec, key, value []byte) (delegation Delegation, err error) {\n\tvar storeValue delegationValue\n\terr = cdc.UnmarshalBinaryLengthPrefixed(value, &storeValue)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"%v: %v\", ErrNoDelegation(DefaultCodespace).Data(), err)\n\t\treturn\n\t}\n\n\taddrs := key[1:] // remove prefix bytes\n\tif len(addrs) != 2*sdk.AddrLen {\n\t\terr = fmt.Errorf(\"%v\", ErrBadDelegationAddr(DefaultCodespace).Data())\n\t\treturn\n\t}\n\n\tdelAddr := sdk.AccAddress(addrs[:sdk.AddrLen])\n\tvalAddr := sdk.ValAddress(addrs[sdk.AddrLen:])\n\n\treturn Delegation{\n\t\tDelegatorAddr: delAddr,\n\t\tValidatorAddr: valAddr,\n\t\tShares: storeValue.Shares,\n\t}, nil\n}", "func (_DelegationController *DelegationControllerSession) DelegationsByHolder(arg0 common.Address, arg1 *big.Int) (*big.Int, error) {\n\treturn _DelegationController.Contract.DelegationsByHolder(&_DelegationController.CallOpts, arg0, arg1)\n}", "func SendPayments() {\n\tif !checkConfigSharingRatio() {\n\t\tlogger.Fatal(\"Unable to calculcate.\")\n\t}\n\n\tpubKey := viper.GetString(\"delegate.pubkey\")\n\tif core.EnvironmentParams.Network.Type == core.DEVNET {\n\t\tpubKey = viper.GetString(\"delegate.Dpubkey\")\n\t}\n\n\tparams := core.DelegateQueryParams{PublicKey: pubKey}\n\tvar payload core.TransactionPayload\n\n\tvotersEarnings := arkclient.CalculateVotersProfit(params, viper.GetFloat64(\"voters.shareratio\"))\n\n\tsumEarned := 0.0\n\tsumRatio := 0.0\n\tsumShareEarned := 0.0\n\n\tp1, p2 := \"\", \"\"\n\tif _, err := os.Stat(\"/path/to/whatever\"); err == nil {\n\t\t// path/to/whatever exists\n\t} else {\n\t\tp1, p2 = readAccountData()\n\t}\n\n\tclearScreen()\n\n\tfor _, element := range votersEarnings {\n\t\tsumEarned += element.EarnedAmount100\n\t\tsumShareEarned += element.EarnedAmountXX\n\t\tsumRatio += element.VoteWeightShare\n\n\t\t//transaction parameters\n\t\ttxAmount2Send := int64(element.EarnedAmountXX*core.SATOSHI) - core.EnvironmentParams.Fees.Send\n\t\ttx := core.CreateTransaction(element.Address, txAmount2Send, viper.GetString(\"voters.txdescription\"), p1, p2)\n\n\t\tpayload.Transactions = append(payload.Transactions, tx)\n\t}\n\n\t//Cost & reserve fund calculation\n\tcostAmount := sumEarned * viper.GetFloat64(\"costs.shareratio\")\n\treserveAmount := sumEarned * viper.GetFloat64(\"reserve.shareratio\")\n\n\t//summary and conversion checks\n\tif (costAmount + reserveAmount + sumShareEarned) != sumEarned {\n\t\tcolor.Set(color.FgHiRed)\n\t\tlog.Println(\"Calculation of ratios NOT OK - overall summary failing\")\n\t\tlogger.Println(\"Calculation of ratios NOT OK - overall summary failing\")\n\t}\n\n\tcostAmount2Send := int64(costAmount*core.SATOSHI) - core.EnvironmentParams.Fees.Send\n\tcostAddress := viper.GetString(\"costs.address\")\n\tif core.EnvironmentParams.Network.Type == core.DEVNET {\n\t\tcostAddress = viper.GetString(\"costs.Daddress\")\n\t}\n\ttxCosts := core.CreateTransaction(costAddress, costAmount2Send, viper.GetString(\"costs.txdescription\"), p1, p2)\n\tpayload.Transactions = append(payload.Transactions, txCosts)\n\n\treserveAddress := viper.GetString(\"reserve.address\")\n\tif core.EnvironmentParams.Network.Type == core.DEVNET {\n\t\treserveAddress = viper.GetString(\"reserve.Daddress\")\n\t}\n\treserveAmount2Send := int64(reserveAmount*core.SATOSHI) - core.EnvironmentParams.Fees.Send\n\n\ttxReserve := core.CreateTransaction(reserveAddress, reserveAmount2Send, viper.GetString(\"reserve.txdescription\"), p1, p2)\n\tpayload.Transactions = append(payload.Transactions, txReserve)\n\n\tcolor.Set(color.FgHiGreen)\n\tfmt.Println(\"--------------------------------------------------------------------------------------------------------------\")\n\tfmt.Println(\"Transactions to be sent:\")\n\tfmt.Println(\"--------------------------------------------------------------------------------------------------------------\")\n\tcolor.Set(color.FgHiCyan)\n\tfor _, el := range payload.Transactions {\n\t\ts := fmt.Sprintf(\"|%s|%15d| %-40s|\", el.RecipientID, el.Amount, el.VendorField)\n\t\tfmt.Println(s)\n\t\tlogger.Println(s)\n\t}\n\n\tcolor.Set(color.FgHiYellow)\n\tfmt.Println(\"\")\n\tfmt.Println(\"--------------------------------------------------------------------------------------------------------------\")\n\tfmt.Print(\"Send transactions and complete reward payments [Y/N]: \")\n\n\tc, _ := reader.ReadByte()\n\n\tif c == []byte(\"Y\")[0] || c == []byte(\"y\")[0] {\n\t\tfmt.Println(\"Sending rewards to voters and sharing accounts.............\")\n\n\t\tres, httpresponse, err := arkclient.PostTransaction(payload)\n\t\tif res.Success {\n\t\t\tcolor.Set(color.FgHiGreen)\n\t\t\tlogger.Println(\"Transactions sent with Success,\", httpresponse.Status, res.TransactionIDs)\n\t\t\tlog.Println(\"Transactions sent with Success,\", httpresponse.Status)\n\t\t\tlog.Println(\"Audit log of sent transactions is in file paymentLog.csv!\")\n\t\t\tlog2csv(payload, res.TransactionIDs, votersEarnings)\n\t\t} else {\n\t\t\tcolor.Set(color.FgHiRed)\n\t\t\tlogger.Println(res.Message, res.Error, httpresponse.Status, err.Error())\n\t\t\tfmt.Println()\n\t\t\tfmt.Println(\"Failed\", res.Error)\n\t\t}\n\t\treader.ReadString('\\n')\n\t\tpause()\n\t}\n}", "func (p *Protocol) NumCandidateDelegates() uint64 {\n\treturn p.numCandidateDelegates\n}", "func (_DelegationController *DelegationControllerRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.DelegationControllerTransactor.contract.Transfer(opts)\n}", "func StoreDelegationFromMessage(\n\theight int64, msg *stakingtypes.MsgDelegate, stakingClient stakingtypes.QueryClient, db *database.Db,\n) error {\n\theader := client.GetHeightRequestHeader(height)\n\tres, err := stakingClient.Delegation(\n\t\tcontext.Background(),\n\t\t&stakingtypes.QueryDelegationRequest{\n\t\t\tDelegatorAddr: msg.DelegatorAddress,\n\t\t\tValidatorAddr: msg.ValidatorAddress,\n\t\t},\n\t\theader,\n\t)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdelegation := ConvertDelegationResponse(height, *res.DelegationResponse)\n\treturn db.SaveDelegations([]types.Delegation{delegation})\n}", "func MustMarshalDelegation(cdc *codec.Codec, delegation Delegation) []byte {\n\tval := delegationValue{\n\t\tdelegation.Shares,\n\t}\n\treturn cdc.MustMarshalBinaryLengthPrefixed(val)\n}", "func (_DelegationController *DelegationControllerTransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.contract.Transfer(opts)\n}", "func (m *ParcelMock) DelegationTokenMinimockCounter() uint64 {\n\treturn atomic.LoadUint64(&m.DelegationTokenCounter)\n}", "func (s *ArkClient) GetDelegateVoteWeight(params DelegateQueryParams) (int, *http.Response, error) {\n\trespData := new(DelegateVoters)\n\trespError := new(ArkApiResponseError)\n\tresp, err := s.sling.New().Get(\"api/delegates/voters\").QueryStruct(&params).Receive(respData, respError)\n\tif err == nil {\n\t\terr = respError\n\t}\n\n\t//calculating vote weight\n\tbalance := 0\n\tif respData.Success {\n\t\tfor _, element := range respData.Accounts {\n\t\t\tintBalance, _ := strconv.Atoi(element.Balance)\n\t\t\tbalance += intBalance\n\t\t}\n\t}\n\n\treturn balance, resp, err\n}", "func (_DelegationController *DelegationControllerTransactor) Confiscate(opts *bind.TransactOpts, validatorId *big.Int, amount *big.Int) (*types.Transaction, error) {\n\treturn _DelegationController.contract.Transact(opts, \"confiscate\", validatorId, amount)\n}", "func (_Bep20 *Bep20TransactorSession) DelegateBySig(delegatee common.Address, nonce *big.Int, expiry *big.Int, v uint8, r [32]byte, s [32]byte) (*types.Transaction, error) {\n\treturn _Bep20.Contract.DelegateBySig(&_Bep20.TransactOpts, delegatee, nonce, expiry, v, r, s)\n}", "func Transfer(\n\tctx *vm.Context, db vm.StateDB, sender, recipient types.AddressHash, amount *big.Int,\n) {\n\t// NOTE: amount is a re-used pointer varaible\n\tdb.SubBalance(sender, amount)\n\tdb.AddBalance(recipient, amount)\n\tif db.IsContractAddr(sender) && amount.Uint64() > 0 {\n\t\ttransferInfo := vm.NewTransferInfo(sender, recipient, amount.Uint64())\n\t\tlogger.Debugf(\"new transfer info: sender: %x, recipient: %x, amount: %d\",\n\t\t\tsender[:], recipient[:], amount)\n\t\tif v, ok := ctx.Transfers[sender]; ok {\n\t\t\t// if sender and recipient already exists in Transfers, update it instead\n\t\t\t// of append to it\n\t\t\tfor _, w := range v {\n\t\t\t\tif w.To == recipient {\n\t\t\t\t\t// NOTE: cannot miss 'w.value = '\n\t\t\t\t\tw.Value += amount.Uint64()\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tctx.Transfers[sender] = append(ctx.Transfers[sender], transferInfo)\n\t}\n}", "func (o *Member) SetDelegateCur(v int32) {\n\to.DelegateCur = &v\n}", "func (_DelegationController *DelegationControllerCallerSession) DelegationsByHolder(arg0 common.Address, arg1 *big.Int) (*big.Int, error) {\n\treturn _DelegationController.Contract.DelegationsByHolder(&_DelegationController.CallOpts, arg0, arg1)\n}", "func (vi *votedInfo) CalculateReward(multiplier, divider *big.Int, period int) {\n\tif multiplier.Sign() == 0 || period == 0 {\n\t\treturn\n\t}\n\tif divider.Sign() == 0 || vi.totalBondedDelegation.Sign() == 0 {\n\t\treturn\n\t}\n\t// reward = multiplier * period * bondedDelegation / (divider * totalBondedDelegation)\n\tbase := new(big.Int).Mul(multiplier, big.NewInt(int64(period)))\n\treward := new(big.Int)\n\tfor i, addrKey := range vi.rank {\n\t\tif i == vi.maxRankForReward {\n\t\t\tbreak\n\t\t}\n\t\tprep := vi.preps[addrKey]\n\t\tif prep.Enable() == false {\n\t\t\tcontinue\n\t\t}\n\n\t\treward.Mul(base, prep.GetBondedDelegation())\n\t\treward.Div(reward, divider)\n\t\treward.Div(reward, vi.totalBondedDelegation)\n\n\t\tlog.Tracef(\"VOTED REWARD %d = %d * %d * %d / (%d * %d)\",\n\t\t\treward, multiplier, period, prep.GetBondedDelegation(), divider, vi.totalBondedDelegation)\n\n\t\tprep.SetIScore(new(big.Int).Add(prep.IScore(), reward))\n\t}\n}", "func TestDonationCase1(t *testing.T) {\n\tassert := assert.New(t)\n\tstore := newReputationStoreOnMock()\n\trep := NewTestReputationImpl(store)\n\tt1 := time.Date(1995, time.February, 5, 11, 11, 0, 0, time.UTC)\n\tt3 := time.Date(1995, time.February, 6, 12, 11, 0, 0, time.UTC)\n\tt4 := time.Date(1995, time.February, 7, 13, 11, 1, 0, time.UTC)\n\tuser1 := \"user1\"\n\tpost1 := \"post1\"\n\tpost2 := \"post2\"\n\n\t// round 2\n\trep.Update(t1.Unix())\n\trep.DonateAt(user1, post1, big.NewInt(100*OneLinoCoin))\n\tassert.Equal(big.NewInt(100*OneLinoCoin), rep.store.GetRoundPostSumStake(2, post1))\n\tassert.Equal(rep.GetReputation(user1), big.NewInt(InitialCustomerScore))\n\tassert.Equal(big.NewInt(OneLinoCoin), rep.store.GetRoundSumDp(2)) // bounded by this user's dp\n\n\t// round 3\n\trep.Update(t3.Unix())\n\t// (1 * 9 + 100) / 10\n\tassert.Equal(big.NewInt(1090000), rep.GetReputation(user1))\n\tassert.Equal(big.NewInt(OneLinoCoin), rep.GetSumRep(post1))\n\trep.DonateAt(user1, post1, big.NewInt(1*OneLinoCoin)) // does not count\n\trep.DonateAt(user1, post2, big.NewInt(900*OneLinoCoin))\n\trep.Update(t4.Unix())\n\t// (10.9 * 9 + 900) / 10\n\tassert.Equal(big.NewInt(9981000), rep.GetReputation(user1))\n\tassert.Equal([]Pid{post2}, rep.store.GetRoundResult(3))\n\t// round 4\n}", "func (s *Streams) Delegate(data interface{}) {\n\tlisteners := s.Size()\n\n\tif listeners <= 0 {\n\t\treturn\n\t}\n\n\tif s.reverse {\n\t\ts.RevMunch(data)\n\t} else {\n\t\ts.Munch(data)\n\t}\n\n}", "func bindDelegationController(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) {\n\tparsed, err := abi.JSON(strings.NewReader(DelegationControllerABI))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn bind.NewBoundContract(address, parsed, caller, transactor, filterer), nil\n}", "func (_DelegationController *DelegationControllerSession) GetAndUpdateDelegatedAmount(holder common.Address) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.GetAndUpdateDelegatedAmount(&_DelegationController.TransactOpts, holder)\n}", "func CheckPercentageSumForCycle(cycle int, delegatedContracts []DelegatedContract) float64{\n var sum float64\n sum = 0\n for x := 0; x < len(delegatedContracts); x++{\n counter := 0\n for y := 0; y < len(delegatedContracts[x].Contracts); y++{\n if (delegatedContracts[x].Contracts[y].Cycle == cycle){\n break\n }\n counter = counter + 1\n }\n\n sum = sum + delegatedContracts[x].Contracts[counter].SharePercentage\n }\n return sum\n}" ]
[ "0.8186739", "0.78986955", "0.7758992", "0.7719915", "0.771544", "0.76586753", "0.68335116", "0.6127206", "0.57611525", "0.5744714", "0.55410737", "0.54945636", "0.53738403", "0.525632", "0.51828635", "0.5127563", "0.50054365", "0.49724385", "0.48735827", "0.47643253", "0.47592086", "0.47452763", "0.47430617", "0.47186527", "0.47163785", "0.46777984", "0.4667469", "0.46416298", "0.46373415", "0.46287012", "0.46216467", "0.4617887", "0.45736095", "0.4554503", "0.45433795", "0.4504223", "0.44952923", "0.44740695", "0.44492382", "0.44422507", "0.44178447", "0.44167107", "0.44124287", "0.44094008", "0.43884954", "0.43874386", "0.43857923", "0.43848667", "0.43704173", "0.43566206", "0.43529165", "0.43481147", "0.43447784", "0.43339086", "0.432709", "0.43137926", "0.43087724", "0.4305019", "0.42988434", "0.428515", "0.42665547", "0.4264271", "0.42588475", "0.42540178", "0.42346898", "0.4228449", "0.42130634", "0.4212814", "0.4203086", "0.4202795", "0.4196768", "0.4194453", "0.41939968", "0.418549", "0.41693345", "0.41627702", "0.41447446", "0.4133161", "0.41224656", "0.4118622", "0.41113845", "0.40982234", "0.40974483", "0.40961212", "0.40827057", "0.40819907", "0.4075136", "0.4069344", "0.406882", "0.40687174", "0.40602574", "0.40580395", "0.4051984", "0.40502408", "0.4046042", "0.40445724", "0.4042797", "0.4033447", "0.40308136", "0.40252668" ]
0.78264594
2
GetStartTime returns the time when vesting starts for a periodic vesting account.
func (pva PeriodicVestingAccount) GetStartTime() int64 { return pva.StartTime }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (dva DelayedVestingAccount) GetStartTime() int64 {\n\treturn 0\n}", "func (va ClawbackVestingAccount) GetStartTime() int64 {\n\treturn va.StartTime\n}", "func (cva ContinuousVestingAccount) GetStartTime() int64 {\n\treturn cva.StartTime\n}", "func GetStartTime() time.Time {\n\treturn startAtTime\n}", "func (txn TxnProbe) GetStartTime() time.Time {\n\treturn txn.startTime\n}", "func (plva PermanentLockedAccount) GetStartTime() int64 {\n\treturn 0\n}", "func (this *SyncFlightInfo) GetStartTime() time.Time {\n\tthis.lock.RLock()\n\tdefer this.lock.RUnlock()\n\treturn this.startTime\n}", "func (o *ApplianceSetupInfoAllOf) GetStartTime() time.Time {\n\tif o == nil || o.StartTime == nil {\n\t\tvar ret time.Time\n\t\treturn ret\n\t}\n\treturn *o.StartTime\n}", "func (req *StartWFSRequest) GetStartTime() time.Time {\n\treturn req.StartTime\n}", "func (instance *Instance) StartTime() time.Time {\n\tuptimeDuration := time.Duration(instance.Uptime) * time.Second\n\n\treturn time.Now().Add(-uptimeDuration)\n}", "func (o ReservedInstanceOutput) StartTime() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *ReservedInstance) pulumi.StringOutput { return v.StartTime }).(pulumi.StringOutput)\n}", "func (m *RequestSchedule) GetStartDateTime()(*i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time) {\n val, err := m.GetBackingStore().Get(\"startDateTime\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time)\n }\n return nil\n}", "func (o *ApplianceClusterInstallPhase) GetStartTime() time.Time {\n\tif o == nil || o.StartTime == nil {\n\t\tvar ret time.Time\n\t\treturn ret\n\t}\n\treturn *o.StartTime\n}", "func (o *UcsdBackupInfoAllOf) GetStartTime() time.Time {\n\tif o == nil || o.StartTime == nil {\n\t\tvar ret time.Time\n\t\treturn ret\n\t}\n\treturn *o.StartTime\n}", "func (f *Filler) StartTime() time.Time {\n\treturn f.tp\n}", "func (o BeanstalkScheduledTaskOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v BeanstalkScheduledTask) *string { return v.StartTime }).(pulumi.StringPtrOutput)\n}", "func (s *Session) GetStartTime() time.Time {\n\treturn s.started\n}", "func (o *OnpremUpgradePhase) GetStartTime() time.Time {\n\tif o == nil || o.StartTime == nil {\n\t\tvar ret time.Time\n\t\treturn ret\n\t}\n\treturn *o.StartTime\n}", "func (a *Auction) StartTime() time.Time {\n\treturn a.startTime\n}", "func StartTime() time.Time {\n\treturn processStartTime\n}", "func (o ElastigroupScheduledTaskOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ElastigroupScheduledTask) *string { return v.StartTime }).(pulumi.StringPtrOutput)\n}", "func (m *SimulationAutomationRun) GetStartDateTime()(*i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time) {\n val, err := m.GetBackingStore().Get(\"startDateTime\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time)\n }\n return nil\n}", "func (o ResourcePolicyInstanceSchedulePolicyOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ResourcePolicyInstanceSchedulePolicy) *string { return v.StartTime }).(pulumi.StringPtrOutput)\n}", "func (v *Validator) StartTime() time.Time {\n\treturn time.Unix(int64(v.Start), 0)\n}", "func (o *VirtualizationIweVirtualMachine) GetStartTime() string {\n\tif o == nil || o.StartTime == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.StartTime\n}", "func (r Reservation) StartTime() string {\n\thr := r.Start / 60\n\tmin := r.Start % 60\n\tvar ampm string\n\tif ampm = \"AM\"; hr >= 12 {\n\t\tampm = \"PM\"\n\t}\n\tif hr > 12 {\n\t\thr = hr - 12\n\t}\n\tif hr == 0 {\n\t\thr = 12\n\t}\n\treturn fmt.Sprintf(\"%02d:%02d %s\", hr, min, ampm)\n}", "func (o ResourcePolicyWeeklyCycleDayOfWeekOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ResourcePolicyWeeklyCycleDayOfWeek) *string { return v.StartTime }).(pulumi.StringPtrOutput)\n}", "func (r *ScheduledAction) StartTime() pulumi.StringOutput {\n\treturn (pulumi.StringOutput)(r.s.State[\"startTime\"])\n}", "func (c *Context) StartTime() *time.Time {\n\treturn &c.startTime\n}", "func (o InstanceMaintenanceScheduleOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v InstanceMaintenanceSchedule) *string { return v.StartTime }).(pulumi.StringPtrOutput)\n}", "func (o InstanceMaintenanceScheduleOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v InstanceMaintenanceSchedule) *string { return v.StartTime }).(pulumi.StringPtrOutput)\n}", "func (o ResourcePolicyDailyCycleOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ResourcePolicyDailyCycle) *string { return v.StartTime }).(pulumi.StringPtrOutput)\n}", "func (c *Container) GetStartTime() time.Time {\n\treturn c.start\n}", "func (mgr *Manager) StartTime() time.Time {\n\treturn mgr.startTime\n}", "func (o *WorkflowServiceItemActionInstance) GetStartTime() time.Time {\n\tif o == nil || o.StartTime == nil {\n\t\tvar ret time.Time\n\t\treturn ret\n\t}\n\treturn *o.StartTime\n}", "func (o *Job) GetStartTime(ctx context.Context) (startTime uint64, err error) {\n\terr = o.object.CallWithContext(ctx, \"org.freedesktop.DBus.Properties.Get\", 0, InterfaceJob, \"StartTime\").Store(&startTime)\n\treturn\n}", "func (o ResourcePolicyHourlyCycleOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ResourcePolicyHourlyCycle) *string { return v.StartTime }).(pulumi.StringPtrOutput)\n}", "func (o ResourcePolicyInstanceSchedulePolicyResponseOutput) StartTime() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ResourcePolicyInstanceSchedulePolicyResponse) string { return v.StartTime }).(pulumi.StringOutput)\n}", "func (m *GetSchedulePostRequestBody) GetStartTime()(iadcd81124412c61e647227ecfc4449d8bba17de0380ddda76f641a29edf2b242.DateTimeTimeZoneable) {\n return m.startTime\n}", "func (req *ServerHTTPRequest) StartTime() time.Time {\n\treturn req.startTime\n}", "func (b *fixedResolutionValues) StartTime() xtime.UnixNano {\n\treturn b.startTime\n}", "func (o ResourcePolicyInstanceSchedulePolicyPtrOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ResourcePolicyInstanceSchedulePolicy) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.StartTime\n\t}).(pulumi.StringPtrOutput)\n}", "func (o GoogleCloudRetailV2alphaConditionTimeRangeOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v GoogleCloudRetailV2alphaConditionTimeRange) *string { return v.StartTime }).(pulumi.StringPtrOutput)\n}", "func (o ResourcePolicyWeeklyCycleDayOfWeekResponseOutput) StartTime() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ResourcePolicyWeeklyCycleDayOfWeekResponse) string { return v.StartTime }).(pulumi.StringOutput)\n}", "func (p *SASQueryParameters) StartTime() time.Time {\n\treturn p.startTime\n}", "func (_LvRecording *LvRecordingCaller) StartTime(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _LvRecording.contract.Call(opts, &out, \"startTime\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (gm GlobalManager) GetChainStartTime(ctx sdk.Context) (int64, sdk.Error) {\n\tglobalTime, err := gm.storage.GetGlobalTime(ctx)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn globalTime.ChainStartTime, nil\n}", "func (o DataTransferConfigScheduleOptionsOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v DataTransferConfigScheduleOptions) *string { return v.StartTime }).(pulumi.StringPtrOutput)\n}", "func (m *BookingWorkTimeSlot) GetStart()(*i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.TimeOnly) {\n val, err := m.GetBackingStore().Get(\"start\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.TimeOnly)\n }\n return nil\n}", "func (o InstanceMaintenanceSchedulePtrOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *InstanceMaintenanceSchedule) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.StartTime\n\t}).(pulumi.StringPtrOutput)\n}", "func (o InstanceMaintenanceWindowOutput) StartTime() InstanceMaintenanceWindowStartTimeOutput {\n\treturn o.ApplyT(func(v InstanceMaintenanceWindow) InstanceMaintenanceWindowStartTime { return v.StartTime }).(InstanceMaintenanceWindowStartTimeOutput)\n}", "func (o JobScheduleOutput) StartTime() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *JobSchedule) pulumi.StringOutput { return v.StartTime }).(pulumi.StringOutput)\n}", "func (o InstanceMaintenancePolicyWeeklyMaintenanceWindowOutput) StartTime() InstanceMaintenancePolicyWeeklyMaintenanceWindowStartTimeOutput {\n\treturn o.ApplyT(func(v InstanceMaintenancePolicyWeeklyMaintenanceWindow) InstanceMaintenancePolicyWeeklyMaintenanceWindowStartTime {\n\t\treturn v.StartTime\n\t}).(InstanceMaintenancePolicyWeeklyMaintenanceWindowStartTimeOutput)\n}", "func (o InstanceMaintenancePolicyWeeklyMaintenanceWindowOutput) StartTime() InstanceMaintenancePolicyWeeklyMaintenanceWindowStartTimeOutput {\n\treturn o.ApplyT(func(v InstanceMaintenancePolicyWeeklyMaintenanceWindow) InstanceMaintenancePolicyWeeklyMaintenanceWindowStartTime {\n\t\treturn v.StartTime\n\t}).(InstanceMaintenancePolicyWeeklyMaintenanceWindowStartTimeOutput)\n}", "func StartTime() {\n\tstart = time.Now()\n}", "func (m *ExternalActivity) GetStartDateTime()(*i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time) {\n val, err := m.GetBackingStore().Get(\"startDateTime\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time)\n }\n return nil\n}", "func (o ResourcePolicyDailyCycleResponseOutput) StartTime() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ResourcePolicyDailyCycleResponse) string { return v.StartTime }).(pulumi.StringOutput)\n}", "func (e *Event) StartTime() Time {\n\treturn e.start\n}", "func (o ResourcePolicyDailyCyclePtrOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ResourcePolicyDailyCycle) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.StartTime\n\t}).(pulumi.StringPtrOutput)\n}", "func (o DataTransferConfigScheduleOptionsPtrOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *DataTransferConfigScheduleOptions) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.StartTime\n\t}).(pulumi.StringPtrOutput)\n}", "func (m *UserExperienceAnalyticsDeviceStartupHistory) GetStartTime()(*i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time) {\n val, err := m.GetBackingStore().Get(\"startTime\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time)\n }\n return nil\n}", "func (m *MobileAppInstallTimeSettings) GetStartDateTime()(*i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time) {\n return m.startDateTime\n}", "func (o *ProjectDeploymentRuleResponse) GetStartTime() time.Time {\n\tif o == nil || o.StartTime.Get() == nil {\n\t\tvar ret time.Time\n\t\treturn ret\n\t}\n\treturn *o.StartTime.Get()\n}", "func (pb *Bar) StartTime() time.Time {\n\tpb.mu.RLock()\n\tdefer pb.mu.RUnlock()\n\treturn pb.startTime\n}", "func (o BaselineStrategyOutput) StartTime() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *BaselineStrategy) pulumi.StringOutput { return v.StartTime }).(pulumi.StringOutput)\n}", "func (o StorageCapacityUnitOutput) StartTime() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *StorageCapacityUnit) pulumi.StringOutput { return v.StartTime }).(pulumi.StringOutput)\n}", "func (s *Storage) StartTime() (int64, error) {\n\treturn int64(model.Latest), nil\n}", "func (o GoogleCloudRetailV2alphaConditionTimeRangeResponseOutput) StartTime() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GoogleCloudRetailV2alphaConditionTimeRangeResponse) string { return v.StartTime }).(pulumi.StringOutput)\n}", "func (m *TermsExpiration) GetStartDateTime()(*i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time) {\n return m.startDateTime\n}", "func (o ScanRunResponseOutput) StartTime() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ScanRunResponse) string { return v.StartTime }).(pulumi.StringOutput)\n}", "func (o ScanRunResponseOutput) StartTime() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ScanRunResponse) string { return v.StartTime }).(pulumi.StringOutput)\n}", "func (o ScanRunOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ScanRun) *string { return v.StartTime }).(pulumi.StringPtrOutput)\n}", "func (o ScanRunOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ScanRun) *string { return v.StartTime }).(pulumi.StringPtrOutput)\n}", "func (o *KubernetesPodStatus) GetStartTime() string {\n\tif o == nil || o.StartTime == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.StartTime\n}", "func (o ResourcePolicyHourlyCycleResponseOutput) StartTime() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ResourcePolicyHourlyCycleResponse) string { return v.StartTime }).(pulumi.StringOutput)\n}", "func (o LicenseOutput) StartTime() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *License) pulumi.StringOutput { return v.StartTime }).(pulumi.StringOutput)\n}", "func (o ResourcePolicyHourlyCyclePtrOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ResourcePolicyHourlyCycle) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.StartTime\n\t}).(pulumi.StringPtrOutput)\n}", "func (c *Clock) GetStart() time.Time {\n\tc.init()\n\tc.mu.Lock()\n\tdefer c.mu.Unlock()\n\treturn c.start\n}", "func (o ResourcePolicyInstanceSchedulePolicyResponsePtrOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ResourcePolicyInstanceSchedulePolicyResponse) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.StartTime\n\t}).(pulumi.StringPtrOutput)\n}", "func (m *Reminder) GetEventStartTime()(DateTimeTimeZoneable) {\n val, err := m.GetBackingStore().Get(\"eventStartTime\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(DateTimeTimeZoneable)\n }\n return nil\n}", "func (o KubernetesClusterMaintenanceWindowAutoUpgradeOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v KubernetesClusterMaintenanceWindowAutoUpgrade) *string { return v.StartTime }).(pulumi.StringPtrOutput)\n}", "func (o TriggerBuildArtifactsObjectsTimingOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v TriggerBuildArtifactsObjectsTiming) *string { return v.StartTime }).(pulumi.StringPtrOutput)\n}", "func (o NodeGroupMaintenanceWindowResponseOutput) StartTime() pulumi.StringOutput {\n\treturn o.ApplyT(func(v NodeGroupMaintenanceWindowResponse) string { return v.StartTime }).(pulumi.StringOutput)\n}", "func (o NodeGroupMaintenanceWindowOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v NodeGroupMaintenanceWindow) *string { return v.StartTime }).(pulumi.StringPtrOutput)\n}", "func (p *protocol) TimeSlotStart() time.Time {\n\treturn p.refTime().Truncate(TruncateDuration)\n}", "func GetBeginningOfDay(t time.Time) time.Time {\n\tyear, month, day := t.Date()\n\tstartOfDay := time.Date(year, month, day, 0, 0, 0, 0, t.Location())\n\treturn startOfDay\n}", "func (o JobStatusPtrOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v JobStatus) *string { return v.StartTime }).(pulumi.StringPtrOutput)\n}", "func (o JobStatusOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v JobStatus) *string { return v.StartTime }).(pulumi.StringPtrOutput)\n}", "func GetBeginningOfDay(t time.Time) time.Time {\n\ty, m, d := t.Date()\n\ttimeBOD := time.Date(y, m, d, 0, 0, 0, 0, t.Location())\n\treturn timeBOD\n}", "func (n *ssvNode) getSlotStartTime(slot uint64) time.Time {\n\ttimeSinceGenesisStart := slot * uint64(n.ethNetwork.SlotDurationSec().Seconds())\n\tstart := time.Unix(int64(n.ethNetwork.MinGenesisTime()+timeSinceGenesisStart), 0)\n\treturn start\n}", "func (o *Run) GetStartedAt() time.Time {\n\tif o == nil || o.StartedAt == nil {\n\t\tvar ret time.Time\n\t\treturn ret\n\t}\n\treturn *o.StartedAt\n}", "func (o KubernetesClusterMaintenanceWindowAutoUpgradePtrOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *KubernetesClusterMaintenanceWindowAutoUpgrade) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.StartTime\n\t}).(pulumi.StringPtrOutput)\n}", "func (q *Queries) EventStartTime(ctx context.Context, id models.EventID) (time.Time, error) {\n\tdefer daoSpan(&ctx)()\n\treturn q.dbc.EventStartTime(ctx, id)\n}", "func (o ResourcePolicyDailyCycleResponsePtrOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ResourcePolicyDailyCycleResponse) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.StartTime\n\t}).(pulumi.StringPtrOutput)\n}", "func (o ScanRunPtrOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ScanRun) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.StartTime\n\t}).(pulumi.StringPtrOutput)\n}", "func (o ScanRunPtrOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ScanRun) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.StartTime\n\t}).(pulumi.StringPtrOutput)\n}", "func (c deploymentChecker) BeginTime() uint64 {\n\treturn c.deployment.StartTime\n}", "func (c *PurchasesVoidedpurchasesListCall) StartTime(startTime int64) *PurchasesVoidedpurchasesListCall {\n\tc.urlParams_.Set(\"startTime\", fmt.Sprint(startTime))\n\treturn c\n}", "func (o *AvailableBudget) GetStart() time.Time {\n\tif o == nil {\n\t\tvar ret time.Time\n\t\treturn ret\n\t}\n\n\treturn o.Start\n}", "func (o TimelineOutput) StartTime() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v *Timeline) pulumi.IntPtrOutput { return v.StartTime }).(pulumi.IntPtrOutput)\n}" ]
[ "0.7655847", "0.75100744", "0.74109447", "0.7287526", "0.7022211", "0.6954829", "0.68399805", "0.6801164", "0.67397594", "0.6674122", "0.6627324", "0.6578017", "0.65748435", "0.65689546", "0.65134203", "0.65009487", "0.64612186", "0.6450997", "0.643786", "0.642462", "0.6406995", "0.64020413", "0.63844717", "0.63653165", "0.6363701", "0.6362074", "0.63568324", "0.63560975", "0.6351524", "0.6326262", "0.6326262", "0.6322486", "0.62883705", "0.6282691", "0.6263698", "0.62592334", "0.6217309", "0.6189734", "0.6187015", "0.6172441", "0.6166757", "0.61435354", "0.613561", "0.61327374", "0.6132541", "0.61275315", "0.6104715", "0.61028135", "0.60947555", "0.6081573", "0.60768026", "0.6073922", "0.60674924", "0.60674924", "0.60597277", "0.6058721", "0.6052556", "0.60444885", "0.6044333", "0.60334176", "0.6029354", "0.6017658", "0.60030395", "0.59931475", "0.5987374", "0.5965816", "0.5962567", "0.59595406", "0.5952699", "0.59525454", "0.59525454", "0.59427196", "0.59427196", "0.5940991", "0.5937808", "0.59377974", "0.59280425", "0.5918721", "0.5907899", "0.5878239", "0.5866926", "0.58605766", "0.58487654", "0.5848024", "0.5837422", "0.5834961", "0.5832232", "0.5817391", "0.5808867", "0.5792745", "0.57913506", "0.57725316", "0.5770113", "0.57655764", "0.57499284", "0.57499284", "0.5732525", "0.57268167", "0.5726121", "0.5718125" ]
0.76758254
0
GetVestingPeriods returns vesting periods associated with periodic vesting account.
func (pva PeriodicVestingAccount) GetVestingPeriods() Periods { return pva.VestingPeriods }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (va ClawbackVestingAccount) GetVestingPeriods() Periods {\n\treturn va.VestingPeriods\n}", "func NewPeriodicVestingAccount(baseAcc *authtypes.BaseAccount, originalVesting sdk.Coins, startTime int64, periods Periods) *PeriodicVestingAccount {\n\tendTime := startTime\n\tfor _, p := range periods {\n\t\tendTime += p.Length\n\t}\n\tbaseVestingAcc := &BaseVestingAccount{\n\t\tBaseAccount: baseAcc,\n\t\tOriginalVesting: originalVesting,\n\t\tEndTime: endTime,\n\t}\n\n\treturn &PeriodicVestingAccount{\n\t\tBaseVestingAccount: baseVestingAcc,\n\t\tStartTime: startTime,\n\t\tVestingPeriods: periods,\n\t}\n}", "func (pva PeriodicVestingAccount) Validate() error {\n\tif pva.GetStartTime() >= pva.GetEndTime() {\n\t\treturn errors.New(\"vesting start-time cannot be before end-time\")\n\t}\n\tendTime := pva.StartTime\n\toriginalVesting := sdk.NewCoins()\n\tfor _, p := range pva.VestingPeriods {\n\t\tendTime += p.Length\n\t\toriginalVesting = originalVesting.Add(p.Amount...)\n\t}\n\tif endTime != pva.EndTime {\n\t\treturn errors.New(\"vesting end time does not match length of all vesting periods\")\n\t}\n\tif !originalVesting.IsEqual(pva.OriginalVesting) {\n\t\treturn errors.New(\"original vesting coins does not match the sum of all coins in vesting periods\")\n\t}\n\n\treturn pva.BaseVestingAccount.Validate()\n}", "func newPeriodicVestingAccount(address sdk.AccAddress, periods vestingtypes.Periods, firstPeriodStartTimestamp int64) *vestingtypes.PeriodicVestingAccount {\n\tbaseAccount := authtypes.NewBaseAccount(address, nil, 0, 0)\n\n\toriginalVesting := sdk.NewCoins()\n\tfor _, p := range periods {\n\t\toriginalVesting = originalVesting.Add(p.Amount...)\n\t}\n\n\tvar totalPeriods int64\n\tfor _, p := range periods {\n\t\ttotalPeriods += p.Length\n\t}\n\tendTime := firstPeriodStartTimestamp + totalPeriods\n\n\tbaseVestingAccount := vestingtypes.NewBaseVestingAccount(baseAccount, originalVesting, endTime)\n\treturn vestingtypes.NewPeriodicVestingAccountRaw(baseVestingAccount, firstPeriodStartTimestamp, periods)\n}", "func (n Network) VestingAccounts(ctx context.Context, launchID uint64) (vestingAccs []networktypes.VestingAccount, err error) {\n\tn.ev.Send(events.New(events.StatusOngoing, \"Fetching genesis vesting accounts\"))\n\tres, err := n.launchQuery.\n\t\tVestingAccountAll(ctx,\n\t\t\t&launchtypes.QueryAllVestingAccountRequest{\n\t\t\t\tLaunchID: launchID,\n\t\t\t},\n\t\t)\n\tif err != nil {\n\t\treturn vestingAccs, err\n\t}\n\n\tfor i, acc := range res.VestingAccount {\n\t\tparsedAcc, err := networktypes.ToVestingAccount(acc)\n\t\tif err != nil {\n\t\t\treturn vestingAccs, errors.Wrapf(err, \"error parsing vesting account %d\", i)\n\t\t}\n\n\t\tvestingAccs = append(vestingAccs, parsedAcc)\n\t}\n\n\treturn vestingAccs, nil\n}", "func (db *DB) GetAllPeriods() ([]string, error) {\n\tvar allPeriods []string\n\n\tconn, err := redishelper.GetRedisConn(db.RedisServer, db.RedisPassword)\n\tif err != nil {\n\t\treturn []string{}, err\n\t}\n\tdefer conn.Close()\n\n\tk := \"ming:campuses\"\n\tcampuses, err := redis.Strings(conn.Do(\"ZRANGE\", k, 0, -1))\n\tif err != nil {\n\t\treturn []string{}, err\n\t}\n\n\tfor _, campus := range campuses {\n\t\tk = fmt.Sprintf(\"ming:%v:categories\", campus)\n\t\tcategories, err := redis.Strings(conn.Do(\"ZRANGE\", k, 0, -1))\n\t\tif err != nil {\n\t\t\treturn []string{}, err\n\t\t}\n\n\t\tfor _, category := range categories {\n\t\t\tk = fmt.Sprintf(\"ming:%v:%v:periods\", campus, category)\n\t\t\tperiods, err := redis.Strings(conn.Do(\"ZRANGE\", k, 0, -1))\n\t\t\tif err != nil {\n\t\t\t\treturn []string{}, err\n\t\t\t}\n\n\t\t\tfor _, period := range periods {\n\t\t\t\tallPeriods = append(allPeriods, fmt.Sprintf(\"%v:%v:%v\", campus, category, period))\n\t\t\t}\n\n\t\t}\n\t}\n\treturn allPeriods, nil\n}", "func (vp Periods) String() string {\n\tperiodsListString := make([]string, len(vp))\n\tfor _, period := range vp {\n\t\tperiodsListString = append(periodsListString, period.String())\n\t}\n\n\treturn strings.TrimSpace(fmt.Sprintf(`Vesting Periods:\n\t\t%s`, strings.Join(periodsListString, \", \")))\n}", "func PeriodGET(w http.ResponseWriter, r *http.Request) {\n\tsess := model.Instance(r)\n lisPeriods, _ := model.Periods()\n\tv := view.New(r)\n\tv.Name = \"periodo/period\"\n\tv.Vars[\"token\"] = csrfbanana.Token(w, r, sess)\n v.Vars[\"LisPeriods\"] = lisPeriods\n// Refill any form fields\n// view.Repopulate([]string{\"name\"}, r.Form, v.Vars)\n\tv.Render(w)\n }", "func NewValidatorVestingAccount(baseAcc *authtypes.BaseAccount, startTime int64, periods vestingtypes.Periods, validatorAddress sdk.ConsAddress, returnAddress sdk.AccAddress, signingThreshold int64) *ValidatorVestingAccount {\n\n\tendTime := startTime\n\tfor _, p := range periods {\n\t\tendTime += p.Length\n\t}\n\tbaseVestingAcc := &vestingtypes.BaseVestingAccount{\n\t\tBaseAccount: baseAcc,\n\t\tOriginalVesting: baseAcc.Coins,\n\t\tEndTime: endTime,\n\t}\n\tpva := &vestingtypes.PeriodicVestingAccount{\n\t\tBaseVestingAccount: baseVestingAcc,\n\t\tStartTime: startTime,\n\t\tVestingPeriods: periods,\n\t}\n\tvar vestingPeriodProgress []VestingProgress\n\tfor i := 0; i < len(periods); i++ {\n\t\tvestingPeriodProgress = append(vestingPeriodProgress, VestingProgress{false, false})\n\t}\n\n\treturn &ValidatorVestingAccount{\n\t\tPeriodicVestingAccount: pva,\n\t\tValidatorAddress: validatorAddress,\n\t\tReturnAddress: returnAddress,\n\t\tSigningThreshold: signingThreshold,\n\t\tCurrentPeriodProgress: CurrentPeriodProgress{0, 0},\n\t\tVestingPeriodProgress: vestingPeriodProgress,\n\t\tDebtAfterFailedVesting: sdk.NewCoins(),\n\t}\n}", "func (c *UptimeCommand) GetPeriodOptions() []string {\n\treturn []string{\n\t\t\"Today\",\n\t\t\"Yesterday\",\n\t\t\"ThisWeek\",\n\t\t\"LastWeek\",\n\t\t\"ThisMonth\",\n\t\t\"LastMonth\",\n\t\t\"ThisYear\",\n\t\t\"LastYear\",\n\t}\n}", "func LoadPeriods(api *eos.API, includePast, includeFuture bool) []Period {\n\n\tvar periods []Period\n\tvar periodRequest eos.GetTableRowsRequest\n\tperiodRequest.Code = \"dao.hypha\"\n\tperiodRequest.Scope = \"dao.hypha\"\n\tperiodRequest.Table = \"periods\"\n\tperiodRequest.Limit = 1000\n\tperiodRequest.JSON = true\n\n\tperiodResponse, err := api.GetTableRows(context.Background(), periodRequest)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tperiodResponse.JSONToStructs(&periods)\n\n\tvar returnPeriods []Period\n\tcurrentPeriod, err := CurrentPeriod(&periods)\n\tif (includePast || includeFuture) && err != nil {\n\t\tpanic(err)\n\t}\n\n\tfor _, period := range periods {\n\t\tif includePast || includeFuture {\n\t\t\tif includePast && period.PeriodID <= uint64(currentPeriod) {\n\t\t\t\treturnPeriods = append(returnPeriods, period)\n\t\t\t} else if includeFuture && period.PeriodID >= uint64(currentPeriod) {\n\t\t\t\treturnPeriods = append(returnPeriods, period)\n\t\t\t}\n\t\t}\n\t}\n\treturn returnPeriods\n}", "func NewPeriodicVestingAccountRaw(bva *BaseVestingAccount, startTime int64, periods Periods) *PeriodicVestingAccount {\n\treturn &PeriodicVestingAccount{\n\t\tBaseVestingAccount: bva,\n\t\tStartTime: startTime,\n\t\tVestingPeriods: periods,\n\t}\n}", "func vestingDataToEvents(data cli.VestingData) ([]event, error) {\n\tstartTime := time.Unix(data.StartTime, 0)\n\tevents := []event{}\n\tlastTime := startTime\n\tfor _, p := range data.Periods {\n\t\tcoins, err := sdk.ParseCoinsNormalized(p.Coins)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tnewTime := lastTime.Add(time.Duration(p.Length) * time.Second)\n\t\te := event{\n\t\t\tTime: newTime,\n\t\t\tCoins: coins,\n\t\t}\n\t\tevents = append(events, e)\n\t\tlastTime = newTime\n\t}\n\treturn events, nil\n}", "func GetTotalVestingPeriodLength(periods vestingtypes.Periods) int64 {\n\tlength := int64(0)\n\tfor _, period := range periods {\n\t\tlength += period.Length\n\t}\n\treturn length\n}", "func (o *GetOutagesParams) WithPeriod(period *float64) *GetOutagesParams {\n\to.SetPeriod(period)\n\treturn o\n}", "func GetTotalVestingPeriodLength(periods vesting.Periods) int64 {\n\tlength := int64(0)\n\tfor _, period := range periods {\n\t\tlength += period.Length\n\t}\n\treturn length\n}", "func (pva PeriodicVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn pva.OriginalVesting.Sub(pva.GetVestedCoins(blockTime))\n}", "func monthlyVestTimes(startTime time.Time, months int, timeOfDay time.Time) ([]time.Time, error) {\n\tif months < 1 {\n\t\treturn nil, fmt.Errorf(\"must have at least one vesting period\")\n\t}\n\tlocation := startTime.Location()\n\thour := timeOfDay.Hour()\n\tminute := timeOfDay.Minute()\n\tsecond := timeOfDay.Second()\n\ttimes := make([]time.Time, months)\n\tfor i := 1; i <= months; i++ {\n\t\ttm := startTime.AddDate(0, i, 0)\n\t\tif tm.Day() != startTime.Day() {\n\t\t\t// The starting day-of-month cannot fit in this month,\n\t\t\t// and we've wrapped to the next month. Back up to the\n\t\t\t// end of the previous month.\n\t\t\ttm = tm.AddDate(0, 0, -tm.Day())\n\t\t}\n\t\ttimes[i-1] = time.Date(tm.Year(), tm.Month(), tm.Day(), hour, minute, second, 0, location)\n\t}\n\t// Integrity check: dates must be sequential and 26-33 days apart.\n\tlastTime := startTime\n\tfor _, tm := range times {\n\t\tduration := tm.Sub(lastTime)\n\t\tif duration < 26*24*time.Hour {\n\t\t\treturn nil, fmt.Errorf(\"vesting dates too close: %v and %v\", lastTime, tm)\n\t\t}\n\t\tif duration > 33*24*time.Hour {\n\t\t\treturn nil, fmt.Errorf(\"vesting dates too distant: %v and %v\", lastTime, tm)\n\t\t}\n\t\tlastTime = tm\n\t}\n\treturn times, nil\n}", "func (thisCalendar *Calendar) GetEventsByPeriod(start string, end string) ([]*Event, error) {\n\tvar startTime, endTime *entities.EventTime\n\tvar err error\n\n\tif start != \"\" {\n\t\tstartTime, err = ConvertToCalendarEventTime(start)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tif end != \"\" {\n\t\tendTime, err = ConvertToCalendarEventTime(end)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tcalendarEvents, err := thisCalendar.storage.GetEventsByPeriod(startTime, endTime)\n\tif len(calendarEvents) == 0 {\n\t\treturn nil, err\n\t}\n\tvar events []*Event\n\tfor _, calendarEvent := range calendarEvents {\n\t\tevents = append(events, ConvertFromCalendarEvent(calendarEvent))\n\t}\n\treturn events, nil\n}", "func (h *Periods) Index(ctx context.Context, w http.ResponseWriter, r *http.Request, params map[string]string) error {\n\n\tclaims, err := auth.ClaimsFromContext(ctx)\n\tif err != nil {\n\t\treturn err\n\t} \n\n\tfields := []datatable.DisplayField{\n\t\t{Field: \"id\", Title: \"ID\", Visible: false, Searchable: true, Orderable: true, Filterable: false},\n\t\t{Field: \"period\", Title: \"Period\", Visible: true, Orderable: true, },\n\t\t{Field: \"start_hour\", Title: \"Start Hour\", Visible: true, Orderable: true, },\n\t\t{Field: \"start_minute\", Title: \"Start Minute\", Visible: true, Orderable: true, },\n\t\t{Field: \"end_hour\", Title: \"End Hour\", Visible: true, Orderable: true, },\n\t\t{Field: \"end_minute\", Title: \"End Minute\", Visible: true, Orderable: true, },\n\t}\n\n\tmapFunc := func(q *period.Period, cols []datatable.DisplayField) (resp []datatable.ColumnValue, err error) {\n\t\tfor i := 0; i < len(cols); i++ {\n\t\t\tcol := cols[i]\n\t\t\tvar v datatable.ColumnValue\n\t\t\tswitch col.Field {\n\t\t\tcase \"id\":\n\t\t\t\tv.Value = fmt.Sprintf(\"%s\", q.ID)\n\t\t\tcase \"period\":\n\t\t\t\tv.Value = q.String()\n\t\t\t\tv.Formatted = fmt.Sprintf(\"<a href='%s'>%s</a>\", urlPeriodsView(q.ID), v.Value)\n\t\t\tcase \"start_hour\":\n\t\t\t\tv.Value = fmt.Sprintf(\"%d\", q.StartHour)\n\t\t\t\tv.Formatted = v.Value\n\t\t\tcase \"start_minute\":\n\t\t\t\tv.Value = fmt.Sprintf(\"%20d\", q.StartMinute)\n\t\t\t\tv.Formatted = v.Value\n\t\t\tcase \"end_hour\":\n\t\t\t\tv.Value = fmt.Sprintf(\"%d\", q.EndHour)\n\t\t\t\tv.Formatted = v.Value\n\t\t\tcase \"end_minute\":\n\t\t\t\tv.Value = fmt.Sprintf(\"%20d\", q.EndMinute)\n\t\t\t\tv.Formatted = v.Value\n\t\t\tdefault:\n\t\t\t\treturn resp, errors.Errorf(\"Failed to map value for %s.\", col.Field)\n\t\t\t}\n\t\t\tresp = append(resp, v)\n\t\t}\n\n\t\treturn resp, nil\n\t}\n\n\tloadFunc := func(ctx context.Context, sorting string, fields []datatable.DisplayField) (resp [][]datatable.ColumnValue, err error) {\n\t\tres, err := h.Repo.Find(ctx, claims, period.FindRequest{\n\t\t\tOrder: strings.Split(sorting, \",\"),\n\t\t})\n\t\tif err != nil {\n\t\t\treturn resp, err\n\t\t}\n\n\t\tfor _, a := range res {\n\t\t\tl, err := mapFunc(a, fields)\n\t\t\tif err != nil {\n\t\t\t\treturn resp, errors.Wrapf(err, \"Failed to map checklist for display.\")\n\t\t\t}\n\n\t\t\tresp = append(resp, l)\n\t\t}\n\n\t\treturn resp, nil\n\t}\n\n\tdt, err := datatable.New(ctx, w, r, h.Redis, fields, loadFunc)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif dt.HasCache() {\n\t\treturn nil\n\t}\n\n\tif ok, err := dt.Render(); ok {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t}\n\n\tdata := map[string]interface{}{\n\t\t\"datatable\": dt.Response(),\n\t\t\"urlPeriodsCreate\": urlPeriodsCreate(),\n\t\t\"urlPeriodsIndex\": urlPeriodsIndex(),\n\t}\n\n\treturn h.Renderer.Render(ctx, w, r, TmplLayoutBase, \"admin-periods-index.gohtml\", web.MIMETextHTMLCharsetUTF8, http.StatusOK, data)\n}", "func GetTeamsByVID(v int64) ([]TeamID, error) {\n\tvar teams []TeamID\n\n\trow, err := db.Query(\"SELECT teamID FROM team WHERE vteam = ?\", v)\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn teams, err\n\t}\n\tdefer row.Close()\n\n\tfor row.Next() {\n\t\tvar teamID TeamID\n\t\terr = row.Scan(&teamID)\n\t\tif err != nil {\n\t\t\tlog.Error(err)\n\t\t\tcontinue\n\t\t}\n\t\tteams = append(teams, teamID)\n\t}\n\treturn teams, nil\n}", "func (vva ValidatorVestingAccount) GetVestedCoins(blockTime time.Time) sdk.Coins {\n\tvar vestedCoins sdk.Coins\n\tif blockTime.Unix() <= vva.StartTime {\n\t\treturn vestedCoins\n\t}\n\tcurrentPeriodStartTime := vva.StartTime\n\tnumberPeriods := len(vva.VestingPeriods)\n\tfor i := 0; i < numberPeriods; i++ {\n\t\tx := blockTime.Unix() - currentPeriodStartTime\n\t\tif x >= vva.VestingPeriods[i].Length {\n\t\t\tif vva.VestingPeriodProgress[i].PeriodComplete {\n\t\t\t\tvestedCoins = vestedCoins.Add(vva.VestingPeriods[i].Amount)\n\t\t\t}\n\t\t\tcurrentPeriodStartTime += vva.VestingPeriods[i].Length\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn vestedCoins\n\n}", "func NewPeriod(amount sdk.Coins, length int64) vestingtypes.Period {\n\treturn vestingtypes.Period{Amount: amount, Length: length}\n}", "func NewSLAGetExclusionPeriodsParams() *SLAGetExclusionPeriodsParams {\n\tvar ()\n\treturn &SLAGetExclusionPeriodsParams{\n\n\t\ttimeout: cr.DefaultTimeout,\n\t}\n}", "func (o MrScalarTerminationPolicyStatementOutput) EvaluationPeriods() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v MrScalarTerminationPolicyStatement) *int { return v.EvaluationPeriods }).(pulumi.IntPtrOutput)\n}", "func (v *visitor) GetPolicies() []*rbac.Policy {\n\tif v.ctx.IsSysAdmin() {\n\t\treturn GetAllPolicies(v.namespace)\n\t}\n\n\tif v.namespace.IsPublic() {\n\t\treturn PoliciesForPublicProject(v.namespace)\n\t}\n\n\treturn nil\n}", "func (v *visitor) GetPolicies() []*rbac.Policy {\n\tif v.ctx.IsSysAdmin() {\n\t\treturn GetAllPolicies(v.namespace)\n\t}\n\n\tif v.namespace.IsPublic() {\n\t\treturn PoliciesForPublicProject(v.namespace)\n\t}\n\n\treturn nil\n}", "func (_Vault *VaultSession) GetDecimals(token common.Address) (uint8, error) {\n\treturn _Vault.Contract.GetDecimals(&_Vault.CallOpts, token)\n}", "func DefaultListPeriod(ctx context.Context, db *gorm.DB) ([]*Period, error) {\n\tin := Period{}\n\tormObj, err := in.ToORM(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif hook, ok := interface{}(&ormObj).(PeriodORMWithBeforeListApplyQuery); ok {\n\t\tif db, err = hook.BeforeListApplyQuery(ctx, db); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tdb, err = gorm1.ApplyCollectionOperators(ctx, db, &PeriodORM{}, &Period{}, nil, nil, nil, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif hook, ok := interface{}(&ormObj).(PeriodORMWithBeforeListFind); ok {\n\t\tif db, err = hook.BeforeListFind(ctx, db); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tdb = db.Where(&ormObj)\n\tdb = db.Order(\"id\")\n\tormResponse := []PeriodORM{}\n\tif err := db.Find(&ormResponse).Error; err != nil {\n\t\treturn nil, err\n\t}\n\tif hook, ok := interface{}(&ormObj).(PeriodORMWithAfterListFind); ok {\n\t\tif err = hook.AfterListFind(ctx, db, &ormResponse); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tpbResponse := []*Period{}\n\tfor _, responseEntry := range ormResponse {\n\t\ttemp, err := responseEntry.ToPB(ctx)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tpbResponse = append(pbResponse, &temp)\n\t}\n\treturn pbResponse, nil\n}", "func (c *JobConfig) AllPeriodics() []Periodic {\n\tlistPeriodic := func(ps []Periodic) []Periodic {\n\t\tvar res []Periodic\n\t\tres = append(res, ps...)\n\t\treturn res\n\t}\n\n\treturn listPeriodic(c.Periodics)\n}", "func (o ElastigroupScalingDownPolicyOutput) EvaluationPeriods() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v ElastigroupScalingDownPolicy) *int { return v.EvaluationPeriods }).(pulumi.IntPtrOutput)\n}", "func (c Cart) GetVoucherSavings() domain.Price {\n\tprice := domain.Price{}\n\tvar err error\n\n\tfor _, item := range c.Totalitems {\n\t\tif item.Type == TotalsTypeVoucher {\n\t\t\tprice, err = price.Add(item.Price)\n\t\t\tif err != nil {\n\t\t\t\treturn price\n\t\t\t}\n\t\t}\n\t}\n\n\tif price.IsNegative() {\n\t\treturn domain.Price{}\n\t}\n\n\treturn price\n}", "func (o UsagePlanQuotaSettingsOutput) Period() pulumi.StringOutput {\n\treturn o.ApplyT(func(v UsagePlanQuotaSettings) string { return v.Period }).(pulumi.StringOutput)\n}", "func PeriodsDynamic(first map[types.Category]types.Money, second map[types.Category]types.Money) map[types.Category]types.Money {\n\tresult := map[types.Category]types.Money{}\n\tfor k := range second {\n\t\tif _, ok := first[k]; ok {\n\t\t\tresult[k] = second[k] - first[k]\n\t\t} else {\n\t\t\tresult[k] = second[k]\n\t\t}\n\t}\n\tfor k := range first {\n\t\tif _, ok := second[k]; !ok {\n\t\t\tresult[k] = -first[k]\n\t\t}\n\t}\n\treturn result\n}", "func (p Period) Days() []LocalDate {\n\tvar days []LocalDate\n\tfor current := p.from; current.BeforeOrEqual(p.to); current = current.Next() {\n\t\tdays = append(days, current)\n\t}\n\treturn days\n}", "func (w *rpcWallet) VotingPreferences(ctx context.Context) ([]*walletjson.VoteChoice, []*asset.TBTreasurySpend, []*walletjson.TreasuryPolicyResult, error) {\n\t// Get consensus vote choices.\n\tchoices, err := w.rpcClient.GetVoteChoices(ctx)\n\tif err != nil {\n\t\treturn nil, nil, nil, fmt.Errorf(\"unable to get vote choices: %v\", err)\n\t}\n\tvoteChoices := make([]*walletjson.VoteChoice, len(choices.Choices))\n\tfor i, v := range choices.Choices {\n\t\tvc := v\n\t\tvoteChoices[i] = &vc\n\t}\n\t// Get tspend voting policy.\n\tconst tSpendPolicyMethod = \"tspendpolicy\"\n\tvar tSpendRes []walletjson.TSpendPolicyResult\n\terr = w.rpcClientRawRequest(ctx, tSpendPolicyMethod, nil, &tSpendRes)\n\tif err != nil {\n\t\treturn nil, nil, nil, fmt.Errorf(\"unable to get treasury spend policy: %v\", err)\n\t}\n\ttSpendPolicy := make([]*asset.TBTreasurySpend, len(tSpendRes))\n\tfor i, tp := range tSpendRes {\n\t\t// TODO: Find a way to get the tspend total value? Probably only\n\t\t// possible with a full node and txindex.\n\t\ttSpendPolicy[i] = &asset.TBTreasurySpend{\n\t\t\tHash: tp.Hash,\n\t\t\tCurrentPolicy: tp.Policy,\n\t\t}\n\t}\n\t// Get treasury voting policy.\n\tconst treasuryPolicyMethod = \"treasurypolicy\"\n\tvar treasuryRes []walletjson.TreasuryPolicyResult\n\terr = w.rpcClientRawRequest(ctx, treasuryPolicyMethod, nil, &treasuryRes)\n\tif err != nil {\n\t\treturn nil, nil, nil, fmt.Errorf(\"unable to get treasury policy: %v\", err)\n\t}\n\ttreasuryPolicy := make([]*walletjson.TreasuryPolicyResult, len(treasuryRes))\n\tfor i, v := range treasuryRes {\n\t\ttp := v\n\t\ttreasuryPolicy[i] = &tp\n\t}\n\treturn voteChoices, tSpendPolicy, treasuryPolicy, nil\n}", "func (o *SLAGetExclusionPeriodsParams) WithContext(ctx context.Context) *SLAGetExclusionPeriodsParams {\n\to.SetContext(ctx)\n\treturn o\n}", "func (api *tenantAPI) List(ctx context.Context, opts *api.ListWatchOptions) ([]*Tenant, error) {\n\tvar objlist []*Tenant\n\tobjs, err := api.ct.List(\"Tenant\", ctx, opts)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, obj := range objs {\n\t\tswitch tp := obj.(type) {\n\t\tcase *Tenant:\n\t\t\teobj := obj.(*Tenant)\n\t\t\tobjlist = append(objlist, eobj)\n\t\tdefault:\n\t\t\tlog.Fatalf(\"Got invalid object type %v while looking for Tenant\", tp)\n\t\t}\n\t}\n\n\treturn objlist, nil\n}", "func NewSLAGetExclusionPeriodsParamsWithTimeout(timeout time.Duration) *SLAGetExclusionPeriodsParams {\n\tvar ()\n\treturn &SLAGetExclusionPeriodsParams{\n\n\t\ttimeout: timeout,\n\t}\n}", "func (pva *PeriodicVestingAccount) UnmarshalJSON(bz []byte) error {\n\tvar alias vestingAccountJSON\n\tif err := legacy.Cdc.UnmarshalJSON(bz, &alias); err != nil {\n\t\treturn err\n\t}\n\n\tpva.BaseVestingAccount = &BaseVestingAccount{\n\t\tBaseAccount: NewBaseAccount(alias.Address, alias.Coins, alias.PubKey, alias.AccountNumber, alias.Sequence),\n\t\tOriginalVesting: alias.OriginalVesting,\n\t\tDelegatedFree: alias.DelegatedFree,\n\t\tDelegatedVesting: alias.DelegatedVesting,\n\t\tEndTime: alias.EndTime,\n\t}\n\tpva.StartTime = alias.StartTime\n\tpva.VestingPeriods = alias.VestingPeriods\n\n\treturn nil\n}", "func (g Graph) GetDrives(w http.ResponseWriter, r *http.Request) {\n\tg.getDrives(w, r, false)\n}", "func (v PingSlotPeriod) MarshalJSON() ([]byte, error) {\n\treturn marshalJSONEnum(PingSlotPeriod_name, int32(v))\n}", "func (m *MongoDB) GetEnabledVehicles() ([]model.Vehicle, error) {\n\tvar vehicles []model.Vehicle\n\terr := m.vehicles.Find(bson.M{\"enabled\": true}).All(&vehicles)\n\treturn vehicles, err\n}", "func (plva PermanentLockedAccount) GetVestingCoins(_ time.Time) sdk.Coins {\n\treturn plva.OriginalVesting\n}", "func (h *stubDriveHandler) GetDrives() []models.Drive {\n\treturn h.drives\n}", "func (o ElastigroupIntegrationEcsAutoscaleDownOutput) EvaluationPeriods() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v ElastigroupIntegrationEcsAutoscaleDown) *int { return v.EvaluationPeriods }).(pulumi.IntPtrOutput)\n}", "func (builder *AuthBankGenesisBuilder) WithSimplePeriodicVestingAccount(address sdk.AccAddress, balance sdk.Coins, periods vestingtypes.Periods, firstPeriodStartTimestamp int64) *AuthBankGenesisBuilder {\n\tvestingAccount := newPeriodicVestingAccount(address, periods, firstPeriodStartTimestamp)\n\n\treturn builder.\n\t\tWithAccounts(vestingAccount).\n\t\tWithBalances(banktypes.Balance{Address: address.String(), Coins: balance})\n}", "func GetTimings(c *gin.Context) {\n\t// parse input\n\tvar input models.TimingSearchInput\n\tif err := c.ShouldBindQuery(&input); err != nil {\n\t\tc.JSON(http.StatusBadRequest, gin.H{\"error\": err.Error(), \"message\": \"Check input fields\"})\n\t\tfmt.Println(\"Error in getting date and venues. \" + err.Error() + \"\\n\")\n\t\treturn\n\t}\n\n\toperatingHours, err := GetOperatingHours(DB, input)\n\tif err != nil {\n\t\tc.JSON(http.StatusBadRequest, gin.H{\"error\": err.Error(), \"message\": \"Error in querying for unavailable timings.\"})\n\t\tfmt.Println(\"Check tempQuery \" + err.Error() + \"\\n\")\n\t}\n\n\tstatusIDArr, err := GetAllBookingStatusCodes(DB)\n\tif err != nil {\n\t\tc.JSON(http.StatusBadRequest, gin.H{\"error\": err.Error(), \"message\": \"Error in querying for booking statusID.\"})\n\t\tfmt.Println(\"Check bookingstatus query \" + err.Error() + \"\\n\")\n\t}\n\n\tvenue, err := GetVenueIDAndMaxCapacity(DB, input)\n\tif err != nil {\n\t\tc.JSON(http.StatusBadRequest, gin.H{\"error\": err.Error(), \"message\": \"Error in querying for venueID.\"})\n\t\tfmt.Println(\"Check venueQuery. \" + err.Error() + \"\\n\")\n\t}\n\n\ttimingWithPax, err := GetBookingsOfDay(DB, input, venue, statusIDArr)\n\tif err != nil {\n\t\tc.JSON(http.StatusBadRequest, gin.H{\"error\": err.Error(), \"message\": \"Error in querying for unavailable timings.\"})\n\t\tfmt.Println(\"Check timingsQuery \" + err.Error() + \"\\n\")\n\t}\n\n\ttimeslots := MakeTimeslotArr(operatingHours, timingWithPax, input, venue)\n\n\tc.JSON(http.StatusOK, gin.H{\"data\": timeslots})\n\tfmt.Println(\"Return successful!\")\n}", "func (b *Poloniex) GetVolumes() (vc VolumeCollection, err error) {\n\tr, err := b.client.do(\"GET\", \"public?command=return24hVolume\", nil, false)\n\tif err != nil {\n\t\treturn\n\t}\n\tif err = json.Unmarshal(r, &vc); err != nil {\n\t\treturn\n\t}\n\treturn\n}", "func (db *DB) GetClassesPeriods() (map[string]string, error) {\n\tm := map[string]string{}\n\n\tconn, err := redishelper.GetRedisConn(db.RedisServer, db.RedisPassword)\n\tif err != nil {\n\t\treturn map[string]string{}, err\n\t}\n\tdefer conn.Close()\n\n\tk := \"ming:campuses\"\n\tcampuses, err := redis.Strings(conn.Do(\"ZRANGE\", k, 0, -1))\n\tif err != nil {\n\t\treturn map[string]string{}, err\n\t}\n\n\tfor _, campus := range campuses {\n\t\tk = fmt.Sprintf(\"ming:%v:categories\", campus)\n\t\tcategories, err := redis.Strings(conn.Do(\"ZRANGE\", k, 0, -1))\n\t\tif err != nil {\n\t\t\treturn map[string]string{}, err\n\t\t}\n\n\t\tfor _, category := range categories {\n\t\t\tk = fmt.Sprintf(\"ming:%v:%v:classes\", campus, category)\n\t\t\tclasses, err := redis.Strings(conn.Do(\"ZRANGE\", k, 0, -1))\n\t\t\tif err != nil {\n\t\t\t\treturn map[string]string{}, err\n\t\t\t}\n\n\t\t\tfor _, class := range classes {\n\t\t\t\tperiod, err := db.GetClassPeriod(campus, category, class)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn map[string]string{}, err\n\t\t\t\t}\n\n\t\t\t\tk := fmt.Sprintf(\"%v:%v:%v\", campus, category, class)\n\t\t\t\tm[k] = period\n\t\t\t}\n\n\t\t}\n\t}\n\treturn m, nil\n}", "func (o ElastigroupIntegrationEcsAutoscaleDownPtrOutput) EvaluationPeriods() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v *ElastigroupIntegrationEcsAutoscaleDown) *int {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.EvaluationPeriods\n\t}).(pulumi.IntPtrOutput)\n}", "func (_Vault *VaultCallerSession) GetDecimals(token common.Address) (uint8, error) {\n\treturn _Vault.Contract.GetDecimals(&_Vault.CallOpts, token)\n}", "func (k Keeper) DeleteValidatorSlashingPeriods(ctx sdk.Context) {\n\tstore := ctx.KVStore(k.storeKey)\n\titer := sdk.KVStorePrefixIterator(store, ValidatorSlashingPeriodKey)\n\tfor ; iter.Valid(); iter.Next() {\n\t\tstore.Delete(iter.Key())\n\t}\n\titer.Close()\n}", "func (r Virtual_PlacementGroup) GetGuests() (resp []datatypes.Virtual_Guest, err error) {\n\terr = r.Session.DoRequest(\"SoftLayer_Virtual_PlacementGroup\", \"getGuests\", nil, &r.Options, &resp)\n\treturn\n}", "func (o *GetOutagesParams) SetPeriod(period *float64) {\n\to.Period = period\n}", "func (o ElastigroupScalingUpPolicyOutput) EvaluationPeriods() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v ElastigroupScalingUpPolicy) *int { return v.EvaluationPeriods }).(pulumi.IntPtrOutput)\n}", "func (o ElastigroupIntegrationKubernetesAutoscaleDownOutput) EvaluationPeriods() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v ElastigroupIntegrationKubernetesAutoscaleDown) *int { return v.EvaluationPeriods }).(pulumi.IntPtrOutput)\n}", "func (vva ValidatorVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn vva.OriginalVesting.Sub(vva.GetVestedCoins(blockTime))\n}", "func (va ClawbackVestingAccount) GetVestedOnly(blockTime time.Time) sdk.Coins {\n\treturn ReadSchedule(va.StartTime, va.EndTime, va.VestingPeriods, va.OriginalVesting, blockTime.Unix())\n}", "func (s *intervalSegment) GetSegments(timeRange models.TimeRange) []Segment {\n\tvar segments []Segment\n\tcalc := interval.GetCalculator(s.intervalType)\n\tstart := calc.CalSegmentTime(timeRange.Start)\n\tend := calc.CalSegmentTime(timeRange.End)\n\ts.segments.Range(func(k, v interface{}) bool {\n\t\tsegment, ok := v.(Segment)\n\t\tif ok {\n\t\t\tbaseTime := segment.BaseTime()\n\t\t\tif start >= baseTime && end <= baseTime {\n\t\t\t\tsegments = append(segments, segment)\n\t\t\t}\n\t\t}\n\t\treturn true\n\t})\n\treturn segments\n}", "func (o MrScalarTaskScalingDownPolicyOutput) EvaluationPeriods() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v MrScalarTaskScalingDownPolicy) *int { return v.EvaluationPeriods }).(pulumi.IntPtrOutput)\n}", "func AggregationPeriod_Values() []string {\n\treturn []string{\n\t\tAggregationPeriodPt5m,\n\t\tAggregationPeriodPt1h,\n\t\tAggregationPeriodP1d,\n\t}\n}", "func (m *GroupPolicyDefinition) GetPresentations()([]GroupPolicyPresentationable) {\n val, err := m.GetBackingStore().Get(\"presentations\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.([]GroupPolicyPresentationable)\n }\n return nil\n}", "func (o ElastigroupIntegrationNomadAutoscaleDownOutput) EvaluationPeriods() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v ElastigroupIntegrationNomadAutoscaleDown) *int { return v.EvaluationPeriods }).(pulumi.IntPtrOutput)\n}", "func (o InstanceOutput) Period() pulumi.IntOutput {\n\treturn o.ApplyT(func(v *Instance) pulumi.IntOutput { return v.Period }).(pulumi.IntOutput)\n}", "func (o ElastigroupIntegrationKubernetesAutoscaleDownPtrOutput) EvaluationPeriods() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v *ElastigroupIntegrationKubernetesAutoscaleDown) *int {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.EvaluationPeriods\n\t}).(pulumi.IntPtrOutput)\n}", "func (api *tenantAPI) ApisrvList(ctx context.Context, opts *api.ListWatchOptions) ([]*cluster.Tenant, error) {\n\tif api.ct.resolver != nil {\n\t\tapicl, err := api.ct.apiClient()\n\t\tif err != nil {\n\t\t\tapi.ct.logger.Errorf(\"Error creating API server clent. Err: %v\", err)\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn apicl.ClusterV1().Tenant().List(context.Background(), opts)\n\t}\n\n\t// List from local cache\n\tctkitObjs, err := api.List(ctx, opts)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar ret []*cluster.Tenant\n\tfor _, obj := range ctkitObjs {\n\t\tret = append(ret, &obj.Tenant)\n\t}\n\treturn ret, nil\n}", "func (h *Hosts) Period() time.Duration {\n\tif h.Stopped() {\n\t\treturn -1\n\t}\n\n\th.mux.RLock()\n\tdefer h.mux.RUnlock()\n\n\treturn h.period\n}", "func NewValidatorVestingAccountRaw(bva *vestingtypes.BaseVestingAccount,\n\tstartTime int64, periods vestingtypes.Periods, validatorAddress sdk.ConsAddress, returnAddress sdk.AccAddress, signingThreshold int64) *ValidatorVestingAccount {\n\n\tpva := &vestingtypes.PeriodicVestingAccount{\n\t\tBaseVestingAccount: bva,\n\t\tStartTime: startTime,\n\t\tVestingPeriods: periods,\n\t}\n\tvar vestingPeriodProgress []VestingProgress\n\tfor i := 0; i < len(periods); i++ {\n\t\tvestingPeriodProgress = append(vestingPeriodProgress, VestingProgress{false, false})\n\t}\n\n\treturn &ValidatorVestingAccount{\n\t\tPeriodicVestingAccount: pva,\n\t\tValidatorAddress: validatorAddress,\n\t\tReturnAddress: returnAddress,\n\t\tSigningThreshold: signingThreshold,\n\t\tCurrentPeriodProgress: CurrentPeriodProgress{0, 0},\n\t\tVestingPeriodProgress: vestingPeriodProgress,\n\t\tDebtAfterFailedVesting: sdk.NewCoins(),\n\t}\n}", "func (vva ValidatorVestingAccount) Validate() error {\n\tif vva.SigningThreshold > 100 || vva.SigningThreshold < 0 {\n\t\treturn errors.New(\"signing threshold must be between 0 and 100\")\n\t}\n\tif vva.ReturnAddress.Equals(vva.Address) {\n\t\treturn errors.New(\"return address cannot be the same as the account address\")\n\t}\n\treturn vva.PeriodicVestingAccount.Validate()\n}", "func (msg MsgCreatePeriodicVestingAccount) GetSigners() []sdk.AccAddress {\n\tfrom, err := sdk.AccAddressFromBech32(msg.FromAddress)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn []sdk.AccAddress{from}\n}", "func (pva PeriodicVestingAccount) GetVestedCoins(blockTime time.Time) sdk.Coins {\n\tcoins := ReadSchedule(pva.StartTime, pva.EndTime, pva.VestingPeriods, pva.OriginalVesting, blockTime.Unix())\n\tif coins.IsZero() {\n\t\treturn nil\n\t}\n\treturn coins\n}", "func (dva DelayedVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn dva.OriginalVesting.Sub(dva.GetVestedCoins(blockTime))\n}", "func (di *RealDataitem) GetKVPs() []DataKVP {\n\treturn di.kvps\n}", "func (o *User) GetDrives() []MicrosoftGraphDrive {\n\tif o == nil || o.Drives == nil {\n\t\tvar ret []MicrosoftGraphDrive\n\t\treturn ret\n\t}\n\treturn *o.Drives\n}", "func (o ElastigroupScalingTargetPolicyOutput) EvaluationPeriods() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v ElastigroupScalingTargetPolicy) *int { return v.EvaluationPeriods }).(pulumi.IntPtrOutput)\n}", "func (o ElastigroupIntegrationNomadAutoscaleDownPtrOutput) EvaluationPeriods() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v *ElastigroupIntegrationNomadAutoscaleDown) *int {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.EvaluationPeriods\n\t}).(pulumi.IntPtrOutput)\n}", "func PeriodUpGET(w http.ResponseWriter, r *http.Request) {\n\tsess := model.Instance(r)\n var period model.Periodo\n\tvar params httprouter.Params\n\tparams = context.Get(r, \"params\").(httprouter.Params)\n\tid,_ := atoi32(params.ByName(\"id\"))\n period.Id = id\n path := \"/period/list\"\n err := (&period).PeriodById()\n\tif err != nil { // Si no existe el periodo\n log.Println(err)\n sess.AddFlash(view.Flash{\"Es raro. No tenemos periodo.\", view.FlashError})\n sess.Save(r, w)\n http.Redirect(w, r, path, http.StatusFound)\n return\n\t}\n\tv := view.New(r)\n\tv.Name = \"periodo/periodupdate\"\n\tv.Vars[\"token\"] = csrfbanana.Token(w, r, sess)\n v.Vars[\"Period\"] = period\n//\tview.Repopulate([]string{\"name\"}, r.Form, v.Vars)\n v.Render(w)\n }", "func (_DetailedTestToken *DetailedTestTokenSession) Decimals() (uint8, error) {\n\treturn _DetailedTestToken.Contract.Decimals(&_DetailedTestToken.CallOpts)\n}", "func (rs *StatsPeriodResultSet) All() ([]*StatsPeriod, error) {\n\tvar result []*StatsPeriod\n\tfor rs.Next() {\n\t\trecord, err := rs.Get()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tresult = append(result, record)\n\t}\n\treturn result, nil\n}", "func DescribePVs() {\n\tlist, err := Get()\n\tif err != nil {\n\t\tlog.Printf(\"Unable to get pvs: %s\", err)\n\t}\n\tif list != nil {\n\t\tfor _, pv := range list.PersistentVolumes {\n\t\t\terr := pv.Describe()\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"Unable to describe pv %s: %s\", pv.Metadata.Name, err)\n\t\t\t}\n\t\t}\n\t}\n}", "func (o *SLAGetExclusionPeriodsParams) WithTimeout(timeout time.Duration) *SLAGetExclusionPeriodsParams {\n\to.SetTimeout(timeout)\n\treturn o\n}", "func (v PingSlotPeriod) MarshalJSONPB(m *jsonpb.Marshaler) ([]byte, error) {\n\treturn marshalJSONPBEnum(m, PingSlotPeriod_name, int32(v))\n}", "func (o MrScalarTaskScalingUpPolicyOutput) EvaluationPeriods() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v MrScalarTaskScalingUpPolicy) *int { return v.EvaluationPeriods }).(pulumi.IntPtrOutput)\n}", "func (o ReservedInstanceOutput) Period() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v *ReservedInstance) pulumi.IntPtrOutput { return v.Period }).(pulumi.IntPtrOutput)\n}", "func (_Bep20 *Bep20Session) Decimals() (uint8, error) {\n\treturn _Bep20.Contract.Decimals(&_Bep20.CallOpts)\n}", "func (_TTFT20 *TTFT20Session) Decimals() (uint8, error) {\n\treturn _TTFT20.Contract.Decimals(&_TTFT20.CallOpts)\n}", "func (o ResponsePlanIntegrationOutput) Pagerduties() ResponsePlanIntegrationPagerdutyArrayOutput {\n\treturn o.ApplyT(func(v ResponsePlanIntegration) []ResponsePlanIntegrationPagerduty { return v.Pagerduties }).(ResponsePlanIntegrationPagerdutyArrayOutput)\n}", "func (o *User) GetDrives() []Drive {\n\tif o == nil || o.Drives == nil {\n\t\tvar ret []Drive\n\t\treturn ret\n\t}\n\treturn o.Drives\n}", "func (db *DB) GetAllPeriodsOfCategory(category string) (map[string][]string, error) {\n\tconn, err := redishelper.GetRedisConn(db.RedisServer, db.RedisPassword)\n\tif err != nil {\n\t\treturn map[string][]string{}, err\n\t}\n\tdefer conn.Close()\n\n\tk := fmt.Sprintf(\"ming:%v:campuses\", category)\n\tcampuses, err := redis.Strings(conn.Do(\"ZRANGE\", k, 0, -1))\n\tif err != nil {\n\t\treturn map[string][]string{}, err\n\t}\n\n\tperiodsMap := map[string][]string{}\n\tfor _, campus := range campuses {\n\t\tk = fmt.Sprintf(\"ming:%v:%v:periods\", campus, category)\n\t\tperiods, err := redis.Strings(conn.Do(\"ZRANGE\", k, 0, -1))\n\t\tif err != nil {\n\t\t\treturn map[string][]string{}, err\n\t\t}\n\n\t\tif len(periods) > 0 {\n\t\t\tperiodsMap[campus] = append(periodsMap[campus], periods...)\n\t\t}\n\t}\n\n\treturn periodsMap, nil\n}", "func (env *Env) GetPayments(w http.ResponseWriter, r *http.Request) {\n\tlog.Printf(\"GET payments\")\n\n\ttxs, err := env.db.GetAllTX()\n\n\tif err != nil {\n\t\tlog.Printf(\"Error retrieving payments: %v\\n\", err)\n\t\trender.Status(r, http.StatusNotFound)\n\t\treturn\n\t}\n\trender.JSON(w, r, txs)\n}", "func (test *Test) GetDomains(projectName string) ([]models.Domain, error) {\n\treturn tests.NormalDomains, nil\n}", "func GetDeploymentVolumes(item interface{}) []corev1.Volume {\n\treturn item.(appsv1.Deployment).Spec.Template.Spec.Volumes\n}", "func (o ElastigroupIntegrationDockerSwarmAutoscaleDownPtrOutput) EvaluationPeriods() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v *ElastigroupIntegrationDockerSwarmAutoscaleDown) *int {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.EvaluationPeriods\n\t}).(pulumi.IntPtrOutput)\n}", "func (me *XsdGoPkgHasElems_PeriodsequenceTxsdGeneralLedgerEntriesSequenceJournalSequenceTransactionTransactionsequenceTxsdGeneralLedgerEntriesSequenceJournalJournalsequenceTxsdGeneralLedgerEntriesGeneralLedgerEntriesschema_Period_TSAFPTAccountingPeriod_) Walk() (err error) {\n\tif fn := WalkHandlers.XsdGoPkgHasElems_PeriodsequenceTxsdGeneralLedgerEntriesSequenceJournalSequenceTransactionTransactionsequenceTxsdGeneralLedgerEntriesSequenceJournalJournalsequenceTxsdGeneralLedgerEntriesGeneralLedgerEntriesschema_Period_TSAFPTAccountingPeriod_; me != nil {\n\t\tif fn != nil {\n\t\t\tif err = fn(me, true); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tif fn != nil {\n\t\t\tif err = fn(me, false); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}", "func (o GetResponsePlanIntegrationOutput) Pagerduties() GetResponsePlanIntegrationPagerdutyArrayOutput {\n\treturn o.ApplyT(func(v GetResponsePlanIntegration) []GetResponsePlanIntegrationPagerduty { return v.Pagerduties }).(GetResponsePlanIntegrationPagerdutyArrayOutput)\n}", "func (o InstanceOutput) ServiceAccountScopes() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v *Instance) pulumi.StringArrayOutput { return v.ServiceAccountScopes }).(pulumi.StringArrayOutput)\n}", "func (d *portworx) GetPoolDrives(n *node.Node) (map[string][]string, error) {\n\tsystemOpts := node.SystemctlOpts{\n\t\tConnectionOpts: node.ConnectionOpts{\n\t\t\tTimeout: startDriverTimeout,\n\t\t\tTimeBeforeRetry: defaultRetryInterval,\n\t\t},\n\t\tAction: \"start\",\n\t}\n\tpoolDrives := make(map[string][]string, 0)\n\tlog.Infof(\"Getting available block drives on node [%s]\", n.Name)\n\tblockDrives, err := d.nodeDriver.GetBlockDrives(*n, systemOpts)\n\n\tif err != nil {\n\t\treturn poolDrives, err\n\t}\n\tfor _, v := range blockDrives {\n\t\tlabelsMap := v.Labels\n\t\tif pm, ok := labelsMap[\"pxpool\"]; ok {\n\t\t\tpoolDrives[pm] = append(poolDrives[pm], v.Path)\n\t\t}\n\t}\n\treturn poolDrives, nil\n}", "func (x ApmApplicationEntity) GetDeployments() []ApmApplicationDeployment {\n\treturn x.Deployments\n}", "func getVolunteers(c *gin.Context) {\n\tvar vols []Volunteer\n\t//Read volunteers from database\n\tif err := db.Find(&vols).Error; err != nil {\n\t\tcreateNotFoundResponse(c)\n\t\treturn\n\t}\n\n\t//Authorization if user is reporter\n\tif !reporterAuth(c) {\n\t\treturn\n\t}\n\tc.JSON(200, vols)\n}" ]
[ "0.80092347", "0.53922135", "0.5174269", "0.5134585", "0.5022448", "0.4940613", "0.49172422", "0.47227874", "0.47114304", "0.45741335", "0.45310128", "0.45140642", "0.44248143", "0.44168282", "0.4407911", "0.43513176", "0.42947915", "0.4189046", "0.41723818", "0.4131881", "0.4053247", "0.40236562", "0.39879975", "0.39294922", "0.39213714", "0.39109382", "0.39109382", "0.39024928", "0.3900728", "0.38931066", "0.38889292", "0.38875407", "0.38849813", "0.3861395", "0.385578", "0.38547662", "0.3852182", "0.38343537", "0.38277984", "0.38249394", "0.3822982", "0.38122776", "0.38065004", "0.38047048", "0.37849832", "0.37752026", "0.37729686", "0.3765981", "0.3765211", "0.37588602", "0.37554604", "0.374308", "0.3742636", "0.37376982", "0.37339658", "0.3731735", "0.37252152", "0.37168857", "0.37157488", "0.3714927", "0.3713916", "0.3706755", "0.36981103", "0.36961916", "0.36953577", "0.36876643", "0.3686571", "0.36791754", "0.36789998", "0.3672896", "0.36722428", "0.3664821", "0.36636394", "0.3659449", "0.36582756", "0.36554384", "0.36534506", "0.36353996", "0.36326408", "0.36324763", "0.3626295", "0.36254814", "0.36253777", "0.36230835", "0.36191887", "0.36134937", "0.36130694", "0.36060825", "0.36031994", "0.36020252", "0.35974", "0.3595964", "0.35933015", "0.35926175", "0.3587247", "0.3583429", "0.35788026", "0.35568056", "0.3555782", "0.35547236" ]
0.82599163
0
Validate checks for errors on the account fields
func (pva PeriodicVestingAccount) Validate() error { if pva.GetStartTime() >= pva.GetEndTime() { return errors.New("vesting start-time cannot be before end-time") } endTime := pva.StartTime originalVesting := sdk.NewCoins() for _, p := range pva.VestingPeriods { endTime += p.Length originalVesting = originalVesting.Add(p.Amount...) } if endTime != pva.EndTime { return errors.New("vesting end time does not match length of all vesting periods") } if !originalVesting.IsEqual(pva.OriginalVesting) { return errors.New("original vesting coins does not match the sum of all coins in vesting periods") } return pva.BaseVestingAccount.Validate() }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (account *Account) Validate() (map[string]interface{}, bool) {\n\n\tif !strings.Contains(account.Phone, \"+\") {\n\t\treturn u.Message(false, \"Phone Number address is required\"), false\n\t}\n\n\tif len(account.UserName) < 3 {\n\t\treturn u.Message(false, \"Username is required\"), false\n\t}\n\n\t//PhoneNumber must be unique\n\ttemp := &Account{}\n\n\t//check for errors and duplicate phones\n\terr := GetDB().Table(\"accounts\").Where(\"phone = ?\", account.Phone).First(temp).Error\n\tif err != nil && err != gorm.ErrRecordNotFound {\n\t\treturn u.Message(false, \"Connection error. Please retry\"+err.Error()), false\n\t}\n\tif temp.Phone != \"\" {\n\t\treturn u.Message(false, \"Phone Number address already in use by another user.\"), false\n\t}\n\n\t//check for errors and duplicate username\n\terr = GetDB().Table(\"accounts\").Where(\"user_name = ?\", account.UserName).First(temp).Error\n\tif err != nil && err != gorm.ErrRecordNotFound {\n\t\treturn u.Message(false, \"Connection error. Please retry\"+err.Error()), false\n\t}\n\tif temp.UserName != \"\" {\n\t\tresponse := fmt.Sprintf(\"Username: %d is already in use by another user.\", account.UserName)\n\t\treturn u.Message(false, response), false\n\t}\n\n\treturn u.Message(false, \"Requirement passed\"), true\n}", "func (account Account) Validate() (map[string]interface{}, bool) {\n\n\tif !strings.Contains(account.Email, \"@\") {\n\t\treturn u.Message(false, ERROR_EMAIL), false\n\t}\n\n\tif len(account.Password) < 6 {\n\t\treturn u.Message(false, ERROR_PASSWORD_LENTH), false\n\t}\n\n\t// Email must be unique\n\ttemp := &Account{}\n\n\t// 数据类型合法时,查询数据表,GetDB return the configed db\n\terr := GetDB().Table(\"accounts\").Where(\"email = ?\", account.Email).First(temp).Error\n\tif err != nil && err != gorm.ErrRecordNotFound {\n\t\treturn u.Message(false, ERROR_CONNECTION), false\n\t}\n\t// 存在该email\n\tif temp.Email != \"\" {\n\t\treturn u.Message(false, ERROR_EMAIL_USED), false\n\t}\n\n\treturn u.Message(false, GET_SUCCESS), true\n}", "func (a Account) Validate() error {\n\treturn validation.ValidateStruct(&a,\n\t\tvalidation.Field(&a.Name, validation.Required, validation.Length(3, 75)),\n\t)\n}", "func (m *Account) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateAccountID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateAuditLogs(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateCurrency(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateParentAccountID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validatePaymentMethodID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateReferenceTime(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (account *Account) Validate() (map[string]interface{}, bool) {\n\n\tif !strings.Contains(account.Email, \"@\") {\n\t\treturn u.Message(false, \"Email address is required\"), false\n\t}\n\n\tif len(account.Password) < 6 {\n\t\treturn u.Message(false, \"Password is required\"), false\n\t}\n\n\t//Email must be unique\n\ttemp := &Account{}\n\t//check for errors and duplicate emails\n\terr := GetDB().Table(\"accounts\").Where(\"email = ?\", account.Email).First(temp).Error\n\tif err != nil && err != gorm.ErrRecordNotFound {\n\t\treturn u.Message(false, \"Connection error. Please retry\"), false\n\t}\n\tif temp.Email != \"\" {\n\t\treturn u.Message(false, \"Email address already in use by another user.\"), false\n\t}\n\treturn u.Message(false, \"Requirement passed\"), true\n}", "func (a *Account) Validate() error {\n\treturn nil\n}", "func (mt *Account) Validate() (err error) {\n\tif mt.ID == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`response`, \"id\"))\n\t}\n\tif mt.Password == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`response`, \"password\"))\n\t}\n\n\treturn\n}", "func (accountInfo *AccountInfo) Validate() error {\n\taccountSchema, _ := GetAccountSchema(accountInfo.Domain)\n\tif accountSchema == nil {\n\t\treturn errors.New(\"schema undefined for domain \" + accountInfo.Domain)\n\t}\n\n\t// Group\n\tif !accountSchema.IsGroupExist(accountInfo.Group) {\n\t\treturn errors.New(\"unknown group \" + accountInfo.Group)\n\t}\n\n\t// UserID\n\tif accountInfo.Uid == \"\" {\n\t\treturn errors.New(\"uid can not be empty\")\n\t}\n\n\t// LoginIDs\n\tif len(accountInfo.LoginIDs) == 0 {\n\t\treturn errors.New(\"should have at least one login id\")\n\t}\n\trequiredIDs := accountSchema.getRequiredLogIDs()\n\tfor _, requiredID := range requiredIDs {\n\t\tif _, ok := accountInfo.LoginIDs[requiredID]; !ok {\n\t\t\treturn errors.New(\"login id:\" + requiredID + \" is required but not specified\")\n\t\t}\n\t}\n\tfor k, v := range accountInfo.LoginIDs {\n\t\tloginIDSchema, _ := accountSchema.GetLoginIDSchema(k)\n\t\tif loginIDSchema == nil {\n\t\t\treturn errors.New(\"login id schema for \" + k + \" is not defined\")\n\t\t} else {\n\t\t\tif !loginIDSchema.NeedVerified {\n\t\t\t\tv.Verified = true\n\t\t\t\t// accountInfo.LoginIDs[k] = v\n\t\t\t}\n\t\t\tif !loginIDSchema.Validator.Validate(v.ID) {\n\t\t\t\treturn errors.New(\"invalid format of login id \" + k + \":\" + v.ID)\n\t\t\t}\n\t\t}\n\t}\n\n\t// options\n\toptionsMap := mergeMaps(accountInfo.Profiles, accountInfo.Others)\n\trequiredOptions := accountSchema.getRequiredOptions()\n\tfor _, requiredOption := range requiredOptions {\n\t\tif _, ok := optionsMap[requiredOption]; !ok {\n\t\t\treturn errors.New(\"option:\" + requiredOption + \" is required but not specified\")\n\t\t}\n\t}\n\n\tfor k, v := range optionsMap {\n\t\toptionSchema, _ := accountSchema.GetOptionSchema(k)\n\t\tif optionSchema == nil {\n\t\t\treturn errors.New(\"option schema for \" + k + \" is not defined\")\n\t\t} else {\n\t\t\tif !optionSchema.Validator.Validate(v) {\n\t\t\t\treturn errors.New(\"invalid format of option \" + k)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func (mt *Account) Validate() (err error) {\n\n\tif mt.Href == \"\" {\n\t\terr = goa.MissingAttributeError(`response`, \"href\", err)\n\t}\n\tif mt.Name == \"\" {\n\t\terr = goa.MissingAttributeError(`response`, \"name\", err)\n\t}\n\n\tif mt.CreatedAt != nil {\n\t\tif err2 := goa.ValidateFormat(goa.FormatDateTime, *mt.CreatedAt); err2 != nil {\n\t\t\terr = goa.InvalidFormatError(`response.created_at`, *mt.CreatedAt, goa.FormatDateTime, err2, err)\n\t\t}\n\t}\n\tif mt.CreatedBy != nil {\n\t\tif err2 := goa.ValidateFormat(goa.FormatEmail, *mt.CreatedBy); err2 != nil {\n\t\t\terr = goa.InvalidFormatError(`response.created_by`, *mt.CreatedBy, goa.FormatEmail, err2, err)\n\t\t}\n\t}\n\treturn\n}", "func (c *modAccountRun) validate(args []string) error {\n\tif len(args) < 2 {\n\t\treturn errors.New(\"not enough arguments\")\n\t}\n\n\tif len(args) > 2 {\n\t\treturn errors.New(\"too many arguments\")\n\t}\n\n\treturn nil\n}", "func (m *LedgerAccount) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateAccount(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateCurrency(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validatePostings(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (b *OGame) ValidateAccount(code string) error {\n\treturn b.validateAccount(code)\n}", "func (ut *accountInputPayload) Validate() (err error) {\n\tif ut.Email != nil {\n\t\tif err2 := goa.ValidateFormat(goa.FormatEmail, *ut.Email); err2 != nil {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidFormatError(`response.email`, *ut.Email, goa.FormatEmail, err2))\n\t\t}\n\t}\n\tif ut.Name != nil {\n\t\tif utf8.RuneCountInString(*ut.Name) < 1 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`response.name`, *ut.Name, utf8.RuneCountInString(*ut.Name), 1, true))\n\t\t}\n\t}\n\tif ut.Name != nil {\n\t\tif utf8.RuneCountInString(*ut.Name) > 30 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`response.name`, *ut.Name, utf8.RuneCountInString(*ut.Name), 30, false))\n\t\t}\n\t}\n\tif ut.Surname != nil {\n\t\tif utf8.RuneCountInString(*ut.Surname) < 1 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`response.surname`, *ut.Surname, utf8.RuneCountInString(*ut.Surname), 1, true))\n\t\t}\n\t}\n\tif ut.Surname != nil {\n\t\tif utf8.RuneCountInString(*ut.Surname) > 30 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`response.surname`, *ut.Surname, utf8.RuneCountInString(*ut.Surname), 30, false))\n\t\t}\n\t}\n\treturn\n}", "func (account *Account) ValidateUpdate() (map[string]interface{}, bool) {\n\n\tif !strings.Contains(account.Email, \"@\") {\n\t\treturn u.Message(false, \"Email address is required\"), false\n\t}\n\n\tif len(account.Password) < 6 {\n\t\treturn u.Message(false, \"Password is required\"), false\n\t}\n\n\t//Email must be unique\n\ttemp := &Account{}\n\t//check for errors and duplicate emails\n\terr := GetDB().Table(\"accounts\").Where(\"email = ?\", account.Email).First(temp).Error\n\tif err != nil && err != gorm.ErrRecordNotFound {\n\t\treturn u.Message(false, \"Connection error. Please retry\"), false\n\t}\n\tif temp.Email == \"\" {\n\t\treturn u.Message(false, \"Email address not found in database.\"), false\n\t}\n\treturn u.Message(true, \"Requirement passed\"), true\n}", "func (ut *AccountInputPayload) Validate() (err error) {\n\tif ut.Email != nil {\n\t\tif err2 := goa.ValidateFormat(goa.FormatEmail, *ut.Email); err2 != nil {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidFormatError(`response.email`, *ut.Email, goa.FormatEmail, err2))\n\t\t}\n\t}\n\tif ut.Name != nil {\n\t\tif utf8.RuneCountInString(*ut.Name) < 1 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`response.name`, *ut.Name, utf8.RuneCountInString(*ut.Name), 1, true))\n\t\t}\n\t}\n\tif ut.Name != nil {\n\t\tif utf8.RuneCountInString(*ut.Name) > 30 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`response.name`, *ut.Name, utf8.RuneCountInString(*ut.Name), 30, false))\n\t\t}\n\t}\n\tif ut.Surname != nil {\n\t\tif utf8.RuneCountInString(*ut.Surname) < 1 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`response.surname`, *ut.Surname, utf8.RuneCountInString(*ut.Surname), 1, true))\n\t\t}\n\t}\n\tif ut.Surname != nil {\n\t\tif utf8.RuneCountInString(*ut.Surname) > 30 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`response.surname`, *ut.Surname, utf8.RuneCountInString(*ut.Surname), 30, false))\n\t\t}\n\t}\n\treturn\n}", "func ValidateAccount(client httpclient.IHttpClient, ctx context.Context, lobby, code string) error {\n\tif len(code) != 36 {\n\t\treturn errors.New(\"invalid validation code\")\n\t}\n\treq, err := http.NewRequest(http.MethodPut, \"https://\"+lobby+\".ogame.gameforge.com/api/users/validate/\"+code, strings.NewReader(`{\"language\":\"en\"}`))\n\tif err != nil {\n\t\treturn err\n\t}\n\treq.WithContext(ctx)\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\treturn nil\n}", "func (b *Builder) Validate() (*Account, error) {\n\tb.validate.SetTagName(b.essential.Country)\n\tif err := validateStruct(b.validate, b.essential); err != nil {\n\t\treturn nil, err\n\t}\n\tb.validate.SetTagName(\"validate\")\n\tif err := validateStruct(b.validate, b.essential); err != nil {\n\t\treturn nil, err\n\t}\n\tif err := validateStruct(b.validate, b.optional); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Account{\n\t\tid: b.essential.ID,\n\t\torganizationID: b.essential.OrganizationID,\n\t\tversionIndex: b.optional.VersionIndex,\n\t\tcountry: b.essential.Country,\n\t\tbankIDCode: b.essential.BankIDCode,\n\t\tbankID: b.essential.BankID,\n\t\tbic: b.essential.Bic,\n\t\tiban: b.essential.Iban,\n\t\tbaseCurrency: b.optional.BaseCurrency,\n\t\taccountNumber: b.optional.AccountNumber,\n\t\tcustomerID: b.optional.CustomerID,\n\t\ttitle: b.optional.Title,\n\t\tfirstName: b.optional.FirstName,\n\t\tbankAccountName: b.optional.BankAccountName,\n\t\taltBankAccountNames: b.optional.AltBankAccountNames,\n\t\taccountClassification: b.optional.AccountClassification,\n\t\tjointAccount: b.optional.JointAccount,\n\t\taccountMatchingOptOut: b.optional.AccountMatchingOptOut,\n\t\tsecondaryIdentification: b.optional.SecondaryIdentification,\n\t}, nil\n}", "func (a *Account) Validate() error {\n\tvalidate := validator.New()\n\treturn validate.Struct(a)\n}", "func (ga GenesisAccount) Validate() error {\n\tif ethermint.IsZeroAddress(ga.Address) {\n\t\treturn fmt.Errorf(\"address cannot be the zero address %s\", ga.Address)\n\t}\n\tif len(ethcmn.Hex2Bytes(ga.Code)) == 0 {\n\t\treturn errors.New(\"code cannot be empty\")\n\t}\n\n\treturn ga.Storage.Validate()\n}", "func validate(user *customer_api.DbUser, allowEmpty bool) error {\n\tconst minNameLength, maxNameLength = 3, 20\n\tconst emailRegexString = \"^[a-zA-Z0-9+_.-]+@[a-zA-Z0-9.-]+$\"\n\tvar emailRegex = regexp.MustCompile(emailRegexString)\n\n\tif !(allowEmpty && user.Email == \"\") {\n\t\tif len(user.Email) < 5 || !emailRegex.MatchString(user.Email) {\n\t\t\treturn errors.New(\"invalid email\")\n\t\t}\n\t}\n\n\tif !(allowEmpty && user.FirstName == \"\") {\n\t\tif len(user.FirstName) < minNameLength || len(user.FirstName) > maxNameLength {\n\t\t\treturn errors.New(\"first_name should be between 3 and 20 characters\")\n\t\t}\n\t}\n\n\tif !(allowEmpty && user.LastName == \"\") {\n\t\tif len(user.LastName) < minNameLength || len(user.LastName) > maxNameLength {\n\t\t\treturn errors.New(\"last_name should be between 3 and 20 characters\")\n\t\t}\n\t}\n\n\tif !(allowEmpty && user.Phone == 0) {\n\t\tif user.Phone < 1000000000 || user.Phone > 9999999999 {\n\t\t\treturn errors.New(\"invalid phone no\")\n\t\t}\n\t}\n\n\tif !(allowEmpty && user.Id == \"\") {\n\t\tif user.Id == \"\" {\n\t\t\treturn errors.New(\"id cannot be empty\")\n\t\t}\n\t}\n\treturn nil\n}", "func (server *Server) checkValidAccount(ctx *gin.Context, id int64, curr string) (bool, db.Account) {\n\tacc, err := server.repository.GetAccount(ctx, id)\n\tif err != nil {\n\t\tctx.JSON(http.StatusNotFound, errorResponse(err))\n\t\treturn false, db.Account{}\n\t}\n\tif acc.Currency != curr {\n\t\terr = fmt.Errorf(\"invalid currency for account [%d]: expected %s received %s\", acc.ID, acc.Currency, curr)\n\t\tctx.JSON(http.StatusBadRequest, errorResponse(err))\n\t\treturn false, db.Account{}\n\t}\n\n\treturn true, acc\n}", "func (mt *EasypostCarrierAccounts) Validate() (err error) {\n\tif mt.ID == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`response`, \"id\"))\n\t}\n\tif mt.Object == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`response`, \"object\"))\n\t}\n\n\tif ok := goa.ValidatePattern(`^CarrierAccount$`, mt.Object); !ok {\n\t\terr = goa.MergeErrors(err, goa.InvalidPatternError(`response.object`, mt.Object, `^CarrierAccount$`))\n\t}\n\treturn\n}", "func (m *InfrastructureAccount) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateCostCenter(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateCriticalityLevel(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateEnvironment(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateExternalID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateLifecycleStatus(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateName(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateOwner(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateType(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (m *CloudAccountExtended) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\t// validation for a type composition with CloudAccount\n\tif err := m.CloudAccount.Validate(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateState(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateType(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (a *Account) Validate() error {\n\terr := validation.ValidateStruct(a,\n\t\tvalidation.Field(&a.AdminRoleArn, validateAdminRoleArn...),\n\t\tvalidation.Field(&a.ID, validateID...),\n\t\tvalidation.Field(&a.LastModifiedOn, validateInt64...),\n\t\tvalidation.Field(&a.Status, validateStatus...),\n\t\tvalidation.Field(&a.CreatedOn, validateInt64...),\n\t\tvalidation.Field(&a.PrincipalRoleArn, validatePrincipalRoleArn...),\n\t\tvalidation.Field(&a.PrincipalPolicyHash, validatePrincipalPolicyHash...),\n\t)\n\tif err != nil {\n\t\treturn errors.NewValidation(\"account\", err)\n\t}\n\treturn nil\n}", "func validRawAccount(accountName string) error {\n\t// param absence check\n\tif accountName == \"\" {\n\t\treturn fmt.Errorf(\"invoke NewAccount failed, account name is empty\")\n\t}\n\n\t// account naming rule check\n\tif len(accountName) != accountSize {\n\t\treturn fmt.Errorf(\"invoke NewAccount failed, account name length expect %d, actual: %d\", accountSize, len(accountName))\n\t}\n\n\tfor i := 0; i < accountSize; i++ {\n\t\tif accountName[i] >= '0' && accountName[i] <= '9' {\n\t\t\tcontinue\n\t\t} else {\n\t\t\treturn fmt.Errorf(\"invoke NewAccount failed, account name expect continuous %d number\", accountSize)\n\t\t}\n\t}\n\n\treturn nil\n}", "func (o *CloudSnapshotAccount) Validate() error {\n\n\terrors := elemental.Errors{}\n\trequiredErrors := elemental.Errors{}\n\n\tif err := ValidateTagsWithoutReservedPrefixes(\"associatedTags\", o.AssociatedTags); err != nil {\n\t\terrors = errors.Append(err)\n\t}\n\n\tif err := elemental.ValidateStringInList(\"cloudType\", string(o.CloudType), []string{\"AWS\", \"GCP\"}, false); err != nil {\n\t\terrors = errors.Append(err)\n\t}\n\n\tif len(requiredErrors) > 0 {\n\t\treturn requiredErrors\n\t}\n\n\tif len(errors) > 0 {\n\t\treturn errors\n\t}\n\n\treturn nil\n}", "func (m *ProviderAccountRequest) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateDataset(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateDatasetName(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateField(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validatePreferences(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (uu *UserUpdate) check() error {\n\tif v, ok := uu.mutation.AccountName(); ok {\n\t\tif err := user.AccountNameValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"account_name\", err: fmt.Errorf(\"ent: validator failed for field \\\"account_name\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.StaffType(); ok {\n\t\tif err := user.StaffTypeValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"staff_type\", err: fmt.Errorf(\"ent: validator failed for field \\\"staff_type\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.FamilyName(); ok {\n\t\tif err := user.FamilyNameValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"family_name\", err: fmt.Errorf(\"ent: validator failed for field \\\"family_name\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.GivenName(); ok {\n\t\tif err := user.GivenNameValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"given_name\", err: fmt.Errorf(\"ent: validator failed for field \\\"given_name\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.DisplayName(); ok {\n\t\tif err := user.DisplayNameValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"display_name\", err: fmt.Errorf(\"ent: validator failed for field \\\"display_name\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.IDNumber(); ok {\n\t\tif err := user.IDNumberValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"id_number\", err: fmt.Errorf(\"ent: validator failed for field \\\"id_number\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.Sex(); ok {\n\t\tif err := user.SexValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"sex\", err: fmt.Errorf(\"ent: validator failed for field \\\"sex\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.PhoneNumber(); ok {\n\t\tif err := user.PhoneNumberValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"phone_number\", err: fmt.Errorf(\"ent: validator failed for field \\\"phone_number\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.Address(); ok {\n\t\tif err := user.AddressValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"address\", err: fmt.Errorf(\"ent: validator failed for field \\\"address\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.StaffID(); ok {\n\t\tif err := user.StaffIDValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"staff_id\", err: fmt.Errorf(\"ent: validator failed for field \\\"staff_id\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.PersonalEmail(); ok {\n\t\tif err := user.PersonalEmailValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"personal_email\", err: fmt.Errorf(\"ent: validator failed for field \\\"personal_email\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.IntranetWorkEmail(); ok {\n\t\tif err := user.IntranetWorkEmailValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"intranet_work_email\", err: fmt.Errorf(\"ent: validator failed for field \\\"intranet_work_email\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.ExtranetWorkEmail(); ok {\n\t\tif err := user.ExtranetWorkEmailValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"extranet_work_email\", err: fmt.Errorf(\"ent: validator failed for field \\\"extranet_work_email\\\": %w\", err)}\n\t\t}\n\t}\n\treturn nil\n}", "func (profileImport *ProfileImportRequest) Validate(tx *sql.Tx) error {\n\n\tprofile := profileImport.Profile\n\n\t// Profile fields are valid\n\terrs := tovalidate.ToErrors(validation.Errors{\n\t\t\"name\": validation.Validate(profile.Name, validation.By(\n\t\t\tfunc(value interface{}) error {\n\t\t\t\tname, ok := value.(*string)\n\t\t\t\tif !ok {\n\t\t\t\t\treturn fmt.Errorf(\"wrong type, need: string, got: %T\", value)\n\t\t\t\t}\n\t\t\t\tif name == nil || *name == \"\" {\n\t\t\t\t\treturn errors.New(\"required and cannot be blank\")\n\t\t\t\t}\n\t\t\t\tif strings.Contains(*name, \" \") {\n\t\t\t\t\treturn errors.New(\"cannot contain spaces\")\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t},\n\t\t)),\n\t\t\"description\": validation.Validate(profile.Description, validation.Required),\n\t\t\"cdnName\": validation.Validate(profile.CDNName, validation.Required),\n\t\t\"type\": validation.Validate(profile.Type, validation.Required),\n\t})\n\n\t// Validate CDN exist\n\tif profile.CDNName != nil {\n\t\tif ok, err := CDNExistsByName(*profile.CDNName, tx); err != nil {\n\t\t\terrString := fmt.Sprintf(\"checking cdn name %v existence\", *profile.CDNName)\n\t\t\tlog.Errorf(\"%v: %v\", errString, err.Error())\n\t\t\terrs = append(errs, errors.New(errString))\n\t\t} else if !ok {\n\t\t\terrs = append(errs, fmt.Errorf(\"%v CDN does not exist\", *profile.CDNName))\n\t\t}\n\t}\n\n\t// Validate profile does not already exist\n\tif profile.Name != nil {\n\t\tif ok, err := ProfileExistsByName(*profile.Name, tx); err != nil {\n\t\t\terrString := fmt.Sprintf(\"checking profile name %v existence\", *profile.Name)\n\t\t\tlog.Errorf(\"%v: %v\", errString, err.Error())\n\t\t\terrs = append(errs, errors.New(errString))\n\t\t} else if ok {\n\t\t\terrs = append(errs, fmt.Errorf(\"a profile with the name \\\"%s\\\" already exists\", *profile.Name))\n\t\t}\n\t}\n\n\t// Validate all parameters\n\t// export/import does not include secure flag\n\t// default value to not flag on validation\n\tsecure := 1\n\tfor i, pp := range profileImport.Parameters {\n\t\tif ppErrs := validateProfileParamPostFields(pp.ConfigFile, pp.Name, pp.Value, &secure); len(ppErrs) > 0 {\n\t\t\tfor _, err := range ppErrs {\n\t\t\t\terrs = append(errs, errors.New(\"parameter \"+strconv.Itoa(i)+\": \"+err.Error()))\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(errs) > 0 {\n\t\treturn util.JoinErrs(errs)\n\t}\n\n\treturn nil\n}", "func (u *Usecase) validFields(d *Device) error {\n\tif d.Name == \"\" {\n\t\treturn &InvalidError{\"attribute `Name` must not be empty\"}\n\t}\n\n\tif d.User == 0 {\n\t\treturn &InvalidError{\"invalid user\"}\n\t}\n\n\treturn nil\n}", "func (t *TokenAccount) Validate() error {\n\tv := validator.New()\n\terr := v.RegisterValidation(\"notblank\", validators.NotBlank)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = v.RegisterValidation(\"notall\", validation.NotAll)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn v.Struct(t)\n}", "func (v *Reg) Validate(ctx context.Context, f *reg.Form) error {\n\tvar es Errors\n\n\tif err := validation.Validate(f.Email, validation.Required, is.Email); err != nil {\n\t\tes = append(es, Error{\n\t\t\tField: \"email\",\n\t\t\tMessage: err.Error(),\n\t\t})\n\t}\n\n\tif err := validation.Validate(f.AccountID, validation.Required); err != nil {\n\t\tes = append(es, Error{\n\t\t\tField: \"account_id\",\n\t\t\tMessage: err.Error(),\n\t\t})\n\t}\n\n\tif err := v.Uniquer.Unique(ctx, f.Email); err != nil {\n\t\tswitch errors.Cause(err) {\n\t\tcase reg.ErrEmailExists:\n\t\t\tes = append(es, Error{\n\t\t\t\tField: \"email\",\n\t\t\t\tMessage: err.Error(),\n\t\t\t})\n\t\tdefault:\n\t\t\treturn errors.Wrap(err, \"unique\")\n\t\t}\n\t}\n\n\tfmt.Println(f.Password, f.PasswordConfirmation)\n\n\tif err := validation.Validate(f.Password, validation.Required, validation.Length(6, 32)); err != nil {\n\t\tes = append(es, Error{\n\t\t\tField: \"password\",\n\t\t\tMessage: err.Error(),\n\t\t})\n\t}\n\n\tif err := validation.Validate(f.PasswordConfirmation, validation.Required, validation.Length(6, 32)); err != nil {\n\t\tes = append(es, Error{\n\t\t\tField: \"password_confirmation\",\n\t\t\tMessage: err.Error(),\n\t\t})\n\t}\n\n\tif f.Password != f.PasswordConfirmation {\n\t\tes = append(es, Error{\n\t\t\tField: \"password_confirmation\",\n\t\t\tMessage: \"mismatch\",\n\t\t}, Error{\n\t\t\tField: \"password\",\n\t\t\tMessage: \"mismatch\",\n\t\t})\n\t}\n\n\tif len(es) > 0 {\n\t\treturn es\n\t}\n\n\treturn nil\n}", "func validateAccountName(accountName string) (string, error) {\n\treturn accountName, nil\n}", "func (rcv *controller) validate() error {\n\n\tif err := rcv.read(); err != nil {\n\t\treturn err\n\t}\n\n\t// If account does not exists\n\tif rcv.store.Email == \"\" {\n\t\treturn errors.New(rcv.Translate(\"text11\"))\n\t}\n\n\t// If time for activating account is expired\n\tif time.Now().Unix() > rcv.store.Expired {\n\t\t// Delete registered user from neo4j\n\t\tmaccount.Delete(rcv.store.Email, rcv.Local)\n\t\treturn &expiredError{rcv.Controller}\n\t}\n\n\treturn nil\n}", "func (acc *AccessControlCreate) check() error {\n\tif _, ok := acc.mutation.ServiceID(); !ok {\n\t\treturn &ValidationError{Name: \"service_id\", err: errors.New(\"ent: missing required field \\\"service_id\\\"\")}\n\t}\n\tif _, ok := acc.mutation.OpenAuth(); !ok {\n\t\treturn &ValidationError{Name: \"open_auth\", err: errors.New(\"ent: missing required field \\\"open_auth\\\"\")}\n\t}\n\tif _, ok := acc.mutation.BlackList(); !ok {\n\t\treturn &ValidationError{Name: \"black_list\", err: errors.New(\"ent: missing required field \\\"black_list\\\"\")}\n\t}\n\tif _, ok := acc.mutation.WhiteList(); !ok {\n\t\treturn &ValidationError{Name: \"white_list\", err: errors.New(\"ent: missing required field \\\"white_list\\\"\")}\n\t}\n\tif _, ok := acc.mutation.WhiteHostName(); !ok {\n\t\treturn &ValidationError{Name: \"white_host_name\", err: errors.New(\"ent: missing required field \\\"white_host_name\\\"\")}\n\t}\n\tif _, ok := acc.mutation.ClientipFlowLimit(); !ok {\n\t\treturn &ValidationError{Name: \"clientip_flow_limit\", err: errors.New(\"ent: missing required field \\\"clientip_flow_limit\\\"\")}\n\t}\n\tif _, ok := acc.mutation.ServiceFlowLimit(); !ok {\n\t\treturn &ValidationError{Name: \"service_flow_limit\", err: errors.New(\"ent: missing required field \\\"service_flow_limit\\\"\")}\n\t}\n\treturn nil\n}", "func (u *User) Validate(tx *pop.Connection) (*validate.Errors, error) {\n\tvar err error\n\t//validate based on is agent\n\tif !u.IsAgent { //is not an agent\n\t\treturn validate.Validate(\n\t\t\t&validators.StringIsPresent{Field: u.Email, Name: \"Email\"},\n\t\t\t&validators.StringIsPresent{Field: u.PasswordHash, Name: \"PasswordHash\"},\n\t\t\t&validators.StringIsPresent{Field: u.LastName, Name: \"LastName\"},\n\t\t\t&validators.StringIsPresent{Field: u.FirstName, Name: \"FirstName\"},\n\t\t\t&validators.StringIsPresent{Field: u.Phone, Name: \"Phone\"},\n\t\t\t// check to see if the email address is already taken:\n\t\t\t&validators.FuncValidator{\n\t\t\t\tField: u.Email,\n\t\t\t\tName: \"Email\",\n\t\t\t\tMessage: \"%s is already taken\",\n\t\t\t\tFn: func() bool {\n\t\t\t\t\tvar b bool\n\t\t\t\t\tq := tx.Where(\"email = ?\", u.Email)\n\t\t\t\t\tif u.ID != uuid.Nil {\n\t\t\t\t\t\tq = q.Where(\"id != ?\", u.ID)\n\t\t\t\t\t}\n\t\t\t\t\tb, err = q.Exists(u)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn false\n\t\t\t\t\t}\n\t\t\t\t\treturn !b\n\t\t\t\t},\n\t\t\t},\n\t\t), err\n\n\t} else { // trying to save agent\n\t\treturn validate.Validate(\n\t\t\t&validators.StringIsPresent{Field: u.Email, Name: \"Email\"},\n\t\t\t&validators.StringIsPresent{Field: u.PasswordHash, Name: \"PasswordHash\"},\n\t\t\t&validators.StringIsPresent{Field: u.LastName, Name: \"LastName\"},\n\t\t\t&validators.StringIsPresent{Field: u.FirstName, Name: \"FirstName\"},\n\t\t\t&validators.StringIsPresent{Field: u.Phone, Name: \"Phone\"},\n\t\t\t&validators.StringIsPresent{Field: u.PublicEmail.String, Name: \"PublicEmail\"},\n\t\t\t&validators.StringIsPresent{Field: u.Company.String, Name: \"Company\"},\n\t\t\t&validators.StringIsPresent{Field: u.Address1.String, Name: \"Address1\"},\n\t\t\t&validators.StringIsPresent{Field: u.City.String, Name: \"City\"},\n\t\t\t&validators.StringIsPresent{Field: u.State.String, Name: \"State\"},\n\t\t\t&validators.StringIsPresent{Field: u.Zipcode.String, Name: \"Zipcode\"},\n\t\t\t// check to see if the email address is already taken:\n\t\t\t&validators.FuncValidator{\n\t\t\t\tField: u.Email,\n\t\t\t\tName: \"Email\",\n\t\t\t\tMessage: \"%s is already taken\",\n\t\t\t\tFn: func() bool {\n\t\t\t\t\tvar b bool\n\t\t\t\t\tq := tx.Where(\"email = ?\", u.Email)\n\t\t\t\t\tif u.ID != uuid.Nil {\n\t\t\t\t\t\tq = q.Where(\"id != ?\", u.ID)\n\t\t\t\t\t}\n\t\t\t\t\tb, err = q.Exists(u)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn false\n\t\t\t\t\t}\n\t\t\t\t\treturn !b\n\t\t\t\t},\n\t\t\t},\n\t\t), err\n\n\t}\n}", "func IsValidAccount(a string) bool {\n\t_, err := NewAccount(a)\n\treturn err == nil\n}", "func (u User) IsValid() []error{\n\tvar errs []error\n\tfirstname := strings.Trim(u.FirstName, \" \")\n\tlastname := strings.Trim(u.LastName, \" \")\n\n\tif firstname != \"\" {\n\t\tif strings.Contains(firstname, \" \"){\n\t\t\terrs = append(errs, errors.New(\"FirstName can't have spaces\"))\n\t\t}\n\t\tif len(firstname) < 2 {\n\t\t\terrs = append(errs, errors.New(\"FirstName must be at least 2 characters\"))\n\t\t}\n\t\tif !helper.IsLetter(firstname) {\n\t\t\terrs = append(errs, errors.New(\"Firstname contains a number\"))\n\t\t}\n\t}\n\n\tif lastname != \"\"{\n\t\tif strings.Contains(lastname, \" \"){\n\t\t\terrs = append(errs, errors.New(\"LastName can't have spaces\"))\n\t\t}\n\n\t\tif len(lastname) < 2 {\n\t\t\terrs = append(errs, errors.New(\"LastName must be at least 2 characters\"))\n\t\t}\n\n\t\tif !helper.IsLetter(lastname) {\n\t\t\terrs = append(errs, errors.New(\"Lastname contains a number\"))\n\t\t}\n\t}\n\n\tif u.Email != \"\" {\n\t\tre := regexp.MustCompile(\"^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$\")\n\n\t\tif !re.MatchString(u.Email) {\n\t\t\terrs = append(errs, errors.New(\"Email address is not valid\"))\n\t\t}\n\t}\n\n\n\tyear, _, _, _, _, _ := helper.DateDiff(u.DateOfBirth, time.Now())\n\tif year < 18 {\n\t\terrs = append(errs, errors.New(\"You must be 18 or more\"))\n\t}\n\tif len(errs) > 0 {\n\t\treturn errs\n\t}\n\treturn nil\n}", "func (m *BillingProfiles2) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateAdviceOfCharge(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateCurrency(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateFraudDailyLimit(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateFraudDailyLock(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateFraudDailyNotify(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateFraudIntervalLimit(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateFraudIntervalLock(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateFraudIntervalNotify(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateFraudUseResellerRates(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateHandle(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateIntervalCharge(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateIntervalFreeCash(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateIntervalFreeTime(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateName(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validatePeaktimeSpecial(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validatePeaktimeWeekdays(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validatePrepaid(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validatePrepaidLibrary(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateResellerID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (o *conversionOptions) validate() error {\r\n\tif o.goalID == 0 && len(o.goalName) == 0 {\r\n\t\treturn fmt.Errorf(\"missing required attribute(s): %s or %s\", fieldID, fieldName)\r\n\t} else if o.goalID == 0 && o.tonicPowUserID > 0 {\r\n\t\treturn fmt.Errorf(\"missing required attribute: %s\", fieldID)\r\n\t} else if o.tonicPowUserID == 0 && len(o.tncpwSession) == 0 {\r\n\t\treturn fmt.Errorf(\"missing required attribute(s): %s or %s\", fieldVisitorSessionGUID, fieldUserID)\r\n\t}\r\n\treturn nil\r\n}", "func (m *CustomerTripletexAccount2) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateAccountType(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateAdministrator(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateChartOfAccountsType(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateModules(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateType(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateVatStatusType(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (bva BaseVestingAccount) Validate() error {\n\tif !(bva.DelegatedVesting.IsAllLTE(bva.OriginalVesting)) {\n\t\treturn errors.New(\"delegated vesting amount cannot be greater than original vesting amount\")\n\t}\n\treturn bva.BaseAccount.Validate()\n}", "func (uuo *UserUpdateOne) check() error {\n\tif v, ok := uuo.mutation.AccountName(); ok {\n\t\tif err := user.AccountNameValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"account_name\", err: fmt.Errorf(\"ent: validator failed for field \\\"account_name\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.StaffType(); ok {\n\t\tif err := user.StaffTypeValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"staff_type\", err: fmt.Errorf(\"ent: validator failed for field \\\"staff_type\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.FamilyName(); ok {\n\t\tif err := user.FamilyNameValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"family_name\", err: fmt.Errorf(\"ent: validator failed for field \\\"family_name\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.GivenName(); ok {\n\t\tif err := user.GivenNameValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"given_name\", err: fmt.Errorf(\"ent: validator failed for field \\\"given_name\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.DisplayName(); ok {\n\t\tif err := user.DisplayNameValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"display_name\", err: fmt.Errorf(\"ent: validator failed for field \\\"display_name\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.IDNumber(); ok {\n\t\tif err := user.IDNumberValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"id_number\", err: fmt.Errorf(\"ent: validator failed for field \\\"id_number\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.Sex(); ok {\n\t\tif err := user.SexValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"sex\", err: fmt.Errorf(\"ent: validator failed for field \\\"sex\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.PhoneNumber(); ok {\n\t\tif err := user.PhoneNumberValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"phone_number\", err: fmt.Errorf(\"ent: validator failed for field \\\"phone_number\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.Address(); ok {\n\t\tif err := user.AddressValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"address\", err: fmt.Errorf(\"ent: validator failed for field \\\"address\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.StaffID(); ok {\n\t\tif err := user.StaffIDValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"staff_id\", err: fmt.Errorf(\"ent: validator failed for field \\\"staff_id\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.PersonalEmail(); ok {\n\t\tif err := user.PersonalEmailValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"personal_email\", err: fmt.Errorf(\"ent: validator failed for field \\\"personal_email\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.IntranetWorkEmail(); ok {\n\t\tif err := user.IntranetWorkEmailValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"intranet_work_email\", err: fmt.Errorf(\"ent: validator failed for field \\\"intranet_work_email\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.ExtranetWorkEmail(); ok {\n\t\tif err := user.ExtranetWorkEmailValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"extranet_work_email\", err: fmt.Errorf(\"ent: validator failed for field \\\"extranet_work_email\\\": %w\", err)}\n\t\t}\n\t}\n\treturn nil\n}", "func (m *DomainDiscoverAPIAccount) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateCid(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (msg MsgAddAdminAccount) ValidateBasic() sdk.Error {\n if msg.AdminAddress.Empty() {\n return sdk.ErrInvalidAddress(msg.AdminAddress.String())\n }\n if msg.Owner.Empty() {\n return sdk.ErrInvalidAddress(msg.Owner.String())\n }\n return nil\n}", "func init() {\n\taccountFields := schema.Account{}.Fields()\n\t_ = accountFields\n\t// accountDescProvider is the schema descriptor for provider field.\n\taccountDescProvider := accountFields[1].Descriptor()\n\t// account.ProviderValidator is a validator for the \"provider\" field. It is called by the builders before save.\n\taccount.ProviderValidator = accountDescProvider.Validators[0].(func(string) error)\n\t// accountDescEmail is the schema descriptor for email field.\n\taccountDescEmail := accountFields[2].Descriptor()\n\t// account.EmailValidator is a validator for the \"email\" field. It is called by the builders before save.\n\taccount.EmailValidator = accountDescEmail.Validators[0].(func(string) error)\n\t// accountDescPassword is the schema descriptor for password field.\n\taccountDescPassword := accountFields[3].Descriptor()\n\t// account.PasswordValidator is a validator for the \"password\" field. It is called by the builders before save.\n\taccount.PasswordValidator = func() func(string) error {\n\t\tvalidators := accountDescPassword.Validators\n\t\tfns := [...]func(string) error{\n\t\t\tvalidators[0].(func(string) error),\n\t\t\tvalidators[1].(func(string) error),\n\t\t}\n\t\treturn func(password string) error {\n\t\t\tfor _, fn := range fns {\n\t\t\t\tif err := fn(password); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\t}()\n\t// accountDescLocked is the schema descriptor for locked field.\n\taccountDescLocked := accountFields[4].Descriptor()\n\t// account.DefaultLocked holds the default value on creation for the locked field.\n\taccount.DefaultLocked = accountDescLocked.Default.(bool)\n\t// accountDescConfirmed is the schema descriptor for confirmed field.\n\taccountDescConfirmed := accountFields[5].Descriptor()\n\t// account.DefaultConfirmed holds the default value on creation for the confirmed field.\n\taccount.DefaultConfirmed = accountDescConfirmed.Default.(bool)\n\t// accountDescConfirmationToken is the schema descriptor for confirmation_token field.\n\taccountDescConfirmationToken := accountFields[7].Descriptor()\n\t// account.ConfirmationTokenValidator is a validator for the \"confirmation_token\" field. It is called by the builders before save.\n\taccount.ConfirmationTokenValidator = accountDescConfirmationToken.Validators[0].(func(string) error)\n\t// accountDescRecoveryToken is the schema descriptor for recovery_token field.\n\taccountDescRecoveryToken := accountFields[9].Descriptor()\n\t// account.RecoveryTokenValidator is a validator for the \"recovery_token\" field. It is called by the builders before save.\n\taccount.RecoveryTokenValidator = accountDescRecoveryToken.Validators[0].(func(string) error)\n\t// accountDescOtp is the schema descriptor for otp field.\n\taccountDescOtp := accountFields[11].Descriptor()\n\t// account.OtpValidator is a validator for the \"otp\" field. It is called by the builders before save.\n\taccount.OtpValidator = accountDescOtp.Validators[0].(func(string) error)\n\t// accountDescEmailChange is the schema descriptor for email_change field.\n\taccountDescEmailChange := accountFields[12].Descriptor()\n\t// account.EmailChangeValidator is a validator for the \"email_change\" field. It is called by the builders before save.\n\taccount.EmailChangeValidator = accountDescEmailChange.Validators[0].(func(string) error)\n\t// accountDescEmailChangeToken is the schema descriptor for email_change_token field.\n\taccountDescEmailChangeToken := accountFields[14].Descriptor()\n\t// account.EmailChangeTokenValidator is a validator for the \"email_change_token\" field. It is called by the builders before save.\n\taccount.EmailChangeTokenValidator = accountDescEmailChangeToken.Validators[0].(func(string) error)\n\t// accountDescCreatedAt is the schema descriptor for created_at field.\n\taccountDescCreatedAt := accountFields[18].Descriptor()\n\t// account.DefaultCreatedAt holds the default value on creation for the created_at field.\n\taccount.DefaultCreatedAt = accountDescCreatedAt.Default.(func() time.Time)\n\t// accountDescUpdatedAt is the schema descriptor for updated_at field.\n\taccountDescUpdatedAt := accountFields[19].Descriptor()\n\t// account.DefaultUpdatedAt holds the default value on creation for the updated_at field.\n\taccount.DefaultUpdatedAt = accountDescUpdatedAt.Default.(func() time.Time)\n\t// account.UpdateDefaultUpdatedAt holds the default value on update for the updated_at field.\n\taccount.UpdateDefaultUpdatedAt = accountDescUpdatedAt.UpdateDefault.(func() time.Time)\n\t// accountDescID is the schema descriptor for id field.\n\taccountDescID := accountFields[0].Descriptor()\n\t// account.DefaultID holds the default value on creation for the id field.\n\taccount.DefaultID = accountDescID.Default.(func() uuid.UUID)\n\tsessionFields := schema.Session{}.Fields()\n\t_ = sessionFields\n\t// sessionDescCreatedAt is the schema descriptor for created_at field.\n\tsessionDescCreatedAt := sessionFields[2].Descriptor()\n\t// session.DefaultCreatedAt holds the default value on creation for the created_at field.\n\tsession.DefaultCreatedAt = sessionDescCreatedAt.Default.(func() time.Time)\n\t// sessionDescUpdatedAt is the schema descriptor for updated_at field.\n\tsessionDescUpdatedAt := sessionFields[3].Descriptor()\n\t// session.DefaultUpdatedAt holds the default value on creation for the updated_at field.\n\tsession.DefaultUpdatedAt = sessionDescUpdatedAt.Default.(func() time.Time)\n\t// session.UpdateDefaultUpdatedAt holds the default value on update for the updated_at field.\n\tsession.UpdateDefaultUpdatedAt = sessionDescUpdatedAt.UpdateDefault.(func() time.Time)\n}", "func (mt AccountCollection) Validate() (err error) {\n\tfor _, e := range mt {\n\t\tif e != nil {\n\t\t\tif err2 := e.Validate(); err2 != nil {\n\t\t\t\terr = goa.MergeErrors(err, err2)\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}", "func (frm entryForm) Validate() (map[string]string, bool) {\n\terrs := map[string]string{}\n\tg1 := frm.Department != \"\"\n\tif !g1 {\n\t\terrs[\"department\"] = \"Missing department\"\n\t}\n\tg2 := frm.CheckThis\n\tif !g2 {\n\t\terrs[\"check_this\"] = \"You need to comply\"\n\t}\n\tg3 := frm.Items != \"\"\n\tif !g3 {\n\t\terrs[\"items\"] = \"No items\"\n\t}\n\treturn errs, g1 && g2 && g3\n}", "func (vva ValidatorVestingAccount) Validate() error {\n\tif vva.SigningThreshold > 100 || vva.SigningThreshold < 0 {\n\t\treturn errors.New(\"signing threshold must be between 0 and 100\")\n\t}\n\tif vva.ReturnAddress.Equals(vva.Address) {\n\t\treturn errors.New(\"return address cannot be the same as the account address\")\n\t}\n\treturn vva.PeriodicVestingAccount.Validate()\n}", "func (dva DelayedVestingAccount) Validate() error {\n\treturn dva.BaseVestingAccount.Validate()\n}", "func validate(msgs []*LogMsg) {\n\tif !validatePRAMRegistration(msgs) {\n\t\tlog.Fatalf(\"validatePRAMRegistration\\n\")\n\t}\n}", "func (_PermInterface *PermInterfaceCaller) ValidateAccount(opts *bind.CallOpts, _account common.Address, _orgId string) (bool, error) {\n\tvar out []interface{}\n\terr := _PermInterface.contract.Call(opts, &out, \"validateAccount\", _account, _orgId)\n\n\tif err != nil {\n\t\treturn *new(bool), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(bool)).(*bool)\n\n\treturn out0, err\n\n}", "func (ut *RegisterPayload) Validate() (err error) {\n\tif ut.Email == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`type`, \"email\"))\n\t}\n\tif ut.Password == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`type`, \"password\"))\n\t}\n\tif ut.FirstName == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`type`, \"first_name\"))\n\t}\n\tif ut.LastName == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`type`, \"last_name\"))\n\t}\n\tif err2 := goa.ValidateFormat(goa.FormatEmail, ut.Email); err2 != nil {\n\t\terr = goa.MergeErrors(err, goa.InvalidFormatError(`type.email`, ut.Email, goa.FormatEmail, err2))\n\t}\n\tif utf8.RuneCountInString(ut.Email) < 6 {\n\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`type.email`, ut.Email, utf8.RuneCountInString(ut.Email), 6, true))\n\t}\n\tif utf8.RuneCountInString(ut.Email) > 150 {\n\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`type.email`, ut.Email, utf8.RuneCountInString(ut.Email), 150, false))\n\t}\n\tif utf8.RuneCountInString(ut.FirstName) < 1 {\n\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`type.first_name`, ut.FirstName, utf8.RuneCountInString(ut.FirstName), 1, true))\n\t}\n\tif utf8.RuneCountInString(ut.FirstName) > 200 {\n\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`type.first_name`, ut.FirstName, utf8.RuneCountInString(ut.FirstName), 200, false))\n\t}\n\tif utf8.RuneCountInString(ut.LastName) < 1 {\n\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`type.last_name`, ut.LastName, utf8.RuneCountInString(ut.LastName), 1, true))\n\t}\n\tif utf8.RuneCountInString(ut.LastName) > 200 {\n\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`type.last_name`, ut.LastName, utf8.RuneCountInString(ut.LastName), 200, false))\n\t}\n\tif utf8.RuneCountInString(ut.Password) < 5 {\n\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`type.password`, ut.Password, utf8.RuneCountInString(ut.Password), 5, true))\n\t}\n\tif utf8.RuneCountInString(ut.Password) > 100 {\n\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`type.password`, ut.Password, utf8.RuneCountInString(ut.Password), 100, false))\n\t}\n\treturn\n}", "func (a *Api) validateError() (err error) {\n\tif a.UserID == 0 {\n\t\treturn a.Errors(ErrorMissingValue, \"user_id\")\n\t}\n\n\tif a.Token == \"\" {\n\t\treturn a.Errors(ErrorMissingValue, \"token\")\n\t}\n\n\treturn\n}", "func (uc *UserCreate) check() error {\n\tif _, ok := uc.mutation.Firstname(); !ok {\n\t\treturn &ValidationError{Name: \"firstname\", err: errors.New(\"ent: missing required field \\\"firstname\\\"\")}\n\t}\n\tif _, ok := uc.mutation.Lastname(); !ok {\n\t\treturn &ValidationError{Name: \"lastname\", err: errors.New(\"ent: missing required field \\\"lastname\\\"\")}\n\t}\n\tif _, ok := uc.mutation.Username(); !ok {\n\t\treturn &ValidationError{Name: \"username\", err: errors.New(\"ent: missing required field \\\"username\\\"\")}\n\t}\n\tif _, ok := uc.mutation.Password(); !ok {\n\t\treturn &ValidationError{Name: \"password\", err: errors.New(\"ent: missing required field \\\"password\\\"\")}\n\t}\n\treturn nil\n}", "func (ac *AreahistoryCreate) check() error {\n\tif _, ok := ac.mutation.WalletID(); !ok {\n\t\treturn &ValidationError{Name: \"WalletID\", err: errors.New(\"ent: missing required field \\\"WalletID\\\"\")}\n\t}\n\tif v, ok := ac.mutation.WalletID(); ok {\n\t\tif err := areahistory.WalletIDValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"WalletID\", err: fmt.Errorf(\"ent: validator failed for field \\\"WalletID\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := ac.mutation.ProvinceNameTH(); ok {\n\t\tif err := areahistory.ProvinceNameTHValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"ProvinceNameTH\", err: fmt.Errorf(\"ent: validator failed for field \\\"ProvinceNameTH\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := ac.mutation.DistrictNameTH(); ok {\n\t\tif err := areahistory.DistrictNameTHValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"DistrictNameTH\", err: fmt.Errorf(\"ent: validator failed for field \\\"DistrictNameTH\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := ac.mutation.SubDistrict(); ok {\n\t\tif err := areahistory.SubDistrictValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"SubDistrict\", err: fmt.Errorf(\"ent: validator failed for field \\\"SubDistrict\\\": %w\", err)}\n\t\t}\n\t}\n\treturn nil\n}", "func (_PermInterface *PermInterfaceSession) ValidateAccount(_account common.Address, _orgId string) (bool, error) {\n\treturn _PermInterface.Contract.ValidateAccount(&_PermInterface.CallOpts, _account, _orgId)\n}", "func (uu *UserUpdate) check() error {\n\tif v, ok := uu.mutation.Username(); ok {\n\t\tif err := user.UsernameValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"username\", err: fmt.Errorf(\"ent: validator failed for field \\\"username\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.Fullname(); ok {\n\t\tif err := user.FullnameValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"fullname\", err: fmt.Errorf(\"ent: validator failed for field \\\"fullname\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.Password(); ok {\n\t\tif err := user.PasswordValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"password\", err: fmt.Errorf(\"ent: validator failed for field \\\"password\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.Email(); ok {\n\t\tif err := user.EmailValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"email\", err: fmt.Errorf(\"ent: validator failed for field \\\"email\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.Phone(); ok {\n\t\tif err := user.PhoneValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"phone\", err: fmt.Errorf(\"ent: validator failed for field \\\"phone\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.Bio(); ok {\n\t\tif err := user.BioValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"bio\", err: fmt.Errorf(\"ent: validator failed for field \\\"bio\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.Intro(); ok {\n\t\tif err := user.IntroValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"intro\", err: fmt.Errorf(\"ent: validator failed for field \\\"intro\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.GithubProfile(); ok {\n\t\tif err := user.GithubProfileValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"github_profile\", err: fmt.Errorf(\"ent: validator failed for field \\\"github_profile\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.ProfilePictureURL(); ok {\n\t\tif err := user.ProfilePictureURLValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"profile_picture_url\", err: fmt.Errorf(\"ent: validator failed for field \\\"profile_picture_url\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.Status(); ok {\n\t\tif err := user.StatusValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"status\", err: fmt.Errorf(\"ent: validator failed for field \\\"status\\\": %w\", err)}\n\t\t}\n\t}\n\treturn nil\n}", "func (uc *UserCreate) check() error {\n\tif _, ok := uc.mutation.Age(); !ok {\n\t\treturn &ValidationError{Name: \"age\", err: errors.New(\"ent: missing required field \\\"age\\\"\")}\n\t}\n\tif v, ok := uc.mutation.Age(); ok {\n\t\tif err := user.AgeValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"age\", err: fmt.Errorf(\"ent: validator failed for field \\\"age\\\": %w\", err)}\n\t\t}\n\t}\n\tif _, ok := uc.mutation.Name(); !ok {\n\t\treturn &ValidationError{Name: \"name\", err: errors.New(\"ent: missing required field \\\"name\\\"\")}\n\t}\n\tif v, ok := uc.mutation.ID(); ok {\n\t\tif err := user.IDValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"id\", err: fmt.Errorf(\"ent: validator failed for field \\\"id\\\": %w\", err)}\n\t\t}\n\t}\n\treturn nil\n}", "func (p *PaymentNeed) validate() error {\n\tif p.BeneficiaryID == 0 {\n\t\treturn fmt.Errorf(\"beneficiary ID nul\")\n\t}\n\tif p.Value == 0 {\n\t\treturn fmt.Errorf(\"value nul\")\n\t}\n\treturn nil\n}", "func (r *Result) validate(errMsg *[]string, parentField string) {\n\tjn := resultJsonMap\n\taddErrMessage(errMsg, len(r.Key) > 0 && hasNonEmptyKV(r.Key), \"field '%s' must be non-empty and must not have empty keys or values\", parentField+\".\"+jn[\"Key\"])\n\taddErrMessage(errMsg, hasNonEmptyKV(r.Options), \"field '%s' must not have empty keys or values\", parentField+\".\"+jn[\"Options\"])\n\taddErrMessage(errMsg, regExHexadecimal.MatchString(string(r.Digest)), \"field '%s' must be hexadecimal\", parentField+\".\"+jn[\"Digest\"])\n}", "func CheckAccountResponse(t *testing.T, resp *models.Account, expectedAccount *models.Account) {\n\tif resp.ID != expectedAccount.ID {\n\t\tt.Errorf(\"Response contains wrong ID, got %v expected %v\", resp.ID, expectedAccount.ID)\n\t}\n\tif resp.Type != expectedAccount.Type {\n\t\tt.Errorf(\"Response contains wrong Type, got %v expected %v\", resp.Type, expectedAccount.Type)\n\t}\n\tif resp.OrganisationID != expectedAccount.OrganisationID {\n\t\tt.Errorf(\"Response contains wrong OrganisationID, got %v expected %v\", resp.OrganisationID, expectedAccount.OrganisationID)\n\t}\n\tif resp.Version != expectedAccount.Version {\n\t\tt.Errorf(\"Response contains wrong Version, got %v expected %v\", resp.Version, expectedAccount.Version)\n\t}\n\tif resp.Attributes.Country != expectedAccount.Attributes.Country {\n\t\tt.Errorf(\"Response contains wrong Country, got %v expected %v\", resp.Attributes.Country, expectedAccount.Attributes.Country)\n\t}\n\tif resp.Attributes.BaseCurrency != expectedAccount.Attributes.BaseCurrency {\n\t\tt.Errorf(\"Response contains wrong BaseCurrency, got %v expected %v\", resp.Attributes.BaseCurrency, expectedAccount.Attributes.BaseCurrency)\n\t}\n\tif resp.Attributes.BankID != expectedAccount.Attributes.BankID {\n\t\tt.Errorf(\"Response contains wrong BankID, got %v expected %v\", resp.Attributes.BankID, expectedAccount.Attributes.BankID)\n\t}\n\tif resp.Attributes.BankIDCode != expectedAccount.Attributes.BankIDCode {\n\t\tt.Errorf(\"Response contains wrong BankIDCode, got %v expected %v\", resp.Attributes.BankIDCode, expectedAccount.Attributes.BankIDCode)\n\t}\n\tif resp.Attributes.Bic != expectedAccount.Attributes.Bic {\n\t\tt.Errorf(\"Response contains wrong Bic, got %v expected %v\", resp.Attributes.Bic, expectedAccount.Attributes.Bic)\n\t}\n\tif resp.Attributes.AccountNumber != expectedAccount.Attributes.AccountNumber {\n\t\tt.Errorf(\"Response contains wrong AccountNumber, got %v expected %v\", resp.Attributes.AccountNumber, expectedAccount.Attributes.AccountNumber)\n\t}\n\tif resp.Attributes.CustomerID != expectedAccount.Attributes.CustomerID {\n\t\tt.Errorf(\"Response contains wrong CustomerID, got %v expected %v\", resp.Attributes.CustomerID, expectedAccount.Attributes.CustomerID)\n\t}\n\tif resp.Attributes.FirstName != expectedAccount.Attributes.FirstName {\n\t\tt.Errorf(\"Response contains wrong FirstName, got %v expected %v\", resp.Attributes.FirstName, expectedAccount.Attributes.FirstName)\n\t}\n\tif resp.Attributes.BankAccountName != expectedAccount.Attributes.BankAccountName {\n\t\tt.Errorf(\"Response contains wrong BankAccountName, got %v expected %v\", resp.Attributes.BankAccountName, expectedAccount.Attributes.BankAccountName)\n\t}\n\n\tresponseLength := len(resp.Attributes.AlternativeBankAccountNames)\n\texpectedLength := len(expectedAccount.Attributes.AlternativeBankAccountNames)\n\n\tif responseLength != expectedLength {\n\t\tt.Errorf(\"AlternativeBankAccountNames array is wrong, got %v expected %v\", responseLength, expectedLength)\n\t} else {\n\t\ti := 0\n\t\tfor i < responseLength {\n\t\t\tif resp.Attributes.AlternativeBankAccountNames[i] != expectedAccount.Attributes.AlternativeBankAccountNames[i] {\n\t\t\t\tt.Errorf(\"Response contains wrong AlternativeBankAccountNames, got %v expected %v\", resp.Attributes.AlternativeBankAccountNames[i], expectedAccount.Attributes.AlternativeBankAccountNames[i])\n\t\t\t}\n\t\t\ti = i + 1\n\t\t}\n\t}\n\n\tif resp.Attributes.AlternativeBankAccountNames[0] != expectedAccount.Attributes.AlternativeBankAccountNames[0] {\n\t\tt.Errorf(\"Response contains wrong AlternativeBankAccountNames, got %v expected %v\", resp.Attributes.AlternativeBankAccountNames[0], expectedAccount.Attributes.AlternativeBankAccountNames[0])\n\t}\n\tif resp.Attributes.AccountClassification != expectedAccount.Attributes.AccountClassification {\n\t\tt.Errorf(\"Response contains wrong AccountClassification, got %v expected %v\", resp.Attributes.AccountClassification, expectedAccount.Attributes.AccountClassification)\n\t}\n\tif resp.Attributes.JointAccount != expectedAccount.Attributes.JointAccount {\n\t\tt.Errorf(\"Response contains wrong JointAccount, got %v expected %v\", resp.Attributes.JointAccount, expectedAccount.Attributes.JointAccount)\n\t}\n\tif resp.Attributes.Switched != expectedAccount.Attributes.Switched {\n\t\tt.Errorf(\"Response contains wrong Switched, got %v expected %v\", resp.Attributes.Switched, expectedAccount.Attributes.Switched)\n\t}\n\tif resp.Attributes.AccountMatchingOptOut != expectedAccount.Attributes.AccountMatchingOptOut {\n\t\tt.Errorf(\"Response contains wrong AccountMatchingOptOut, got %v expected %v\", resp.Attributes.AccountMatchingOptOut, expectedAccount.Attributes.AccountMatchingOptOut)\n\t}\n\tif resp.Attributes.Status != expectedAccount.Attributes.Status {\n\t\tt.Errorf(\"Response contains wrong Status, got %v expected %v\", resp.Attributes.Status, expectedAccount.Attributes.Status)\n\t}\n\tif resp.Attributes.SecondaryIdentification != expectedAccount.Attributes.SecondaryIdentification {\n\t\tt.Errorf(\"Response contains wrong SecondaryIdentification, got %v expected %v\", resp.Attributes.SecondaryIdentification, expectedAccount.Attributes.SecondaryIdentification)\n\t}\n}", "func (_PermInterface *PermInterfaceCallerSession) ValidateAccount(_account common.Address, _orgId string) (bool, error) {\n\treturn _PermInterface.Contract.ValidateAccount(&_PermInterface.CallOpts, _account, _orgId)\n}", "func (cfg fromCFN) validate() error {\n\tif cfg.isEmpty() {\n\t\treturn nil\n\t}\n\tif len(aws.StringValue(cfg.Name)) == 0 {\n\t\treturn errors.New(\"name cannot be an empty string\")\n\t}\n\treturn nil\n}", "func isAccountFlagsValid(accountId string) bool {\n\taccount := GetStellarAccount(accountId)\n\treturn account.Flags.AuthRequired && account.Flags.AuthRevocable\n}", "func validate(name, gender string) error {\n\tif name == \"\" {\n\t\treturn &inputError{message: \"name is missing\", missingField: \"name\"}\n\t}\n\tif gender == \"\" {\n\t\treturn &inputError{message: \"gender is missing\", missingField: \"gender\"}\n\t}\n\treturn nil\n}", "func (user *User) Validate() *errors.RestErr {\n\t// Delete spaces at first_name, last_name and email before saving\n\tuser.FirstName = strings.TrimSpace(user.FirstName)\n\tuser.LastName = strings.TrimSpace(user.LastName)\n\tuser.Email = strings.TrimSpace(strings.ToLower(user.Email))\n\n\tif user.Email == \"\"{\n\t\treturn errors.NewBadRequestError(\"Email addres is required\")\n\t}\n\tif !ValidateEmail(user.Email){\n\t\treturn errors.NewBadRequestError(\"Wrong email format\")\n\t}\n\tif strings.TrimSpace(user.Password)== \"\" || len(strings.TrimSpace(user.Password)) < 8{\n\t\treturn errors.NewBadRequestError(\"Password is required and password length must be higher than 8 characters\")\n\t}\n\n\n\treturn nil\n}", "func checkAccount(t *testing.T, tree *avl.Tree, id AccountID, expectedBalance, expectedReward, expectedStake *uint64) {\n\tvar balance, reward, stake uint64\n\tvar exist bool\n\n\tbalance, exist = ReadAccountBalance(tree, id)\n\tassert.Equal(t, expectedBalance != nil, exist, \"account ID: %x\", id)\n\treward, exist = ReadAccountReward(tree, id)\n\tassert.Equal(t, expectedReward != nil, exist, \"account ID: %x\", id)\n\tstake, exist = ReadAccountStake(tree, id)\n\tassert.Equal(t, expectedStake != nil, exist, \"account ID: %x\", id)\n\n\tif expectedBalance != nil {\n\t\tassert.Equal(t, balance, *expectedBalance, \"account ID: %x\", id)\n\t}\n\n\tif expectedReward != nil {\n\t\tassert.Equal(t, reward, *expectedReward, \"account ID: %x\", id)\n\t}\n\n\tif expectedStake != nil {\n\t\tassert.Equal(t, stake, *expectedStake, \"account ID: %x\", id)\n\t}\n}", "func ValidBaseInfo(ctx *gin.Context) {\n\tres := helper.Res{}\n\n\tvar baseInfo BaseInfo\n\tif err := ctx.Bind(&baseInfo); err != nil {\n\t\tres.Status(http.StatusBadRequest).Error(err).Send(ctx)\n\t\treturn\n\t}\n\n\t// user does exist\n\tif _, err := models.FindOneByUsername(baseInfo.Username); err != nil {\n\t\tres.Status(http.StatusBadRequest).Error(err).Send(ctx)\n\t\treturn\n\t}\n\n\t// the email of user does exist\n\tif _, err := models.FindOneByEmail(baseInfo.Email); err != nil {\n\t\tres.Status(http.StatusBadRequest).Error(err).Send(ctx)\n\t\treturn\n\t}\n\n\tres.Success(gin.H{\n\t\t\"isValid\": true,\n\t}).Send(ctx)\n}", "func (w Warrant) Validate() error {\n\tif len(w.FirstName) == 0 {\n\t\treturn errors.New(\"missing first name element\")\n\t}\n\tif len(w.LastName) == 0 {\n\t\treturn errors.New(\"missing last name element\")\n\t}\n\tif len(w.Civility) == 0 {\n\t\treturn errors.New(\"missing civility element\")\n\t}\n\treturn nil\n}", "func (va ClawbackVestingAccount) Validate() error {\n\tif va.GetStartTime() >= va.GetEndTime() {\n\t\treturn errors.New(\"vesting start-time must be before end-time\")\n\t}\n\n\tlockupEnd := va.StartTime\n\tlockupCoins := sdk.NewCoins()\n\tfor _, p := range va.LockupPeriods {\n\t\tlockupEnd += p.Length\n\t\tlockupCoins = lockupCoins.Add(p.Amount...)\n\t}\n\tif lockupEnd > va.EndTime {\n\t\treturn errors.New(\"lockup schedule extends beyond account end time\")\n\t}\n\tif !coinEq(lockupCoins, va.OriginalVesting) {\n\t\treturn errors.New(\"original vesting coins does not match the sum of all coins in lockup periods\")\n\t}\n\n\tvestingEnd := va.StartTime\n\tvestingCoins := sdk.NewCoins()\n\tfor _, p := range va.VestingPeriods {\n\t\tvestingEnd += p.Length\n\t\tvestingCoins = vestingCoins.Add(p.Amount...)\n\t}\n\tif vestingEnd > va.EndTime {\n\t\treturn errors.New(\"vesting schedule exteds beyond account end time\")\n\t}\n\tif !coinEq(vestingCoins, va.OriginalVesting) {\n\t\treturn errors.New(\"original vesting coins does not match the sum of all coins in vesting periods\")\n\t}\n\n\treturn va.BaseVestingAccount.Validate()\n}", "func (ut *registerPayload) Validate() (err error) {\n\tif ut.Email == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`request`, \"email\"))\n\t}\n\tif ut.Password == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`request`, \"password\"))\n\t}\n\tif ut.FirstName == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`request`, \"first_name\"))\n\t}\n\tif ut.LastName == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`request`, \"last_name\"))\n\t}\n\tif ut.Email != nil {\n\t\tif err2 := goa.ValidateFormat(goa.FormatEmail, *ut.Email); err2 != nil {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidFormatError(`request.email`, *ut.Email, goa.FormatEmail, err2))\n\t\t}\n\t}\n\tif ut.Email != nil {\n\t\tif utf8.RuneCountInString(*ut.Email) < 6 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`request.email`, *ut.Email, utf8.RuneCountInString(*ut.Email), 6, true))\n\t\t}\n\t}\n\tif ut.Email != nil {\n\t\tif utf8.RuneCountInString(*ut.Email) > 150 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`request.email`, *ut.Email, utf8.RuneCountInString(*ut.Email), 150, false))\n\t\t}\n\t}\n\tif ut.FirstName != nil {\n\t\tif utf8.RuneCountInString(*ut.FirstName) < 1 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`request.first_name`, *ut.FirstName, utf8.RuneCountInString(*ut.FirstName), 1, true))\n\t\t}\n\t}\n\tif ut.FirstName != nil {\n\t\tif utf8.RuneCountInString(*ut.FirstName) > 200 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`request.first_name`, *ut.FirstName, utf8.RuneCountInString(*ut.FirstName), 200, false))\n\t\t}\n\t}\n\tif ut.LastName != nil {\n\t\tif utf8.RuneCountInString(*ut.LastName) < 1 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`request.last_name`, *ut.LastName, utf8.RuneCountInString(*ut.LastName), 1, true))\n\t\t}\n\t}\n\tif ut.LastName != nil {\n\t\tif utf8.RuneCountInString(*ut.LastName) > 200 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`request.last_name`, *ut.LastName, utf8.RuneCountInString(*ut.LastName), 200, false))\n\t\t}\n\t}\n\tif ut.Password != nil {\n\t\tif utf8.RuneCountInString(*ut.Password) < 5 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`request.password`, *ut.Password, utf8.RuneCountInString(*ut.Password), 5, true))\n\t\t}\n\t}\n\tif ut.Password != nil {\n\t\tif utf8.RuneCountInString(*ut.Password) > 100 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`request.password`, *ut.Password, utf8.RuneCountInString(*ut.Password), 100, false))\n\t\t}\n\t}\n\treturn\n}", "func ValidateWarriorAccount(name string, email string, pwd1 string, pwd2 string) (WarriorName string, WarriorEmail string, WarriorPassword string, validateErr error) {\n\tv := validator.New()\n\ta := warriorAccount{\n\t\tName: name,\n\t\tEmail: email,\n\t\tPassword1: pwd1,\n\t\tPassword2: pwd2,\n\t}\n\terr := v.Struct(a)\n\n\treturn name, email, pwd1, err\n}", "func validateAttributes(attrs map[string]models.ValueType, allAttrs bool) error {\n\t// TBD: to finalize the attributes specifics\n\tattrsOK := false\n\tif vt, ok := attrs[AttrCred]; ok && vt.Kind == com.ValueTypeSecret {\n\t\tif !allAttrs {\n\t\t\tattrsOK = true\n\t\t} else if vt, ok := attrs[AttrZone]; ok && vt.Kind == com.ValueTypeString {\n\t\t\tattrsOK = true\n\t\t}\n\t}\n\tif !attrsOK {\n\t\tmsg := \"required domain attributes missing or invalid: need \" + AttrCred + \"[E]\"\n\t\tif allAttrs {\n\t\t\tmsg += \", \" + AttrZone + \"[S]\"\n\t\t}\n\t\treturn fmt.Errorf(msg)\n\t}\n\treturn nil\n}", "func (cc *CompanyCreate) check() error {\n\tif _, ok := cc.mutation.CreatedAt(); !ok {\n\t\treturn &ValidationError{Name: \"created_at\", err: errors.New(`ent: missing required field \"created_at\"`)}\n\t}\n\tif _, ok := cc.mutation.UpdatedAt(); !ok {\n\t\treturn &ValidationError{Name: \"updated_at\", err: errors.New(`ent: missing required field \"updated_at\"`)}\n\t}\n\tif _, ok := cc.mutation.Name(); !ok {\n\t\treturn &ValidationError{Name: \"name\", err: errors.New(`ent: missing required field \"name\"`)}\n\t}\n\tif v, ok := cc.mutation.Name(); ok {\n\t\tif err := company.NameValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"name\", err: fmt.Errorf(`ent: validator failed for field \"name\": %w`, err)}\n\t\t}\n\t}\n\tif _, ok := cc.mutation.Overview(); !ok {\n\t\treturn &ValidationError{Name: \"overview\", err: errors.New(`ent: missing required field \"overview\"`)}\n\t}\n\tif v, ok := cc.mutation.Overview(); ok {\n\t\tif err := company.OverviewValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"overview\", err: fmt.Errorf(`ent: validator failed for field \"overview\": %w`, err)}\n\t\t}\n\t}\n\tif _, ok := cc.mutation.Website(); !ok {\n\t\treturn &ValidationError{Name: \"website\", err: errors.New(`ent: missing required field \"website\"`)}\n\t}\n\tif v, ok := cc.mutation.Website(); ok {\n\t\tif err := company.WebsiteValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"website\", err: fmt.Errorf(`ent: validator failed for field \"website\": %w`, err)}\n\t\t}\n\t}\n\tif _, ok := cc.mutation.LogoURL(); !ok {\n\t\treturn &ValidationError{Name: \"logo_url\", err: errors.New(`ent: missing required field \"logo_url\"`)}\n\t}\n\tif v, ok := cc.mutation.LogoURL(); ok {\n\t\tif err := company.LogoURLValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"logo_url\", err: fmt.Errorf(`ent: validator failed for field \"logo_url\": %w`, err)}\n\t\t}\n\t}\n\tif _, ok := cc.mutation.Size(); !ok {\n\t\treturn &ValidationError{Name: \"size\", err: errors.New(`ent: missing required field \"size\"`)}\n\t}\n\tif v, ok := cc.mutation.Size(); ok {\n\t\tif err := company.SizeValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"size\", err: fmt.Errorf(`ent: validator failed for field \"size\": %w`, err)}\n\t\t}\n\t}\n\tif _, ok := cc.mutation.FoundedAt(); !ok {\n\t\treturn &ValidationError{Name: \"founded_at\", err: errors.New(`ent: missing required field \"founded_at\"`)}\n\t}\n\tif v, ok := cc.mutation.FoundedAt(); ok {\n\t\tif err := company.FoundedAtValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"founded_at\", err: fmt.Errorf(`ent: validator failed for field \"founded_at\": %w`, err)}\n\t\t}\n\t}\n\treturn nil\n}", "func (m *ProviderAccountPreferences) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func ValidateGetAccountInternalResponseBody(body *GetAccountInternalResponseBody) (err error) {\n\tif body.Name == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"name\", \"body\"))\n\t}\n\tif body.ID == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"id\", \"body\"))\n\t}\n\tif body.Message == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"message\", \"body\"))\n\t}\n\tif body.Temporary == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"temporary\", \"body\"))\n\t}\n\tif body.Timeout == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"timeout\", \"body\"))\n\t}\n\tif body.Fault == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"fault\", \"body\"))\n\t}\n\treturn\n}", "func (o *Virtualserver) validate(dbRecord *common.DbRecord) (ok bool, err error) {\n\t////////////////////////////////////////////////////////////////////////////\n\t// Marshal data interface.\n\t////////////////////////////////////////////////////////////////////////////\n\tvar data virtualserver.Data\n\terr = shared.MarshalInterface(dbRecord.Data, &data)\n\tif err != nil {\n\t\treturn\n\t}\n\t////////////////////////////////////////////////////////////////////////////\n\t// Test required fields.\n\t////////////////////////////////////////////////////////////////////////////\n\tok = true\n\trequired := make(map[string]bool)\n\trequired[\"ProductCode\"] = false\n\trequired[\"IP\"] = false\n\trequired[\"Port\"] = false\n\trequired[\"LoadBalancerIP\"] = false\n\trequired[\"Name\"] = false\n\t////////////////////////////////////////////////////////////////////////////\n\tif data.ProductCode != 0 {\n\t\trequired[\"ProductCode\"] = true\n\t}\n\tif len(dbRecord.LoadBalancerIP) > 0 {\n\t\trequired[\"LoadBalancerIP\"] = true\n\t}\n\tif len(data.Ports) != 0 {\n\t\trequired[\"Port\"] = true\n\t}\n\tif data.IP != \"\" {\n\t\trequired[\"IP\"] = true\n\t}\n\tif data.Name != \"\" {\n\t\trequired[\"Name\"] = true\n\t}\n\tfor _, val := range required {\n\t\tif val == false {\n\t\t\tok = false\n\t\t}\n\t}\n\tif !ok {\n\t\terr = fmt.Errorf(\"missing required fields - %+v\", required)\n\t}\n\treturn\n}", "func (user *User) Validate(action string) map[string]string {\n\tvar errMessages = make(map[string]string)\n\tvar err error\n\n\tswitch strings.ToLower(action) {\n\tcase \"update\":\n\t\tif user.Email == \"\" {\n\t\t\terrMessages[\"email_required\"] = \"email required\"\n\t\t}\n\n\t\tif user.Email != \"\" {\n\t\t\tif err = checkmail.ValidateFormat(user.Email); err != nil {\n\t\t\t\terrMessages[\"invalid_email\"] = \"invalid email\"\n\t\t\t}\n\t\t}\n\tcase \"login\":\n\t\tif user.Password == \"\" {\n\t\t\terrMessages[\"password_required\"] = \"password is required\"\n\t\t}\n\n\t\tif user.Email == \"\" {\n\t\t\terrMessages[\"email_required\"] = \"email required\"\n\t\t}\n\n\t\tif user.Email != \"\" {\n\t\t\tif err = checkmail.ValidateFormat(user.Email); err != nil {\n\t\t\t\terrMessages[\"invalid_email\"] = \"invalid email\"\n\t\t\t}\n\t\t}\n\tcase \"forgotpassword\":\n\t\tif user.Email == \"\" {\n\t\t\terrMessages[\"email_required\"] = \"email required\"\n\t\t}\n\t\tif user.Email != \"\" {\n\t\t\tif err = checkmail.ValidateFormat(user.Email); err != nil {\n\t\t\t\terrMessages[\"invalid_email\"] = \"please provide a valid email\"\n\t\t\t}\n\t\t}\n\tdefault:\n\t\tif user.FirstName == \"\" {\n\t\t\terrMessages[\"firstname_required\"] = \"first name is required\"\n\t\t}\n\n\t\tif user.LastName == \"\" {\n\t\t\terrMessages[\"lastname_required\"] = \"last name is required\"\n\t\t}\n\n\t\tif user.Password == \"\" {\n\t\t\terrMessages[\"password_required\"] = \"password is required\"\n\t\t}\n\n\t\tif user.Password != \"\" && len(user.Password) < 6 {\n\t\t\terrMessages[\"invalid_password\"] = \"password should be at least 6 characters\"\n\t\t}\n\n\t\tif user.Email == \"\" {\n\t\t\terrMessages[\"email_required\"] = \"email is required\"\n\t\t}\n\n\t\tif user.Email != \"\" {\n\t\t\tif err = checkmail.ValidateFormat(user.Email); err != nil {\n\t\t\t\terrMessages[\"invalid_email\"] = \"please provide a valid email\"\n\t\t\t}\n\t\t}\n\t}\n\n\treturn errMessages\n}", "func (a *Application) Validate(tx *pop.Connection) (*validate.Errors, error) {\n\treturn validate.Validate(\n\t\t&validators.StringIsPresent{Field: a.FirstName, Name: \"FirstName\"},\n\t\t&validators.StringIsPresent{Field: a.LastName, Name: \"LastName\"},\n\t), nil\n}", "func (uuo *UserUpdateOne) check() error {\n\tif v, ok := uuo.mutation.Username(); ok {\n\t\tif err := user.UsernameValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"username\", err: fmt.Errorf(\"ent: validator failed for field \\\"username\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.Fullname(); ok {\n\t\tif err := user.FullnameValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"fullname\", err: fmt.Errorf(\"ent: validator failed for field \\\"fullname\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.Password(); ok {\n\t\tif err := user.PasswordValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"password\", err: fmt.Errorf(\"ent: validator failed for field \\\"password\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.Email(); ok {\n\t\tif err := user.EmailValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"email\", err: fmt.Errorf(\"ent: validator failed for field \\\"email\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.Phone(); ok {\n\t\tif err := user.PhoneValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"phone\", err: fmt.Errorf(\"ent: validator failed for field \\\"phone\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.Bio(); ok {\n\t\tif err := user.BioValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"bio\", err: fmt.Errorf(\"ent: validator failed for field \\\"bio\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.Intro(); ok {\n\t\tif err := user.IntroValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"intro\", err: fmt.Errorf(\"ent: validator failed for field \\\"intro\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.GithubProfile(); ok {\n\t\tif err := user.GithubProfileValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"github_profile\", err: fmt.Errorf(\"ent: validator failed for field \\\"github_profile\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.ProfilePictureURL(); ok {\n\t\tif err := user.ProfilePictureURLValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"profile_picture_url\", err: fmt.Errorf(\"ent: validator failed for field \\\"profile_picture_url\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.Status(); ok {\n\t\tif err := user.StatusValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"status\", err: fmt.Errorf(\"ent: validator failed for field \\\"status\\\": %w\", err)}\n\t\t}\n\t}\n\treturn nil\n}", "func (r updateReq) Validate() error {\n\terr := r.addReq.Validate()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif r.ServiceAccountID != r.Body.ID {\n\t\treturn fmt.Errorf(\"service account ID mismatch, you requested to update ServiceAccount = %s but body contains ServiceAccount = %s\", r.ServiceAccountID, r.Body.ID)\n\t}\n\treturn nil\n}", "func (bu *BankdetailUpdate) check() error {\n\tif v, ok := bu.mutation.BankAccountNo(); ok {\n\t\tif err := bankdetail.BankAccountNoValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"Bank_AccountNo\", err: fmt.Errorf(\"ent: validator failed for field \\\"Bank_AccountNo\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := bu.mutation.BankName(); ok {\n\t\tif err := bankdetail.BankNameValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"Bank_Name\", err: fmt.Errorf(\"ent: validator failed for field \\\"Bank_Name\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := bu.mutation.BankAccountName(); ok {\n\t\tif err := bankdetail.BankAccountNameValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"Bank_AccountName\", err: fmt.Errorf(\"ent: validator failed for field \\\"Bank_AccountName\\\": %w\", err)}\n\t\t}\n\t}\n\treturn nil\n}", "func (rc *RentalCreate) check() error {\n\tif _, ok := rc.mutation.Date(); !ok {\n\t\treturn &ValidationError{Name: \"date\", err: errors.New(`ent: missing required field \"Rental.date\"`)}\n\t}\n\tif _, ok := rc.mutation.UserID(); !ok {\n\t\treturn &ValidationError{Name: \"user_id\", err: errors.New(`ent: missing required field \"Rental.user_id\"`)}\n\t}\n\tif _, ok := rc.mutation.CarID(); !ok {\n\t\treturn &ValidationError{Name: \"car_id\", err: errors.New(`ent: missing required field \"Rental.car_id\"`)}\n\t}\n\tif _, ok := rc.mutation.UserID(); !ok {\n\t\treturn &ValidationError{Name: \"user\", err: errors.New(`ent: missing required edge \"Rental.user\"`)}\n\t}\n\tif _, ok := rc.mutation.CarID(); !ok {\n\t\treturn &ValidationError{Name: \"car\", err: errors.New(`ent: missing required edge \"Rental.car\"`)}\n\t}\n\treturn nil\n}", "func (m *ContactAccountAttributesAccountWith) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (m *Customer) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateAutoCollection(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateBalances(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateBillingAddress(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateBillingDateMode(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateBillingDayOfWeek(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateBillingDayOfWeekMode(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateContacts(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateEntityCode(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateFraudFlag(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validatePaymentMethod(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateReferralUrls(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateTaxability(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (m *OBWriteInternational3DataInitiationDebtorAccount) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateIdentification(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateName(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateSchemeName(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateSecondaryIdentification(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (m *ClusterVcenterAccount) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (e *RetrieveBalance) Validate(\n\tr *http.Request,\n) error {\n\tctx := r.Context()\n\n\t// Validate id.\n\tid, owner, token, err := ValidateID(ctx, pat.Param(r, \"balance\"))\n\tif err != nil {\n\t\treturn errors.Trace(err)\n\t}\n\te.ID = *id\n\te.Token = *token\n\te.Owner = *owner\n\n\treturn nil\n}", "func (u *User) Validate() ([]app.Invalid, error) {\n\tvar inv []app.Invalid\n\n\tif u.UserType == 0 {\n\t\tinv = append(inv, app.Invalid{Fld: \"UserType\", Err: \"The value of UserType cannot be 0.\"})\n\t}\n\n\tif u.FirstName == \"\" {\n\t\tinv = append(inv, app.Invalid{Fld: \"FirstName\", Err: \"A value of FirstName cannot be empty.\"})\n\t}\n\n\tif u.LastName == \"\" {\n\t\tinv = append(inv, app.Invalid{Fld: \"LastName\", Err: \"A value of LastName cannot be empty.\"})\n\t}\n\n\tif u.Email == \"\" {\n\t\tinv = append(inv, app.Invalid{Fld: \"Email\", Err: \"A value of Email cannot be empty.\"})\n\t}\n\n\tif u.Company == \"\" {\n\t\tinv = append(inv, app.Invalid{Fld: \"Company\", Err: \"A value of Company cannot be empty.\"})\n\t}\n\n\tif len(u.Addresses) == 0 {\n\t\tinv = append(inv, app.Invalid{Fld: \"Addresses\", Err: \"There must be at least one address.\"})\n\t} else {\n\t\tfor _, ua := range u.Addresses {\n\t\t\tif va, err := ua.Validate(); err != nil {\n\t\t\t\tinv = append(inv, va...)\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(inv) > 0 {\n\t\treturn inv, errors.New(\"Validation failures identified\")\n\t}\n\n\treturn nil, nil\n}", "func ValidateGetAccountResponseBody(body *GetAccountResponseBody) (err error) {\n\tif body.Account != nil {\n\t\tif err2 := ValidateRelayerAccountResponseBody(body.Account); err2 != nil {\n\t\t\terr = goa.MergeErrors(err, err2)\n\t\t}\n\t}\n\treturn\n}", "func (p *Pass) FieldsValid() bool {\n\tfmt.Printf(\"validating: \")\n\tvalid := true\n\tfor k, v := range *p {\n\t\tfmt.Printf(\"%v...\", k)\n\t\tv := isFieldValid(k, v)\n\t\tvalid = valid && v\n\t\tif v {\n\t\t\tfmt.Printf(\"VALID \")\n\t\t} else {\n\t\t\tfmt.Printf(\"INVALID \")\n\t\t}\n\t}\n\n\tfmt.Println(\"\")\n\treturn valid\n}", "func (t AuthToken) Validate() error {\n\t// Holds names of empty fields\n\tempty := []string{}\n\n\t// Check user id\n\tif len(t.UserID) == 0 {\n\t\tempty = append(empty, \"UserID\")\n\t}\n\n\t// Check device id\n\tif len(t.DeviceID) == 0 {\n\t\tempty = append(empty, \"DeviceID\")\n\t}\n\n\t// Check if any empty fields\n\tif len(empty) != 0 {\n\t\treturn fmt.Errorf(\"the following fields were empty: %s\",\n\t\t\tStrings.join(empty))\n\t}\n\n\t// All good\n\treturn nil\n}", "func (p *Passport) ValidateStrict(input string) {\r\n\tbyr := regexp.MustCompile(`byr:(\\d*)`)\r\n\tif byr.MatchString(input) {\r\n\t\tmatches := byr.FindStringSubmatch(input)\r\n\t\tf, err := NewYearField(matches[1], byrMin, byrMax)\r\n\t\tif err == nil {\r\n\t\t\tp.byr = f\r\n\t\t}\r\n\t}\r\n\r\n\tiyr := regexp.MustCompile(`iyr:(\\d*)`)\r\n\tif iyr.MatchString(input) {\r\n\t\tmatches := iyr.FindStringSubmatch(input)\r\n\t\tf, err := NewYearField(matches[1], iyrMin, iyrMax)\r\n\t\tif err == nil {\r\n\t\t\tp.iyr = f\r\n\t\t}\r\n\t}\r\n\r\n\teyr := regexp.MustCompile(`eyr:(\\d*)`)\r\n\tif eyr.MatchString(input) {\r\n\t\tmatches := eyr.FindStringSubmatch(input)\r\n\t\tf, err := NewYearField(matches[1], eyrMin, eyrMax)\r\n\t\tif err == nil {\r\n\t\t\tp.eyr = f\r\n\t\t}\r\n\t}\r\n\r\n\thgt := regexp.MustCompile(`hgt:(\\d*)(cm|in)?`)\r\n\tif hgt.MatchString(input) {\r\n\t\tmatches := hgt.FindStringSubmatch(input)\r\n\t\tf, err := NewHeightField(matches[1], matches[2])\r\n\t\tif err == nil {\r\n\t\t\tp.hgt = f\r\n\t\t}\r\n\t}\r\n\r\n\thcl := regexp.MustCompile(`hcl:(#[a-f0-9]*)`)\r\n\tif hcl.MatchString(input) {\r\n\t\tmatches := hcl.FindStringSubmatch(input)\r\n\t\tf, err := NewTextField(matches[1], hclExp)\r\n\t\tif err == nil {\r\n\t\t\tp.hcl = f\r\n\t\t}\r\n\t}\r\n\r\n\tecl := regexp.MustCompile(`ecl:(\\w*)`)\r\n\tif ecl.MatchString(input) {\r\n\t\tmatches := ecl.FindStringSubmatch(input)\r\n\t\tf, err := NewTextField(matches[1], eclExp)\r\n\t\tif err == nil {\r\n\t\t\tp.ecl = f\r\n\t\t}\r\n\t}\r\n\r\n\tpid := regexp.MustCompile(`pid:(\\d*)`)\r\n\tif pid.MatchString(input) {\r\n\t\tmatches := pid.FindStringSubmatch(input)\r\n\t\tf, err := NewTextField(matches[1], pidExp)\r\n\t\tif err == nil {\r\n\t\t\tp.pid = f\r\n\t\t}\r\n\t}\r\n}", "func (u *User) Validate(tx *pop.Connection) (*validate.Errors, error) {\n\treturn validate.Validate(\n\t\t&validators.StringIsPresent{Field: u.Email, Name: \"Email\"},\n\t\t&validators.StringIsPresent{Field: u.FirstName, Name: \"FirstName\"},\n\t\t&validators.StringIsPresent{Field: u.LastName, Name: \"LastName\"},\n\t\t&validators.StringIsPresent{Field: u.Nickname, Name: \"Nickname\"},\n\t\t&validators.UUIDIsPresent{Field: u.UUID, Name: \"UUID\"},\n\t\t&NullsStringIsURL{Field: u.AuthPhotoURL, Name: \"AuthPhotoURL\"},\n\t\t&domain.StringIsVisible{Field: u.Nickname, Name: \"Nickname\"},\n\t), nil\n}", "func (r *registrationRequest) isValid() error {\n\n\t//check recaptcha\n\trc := recaptcha.R{Secret: config.CaptchaSecretKey}\n\tif !rc.VerifyResponse(r.Captcha) {\n\t\treturn fmt.Errorf(\"ReCaptcha error: %s\", strings.Join(rc.LastError()[1:], \", \"))\n\t}\n\n\t// check if any of this is empty\n\tif r.Email == \"\" || r.Password == \"\" || r.PasswordConfirmation == \"\" ||\n\t\tr.First == \"\" || r.Last == \"\" {\n\t\treturn fmt.Errorf(\"%s\\n\", \"You entered incomplete data. First and last name, email and \"+\n\t\t\t\"password are mandatory fields.\")\n\t}\n\n\t// check if the password match and that the length is at least 8 chars\n\treturn passwordsAreValid(r.Password, r.PasswordConfirmation)\n}", "func (i *infoOptions) validate() error {\n\t// date-field required\n\tif len(i.DateField) == 0 {\n\t\treturn errors.New(`date-field required`)\n\t}\n\n\t// date-field index value if sep is present\n\tif len(i.Sep) > 0 {\n\t\t// attempt to convert DateField to int\n\t\tvar err error\n\t\t_, err = strconv.Atoi(i.DateField)\n\t\tif err != nil {\n\t\t\treturn errors.New(`date-field must be an integer when using a csv field separator`)\n\t\t}\n\t}\n\n\t// dest-template required\n\tif i.DestTemplate == \"\" {\n\t\treturn errors.New(`dest-template required`)\n\t}\n\n\treturn nil\n}", "func (p paymentJson) Validate() error {\n\tif p.AccountId == \"\" {\n\t\treturn errors.New(\"missing customer id\")\n\t}\n\tif p.Amount == 0 {\n\t\treturn errors.New(\"missing amount\")\n\t}\n\treturn nil\n}", "func Validation(a User) error {\n\tfmt.Println(\"user :: \", a)\n\tvar rxEmail = regexp.MustCompile(\"^[a-zA-Z0-9.!#$%&'*+\\\\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$\")\n\tswitch {\n\tcase len(strings.TrimSpace(a.Password)) == 0:\n\t\treturn ErrPasswordInvalid\n\tcase len(strings.TrimSpace(a.Email)) == 0 || !rxEmail.MatchString(a.Email):\n\t\treturn ErrEmailInvalid\n\tdefault:\n\t\treturn nil\n\t}\n}", "func (account *DatabaseAccount) createValidations() []func() (admission.Warnings, error) {\n\treturn []func() (admission.Warnings, error){account.validateResourceReferences, account.validateSecretDestinations}\n}" ]
[ "0.6950377", "0.6660194", "0.6604518", "0.660115", "0.6589453", "0.6474401", "0.6469365", "0.6463922", "0.64215875", "0.63889915", "0.6362919", "0.63358384", "0.6252108", "0.62329525", "0.6229978", "0.61784095", "0.61675555", "0.61494285", "0.6107046", "0.6084981", "0.6062506", "0.6018709", "0.59835136", "0.5935781", "0.59250987", "0.5920425", "0.5918846", "0.5906061", "0.58879864", "0.5874278", "0.5862281", "0.5844713", "0.5843288", "0.58394945", "0.58318245", "0.58267343", "0.5805197", "0.5782027", "0.577867", "0.5762948", "0.57397187", "0.57109004", "0.567482", "0.5670878", "0.5664908", "0.5659827", "0.56587", "0.5648205", "0.5621579", "0.55948484", "0.55917954", "0.55910474", "0.5587459", "0.55859625", "0.55767894", "0.5549079", "0.5528815", "0.5525437", "0.5523396", "0.551239", "0.55084354", "0.55050844", "0.54942113", "0.54916596", "0.5487635", "0.5478365", "0.54646176", "0.54524314", "0.54512787", "0.5443251", "0.54331243", "0.5430431", "0.54267573", "0.54245096", "0.5422896", "0.54207206", "0.54192007", "0.54148257", "0.540501", "0.5398671", "0.5397307", "0.5396947", "0.5394909", "0.53946984", "0.53905594", "0.53878796", "0.5384738", "0.5380616", "0.53800863", "0.53762895", "0.5367286", "0.5357383", "0.5353596", "0.5347578", "0.5342094", "0.5340789", "0.53367335", "0.5334526", "0.5331692", "0.5330748", "0.532834" ]
0.0
-1
MarshalYAML returns the YAML representation of a PeriodicVestingAccount.
func (pva PeriodicVestingAccount) MarshalYAML() (interface{}, error) { accAddr, err := sdk.AccAddressFromBech32(pva.Address) if err != nil { return nil, err } out := vestingAccountYAML{ Address: accAddr, AccountNumber: pva.AccountNumber, PubKey: getPKString(pva), Sequence: pva.Sequence, OriginalVesting: pva.OriginalVesting, DelegatedFree: pva.DelegatedFree, DelegatedVesting: pva.DelegatedVesting, EndTime: pva.EndTime, StartTime: pva.StartTime, VestingPeriods: pva.VestingPeriods, } return marshalYaml(out) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (bva BaseVestingAccount) MarshalYAML() (interface{}, error) {\n\taccAddr, err := sdk.AccAddressFromBech32(bva.Address)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tout := vestingAccountYAML{\n\t\tAddress: accAddr,\n\t\tAccountNumber: bva.AccountNumber,\n\t\tPubKey: getPKString(bva),\n\t\tSequence: bva.Sequence,\n\t\tOriginalVesting: bva.OriginalVesting,\n\t\tDelegatedFree: bva.DelegatedFree,\n\t\tDelegatedVesting: bva.DelegatedVesting,\n\t\tEndTime: bva.EndTime,\n\t}\n\treturn marshalYaml(out)\n}", "func (va ClawbackVestingAccount) MarshalYAML() (interface{}, error) {\n\taccAddr, err := sdk.AccAddressFromBech32(va.Address)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tout := vestingAccountYAML{\n\t\tAddress: accAddr,\n\t\tAccountNumber: va.AccountNumber,\n\t\tPubKey: getPKString(va),\n\t\tSequence: va.Sequence,\n\t\tOriginalVesting: va.OriginalVesting,\n\t\tDelegatedFree: va.DelegatedFree,\n\t\tDelegatedVesting: va.DelegatedVesting,\n\t\tEndTime: va.EndTime,\n\t\tStartTime: va.StartTime,\n\t\tVestingPeriods: va.VestingPeriods,\n\t}\n\treturn marshalYaml(out)\n}", "func (cva ContinuousVestingAccount) MarshalYAML() (interface{}, error) {\n\taccAddr, err := sdk.AccAddressFromBech32(cva.Address)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tout := vestingAccountYAML{\n\t\tAddress: accAddr,\n\t\tAccountNumber: cva.AccountNumber,\n\t\tPubKey: getPKString(cva),\n\t\tSequence: cva.Sequence,\n\t\tOriginalVesting: cva.OriginalVesting,\n\t\tDelegatedFree: cva.DelegatedFree,\n\t\tDelegatedVesting: cva.DelegatedVesting,\n\t\tEndTime: cva.EndTime,\n\t\tStartTime: cva.StartTime,\n\t}\n\treturn marshalYaml(out)\n}", "func (vva ValidatorVestingAccount) MarshalYAML() (interface{}, error) {\n\tvar bs []byte\n\tvar err error\n\tvar pubkey string\n\n\tif vva.PubKey != nil {\n\t\tpubkey, err = sdk.Bech32ifyAccPub(vva.PubKey)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tbs, err = yaml.Marshal(struct {\n\t\tAddress sdk.AccAddress\n\t\tCoins sdk.Coins\n\t\tPubKey string\n\t\tAccountNumber uint64\n\t\tSequence uint64\n\t\tOriginalVesting sdk.Coins\n\t\tDelegatedFree sdk.Coins\n\t\tDelegatedVesting sdk.Coins\n\t\tEndTime int64\n\t\tStartTime int64\n\t\tVestingPeriods vestingtypes.Periods\n\t\tValidatorAddress sdk.ConsAddress\n\t\tReturnAddress sdk.AccAddress\n\t\tSigningThreshold int64\n\t\tCurrentPeriodProgress CurrentPeriodProgress\n\t\tVestingPeriodProgress []VestingProgress\n\t\tDebtAfterFailedVesting sdk.Coins\n\t}{\n\t\tAddress: vva.Address,\n\t\tCoins: vva.Coins,\n\t\tPubKey: pubkey,\n\t\tAccountNumber: vva.AccountNumber,\n\t\tSequence: vva.Sequence,\n\t\tOriginalVesting: vva.OriginalVesting,\n\t\tDelegatedFree: vva.DelegatedFree,\n\t\tDelegatedVesting: vva.DelegatedVesting,\n\t\tEndTime: vva.EndTime,\n\t\tStartTime: vva.StartTime,\n\t\tVestingPeriods: vva.VestingPeriods,\n\t\tValidatorAddress: vva.ValidatorAddress,\n\t\tReturnAddress: vva.ReturnAddress,\n\t\tSigningThreshold: vva.SigningThreshold,\n\t\tCurrentPeriodProgress: vva.CurrentPeriodProgress,\n\t\tVestingPeriodProgress: vva.VestingPeriodProgress,\n\t\tDebtAfterFailedVesting: vva.DebtAfterFailedVesting,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn string(bs), err\n}", "func (b *Backend) MarshalYAML() (interface{}, error) {\n\tb.mu.RLock()\n\tdefer b.mu.RUnlock()\n\n\tpayload := struct {\n\t\tAddress string\n\t\tDisabledUntil time.Time `yaml:\"disabledUntil\"`\n\t\tForcePromotionsAfter time.Duration `yaml:\"forcePromotionsAfter\"`\n\t\tLatency time.Duration `yaml:\"latency\"`\n\t\tMaxConnections int `yaml:\"maxConnections\"`\n\t\tTier int `yaml:\"tier\"`\n\t}{\n\t\tAddress: b.addr.String(),\n\t\tDisabledUntil: b.mu.disabledUntil,\n\t\tForcePromotionsAfter: b.mu.forcePromotionAfter,\n\t\tLatency: b.mu.lastLatency,\n\t\tMaxConnections: b.mu.maxConnections,\n\t\tTier: b.mu.tier,\n\t}\n\treturn payload, nil\n}", "func (a ApprovalStrategy) MarshalYAML() (interface{}, error) {\n\treturn approvalStrategyToString[a], nil\n\t//buffer := bytes.NewBufferString(`\"`)\n\t//buffer.WriteString(approvalStrategyToString[*s])\n\t//buffer.WriteString(`\"`)\n\t//return buffer.Bytes(), nil\n}", "func (r RetryConfig) MarshalYAML() (interface{}, error) {\n\tdummy := dummyRetryConfig{\n\t\tOutput: r.Output,\n\t\tConfig: r.Config,\n\t}\n\tif r.Output == nil {\n\t\tdummy.Output = struct{}{}\n\t}\n\treturn dummy, nil\n}", "func (o *OAuthFlow) MarshalYAML() (interface{}, error) {\n\tnb := high.NewNodeBuilder(o, o.low)\n\treturn nb.Render(), nil\n}", "func (p *Parameter) MarshalYAML() (interface{}, error) {\n\tnb := high.NewNodeBuilder(p, p.low)\n\treturn nb.Render(), nil\n}", "func (i Instance) MarshalYAML() (interface{}, error) {\n\treturn i.Vars, nil\n}", "func (r OAuthFlow) MarshalYAML() (interface{}, error) {\n\tobj := make(map[string]interface{})\n\n\tobj[\"authorizationUrl\"] = r.AuthorizationURL\n\n\tobj[\"tokenUrl\"] = r.TokenURL\n\n\tif r.RefreshURL != \"\" {\n\t\tobj[\"refreshUrl\"] = r.RefreshURL\n\t}\n\n\tobj[\"scopes\"] = r.Scopes\n\n\tfor key, val := range r.Extensions {\n\t\tobj[key] = val\n\t}\n\n\treturn obj, nil\n}", "func (v Validator) MarshalYAML() (interface{}, error) {\n\tbs, err := yaml.Marshal(struct {\n\t\tStatus sdk.BondStatus\n\t\tJailed bool\n\t\tUnbondingHeight int64\n\t\tConsPubKey string\n\t\tOperatorAddress sdk.ValAddress\n\t\tTokens sdk.Int\n\t\tDelegatorShares sdk.Dec\n\t\tDescription Description\n\t\tUnbondingCompletionTime time.Time\n\t\tCommission Commission\n\t\tMinSelfDelegation sdk.Dec\n\t}{\n\t\tOperatorAddress: v.OperatorAddress,\n\t\tConsPubKey: MustBech32ifyConsPub(v.ConsPubKey),\n\t\tJailed: v.Jailed,\n\t\tStatus: v.Status,\n\t\tTokens: v.Tokens,\n\t\tDelegatorShares: v.DelegatorShares,\n\t\tDescription: v.Description,\n\t\tUnbondingHeight: v.UnbondingHeight,\n\t\tUnbondingCompletionTime: v.UnbondingCompletionTime,\n\t\tCommission: v.Commission,\n\t\tMinSelfDelegation: v.MinSelfDelegation,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn string(bs), nil\n}", "func (r ReadUntilConfig) MarshalYAML() (interface{}, error) {\n\tdummy := dummyReadUntilConfig{\n\t\tInput: r.Input,\n\t\tRestart: r.Restart,\n\t\tCheck: r.Check,\n\t}\n\tif r.Input == nil {\n\t\tdummy.Input = struct{}{}\n\t}\n\treturn dummy, nil\n}", "func (d Rate) MarshalYAML() (interface{}, error) {\n\treturn d.String(), nil\n}", "func (key PrivateKey) MarshalYAML() (interface{}, error) {\n\treturn key.String(), nil\n}", "func (export WebAuthnDeviceExport) MarshalYAML() (any, error) {\n\treturn export.ToData(), nil\n}", "func (c *Components) MarshalYAML() (interface{}, error) {\n\tnb := high.NewNodeBuilder(c, c.low)\n\treturn nb.Render(), nil\n}", "func (d *WebAuthnDevice) MarshalYAML() (any, error) {\n\treturn d.ToData(), nil\n}", "func (i UserGroupAccess) MarshalYAML() (interface{}, error) {\n\treturn i.String(), nil\n}", "func (key PublicKey) MarshalYAML() (interface{}, error) {\n\treturn key.String(), nil\n}", "func (p Params) MarshalYAML() (interface{}, error) {\n\treturn p.String(), nil\n}", "func (i ChannelName) MarshalYAML() (interface{}, error) {\n\treturn i.String(), nil\n}", "func (z Z) MarshalYAML() (interface{}, error) {\n\ttype Z struct {\n\t\tS string `json:\"s\"`\n\t\tI int32 `json:\"iVal\"`\n\t\tHash string\n\t\tMultiplyIByTwo int64 `json:\"multipliedByTwo\"`\n\t}\n\tvar enc Z\n\tenc.S = z.S\n\tenc.I = z.I\n\tenc.Hash = z.Hash()\n\tenc.MultiplyIByTwo = int64(z.MultiplyIByTwo())\n\treturn &enc, nil\n}", "func (s GitEvent) MarshalYAML() (interface{}, error) {\n\treturn toString[s], nil\n}", "func (bc *ByteCount) MarshalYAML() (interface{}, error) {\n\treturn uint64(AtomicLoadByteCount(bc)), nil\n}", "func (d Duration) MarshalYAML() (interface{}, error) {\n\treturn d.String(), nil\n}", "func (o *OpenAPI3SchemaExtension) MarshalYAML() (interface{}, error) {\n\treturn util.MarshalYAMLWithDescriptions(o)\n}", "func (ec EllipticCurve) MarshalYAML() (interface{}, error) {\n\treturn ec.String(), nil\n}", "func (f Fixed8) MarshalYAML() (interface{}, error) {\n\treturn f.String(), nil\n}", "func (d Duration) MarshalYAML() (interface{}, error) {\n\treturn d.Duration.String(), nil\n}", "func (o *OpenAPI3PathExtension) MarshalYAML() (interface{}, error) {\n\treturn util.MarshalYAMLWithDescriptions(o)\n}", "func (ss StdSignature) MarshalYAML() (interface{}, error) {\n\tpk := \"\"\n\tif ss.PubKey != nil {\n\t\tpk = ss.PubKey.String()\n\t}\n\n\tbz, err := yaml.Marshal(struct {\n\t\tPubKey string `json:\"pub_key\"`\n\t\tSignature string `json:\"signature\"`\n\t}{\n\t\tpk,\n\t\tfmt.Sprintf(\"%X\", ss.Signature),\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn string(bz), err\n}", "func (d LegacyDec) MarshalYAML() (interface{}, error) {\n\treturn d.String(), nil\n}", "func (m *BootstrapMode) MarshalYAML() (interface{}, error) {\n\treturn m.String(), nil\n}", "func (o *OpenAPI3ResponseExtension) MarshalYAML() (interface{}, error) {\n\treturn util.MarshalYAMLWithDescriptions(o)\n}", "func (d *Discriminator) MarshalYAML() (interface{}, error) {\n\tnb := low2.NewNodeBuilder(d, d.low)\n\treturn nb.Render(), nil\n}", "func (n Nil) MarshalYAML() (interface{}, error) {\n\treturn nil, nil\n}", "func (d *DefaultOptions) MarshalYAML() (interface{}, error) {\n\treturn util.MarshalYAMLWithDescriptions(d)\n}", "func (s Secret) MarshalYAML() (interface{}, error) {\n\tif s != \"\" {\n\t\treturn \"<secret>\", nil\n\t}\n\treturn nil, nil\n}", "func (s Secret) MarshalYAML() (interface{}, error) {\n\tif s != \"\" {\n\t\treturn \"<secret>\", nil\n\t}\n\treturn nil, nil\n}", "func (d DurationMinutes) MarshalYAML() (interface{}, error) {\n\tif !d.IsPresent() {\n\t\treturn nil, nil\n\t}\n\treturn int(d.value / time.Minute), nil\n}", "func (ep Endpoint) MarshalYAML() (interface{}, error) {\n\ts, err := ep.toString()\n\treturn s, err\n}", "func (m MixinDeclaration) MarshalYAML() (interface{}, error) {\n\tif m.Config == nil {\n\t\treturn m.Name, nil\n\t}\n\n\traw := map[string]interface{}{\n\t\tm.Name: m.Config,\n\t}\n\treturn raw, nil\n}", "func (d DurationMillis) MarshalYAML() (interface{}, error) {\n\tif !d.IsPresent() {\n\t\treturn nil, nil\n\t}\n\treturn int(d.value / time.Millisecond), nil\n}", "func (v *Int8) MarshalYAML() (interface{}, error) {\n\tif v.IsAssigned {\n\t\treturn v.Val, nil\n\t}\n\treturn nil, nil\n}", "func (schema SchemaType) MarshalYAML() (interface{}, error) {\n\treturn schema.String(), nil\n}", "func MarshalYAML(v interface{}, extensions map[string]interface{}) (interface{}, error) {\n\tif len(extensions) == 0 {\n\t\treturn v, nil\n\t}\n\tmarshaled, err := yaml.Marshal(v)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar unmarshaled map[string]interface{}\n\tif err := yaml.Unmarshal(marshaled, &unmarshaled); err != nil {\n\t\treturn nil, err\n\t}\n\tfor k, v := range extensions {\n\t\tunmarshaled[k] = v\n\t}\n\treturn unmarshaled, nil\n}", "func (b ByteCount) MarshalYAML() (interface{}, error) {\n\treturn uint64(b), nil\n}", "func (cp *CertPool) MarshalYAML() (interface{}, error) {\n\treturn cp.Files, nil\n}", "func Marshal(v interface{}) ([]byte, error) {\n\tvar buf bytes.Buffer\n\tenc := yaml.NewEncoder(&buf)\n\tenc.SetIndent(2)\n\terr := enc.Encode(v)\n\treturn buf.Bytes(), err\n}", "func (v *VersionInfo) MarshalYAML() (interface{}, error) {\n\n\treturn &struct {\n\t\tSemVer string `yaml:\"semver\"`\n\t\tShaLong string `yaml:\"shaLong\"`\n\t\tBuildTimestamp int64 `yaml:\"buildTimestamp\"`\n\t\tBranch string `yaml:\"branch\"`\n\t\tArch string `yaml:\"arch\"`\n\t}{\n\t\tSemVer: v.SemVer,\n\t\tShaLong: v.ShaLong,\n\t\tBuildTimestamp: v.BuildTimestamp.Unix(),\n\t\tBranch: v.Branch,\n\t\tArch: v.Arch,\n\t}, nil\n}", "func (m OrderedMap[K, V]) MarshalYAML() ([]byte, error) {\n\tvar s yaml.MapSlice\n\tfor _, item := range m.ToSlice() {\n\t\ts = append(s, yaml.MapItem{\n\t\t\tKey: item.Key,\n\t\t\tValue: item.Value,\n\t\t})\n\t}\n\treturn yaml.Marshal(s)\n}", "func (k *Kluster) YAML() ([]byte, error) {\n\treturn yaml.Marshal(k)\n}", "func (op OpRetain) MarshalYAML() (interface{}, error) {\n\treturn op.Fields, nil\n}", "func (f BodyField) MarshalYAML() (interface{}, error) {\n\treturn toJSONDot(f), nil\n}", "func (r *Regexp) MarshalYAML() (interface{}, error) {\n\treturn r.String(), nil\n}", "func (i UOM) MarshalYAML() (interface{}, error) {\n\treturn i.String(), nil\n}", "func (r Discriminator) MarshalYAML() (interface{}, error) {\n\tobj := make(map[string]interface{})\n\n\tobj[\"propertyName\"] = r.PropertyName\n\n\tif len(r.Mapping) > 0 {\n\t\tobj[\"mapping\"] = r.Mapping\n\t}\n\n\treturn obj, nil\n}", "func (r ParseKind) MarshalYAML() ([]byte, error) {\n\tif s, ok := interface{}(r).(fmt.Stringer); ok {\n\t\treturn yaml.Marshal(s.String())\n\t}\n\ts, ok := _ParseKindValueToName[r]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"invalid ParseKind: %d\", r)\n\t}\n\treturn yaml.Marshal(s)\n}", "func (t TimeUnixSeconds) MarshalYAML() (interface{}, error) {\n\tif !t.IsPresent() {\n\t\treturn nil, nil\n\t}\n\treturn t.value.Unix(), nil\n}", "func (i Int) MarshalYAML() (interface{}, error) {\n\tif !i.IsPresent() {\n\t\treturn nil, nil\n\t}\n\treturn i.value, nil\n}", "func (o *OpenAPI3Options) MarshalYAML() (interface{}, error) {\n\treturn util.MarshalYAMLWithDescriptions(o)\n}", "func (d DurationSeconds) MarshalYAML() (interface{}, error) {\n\tif !d.IsPresent() {\n\t\treturn nil, nil\n\t}\n\n\treturn int(d.value / time.Second), nil\n}", "func (f Flag) MarshalYAML() (interface{}, error) {\n\treturn f.Name, nil\n}", "func (date Date) MarshalYAML() (interface{}, error) {\n\tvar d = string(date)\n\tif err := checkDateFormat(d); err != nil {\n\t\treturn nil, err\n\t}\n\treturn d, nil\n}", "func (i Interface) MarshalYAML() (interface{}, error) {\n\treturn i.String(), nil\n}", "func (re Regexp) MarshalYAML() (interface{}, error) {\n\tif re.original != \"\" {\n\t\treturn re.original, nil\n\t}\n\treturn nil, nil\n}", "func (re Regexp) MarshalYAML() (interface{}, error) {\n\tif re.original != \"\" {\n\t\treturn re.original, nil\n\t}\n\treturn nil, nil\n}", "func (op OpFlatten) MarshalYAML() (interface{}, error) {\n\treturn op.Field.String(), nil\n}", "func (d Document) MarshalYAML() (interface{}, error) {\n\treturn d.raw, nil\n}", "func (b Bool) MarshalYAML() (interface{}, error) {\n\tif !b.IsPresent() {\n\t\treturn nil, nil\n\t}\n\treturn b.value, nil\n}", "func (c Configuration) YAML() ([]byte, error) {\n\treturn yaml.Marshal(c)\n}", "func (o Op) MarshalYAML() (interface{}, error) {\n\treturn map[string]interface{}{\n\t\to.Type(): o.OpApplier,\n\t}, nil\n}", "func (c *Config) YAML() ([]byte, error) {\n\treturn yaml.Marshal(c)\n}", "func MarshalToYaml(obj runtime.Object, gv schema.GroupVersion) ([]byte, error) {\n\treturn MarshalToYamlForCodecs(obj, gv, clientsetscheme.Codecs)\n}", "func MarshalMetricsYAML(metrics pmetric.Metrics) ([]byte, error) {\n\tunmarshaler := &pmetric.JSONMarshaler{}\n\tfileBytes, err := unmarshaler.MarshalMetrics(metrics)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar jsonVal map[string]interface{}\n\tif err = json.Unmarshal(fileBytes, &jsonVal); err != nil {\n\t\treturn nil, err\n\t}\n\tb := &bytes.Buffer{}\n\tenc := yaml.NewEncoder(b)\n\tenc.SetIndent(2)\n\tif err := enc.Encode(jsonVal); err != nil {\n\t\treturn nil, err\n\t}\n\treturn b.Bytes(), nil\n}", "func (v *Uint16) MarshalYAML() (interface{}, error) {\n\tif v.IsAssigned {\n\t\treturn v.Val, nil\n\t}\n\treturn nil, nil\n}", "func (c CompressionType) MarshalYAML() (interface{}, error) {\n\treturn compressionTypeID[c], nil\n}", "func (s SensitiveString) MarshalYAML() (interface{}, error) {\n\treturn s.String(), nil\n}", "func (o *Output) MarshalYAML() (interface{}, error) {\n\tif o.ShowValue {\n\t\treturn withvalue(*o), nil\n\t}\n\to.Value = nil // explicitly make empty\n\to.Sensitive = false // explicitly make empty\n\treturn *o, nil\n}", "func (c *Configmap) AsYAML() []byte {\n\tresult, err := yaml.Marshal(*c)\n\tif err != nil {\n\t\tlog.Printf(\"error marshaling YAML: %s\", err)\n\t}\n\treturn result\n}", "func ToYAML(v interface{}) ([]byte, error) {\n\treturn yaml.Marshal(v)\n}", "func (f *Fzp) ToYAML() ([]byte, error) {\n\tdata, err := yaml.Marshal(f)\n\treturn data, err\n}", "func (t *YAMLData) ToYAML() (*bytes.Buffer, error) {\n\td, err := yaml.Marshal(t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tb := bytes.NewBuffer(d)\n\n\treturn b, nil\n}", "func (u *URL) MarshalYAML() (interface{}, error) {\n\treturn u.String(), nil\n}", "func (s *Siegfried) YAML() string {\n\tversion := config.Version()\n\tstr := fmt.Sprintf(\n\t\t\"---\\nsiegfried : %d.%d.%d\\nscandate : %v\\nsignature : %s\\ncreated : %v\\nidentifiers : \\n\",\n\t\tversion[0], version[1], version[2],\n\t\ttime.Now().Format(time.RFC3339),\n\t\tconfig.SignatureBase(),\n\t\ts.C.Format(time.RFC3339))\n\tfor _, id := range s.ids {\n\t\td := id.Describe()\n\t\tstr += fmt.Sprintf(\" - name : '%v'\\n details : '%v'\\n\", d[0], d[1])\n\t}\n\treturn str\n}", "func (vm ValidationMap) AsYAML() (string, error) {\n\tdata, err := yaml.Marshal(vm)\n\treturn string(data), err\n}", "func SortYAML(in io.Reader, out io.Writer, indent int) error {\n\n\tincomingYAML, err := ioutil.ReadAll(in)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"can't read input: %v\", err)\n\t}\n\n\tvar hasNoStartingLabel bool\n\trootIndent, err := detectRootIndent(incomingYAML)\n\tif err != nil {\n\t\tif !errors.Is(err, ErrNoStartingLabel) {\n\t\t\tfmt.Fprint(out, string(incomingYAML))\n\t\t\treturn fmt.Errorf(\"can't detect root indentation: %v\", err)\n\t\t}\n\n\t\thasNoStartingLabel = true\n\t}\n\n\tif hasNoStartingLabel {\n\t\tincomingYAML = append([]byte(CustomLabel+\"\\n\"), incomingYAML...)\n\t}\n\n\tvar value map[string]interface{}\n\tif err := yaml.Unmarshal(incomingYAML, &value); err != nil {\n\t\tfmt.Fprint(out, string(incomingYAML))\n\n\t\treturn fmt.Errorf(\"can't decode YAML: %v\", err)\n\t}\n\n\tvar outgoingYAML bytes.Buffer\n\tencoder := yaml.NewEncoder(&outgoingYAML)\n\tencoder.SetIndent(indent)\n\n\tif err := encoder.Encode(&value); err != nil {\n\t\tfmt.Fprint(out, string(incomingYAML))\n\t\treturn fmt.Errorf(\"can't re-encode YAML: %v\", err)\n\t}\n\n\treindentedYAML, err := indentYAML(outgoingYAML.String(), rootIndent, indent, hasNoStartingLabel)\n\tif err != nil {\n\t\tfmt.Fprint(out, string(incomingYAML))\n\t\treturn fmt.Errorf(\"can't re-indent YAML: %v\", err)\n\t}\n\n\tfmt.Fprint(out, reindentedYAML)\n\treturn nil\n}", "func (p Period) String() string {\n\tout, _ := yaml.Marshal(p)\n\treturn string(out)\n}", "func (c Config) ToYAML() string {\n\tdata, _ := yaml.Marshal(c)\n\treturn string(data)\n}", "func (s *Schema) ToYAML() ([]byte, error) {\n\treturn yaml.Marshal(s)\n}", "func (s String) MarshalYAML() (interface{}, error) {\n\tif !s.IsPresent() {\n\t\treturn nil, nil\n\t}\n\treturn s.value, nil\n}", "func (v Values) YAML() (string, error) {\n\tb, err := yaml.Marshal(v)\n\treturn string(b), err\n}", "func FormatAsYAML(obj interface{}, indent int) string {\n\tif obj == nil {\n\t\treturn \"none\"\n\t}\n\tdata, err := yaml.Marshal(obj)\n\tif err != nil {\n\t\treturn fmt.Sprintf(\"Error during yaml serialization: %s\", err.Error())\n\t}\n\t// add an additional newline to properly inline\n\treturn ApplyIdent(\"\\n\"+string(data), indent)\n}", "func ToYAML(configuration interface{}) string {\n\tcontent, err := yaml.Marshal(configuration)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\treturn string(content)\n}", "func (c *Config) DumpYaml(filename string) error {\n\t// set timestamp with now()\n\tnow := time.Now().Format(time.ANSIC)\n\tc.Timestamp = now\n\tyamlString, err := yaml.Marshal(&c)\n\t// log.Printf(\"yamlString = %s\", yamlString)\n\n\terr = ioutil.WriteFile(filename, yamlString, 0)\n\treturn err\n}", "func (service Service) ToYAML() (string, error) {\n\tbytes, err := yaml.Marshal(service)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(bytes), nil\n}", "func (v PingSlotPeriod) MarshalBinary() ([]byte, error) {\n\treturn marshalBinaryEnum(int32(v)), nil\n}", "func (f Float64) MarshalYAML() (interface{}, error) {\n\tif !f.IsPresent() {\n\t\treturn nil, nil\n\t}\n\treturn f.value, nil\n}", "func toYAML(v interface{}) string {\n\tdata, err := yaml.Marshal(v)\n\tif err != nil {\n\t\t// Swallow errors inside of a template.\n\t\treturn \"\"\n\t}\n\n\treturn strings.TrimSuffix(string(data), \"\\n\")\n}" ]
[ "0.79740006", "0.79260373", "0.78480417", "0.77300644", "0.65652984", "0.62953556", "0.6279168", "0.6233041", "0.6193101", "0.60612226", "0.6042137", "0.5997969", "0.59689313", "0.5929271", "0.590953", "0.58872837", "0.58425134", "0.57967377", "0.5759037", "0.5754271", "0.57210827", "0.5648413", "0.5617461", "0.55981696", "0.55696446", "0.555271", "0.5549364", "0.55485266", "0.5546802", "0.5526156", "0.55066174", "0.55011785", "0.5484244", "0.54678977", "0.5463638", "0.5461245", "0.54519624", "0.5435896", "0.5424015", "0.5424015", "0.5413009", "0.54111516", "0.5404213", "0.5396494", "0.5393876", "0.53672904", "0.5359762", "0.5330223", "0.52994144", "0.529399", "0.52898425", "0.5281368", "0.52813554", "0.52419704", "0.5229916", "0.5211179", "0.52012104", "0.519821", "0.5172233", "0.51555836", "0.51500094", "0.51435983", "0.5126453", "0.51158124", "0.510647", "0.5089772", "0.50881", "0.50881", "0.5079991", "0.50746727", "0.5074032", "0.5030641", "0.50124764", "0.5001888", "0.49723357", "0.49659842", "0.49174768", "0.4873055", "0.48595425", "0.48509377", "0.48447785", "0.4817515", "0.4793211", "0.47819468", "0.47756645", "0.477434", "0.47736543", "0.47592208", "0.47590494", "0.4727706", "0.47102803", "0.47101897", "0.4706938", "0.4656327", "0.4626292", "0.46096212", "0.4597632", "0.45967078", "0.45923334", "0.4589245" ]
0.8524174
0
NewPeriodicGrantAction returns an AddGrantAction for a PeriodicVestingAccount
func NewPeriodicGrantAction( sk StakingKeeper, grantStartTime int64, grantVestingPeriods []Period, grantCoins sdk.Coins, ) exported.AddGrantAction { return periodicGrantAction{ sk: sk, grantStartTime: grantStartTime, grantVestingPeriods: grantVestingPeriods, grantCoins: grantCoins, } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (pva *PeriodicVestingAccount) AddGrant(ctx sdk.Context, action exported.AddGrantAction) error {\n\treturn action.AddToAccount(ctx, pva)\n}", "func (pva *PeriodicVestingAccount) addGrant(ctx sdk.Context, sk StakingKeeper, grantStartTime int64, grantVestingPeriods []Period, grantCoins sdk.Coins) {\n\t// how much is really delegated?\n\tbondedAmt := sk.GetDelegatorBonded(ctx, pva.GetAddress())\n\tunbondingAmt := sk.GetDelegatorUnbonding(ctx, pva.GetAddress())\n\tdelegatedAmt := bondedAmt.Add(unbondingAmt)\n\tdelegated := sdk.NewCoins(sdk.NewCoin(sk.BondDenom(ctx), delegatedAmt))\n\n\t// discover what has been slashed\n\toldDelegated := pva.DelegatedVesting.Add(pva.DelegatedFree...)\n\tslashed := oldDelegated.Sub(coinsMin(oldDelegated, delegated))\n\n\t// rebase the DV+DF by capping slashed at the current unvested amount\n\tunvested := pva.GetVestingCoins(ctx.BlockTime())\n\tnewSlashed := coinsMin(unvested, slashed)\n\tnewTotalDelegated := delegated.Add(newSlashed...)\n\n\t// modify vesting schedule for the new grant\n\tnewStart, newEnd, newPeriods := DisjunctPeriods(pva.StartTime, grantStartTime,\n\t\tpva.GetVestingPeriods(), grantVestingPeriods)\n\tpva.StartTime = newStart\n\tpva.EndTime = newEnd\n\tpva.VestingPeriods = newPeriods\n\tpva.OriginalVesting = pva.OriginalVesting.Add(grantCoins...)\n\n\t// cap DV at the current unvested amount, DF rounds out to newTotalDelegated\n\tunvested2 := pva.GetVestingCoins(ctx.BlockTime())\n\tpva.DelegatedVesting = coinsMin(newTotalDelegated, unvested2)\n\tpva.DelegatedFree = newTotalDelegated.Sub(pva.DelegatedVesting)\n}", "func newPeriodicVestingAccount(address sdk.AccAddress, periods vestingtypes.Periods, firstPeriodStartTimestamp int64) *vestingtypes.PeriodicVestingAccount {\n\tbaseAccount := authtypes.NewBaseAccount(address, nil, 0, 0)\n\n\toriginalVesting := sdk.NewCoins()\n\tfor _, p := range periods {\n\t\toriginalVesting = originalVesting.Add(p.Amount...)\n\t}\n\n\tvar totalPeriods int64\n\tfor _, p := range periods {\n\t\ttotalPeriods += p.Length\n\t}\n\tendTime := firstPeriodStartTimestamp + totalPeriods\n\n\tbaseVestingAccount := vestingtypes.NewBaseVestingAccount(baseAccount, originalVesting, endTime)\n\treturn vestingtypes.NewPeriodicVestingAccountRaw(baseVestingAccount, firstPeriodStartTimestamp, periods)\n}", "func (r *refreshTokenGranter) Grant(_ context.Context, requestedScopes []string) grants.Grant {\n\treturn grants.Grant{\n\t\tSourceType: \"refresh_token\",\n\t\tSourceID: r.token.ID,\n\t\tScopes: requestedScopes,\n\t\tAccountID: r.token.AccountID,\n\t\tProfileID: r.token.ProfileID,\n\t\tClientID: r.token.ClientID,\n\t\tUsed: false,\n\t}\n}", "func (va *ClawbackVestingAccount) addGrant(ctx sdk.Context, sk StakingKeeper, grantStartTime int64, grantLockupPeriods, grantVestingPeriods []Period, grantCoins sdk.Coins) {\n\t// how much is really delegated?\n\tbondedAmt := sk.GetDelegatorBonded(ctx, va.GetAddress())\n\tunbondingAmt := sk.GetDelegatorUnbonding(ctx, va.GetAddress())\n\tdelegatedAmt := bondedAmt.Add(unbondingAmt)\n\tdelegated := sdk.NewCoins(sdk.NewCoin(sk.BondDenom(ctx), delegatedAmt))\n\n\t// discover what has been slashed\n\toldDelegated := va.DelegatedVesting.Add(va.DelegatedFree...)\n\tslashed := oldDelegated.Sub(coinsMin(oldDelegated, delegated))\n\n\t// rebase the DV + DF by capping slashed at the current unvested amount\n\tunvested := va.OriginalVesting.Sub(va.GetVestedOnly(ctx.BlockTime()))\n\tnewSlashed := coinsMin(slashed, unvested)\n\tnewDelegated := delegated.Add(newSlashed...)\n\n\t// modify schedules for the new grant\n\tnewLockupStart, newLockupEnd, newLockupPeriods := DisjunctPeriods(va.StartTime, grantStartTime, va.LockupPeriods, grantLockupPeriods)\n\tnewVestingStart, newVestingEnd, newVestingPeriods := DisjunctPeriods(va.StartTime, grantStartTime,\n\t\tva.GetVestingPeriods(), grantVestingPeriods)\n\tif newLockupStart != newVestingStart {\n\t\tpanic(\"bad start time calculation\")\n\t}\n\tva.StartTime = newLockupStart\n\tva.EndTime = max64(newLockupEnd, newVestingEnd)\n\tva.LockupPeriods = newLockupPeriods\n\tva.VestingPeriods = newVestingPeriods\n\tva.OriginalVesting = va.OriginalVesting.Add(grantCoins...)\n\n\t// cap DV at the current unvested amount, DF rounds out to newDelegated\n\tunvested2 := va.GetVestingCoins(ctx.BlockTime())\n\tva.DelegatedVesting = coinsMin(newDelegated, unvested2)\n\tva.DelegatedFree = newDelegated.Sub(va.DelegatedVesting)\n}", "func (pga periodicGrantAction) AddToAccount(ctx sdk.Context, rawAccount exported.VestingAccount) error {\n\tpva, ok := rawAccount.(*PeriodicVestingAccount)\n\tif !ok {\n\t\treturn sdkerrors.Wrapf(sdkerrors.ErrNotSupported,\n\t\t\t\"account %s must be a PeriodicVestingAccount, got %T\",\n\t\t\trawAccount.GetAddress(), rawAccount)\n\t}\n\tpva.addGrant(ctx, pga.sk, pga.grantStartTime, pga.grantVestingPeriods, pga.grantCoins)\n\treturn nil\n}", "func NewPeriodicVestingAccount(baseAcc *authtypes.BaseAccount, originalVesting sdk.Coins, startTime int64, periods Periods) *PeriodicVestingAccount {\n\tendTime := startTime\n\tfor _, p := range periods {\n\t\tendTime += p.Length\n\t}\n\tbaseVestingAcc := &BaseVestingAccount{\n\t\tBaseAccount: baseAcc,\n\t\tOriginalVesting: originalVesting,\n\t\tEndTime: endTime,\n\t}\n\n\treturn &PeriodicVestingAccount{\n\t\tBaseVestingAccount: baseVestingAcc,\n\t\tStartTime: startTime,\n\t\tVestingPeriods: periods,\n\t}\n}", "func AccountGrant() GrantBuilder {\n\treturn &CurrentGrantBuilder{\n\t\tgrantType: accountType,\n\t}\n}", "func Grant(ctx context.Context, i grantRequest) error {\n\tclient, err := New(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn client.Grant(ctx, i)\n}", "func (ge *CurrentGrantExecutable) Grant(p string) string {\n\tvar template string\n\tif p == `OWNERSHIP` {\n\t\ttemplate = `GRANT %v ON %v %v TO %v \"%v\" COPY CURRENT GRANTS`\n\t} else {\n\t\ttemplate = `GRANT %v ON %v %v TO %v \"%v\"`\n\t}\n\treturn fmt.Sprintf(template,\n\t\tp, ge.grantType, ge.grantName, ge.granteeType, ge.granteeName)\n}", "func NewAutoGrant() GrantHandler {\n\treturn &autoGrant{}\n}", "func (r *jsiiProxy_RepositoryBase) Grant(grantee awsiam.IGrantable, actions ...*string) awsiam.Grant {\n\targs := []interface{}{grantee}\n\tfor _, a := range actions {\n\t\targs = append(args, a)\n\t}\n\n\tvar returns awsiam.Grant\n\n\t_jsii_.Invoke(\n\t\tr,\n\t\t\"grant\",\n\t\targs,\n\t\t&returns,\n\t)\n\n\treturn returns\n}", "func AccountGrant() *TerraformGrantResource {\n\treturn &TerraformGrantResource{\n\t\tResource: &schema.Resource{\n\t\t\tCreate: CreateAccountGrant,\n\t\t\tRead: ReadAccountGrant,\n\t\t\tDelete: DeleteAccountGrant,\n\t\t\tUpdate: UpdateAccountGrant,\n\n\t\t\tSchema: accountGrantSchema,\n\t\t\tImporter: &schema.ResourceImporter{\n\t\t\t\tStateContext: schema.ImportStatePassthroughContext,\n\t\t\t},\n\t\t},\n\t\tValidPrivs: validAccountPrivileges,\n\t}\n}", "func (r *jsiiProxy_Repository) Grant(grantee awsiam.IGrantable, actions ...*string) awsiam.Grant {\n\targs := []interface{}{grantee}\n\tfor _, a := range actions {\n\t\targs = append(args, a)\n\t}\n\n\tvar returns awsiam.Grant\n\n\t_jsii_.Invoke(\n\t\tr,\n\t\t\"grant\",\n\t\targs,\n\t\t&returns,\n\t)\n\n\treturn returns\n}", "func (n *noopRules) Grant(rule *Rule) error {\n\treturn nil\n}", "func CreateCreateVpdGrantRuleRequest() (request *CreateVpdGrantRuleRequest) {\n\trequest = &CreateVpdGrantRuleRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"eflo\", \"2022-05-30\", \"CreateVpdGrantRule\", \"eflo\", \"openAPI\")\n\trequest.Method = requests.POST\n\treturn\n}", "func NewApprove(proposer uos.AccountName, proposalName uos.Name, level uos.PermissionLevel) *uos.Action {\n\treturn &uos.Action{\n\t\tAccount: uos.AccountName(\"wxbio.msig\"),\n\t\tName: uos.ActionName(\"approve\"),\n\t\tAuthorization: []uos.PermissionLevel{level},\n\t\tActionData: uos.NewActionData(Approve{proposer, proposalName, level}),\n\t}\n}", "func NewPermissionGrantPolicy()(*PermissionGrantPolicy) {\n m := &PermissionGrantPolicy{\n PolicyBase: *NewPolicyBase(),\n }\n odataTypeValue := \"#microsoft.graph.permissionGrantPolicy\"\n m.SetOdataType(&odataTypeValue)\n return m\n}", "func CreateGetBaseStrategyPeriodRequest() (request *GetBaseStrategyPeriodRequest) {\n\trequest = &GetBaseStrategyPeriodRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"OutboundBot\", \"2019-12-26\", \"GetBaseStrategyPeriod\", \"\", \"\")\n\trequest.Method = requests.POST\n\treturn\n}", "func (policy *ticketPolicy) OnCreateNewAccount(acc *types.Account) {\n}", "func NewClawbackGrantAction(\n\tfunderAddress string,\n\tsk StakingKeeper,\n\tgrantStartTime int64,\n\tgrantLockupPeriods, grantVestingPeriods []Period,\n\tgrantCoins sdk.Coins,\n) exported.AddGrantAction {\n\treturn clawbackGrantAction{\n\t\tfunderAddress: funderAddress,\n\t\tsk: sk,\n\t\tgrantStartTime: grantStartTime,\n\t\tgrantLockupPeriods: grantLockupPeriods,\n\t\tgrantVestingPeriods: grantVestingPeriods,\n\t\tgrantCoins: grantCoins,\n\t}\n}", "func grantType(creds config.Credentials) OAuthGrantType {\n\tif config.UseDeviceFlow() {\n\t\treturn OAuthGrantTypeDeviceFlow\n\t}\n\tif creds.UseManagedIdentity() {\n\t\treturn OAuthGrantTypeManagedIdentity\n\t}\n\treturn OAuthGrantTypeServicePrincipal\n}", "func newServiceAccount(cr *storagev1.CSIPowerMaxRevProxy) *v1.ServiceAccount {\n\treturn &v1.ServiceAccount{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: ReverseProxyName,\n\t\t\tNamespace: cr.Namespace,\n\t\t\tOwnerReferences: getOwnerReferences(cr),\n\t\t},\n\t}\n}", "func (m *GraphBaseServiceClient) PermissionGrants()(*i1a1369b1521a8ac4885166fd68eae4247248a891006fea464d2eea2a271b2cdb.PermissionGrantsRequestBuilder) {\n return i1a1369b1521a8ac4885166fd68eae4247248a891006fea464d2eea2a271b2cdb.NewPermissionGrantsRequestBuilderInternal(m.pathParameters, m.requestAdapter);\n}", "func (m *GraphBaseServiceClient) PermissionGrants()(*i1a1369b1521a8ac4885166fd68eae4247248a891006fea464d2eea2a271b2cdb.PermissionGrantsRequestBuilder) {\n return i1a1369b1521a8ac4885166fd68eae4247248a891006fea464d2eea2a271b2cdb.NewPermissionGrantsRequestBuilderInternal(m.pathParameters, m.requestAdapter);\n}", "func (r *refreshTokenGranter) Granted(ctx context.Context) error {\n\treturn r.deps.UseRefreshToken(ctx, r.token.ID)\n}", "func (_LvRecording *LvRecordingTransactor) RunGrant(opts *bind.TransactOpts, arg0 *big.Int, arg1 bool) (*types.Transaction, error) {\n\treturn _LvRecording.contract.Transact(opts, \"runGrant\", arg0, arg1)\n}", "func (msg MsgCreatePeriodicVestingAccount) Type() string { return TypeMsgCreatePeriodicVestingAccount }", "func NewEmptyGrant() GrantHandler {\n\treturn emptyGrant{}\n}", "func (k *Kerberos) Grant(encTGT, appID, encAuthenticator string) (*KerberosGrantResult, error) {\n\ttgt := &kerberosTGT{}\n\tif err := k.decrypt(encTGT, k.tgsSecretKey, tgt); err != nil {\n\t\treturn nil, errTGTInvalid\n\t}\n\tif tgt.Expired < time.Now().Unix() {\n\t\treturn nil, errTGTInvalid\n\t}\n\tauthenticator := &kerberosAuthenticator{}\n\tif err := k.decrypt(encAuthenticator, tgt.CTSK, authenticator); err != nil {\n\t\treturn nil, errAuthenticatorInvalid\n\t}\n\n\tvar appSecret string\n\tif appID == \"cell\" {\n\t\tappSecret = k.appSecretKey\n\t} else {\n\t\terr := k.db.QueryRowContext(\n\t\t\tdbCtx(),\n\t\t\t\"SELECT `secret` FROM `app` WHERE `app_id`=? LIMIT 1\",\n\t\t\tappID,\n\t\t).Scan(&appSecret)\n\t\tswitch {\n\t\tcase err == sql.ErrNoRows:\n\t\t\treturn nil, errAppNotExist\n\t\tcase err != nil:\n\t\t\tpanic(err)\n\t\t}\n\t}\n\n\tst := &kerberosServiceTicket{\n\t\tCSSK: RandToken(),\n\t\tUsername: authenticator.Username,\n\t\tExpired: time.Now().Add(2 * time.Hour).Unix(),\n\t}\n\n\tencCSSK := k.encrypt(st.CSSK, tgt.CTSK)\n\tencST := k.encrypt(st, appSecret)\n\n\tres := &KerberosGrantResult{\n\t\tencCSSK,\n\t\tencST,\n\t}\n\treturn res, nil\n}", "func NewPerClientGrant(prompt GrantHandler, defaultMethod oauthapi.GrantHandlerType) GrantHandler {\n\treturn &perClientGrant{\n\t\tauto: NewAutoGrant(),\n\t\tprompt: prompt,\n\t\tdeny: NewEmptyGrant(),\n\t\tdefaultMethod: defaultMethod,\n\t}\n}", "func (c *Client) Grant(ctx context.Context, i grantRequest) error {\n\tif i == nil {\n\t\treturn fmt.Errorf(\"missing request\")\n\t}\n\n\tswitch t := i.(type) {\n\tcase *SecretManagerGrantRequest:\n\t\treturn c.secretManagerGrant(ctx, t)\n\tcase *StorageGrantRequest:\n\t\treturn c.storageGrant(ctx, t)\n\tdefault:\n\t\treturn fmt.Errorf(\"unknown grant type %T\", t)\n\t}\n}", "func ResourceMonitorGrant(w string) GrantBuilder {\n\treturn &CurrentGrantBuilder{\n\t\tname: w,\n\t\tqualifiedName: fmt.Sprintf(`\"%v\"`, w),\n\t\tgrantType: resourceMonitorType,\n\t}\n}", "func (client *Client) CreateVpdGrantRuleWithCallback(request *CreateVpdGrantRuleRequest, callback func(response *CreateVpdGrantRuleResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *CreateVpdGrantRuleResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.CreateVpdGrantRule(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func (client *Client) CreateVpdGrantRuleWithChan(request *CreateVpdGrantRuleRequest) (<-chan *CreateVpdGrantRuleResponse, <-chan error) {\n\tresponseChan := make(chan *CreateVpdGrantRuleResponse, 1)\n\terrChan := make(chan error, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tdefer close(responseChan)\n\t\tdefer close(errChan)\n\t\tresponse, err := client.CreateVpdGrantRule(request)\n\t\tif err != nil {\n\t\t\terrChan <- err\n\t\t} else {\n\t\t\tresponseChan <- response\n\t\t}\n\t})\n\tif err != nil {\n\t\terrChan <- err\n\t\tclose(responseChan)\n\t\tclose(errChan)\n\t}\n\treturn responseChan, errChan\n}", "func newServiceAccount(cr *argoprojv1a1.ArgoCD) *corev1.ServiceAccount {\n\treturn &corev1.ServiceAccount{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: cr.Name,\n\t\t\tNamespace: cr.Namespace,\n\t\t\tLabels: argoutil.LabelsForCluster(cr),\n\t\t},\n\t}\n}", "func NewTriggerAction(agentName string, propertyName string, propertyValue string) *TriggerAction {\n instance := new(TriggerAction)\n instance.agentName = agentName\n instance.propertyName = propertyName\n instance.propertyValue = propertyValue\n return instance\n}", "func NewRefreshGrantType(logger Log, service RefreshGrantTypeService) GrantType {\n\treturn &refreshGT{logger, service}\n}", "func NewAuthorizationGrant(authorization Authorization, expiration time.Time) AuthorizationGrant {\n\treturn AuthorizationGrant{Authorization: authorization, Expiration: expiration}\n}", "func CreateDeleteVpdGrantRuleRequest() (request *DeleteVpdGrantRuleRequest) {\n\trequest = &DeleteVpdGrantRuleRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"eflo\", \"2022-05-30\", \"DeleteVpdGrantRule\", \"eflo\", \"openAPI\")\n\trequest.Method = requests.POST\n\treturn\n}", "func Grant(uid int, ip, mac string) {\n\tif res, e := exec.Command(*iptables,\n\t\t\"-t mangle -I internet 1 -m mac --mac-source\", mac, \"-s\", ip,\n\t\t\"-j RETURN\").Output(); e != nil {\n\n\t\tlog.Printf(\"[EE] %s: %s\", e.Error(), string(res))\n\t\treturn\n\t}\n\n\tvar ttl time.Duration // TODO: calculate and set\n\ttimers[uid] = time.AfterFunc(ttl, func() {\n\t\tblock(uid, ip, mac)\n\t})\n}", "func NewAdaptivePeriodic(startDate time.Time, waitTime time.Duration,\n\trelVal float64, refSymbol string, priceP priceProvider) Strategy {\n\n\treturn &AdaptivePeriodic{\n\t\twaitTime: waitTime,\n\t\tlastInvested: startDate.Add(-waitTime),\n\t\tWithDrawdown: WithDrawdown{\n\t\t\trelVal: relVal,\n\t\t\trefSymbol: refSymbol,\n\t\t\tpriceP: priceP,\n\t\t},\n\t}\n}", "func newRateLimiter(delay time.Duration) *rateLimiter {\n\treturn &rateLimiter{\n\t\tdelay: delay,\n\t\tops: make(map[string]time.Time),\n\t}\n}", "func NewRedirectGrant(url string) GrantHandler {\n\treturn &redirectGrant{url}\n}", "func (h *Handler) NewAction(act action.Action, settings map[string]interface{}) *Action {\n\n\tvalue := reflect.ValueOf(act)\n\tvalue = value.Elem()\n\tref := value.Type().PkgPath()\n\n\tnewAct := &Action{ref: ref, settings: settings}\n\th.actions = append(h.actions, newAct)\n\n\treturn newAct\n}", "func NewGovernancePolicy()(*GovernancePolicy) {\n m := &GovernancePolicy{\n }\n m.backingStore = ie8677ce2c7e1b4c22e9c3827ecd078d41185424dd9eeb92b7d971ed2d49a392e.BackingStoreFactoryInstance();\n m.SetAdditionalData(make(map[string]any))\n return m\n}", "func (m *GraphBaseServiceClient) IdentityGovernance()(*i32d45c1243c349600fbe53b2f9641bb59857a3326037587cbe4e347b46ad207e.IdentityGovernanceRequestBuilder) {\n return i32d45c1243c349600fbe53b2f9641bb59857a3326037587cbe4e347b46ad207e.NewIdentityGovernanceRequestBuilderInternal(m.pathParameters, m.requestAdapter);\n}", "func (m *GraphBaseServiceClient) IdentityGovernance()(*i32d45c1243c349600fbe53b2f9641bb59857a3326037587cbe4e347b46ad207e.IdentityGovernanceRequestBuilder) {\n return i32d45c1243c349600fbe53b2f9641bb59857a3326037587cbe4e347b46ad207e.NewIdentityGovernanceRequestBuilderInternal(m.pathParameters, m.requestAdapter);\n}", "func newReconciledServiceAccount() *corev1.ServiceAccount {\n\treturn NewServiceAccount(newEventSource())()\n}", "func (_Content *ContentTransactor) RunGrant(opts *bind.TransactOpts, arg0 *big.Int, arg1 bool) (*types.Transaction, error) {\n\treturn _Content.contract.Transact(opts, \"runGrant\", arg0, arg1)\n}", "func NewAction(h *Hashlock, tx *types.Transaction, execaddr string) *Action {\n\thash := tx.Hash()\n\tfromaddr := tx.From()\n\treturn &Action{h.GetCoinsAccount(), h.GetStateDB(), hash, fromaddr, h.GetBlockTime(), h.GetHeight(), execaddr, h.GetAPI()}\n}", "func (s *Service) CreatePeriod(ctx context.Context, req *request.CreatePeriod) (*response.Message, error) {\n\tif err := s.db.AddNewPeriod(\n\t\treq.ClubID,\n\t\t&models.Period{Period: req.Period},\n\t); err != nil {\n\t\treturn nil, status.Errorf(codes.Internal, \"failed to create period: %s\", err.Error())\n\t}\n\treturn &response.Message{\n\t\tMessage: \"period successfully created\",\n\t}, nil\n}", "func (_TrialRulesAbstract *TrialRulesAbstractTransactor) StartGracePeriod(opts *bind.TransactOpts, caseId [32]byte, status uint8) (*types.Transaction, error) {\n\treturn _TrialRulesAbstract.contract.Transact(opts, \"startGracePeriod\", caseId, status)\n}", "func NewSendAction(serviceType, actionName string, args any) *Action {\n\treturn &Action{\n\t\tXMLName: xml.Name{Space: serviceType, Local: actionName},\n\t\tArgs: args,\n\t}\n}", "func NewSecretAction(logger logrus.FieldLogger, client client.Client) *SecretAction {\n\treturn &SecretAction{\n\t\tlogger: logger,\n\t\tclient: client,\n\t}\n}", "func (t *Template) AddSchedAction() *SchedAction {\n\taction := &SchedAction{\n\t\tdyn.Vector{XMLName: xml.Name{Local: keys.SchedActionVec}},\n\t}\n\tt.Template.Elements = append(t.Template.Elements, action)\n\n\treturn action\n}", "func NewExportPolicyCreateRequest() *ExportPolicyCreateRequest { return &ExportPolicyCreateRequest{} }", "func (c *cloudChannelGRPCClient) CreateEntitlementOperation(name string) *CreateEntitlementOperation {\n\treturn &CreateEntitlementOperation{\n\t\tlro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}),\n\t}\n}", "func DefaultCreatePeriod(ctx context.Context, in *Period, db *gorm.DB) (*Period, error) {\n\tif in == nil {\n\t\treturn nil, errors.NilArgumentError\n\t}\n\tormObj, err := in.ToORM(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif hook, ok := interface{}(&ormObj).(PeriodORMWithBeforeCreate_); ok {\n\t\tif db, err = hook.BeforeCreate_(ctx, db); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tif err = db.Create(&ormObj).Error; err != nil {\n\t\treturn nil, err\n\t}\n\tif hook, ok := interface{}(&ormObj).(PeriodORMWithAfterCreate_); ok {\n\t\tif err = hook.AfterCreate_(ctx, db); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tpbResponse, err := ormObj.ToPB(ctx)\n\treturn &pbResponse, err\n}", "func (c *Client) Grant(email string) {\n\tif c.CI {\n\t\temail = strings.ToLower(email)\n\t}\n\tc.mu.Lock()\n\tc.whitelist[email] = struct{}{}\n\tc.mu.Unlock()\n}", "func SchemaGrant(db, schema string) GrantBuilder {\n\treturn &CurrentGrantBuilder{\n\t\tname: schema,\n\t\tqualifiedName: fmt.Sprintf(`\"%v\".\"%v\"`, db, schema),\n\t\tgrantType: schemaType,\n\t}\n}", "func (_LvRecordableStream *LvRecordableStreamTransactor) RunGrant(opts *bind.TransactOpts, arg0 *big.Int, arg1 bool) (*types.Transaction, error) {\n\treturn _LvRecordableStream.contract.Transact(opts, \"runGrant\", arg0, arg1)\n}", "func (_TokenStakingEscrow *TokenStakingEscrowCaller) TokenGrant(opts *bind.CallOpts) (common.Address, error) {\n\tvar (\n\t\tret0 = new(common.Address)\n\t)\n\tout := ret0\n\terr := _TokenStakingEscrow.contract.Call(opts, out, \"tokenGrant\")\n\treturn *ret0, err\n}", "func newJWTBase(ctx context.Context, cfg Config) (string, error) {\n\tserviceAccount, project, tokenSource, err := getServiceAccountInfo(ctx, cfg)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"unable to get service account from environment\")\n\t}\n\n\tpayload, err := json.Marshal(map[string]interface{}{\n\t\t\"aud\": \"vault/\" + cfg.Role,\n\t\t\"sub\": serviceAccount,\n\t\t\"exp\": time.Now().UTC().Add(5 * time.Minute).Unix(),\n\t})\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"unable to encode JWT payload\")\n\t}\n\n\thc := getHTTPClient(ctx, cfg)\n\t// reuse base transport and timeout but sprinkle on the token source for IAM access\n\thcIAM := &http.Client{\n\t\tTimeout: hc.Timeout,\n\t\tTransport: &oauth2.Transport{\n\t\t\tSource: tokenSource,\n\t\t\tBase: hc.Transport,\n\t\t},\n\t}\n\tiamClient, err := iam.New(hcIAM)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"unable to init IAM client\")\n\t}\n\n\tif cfg.IAMAddress != \"\" {\n\t\tiamClient.BasePath = cfg.IAMAddress\n\t}\n\n\tresp, err := iamClient.Projects.ServiceAccounts.SignJwt(\n\t\tfmt.Sprintf(\"projects/%s/serviceAccounts/%s\",\n\t\t\tproject, serviceAccount),\n\t\t&iam.SignJwtRequest{Payload: string(payload)}).Context(ctx).Do()\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"unable to sign JWT\")\n\t}\n\treturn resp.SignedJwt, nil\n}", "func (m *GraphBaseServiceClient) Oauth2PermissionGrants()(*i86cada4d4a5f2f8a9d1e7a85eacd70a661ea7b20d2737008c0719e95b5be3e16.Oauth2PermissionGrantsRequestBuilder) {\n return i86cada4d4a5f2f8a9d1e7a85eacd70a661ea7b20d2737008c0719e95b5be3e16.NewOauth2PermissionGrantsRequestBuilderInternal(m.pathParameters, m.requestAdapter);\n}", "func (m *GraphBaseServiceClient) Oauth2PermissionGrants()(*i86cada4d4a5f2f8a9d1e7a85eacd70a661ea7b20d2737008c0719e95b5be3e16.Oauth2PermissionGrantsRequestBuilder) {\n return i86cada4d4a5f2f8a9d1e7a85eacd70a661ea7b20d2737008c0719e95b5be3e16.NewOauth2PermissionGrantsRequestBuilderInternal(m.pathParameters, m.requestAdapter);\n}", "func NewMsgCreatePeriodicVestingAccount(fromAddr, toAddr sdk.AccAddress, startTime int64, periods []Period) *MsgCreatePeriodicVestingAccount {\n\treturn &MsgCreatePeriodicVestingAccount{\n\t\tFromAddress: fromAddr.String(),\n\t\tToAddress: toAddr.String(),\n\t\tStartTime: startTime,\n\t\tVestingPeriods: periods,\n\t}\n}", "func CreateGrantInstanceToVbrRequest() (request *GrantInstanceToVbrRequest) {\n\trequest = &GrantInstanceToVbrRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"Vpc\", \"2016-04-28\", \"GrantInstanceToVbr\", \"vpc\", \"openAPI\")\n\trequest.Method = requests.POST\n\treturn\n}", "func GrantByName(name string) Grant {\n\tfor g, grantName := range grantNameMap {\n\t\tif grantName == name {\n\t\t\treturn g\n\t\t}\n\t}\n\n\treturn GrantNone\n}", "func addPerm(w http.ResponseWriter, r *http.Request) {\r\n\tkey := r.URL.Query().Get(\"key\")\r\n\tp, err := checkKey(key, perm)\r\n\tif err != nil {\r\n\t\thttpError{statusCode: http.StatusForbidden, err: err}.ServeHTTP(w, r)\r\n\t\treturn\r\n\t}\r\n\tif !p.IsWritable {\r\n\t\thttpError{statusCode: http.StatusNotImplemented, err: errors.New(\"Method not implemented\")}.ServeHTTP(w, r)\r\n\t\treturn\r\n\t}\r\n\terr = r.ParseForm()\r\n\tif err != nil {\r\n\t\thttpError{statusCode: http.StatusBadRequest, err: errors.New(\"Bad request\")}.ServeHTTP(w, r)\r\n\t\treturn\r\n\t}\r\n\tnewToken := r.FormValue(\"token\")\r\n\tname := r.FormValue(\"name\")\r\n\tif urls, ok := r.Form[\"url\"]; ok && len(newToken) > 5 && len(name) > 0 {\r\n\t\tvar allPerm []dto.Permission\r\n\t\tfor _, v := range urls {\r\n\t\t\tpair := strings.Split(v, \":\")\r\n\t\t\tif len(pair) == 1 {\r\n\t\t\t\tallPerm = append(allPerm, dto.Permission{URL: pair[0], IsWritable: false})\r\n\t\t\t} else if len(pair) == 2 {\r\n\t\t\t\tflag, _ := strconv.ParseBool(pair[1])\r\n\t\t\t\tallPerm = append(allPerm, dto.Permission{URL: pair[0], IsWritable: flag})\r\n\t\t\t}\r\n\t\t}\r\n\t\tcl := dto.ClientPermission{\r\n\t\t\tName: name,\r\n\t\t\tKey: newToken,\r\n\t\t\tPerm: allPerm,\r\n\t\t}\r\n\t\tlog.Infof(\"Create new tocken %s with permision %v\", cl.Key, cl.Perm)\r\n\t\tstorage, ok := c2cData.GetBoltDbInstance().(c2cData.IPerm)\r\n\t\tif !ok {\r\n\t\t\thttpError{statusCode: http.StatusInternalServerError, err: errors.New(\"Database not supported permissions\")}.ServeHTTP(w, r)\r\n\t\t}\r\n\t\tif err = storage.UpdatePermission(cl); err != nil {\r\n\t\t\thttpError{statusCode: http.StatusInternalServerError, err: errors.New(\"Can not save permission\")}.ServeHTTP(w, r)\r\n\t\t}\r\n\t\tw.Header().Add(\"Content-Type\", \"application/json\")\r\n\t\tw.WriteHeader(http.StatusCreated)\r\n\t\tb, _ := json.Marshal(cl)\r\n\t\tw.Write(b)\r\n\t\treturn\r\n\t}\r\n\thttpError{statusCode: http.StatusBadRequest, err: errors.New(\"Incorrect body in post request\")}.ServeHTTP(w, r)\r\n}", "func (client *Client) CreateVpdGrantRule(request *CreateVpdGrantRuleRequest) (response *CreateVpdGrantRuleResponse, err error) {\n\tresponse = CreateCreateVpdGrantRuleResponse()\n\terr = client.DoAction(request, response)\n\treturn\n}", "func CreateModifyPlanRequest() (request *ModifyPlanRequest) {\n\trequest = &ModifyPlanRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"Yundun-bastionhost\", \"2018-10-10\", \"ModifyPlan\", \"bastionhost\", \"openAPI\")\n\treturn\n}", "func (m *GraphBaseServiceClient) PermissionGrantsById(id string)(*i23bab38fb8688d4bab0b6ffc533eb085d40e58af49a27ab228a8d1ad3e0ab203.ResourceSpecificPermissionGrantItemRequestBuilder) {\n urlTplParams := make(map[string]string)\n for idx, item := range m.pathParameters {\n urlTplParams[idx] = item\n }\n if id != \"\" {\n urlTplParams[\"resourceSpecificPermissionGrant%2Did\"] = id\n }\n return i23bab38fb8688d4bab0b6ffc533eb085d40e58af49a27ab228a8d1ad3e0ab203.NewResourceSpecificPermissionGrantItemRequestBuilderInternal(urlTplParams, m.requestAdapter);\n}", "func (m *GraphBaseServiceClient) PermissionGrantsById(id string)(*i23bab38fb8688d4bab0b6ffc533eb085d40e58af49a27ab228a8d1ad3e0ab203.ResourceSpecificPermissionGrantItemRequestBuilder) {\n urlTplParams := make(map[string]string)\n for idx, item := range m.pathParameters {\n urlTplParams[idx] = item\n }\n if id != \"\" {\n urlTplParams[\"resourceSpecificPermissionGrant%2Did\"] = id\n }\n return i23bab38fb8688d4bab0b6ffc533eb085d40e58af49a27ab228a8d1ad3e0ab203.NewResourceSpecificPermissionGrantItemRequestBuilderInternal(urlTplParams, m.requestAdapter);\n}", "func ViewGrant(db, schema, view string) GrantBuilder {\n\treturn &CurrentGrantBuilder{\n\t\tname: view,\n\t\tqualifiedName: fmt.Sprintf(`\"%v\".\"%v\".\"%v\"`, db, schema, view),\n\t\tgrantType: viewType,\n\t}\n}", "func New(policy *Policy) *RateLimiter {\n\trl := &RateLimiter{\n\t\tpolicy: policy,\n\t\tstartTime: nowFunc(),\n\t}\n\treturn rl\n}", "func OpenAccountManagerSettingsAction(tconn *chrome.TestConn, cr *chrome.Chrome) action.Action {\n\treturn func(ctx context.Context) error {\n\t\tui := uiauto.New(tconn).WithTimeout(DefaultUITimeout)\n\t\t// Open Account Manager page in OS Settings and find Add Google Account button.\n\t\tif _, err := ossettings.LaunchAtPageURL(ctx, tconn, cr, \"accountManager\", ui.Exists(nodewith.Name(\"Add Google Account\").Role(role.Button))); err != nil {\n\t\t\treturn errors.Wrap(err, \"failed to launch Account Manager page\")\n\t\t}\n\t\treturn nil\n\t}\n}", "func NewAppConsentApprovalRoute()(*AppConsentApprovalRoute) {\n m := &AppConsentApprovalRoute{\n Entity: *NewEntity(),\n }\n return m\n}", "func (_CommitteeManager *CommitteeManagerTransactor) CreateModifyDeployAuthProposal(opts *bind.TransactOpts, account common.Address, openFlag bool, blockNumberInterval *big.Int) (*types.Transaction, *types.Receipt, error) {\n\treturn _CommitteeManager.contract.Transact(opts, \"createModifyDeployAuthProposal\", account, openFlag, blockNumberInterval)\n}", "func (c *cloudChannelRESTClient) CreateEntitlementOperation(name string) *CreateEntitlementOperation {\n\toverride := fmt.Sprintf(\"/v1/%s\", name)\n\treturn &CreateEntitlementOperation{\n\t\tlro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}),\n\t\tpollPath: override,\n\t}\n}", "func (r *ApprovalWorkflowProviderPolicyTemplatesCollectionRequest) Add(ctx context.Context, reqObj *GovernancePolicyTemplate) (resObj *GovernancePolicyTemplate, err error) {\n\terr = r.JSONRequest(ctx, \"POST\", \"\", reqObj, &resObj)\n\treturn\n}", "func (c *Client) NewApprove(vaultAddress, erc20Address common.Address, amount *big.Int) *ApproveTransaction {\n\treturn &ApproveTransaction{\n\t\tContractBackend: c.ContractBackend,\n\t\tErc20Address: erc20Address,\n\t\tErc20Binder: abi.NewErc20,\n\t\tPlasmaVault: vaultAddress,\n\t\tAmount: amount,\n\t}\n}", "func NewGrantCheck(check GrantChecker, handler GrantHandler, errorHandler GrantErrorHandler) osinserver.AuthorizeHandler {\n\treturn &GrantCheck{check, handler, errorHandler}\n}", "func newAssigner(period time.Duration, newBucket bucketFactory, clock clock) *assigner {\n\ta := &assigner{\n\t\tperiod: period,\n\t\tclock: clock,\n\t\tnewBucket: newBucket,\n\t}\n\ttc := a.nextT(clock.Now())\n\ttp := a.prevT(tc)\n\ttn := a.nextT(tc)\n\ta.buckets[prev] = newBucket(tp)\n\ta.buckets[curr] = newBucket(tc)\n\ta.buckets[next] = newBucket(tn)\n\ta.tmin = tp.Add(-a.period)\n\treturn a\n}", "func WarehouseGrant(w string) GrantBuilder {\n\treturn &CurrentGrantBuilder{\n\t\tname: w,\n\t\tqualifiedName: fmt.Sprintf(`\"%v\"`, w),\n\t\tgrantType: warehouseType,\n\t}\n}", "func (*ProjectGrantUserGrantCreate) Descriptor() ([]byte, []int) {\n\treturn file_management_proto_rawDescGZIP(), []int{133}\n}", "func (_LvStreamRightsHolder *LvStreamRightsHolderTransactor) RunGrant(opts *bind.TransactOpts, arg0 *big.Int, arg1 bool) (*types.Transaction, error) {\n\treturn _LvStreamRightsHolder.contract.Transact(opts, \"runGrant\", arg0, arg1)\n}", "func NewPeriodical(g Game, s Subject, o Object, name string, routine func(), t InstanceTime) *Periodical {\n\te := &Periodical{\n\t\tUnitPair: MakePair(s, o),\n\t\tname: name,\n\t\troutine: routine,\n\t\texpirationTime: t,\n\t}\n\te.handler = MakeEventHandler(func(p interface{}) { e.handle(g, p) })\n\treturn e\n}", "func (_CommitteeManager *CommitteeManagerSession) CreateModifyDeployAuthProposal(account common.Address, openFlag bool, blockNumberInterval *big.Int) (*types.Transaction, *types.Receipt, error) {\n\treturn _CommitteeManager.Contract.CreateModifyDeployAuthProposal(&_CommitteeManager.TransactOpts, account, openFlag, blockNumberInterval)\n}", "func (c *managementServiceClient) CreateProjectUserGrant(ctx context.Context, in *UserGrantCreate, opts ...grpc.CallOption) (*UserGrant, error) {\n\tout := new(UserGrant)\n\terr := c.cc.Invoke(ctx, \"/caos.zitadel.management.api.v1.ManagementService/CreateProjectUserGrant\", in, out, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn out, nil\n}", "func StageGrant(db, schema, stage string) GrantBuilder {\n\treturn &CurrentGrantBuilder{\n\t\tname: stage,\n\t\tqualifiedName: fmt.Sprintf(`\"%v\".\"%v\".\"%v\"`, db, schema, stage),\n\t\tgrantType: stageType,\n\t}\n}", "func DatabaseGrant() *TerraformGrantResource {\n\treturn &TerraformGrantResource{\n\t\tResource: &schema.Resource{\n\t\t\tCreate: CreateDatabaseGrant,\n\t\t\tRead: ReadDatabaseGrant,\n\t\t\tDelete: DeleteDatabaseGrant,\n\t\t\tUpdate: UpdateDatabaseGrant,\n\n\t\t\tSchema: databaseGrantSchema,\n\t\t\tImporter: &schema.ResourceImporter{\n\t\t\t\tStateContext: schema.ImportStatePassthroughContext,\n\t\t\t},\n\t\t},\n\t\tValidPrivs: validDatabasePrivileges,\n\t}\n}", "func AddAction(c *gin.Context) {\n\tvar action = models.Action{}.MapRequestToAction(c)\n\n\tvar user models.User\n\tresult := models.DB.First(&user, action.CreatedBy)\n\n\tif result.RowsAffected == 0 {\n\t\tc.JSON(http.StatusBadRequest, gin.H{\"data\": \"created_by is not a valid user id\"})\n\t\treturn\n\t}\n\n\tresult = models.DB.Create(&action)\n\n\tif result.Error != nil {\n\t\tc.JSON(http.StatusBadRequest, helpers.BadRequest())\n\t\treturn\n\t}\n\n\tc.JSON(http.StatusOK, gin.H{\"data\": helpers.Results{\n\t\tCount: 1,\n\t\tResults: action,\n\t}})\n}", "func newServiceAccountWithName(name string, cr *argoprojv1a1.ArgoCD) *corev1.ServiceAccount {\n\tsa := newServiceAccount(cr)\n\tsa.ObjectMeta.Name = getServiceAccountName(cr.Name, name)\n\n\tlbls := sa.ObjectMeta.Labels\n\tlbls[common.ArgoCDKeyName] = name\n\tsa.ObjectMeta.Labels = lbls\n\n\treturn sa\n}", "func (c *managementServiceClient) CreateProjectGrantUserGrant(ctx context.Context, in *ProjectGrantUserGrantCreate, opts ...grpc.CallOption) (*UserGrant, error) {\n\tout := new(UserGrant)\n\terr := c.cc.Invoke(ctx, \"/caos.zitadel.management.api.v1.ManagementService/CreateProjectGrantUserGrant\", in, out, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn out, nil\n}", "func (h *Periods) Create(ctx context.Context, w http.ResponseWriter, r *http.Request, params map[string]string) error {\n\n\tctxValues, err := webcontext.ContextValues(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tclaims, err := auth.ClaimsFromContext(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t//\n\treq := new(period.CreateRequest)\n\tdata := make(map[string]interface{})\n\tf := func() (bool, error) {\n\t\tif r.Method == http.MethodPost {\n\t\t\terr := r.ParseForm()\n\t\t\tif err != nil {\n\t\t\t\treturn false, err\n\t\t\t}\n\n\t\t\tdecoder := schema.NewDecoder()\n\t\t\tdecoder.IgnoreUnknownKeys(true)\n\n\t\t\tif err := decoder.Decode(req, r.PostForm); err != nil {\n\t\t\t\treturn false, err\n\t\t\t}\n\n\t\t\tsub, err := h.Repo.Create(ctx, claims, *req, ctxValues.Now)\n\t\t\tif err != nil {\n\t\t\t\tswitch errors.Cause(err) {\n\t\t\t\tdefault:\n\t\t\t\t\tif verr, ok := weberror.NewValidationError(ctx, err); ok {\n\t\t\t\t\t\tdata[\"validationErrors\"] = verr.(*weberror.Error)\n\t\t\t\t\t\treturn false, nil\n\t\t\t\t\t} else {\n\t\t\t\t\t\treturn false, err\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Display a success message to the checklist.\n\t\t\twebcontext.SessionFlashSuccess(ctx,\n\t\t\t\t\"Period Created\",\n\t\t\t\t\"Period successfully created.\")\n\n\t\t\treturn true, web.Redirect(ctx, w, r, urlPeriodsView(sub.ID), http.StatusFound)\n\t\t}\n\n\t\treturn false, nil\n\t}\n\n\tend, err := f()\n\tif err != nil {\n\t\treturn web.RenderError(ctx, w, r, err, h.Renderer, TmplLayoutBase, TmplContentErrorGeneric, web.MIMETextHTMLCharsetUTF8)\n\t} else if end {\n\t\treturn nil\n\t}\n\n\tdata[\"form\"] = req\n\tdata[\"urlPeriodsIndex\"] = urlPeriodsIndex() \n\n\tif verr, ok := weberror.NewValidationError(ctx, webcontext.Validator().Struct(period.CreateRequest{})); ok {\n\t\tdata[\"validationDefaults\"] = verr.(*weberror.Error)\n\t}\n\n\treturn h.Renderer.Render(ctx, w, r, TmplLayoutBase, \"admin-periods-create.gohtml\", web.MIMETextHTMLCharsetUTF8, http.StatusOK, data)\n}", "func (client *ActionsClient) getCreateRequest(ctx context.Context, resourceGroupName string, workspaceName string, ruleID string, actionID string, options *ActionsClientGetOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.OperationalInsights/workspaces/{workspaceName}/providers/Microsoft.SecurityInsights/alertRules/{ruleId}/actions/{actionId}\"\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif workspaceName == \"\" {\n\t\treturn nil, errors.New(\"parameter workspaceName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{workspaceName}\", url.PathEscape(workspaceName))\n\tif ruleID == \"\" {\n\t\treturn nil, errors.New(\"parameter ruleID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{ruleId}\", url.PathEscape(ruleID))\n\tif actionID == \"\" {\n\t\treturn nil, errors.New(\"parameter actionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{actionId}\", url.PathEscape(actionID))\n\treq, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2021-10-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\treturn req, nil\n}", "func newAtomicBased(rate int, opts ...Option) *atomicLimiter {\r\n\tconfig := buildConfig(opts)\r\n\tl := &atomicLimiter{\r\n\t\tperRequest: config.per / time.Duration(rate),\r\n\t\tmaxSlack: -1 * config.maxSlack * time.Second / time.Duration(rate),\r\n\t\tclock: config.clock,\r\n\t}\r\n\r\n\tinitialState := state{\r\n\t\tlast: time.Time{},\r\n\t\tsleepFor: 0,\r\n\t}\r\n\tatomic.StorePointer(&l.state, unsafe.Pointer(&initialState))\r\n\treturn l\r\n}", "func (_CommitteeManager *CommitteeManagerTransactorSession) CreateModifyDeployAuthProposal(account common.Address, openFlag bool, blockNumberInterval *big.Int) (*types.Transaction, *types.Receipt, error) {\n\treturn _CommitteeManager.Contract.CreateModifyDeployAuthProposal(&_CommitteeManager.TransactOpts, account, openFlag, blockNumberInterval)\n}", "func (s *BasePlSqlParserListener) EnterGrant_statement(ctx *Grant_statementContext) {}" ]
[ "0.6319315", "0.60508823", "0.5450652", "0.532292", "0.52668667", "0.5202514", "0.51351124", "0.5118444", "0.50628436", "0.5058438", "0.50192815", "0.4910114", "0.4907542", "0.4897786", "0.4887551", "0.47395888", "0.47365135", "0.47333363", "0.46217752", "0.46140435", "0.46029472", "0.45669082", "0.4540413", "0.4481745", "0.4481745", "0.44653693", "0.44562924", "0.4454453", "0.4452725", "0.44507307", "0.44278055", "0.44184923", "0.44140613", "0.4411618", "0.43931592", "0.43761194", "0.4375842", "0.4363527", "0.42936838", "0.4289456", "0.42524323", "0.423574", "0.42161667", "0.42161104", "0.4212531", "0.41953352", "0.41904157", "0.41904157", "0.41854382", "0.41801053", "0.41460234", "0.4145279", "0.41325638", "0.41290712", "0.4107762", "0.40839", "0.40793008", "0.40759084", "0.40700528", "0.4067438", "0.4064534", "0.40520456", "0.40480125", "0.4045345", "0.40449858", "0.40449858", "0.40449002", "0.4040997", "0.40404144", "0.40361848", "0.40310502", "0.40190613", "0.40153742", "0.40153742", "0.40125892", "0.4012569", "0.4006179", "0.40047604", "0.39983743", "0.3980343", "0.3978584", "0.39760765", "0.39463913", "0.3945956", "0.3942516", "0.39373812", "0.39322913", "0.3924107", "0.39213043", "0.39208677", "0.39207965", "0.39165235", "0.39106297", "0.39087036", "0.39065173", "0.39050707", "0.39022228", "0.38941923", "0.38937744", "0.38928643" ]
0.821403
0
AddToAccount implements the exported.AddGrantAction interface. It checks that rawAccount is a PeriodicVestingAccount, then adds the described grant to it.
func (pga periodicGrantAction) AddToAccount(ctx sdk.Context, rawAccount exported.VestingAccount) error { pva, ok := rawAccount.(*PeriodicVestingAccount) if !ok { return sdkerrors.Wrapf(sdkerrors.ErrNotSupported, "account %s must be a PeriodicVestingAccount, got %T", rawAccount.GetAddress(), rawAccount) } pva.addGrant(ctx, pga.sk, pga.grantStartTime, pga.grantVestingPeriods, pga.grantCoins) return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (cga clawbackGrantAction) AddToAccount(ctx sdk.Context, rawAccount exported.VestingAccount) error {\n\tcva, ok := rawAccount.(*ClawbackVestingAccount)\n\tif !ok {\n\t\treturn sdkerrors.Wrapf(sdkerrors.ErrNotSupported,\n\t\t\t\"account %s must be a ClawbackVestingAccount, got %T\",\n\t\t\trawAccount.GetAddress(), rawAccount)\n\t}\n\tif cga.funderAddress != cva.FunderAddress {\n\t\treturn sdkerrors.Wrapf(sdkerrors.ErrInvalidRequest, \"account %s can only accept grants from account %s\",\n\t\t\trawAccount.GetAddress(), cva.FunderAddress)\n\t}\n\tcva.addGrant(ctx, cga.sk, cga.grantStartTime, cga.grantLockupPeriods, cga.grantVestingPeriods, cga.grantCoins)\n\treturn nil\n}", "func (pva *PeriodicVestingAccount) AddGrant(ctx sdk.Context, action exported.AddGrantAction) error {\n\treturn action.AddToAccount(ctx, pva)\n}", "func (_Storage *StorageTransactor) AddAccount(opts *bind.TransactOpts, addr common.Address, kind uint8, isFrozen bool, parent common.Address) (*types.Transaction, error) {\n\treturn _Storage.contract.Transact(opts, \"addAccount\", addr, kind, isFrozen, parent)\n}", "func (_Storage *StorageTransactorSession) AddAccount(addr common.Address, kind uint8, isFrozen bool, parent common.Address) (*types.Transaction, error) {\n\treturn _Storage.Contract.AddAccount(&_Storage.TransactOpts, addr, kind, isFrozen, parent)\n}", "func (_Storage *StorageSession) AddAccount(addr common.Address, kind uint8, isFrozen bool, parent common.Address) (*types.Transaction, error) {\n\treturn _Storage.Contract.AddAccount(&_Storage.TransactOpts, addr, kind, isFrozen, parent)\n}", "func (pva *PeriodicVestingAccount) addGrant(ctx sdk.Context, sk StakingKeeper, grantStartTime int64, grantVestingPeriods []Period, grantCoins sdk.Coins) {\n\t// how much is really delegated?\n\tbondedAmt := sk.GetDelegatorBonded(ctx, pva.GetAddress())\n\tunbondingAmt := sk.GetDelegatorUnbonding(ctx, pva.GetAddress())\n\tdelegatedAmt := bondedAmt.Add(unbondingAmt)\n\tdelegated := sdk.NewCoins(sdk.NewCoin(sk.BondDenom(ctx), delegatedAmt))\n\n\t// discover what has been slashed\n\toldDelegated := pva.DelegatedVesting.Add(pva.DelegatedFree...)\n\tslashed := oldDelegated.Sub(coinsMin(oldDelegated, delegated))\n\n\t// rebase the DV+DF by capping slashed at the current unvested amount\n\tunvested := pva.GetVestingCoins(ctx.BlockTime())\n\tnewSlashed := coinsMin(unvested, slashed)\n\tnewTotalDelegated := delegated.Add(newSlashed...)\n\n\t// modify vesting schedule for the new grant\n\tnewStart, newEnd, newPeriods := DisjunctPeriods(pva.StartTime, grantStartTime,\n\t\tpva.GetVestingPeriods(), grantVestingPeriods)\n\tpva.StartTime = newStart\n\tpva.EndTime = newEnd\n\tpva.VestingPeriods = newPeriods\n\tpva.OriginalVesting = pva.OriginalVesting.Add(grantCoins...)\n\n\t// cap DV at the current unvested amount, DF rounds out to newTotalDelegated\n\tunvested2 := pva.GetVestingCoins(ctx.BlockTime())\n\tpva.DelegatedVesting = coinsMin(newTotalDelegated, unvested2)\n\tpva.DelegatedFree = newTotalDelegated.Sub(pva.DelegatedVesting)\n}", "func (client *Client) GrantAccountPrivilegeWithOptions(request *GrantAccountPrivilegeRequest, runtime *util.RuntimeOptions) (_result *GrantAccountPrivilegeResponse, _err error) {\n\t_err = util.ValidateModel(request)\n\tif _err != nil {\n\t\treturn _result, _err\n\t}\n\tquery := map[string]interface{}{}\n\tif !tea.BoolValue(util.IsUnset(request.AccountName)) {\n\t\tquery[\"AccountName\"] = request.AccountName\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.AccountPrivilege)) {\n\t\tquery[\"AccountPrivilege\"] = request.AccountPrivilege\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.InstanceId)) {\n\t\tquery[\"InstanceId\"] = request.InstanceId\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.OwnerAccount)) {\n\t\tquery[\"OwnerAccount\"] = request.OwnerAccount\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.OwnerId)) {\n\t\tquery[\"OwnerId\"] = request.OwnerId\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.ResourceOwnerAccount)) {\n\t\tquery[\"ResourceOwnerAccount\"] = request.ResourceOwnerAccount\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.ResourceOwnerId)) {\n\t\tquery[\"ResourceOwnerId\"] = request.ResourceOwnerId\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.SecurityToken)) {\n\t\tquery[\"SecurityToken\"] = request.SecurityToken\n\t}\n\n\treq := &openapi.OpenApiRequest{\n\t\tQuery: openapiutil.Query(query),\n\t}\n\tparams := &openapi.Params{\n\t\tAction: tea.String(\"GrantAccountPrivilege\"),\n\t\tVersion: tea.String(\"2015-01-01\"),\n\t\tProtocol: tea.String(\"HTTPS\"),\n\t\tPathname: tea.String(\"/\"),\n\t\tMethod: tea.String(\"POST\"),\n\t\tAuthType: tea.String(\"AK\"),\n\t\tStyle: tea.String(\"RPC\"),\n\t\tReqBodyType: tea.String(\"formData\"),\n\t\tBodyType: tea.String(\"json\"),\n\t}\n\t_result = &GrantAccountPrivilegeResponse{}\n\t_body, _err := client.CallApi(params, req, runtime)\n\tif _err != nil {\n\t\treturn _result, _err\n\t}\n\t_err = tea.Convert(_body, &_result)\n\treturn _result, _err\n}", "func (trd *trxDispatcher) pushAccount(at string, adr *common.Address, blk *types.Block, trx *types.Transaction, wg *sync.WaitGroup) bool {\n\twg.Add(1)\n\tselect {\n\tcase trd.outAccount <- &eventAcc{\n\t\twatchDog: wg,\n\t\taddr: adr,\n\t\tact: at,\n\t\tblk: blk,\n\t\ttrx: trx,\n\t\tdeploy: nil,\n\t}:\n\tcase <-trd.sigStop:\n\t\treturn false\n\t}\n\treturn true\n}", "func (va *ClawbackVestingAccount) addGrant(ctx sdk.Context, sk StakingKeeper, grantStartTime int64, grantLockupPeriods, grantVestingPeriods []Period, grantCoins sdk.Coins) {\n\t// how much is really delegated?\n\tbondedAmt := sk.GetDelegatorBonded(ctx, va.GetAddress())\n\tunbondingAmt := sk.GetDelegatorUnbonding(ctx, va.GetAddress())\n\tdelegatedAmt := bondedAmt.Add(unbondingAmt)\n\tdelegated := sdk.NewCoins(sdk.NewCoin(sk.BondDenom(ctx), delegatedAmt))\n\n\t// discover what has been slashed\n\toldDelegated := va.DelegatedVesting.Add(va.DelegatedFree...)\n\tslashed := oldDelegated.Sub(coinsMin(oldDelegated, delegated))\n\n\t// rebase the DV + DF by capping slashed at the current unvested amount\n\tunvested := va.OriginalVesting.Sub(va.GetVestedOnly(ctx.BlockTime()))\n\tnewSlashed := coinsMin(slashed, unvested)\n\tnewDelegated := delegated.Add(newSlashed...)\n\n\t// modify schedules for the new grant\n\tnewLockupStart, newLockupEnd, newLockupPeriods := DisjunctPeriods(va.StartTime, grantStartTime, va.LockupPeriods, grantLockupPeriods)\n\tnewVestingStart, newVestingEnd, newVestingPeriods := DisjunctPeriods(va.StartTime, grantStartTime,\n\t\tva.GetVestingPeriods(), grantVestingPeriods)\n\tif newLockupStart != newVestingStart {\n\t\tpanic(\"bad start time calculation\")\n\t}\n\tva.StartTime = newLockupStart\n\tva.EndTime = max64(newLockupEnd, newVestingEnd)\n\tva.LockupPeriods = newLockupPeriods\n\tva.VestingPeriods = newVestingPeriods\n\tva.OriginalVesting = va.OriginalVesting.Add(grantCoins...)\n\n\t// cap DV at the current unvested amount, DF rounds out to newDelegated\n\tunvested2 := va.GetVestingCoins(ctx.BlockTime())\n\tva.DelegatedVesting = coinsMin(newDelegated, unvested2)\n\tva.DelegatedFree = newDelegated.Sub(va.DelegatedVesting)\n}", "func NewPeriodicVestingAccountRaw(bva *BaseVestingAccount, startTime int64, periods Periods) *PeriodicVestingAccount {\n\treturn &PeriodicVestingAccount{\n\t\tBaseVestingAccount: bva,\n\t\tStartTime: startTime,\n\t\tVestingPeriods: periods,\n\t}\n}", "func (am *AccountManager) AddAccount(a *Account) {\n\tam.cmdChan <- &addAccountCmd{\n\t\ta: a,\n\t}\n}", "func (service *AccountService) AddAccount(ctx context.Context, req *protoAccount.NewAccountRequest, res *protoAccount.AccountResponse) error {\n\t// supported exchange keys check\n\tif !supportedExchange(req.Exchange) {\n\t\tres.Status = constRes.Fail\n\t\tres.Message = fmt.Sprintf(\"%s is not supported\", req.Exchange)\n\t\treturn nil\n\t}\n\tif !supportedType(req.AccountType) {\n\t\tres.Status = constRes.Fail\n\t\tres.Message = fmt.Sprintf(\"accountType must be paper or real\")\n\t\treturn nil\n\t}\n\n\taccountID := uuid.New().String()\n\tnow := string(pq.FormatTimestamp(time.Now().UTC()))\n\tbalances := make([]*protoBalance.Balance, 0, len(req.Balances))\n\n\t// user specified balances will be ignored if a\n\t// valid public/secret is send in with request\n\tfor _, b := range req.Balances {\n\t\tbalance := protoBalance.Balance{\n\t\t\tUserID: req.UserID,\n\t\t\tAccountID: accountID,\n\t\t\tCurrencySymbol: b.CurrencySymbol,\n\t\t\tAvailable: b.Available,\n\t\t\tLocked: 0,\n\t\t\tCreatedOn: now,\n\t\t\tUpdatedOn: now,\n\t\t}\n\t\tbalances = append(balances, &balance)\n\t}\n\n\t// assume account valid\n\taccount := protoAccount.Account{\n\t\tAccountID: accountID,\n\t\tAccountType: req.AccountType,\n\t\tUserID: req.UserID,\n\t\tExchange: req.Exchange,\n\t\tKeyPublic: req.KeyPublic,\n\t\tKeySecret: util.Rot32768(req.KeySecret),\n\t\tTitle: req.Title,\n\t\tColor: req.Color,\n\t\tDescription: req.Description,\n\t\tStatus: constAccount.AccountValid,\n\t\tCreatedOn: now,\n\t\tUpdatedOn: now,\n\t\tBalances: balances,\n\t}\n\n\t// validate account request when keys are present\n\tswitch {\n\tcase account.KeyPublic != \"\" && account.KeySecret == \"\":\n\t\tres.Status = constRes.Fail\n\t\tres.Message = \"keySecret required with keyPublic!\"\n\t\treturn nil\n\tcase account.KeyPublic == \"\" && account.KeySecret != \"\":\n\t\tres.Status = constRes.Fail\n\t\tres.Message = \"keyPublic required with keySecret!\"\n\t\treturn nil\n\tcase account.Color == \"\":\n\t\tres.Status = constRes.Fail\n\t\tres.Message = \"color required\"\n\t\treturn nil\n\t}\n\n\tswitch {\n\tcase account.Exchange == constExch.Binance && account.AccountType == constAccount.AccountReal:\n\t\t// if api key ask exchange for balances\n\t\tif account.KeyPublic == \"\" || account.KeySecret == \"\" {\n\t\t\tres.Status = constRes.Fail\n\t\t\tres.Message = \"keyPublic and keySecret required!\"\n\t\t\treturn nil\n\t\t}\n\t\treqBal := protoBinanceBal.BalanceRequest{\n\t\t\tUserID: account.UserID,\n\t\t\tKeyPublic: account.KeyPublic,\n\t\t\tKeySecret: util.Rot32768(account.KeySecret),\n\t\t}\n\t\tresBal, _ := service.BinanceClient.GetBalances(ctx, &reqBal)\n\n\t\t// reponse to client on invalid key\n\t\tif resBal.Status != constRes.Success {\n\t\t\tres.Status = resBal.Status\n\t\t\tres.Message = resBal.Message\n\t\t\treturn nil\n\t\t}\n\n\t\texBalances := make([]*protoBalance.Balance, 0)\n\t\tfor _, b := range resBal.Data.Balances {\n\t\t\ttotal := b.Free + b.Locked\n\n\t\t\t// only add non-zero balances\n\t\t\tif total > 0 {\n\t\t\t\tbalance := protoBalance.Balance{\n\t\t\t\t\tUserID: account.UserID,\n\t\t\t\t\tAccountID: account.AccountID,\n\t\t\t\t\tCurrencySymbol: b.CurrencySymbol,\n\t\t\t\t\tAvailable: b.Free,\n\t\t\t\t\tLocked: 0.0,\n\t\t\t\t\tExchangeTotal: total,\n\t\t\t\t\tExchangeAvailable: b.Free,\n\t\t\t\t\tExchangeLocked: b.Locked,\n\t\t\t\t\tCreatedOn: now,\n\t\t\t\t\tUpdatedOn: now,\n\t\t\t\t}\n\n\t\t\t\texBalances = append(exBalances, &balance)\n\t\t\t}\n\t\t}\n\t\taccount.Balances = exBalances\n\t}\n\n\tif err := repoAccount.InsertAccount(service.DB, &account); err != nil {\n\t\tmsg := fmt.Sprintf(\"insert account failed %s\", err.Error())\n\t\tlog.Println(msg)\n\n\t\tres.Status = constRes.Error\n\t\tres.Message = msg\n\t}\n\n\tres.Status = constRes.Success\n\tres.Data = &protoAccount.UserAccount{Account: &account}\n\n\treturn nil\n}", "func (auth Authenticate) RegisterAccount(session *types.Session, newAccount *types.Account) (string, error) {\n\taccount, err := auth.CheckAccountSession(session)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t//Get Account Roles\n\taccount = account.GetAccountPermissions()\n\n\t//Only Accounts with ADMIN privliges can make this request\n\tif !utils.Contains(\"ADMIN\", account.Roles) {\n\t\treturn \"\", errors.New(\"Invalid Privilges: \" + account.Name)\n\t}\n\n\t//Get newAccount Roles\n\tnewAccount = newAccount.GetAccountPermissions()\n\n\tres, err := manager.AccountManager{}.CreateAccount(newAccount, account, auth.DB)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn res, nil\n}", "func (_ChpRegistry *ChpRegistryTransactor) AddPauser(opts *bind.TransactOpts, account common.Address) (*types.Transaction, error) {\n\treturn _ChpRegistry.contract.Transact(opts, \"addPauser\", account)\n}", "func (policy *ticketPolicy) OnCreateNewAccount(acc *types.Account) {\n}", "func (client *Client) GrantAccountPrivilege(request *GrantAccountPrivilegeRequest) (_result *GrantAccountPrivilegeResponse, _err error) {\n\truntime := &util.RuntimeOptions{}\n\t_result = &GrantAccountPrivilegeResponse{}\n\t_body, _err := client.GrantAccountPrivilegeWithOptions(request, runtime)\n\tif _err != nil {\n\t\treturn _result, _err\n\t}\n\t_result = _body\n\treturn _result, _err\n}", "func (t *SimpleChaincode) add_account(stub *shim.ChaincodeStub, args []string) ([]byte, error) {\n\n\t//Args\n\t//\t\t\t0\t\t\t\t1\n\t//\t\t index\t\taccount JSON object (as string)\n\n\tid, err := append_id(stub, accountIndexStr, args[0], false)\n\tif err != nil {\n\t\treturn nil, errors.New(\"Error creating new id for user \" + args[0])\n\t}\n\n\terr = stub.PutState(string(id), []byte(args[1]))\n\tif err != nil {\n\t\treturn nil, errors.New(\"Error putting user data on ledger\")\n\t}\n\n\treturn nil, nil\n}", "func (_PermInterface *PermInterfaceTransactor) AddAdminAccount(opts *bind.TransactOpts, _acct common.Address) (*types.Transaction, error) {\n\treturn _PermInterface.contract.Transact(opts, \"addAdminAccount\", _acct)\n}", "func (m *MockupAccountProvider) Add(account entities.Account) derrors.Error {\n\tm.Lock()\n\tdefer m.Unlock()\n\n\tif !m.unsafeExists(account.AccountId) {\n\t\tm.accounts[account.AccountId] = account\n\t\tm.accountNames[account.Name] = true\n\t\treturn nil\n\t}\n\treturn derrors.NewAlreadyExistsError(account.AccountId)\n}", "func (e *copyS2SMigrationFileEnumerator) addTransferFromAccount(ctx context.Context,\n\tsrcServiceURL azfile.ServiceURL, destBaseURL url.URL,\n\tsharePrefix, fileOrDirectoryPrefix, fileNamePattern string, cca *cookedCopyCmdArgs) error {\n\treturn enumerateSharesInAccount(\n\t\tctx,\n\t\tsrcServiceURL,\n\t\tsharePrefix,\n\t\tfunc(shareItem azfile.ShareItem) error {\n\t\t\t// Whatever the destination type is, it should be equivalent to account level,\n\t\t\t// so directly append share name to it.\n\t\t\ttmpDestURL := urlExtension{URL: destBaseURL}.generateObjectPath(shareItem.Name)\n\t\t\t// create bucket for destination, in case bucket doesn't exist.\n\t\t\tif err := e.createDestBucket(ctx, tmpDestURL, nil); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t// Two cases for exclude/include which need to match share names in account:\n\t\t\t// a. https://<fileservice>/share*/file*.vhd\n\t\t\t// b. https://<fileservice>/ which equals to https://<fileservice>/*\n\t\t\treturn e.addTransfersFromDirectory(\n\t\t\t\tctx,\n\t\t\t\tsrcServiceURL.NewShareURL(shareItem.Name).NewRootDirectoryURL(),\n\t\t\t\ttmpDestURL,\n\t\t\t\tfileOrDirectoryPrefix,\n\t\t\t\tfileNamePattern,\n\t\t\t\t\"\",\n\t\t\t\ttrue,\n\t\t\t\ttrue,\n\t\t\t\tcca)\n\t\t})\n}", "func AddLightweightAccountScope(role authpb.Role, scopes map[string]*authpb.Scope) (map[string]*authpb.Scope, error) {\n\tref := &provider.Reference{Path: \"/\"}\n\tval, err := utils.MarshalProtoV1ToJSON(ref)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif scopes == nil {\n\t\tscopes = make(map[string]*authpb.Scope)\n\t}\n\tscopes[\"lightweight\"] = &authpb.Scope{\n\t\tResource: &types.OpaqueEntry{\n\t\t\tDecoder: \"json\",\n\t\t\tValue: val,\n\t\t},\n\t\tRole: role,\n\t}\n\treturn scopes, nil\n}", "func NewPeriodicVestingAccount(baseAcc *authtypes.BaseAccount, originalVesting sdk.Coins, startTime int64, periods Periods) *PeriodicVestingAccount {\n\tendTime := startTime\n\tfor _, p := range periods {\n\t\tendTime += p.Length\n\t}\n\tbaseVestingAcc := &BaseVestingAccount{\n\t\tBaseAccount: baseAcc,\n\t\tOriginalVesting: originalVesting,\n\t\tEndTime: endTime,\n\t}\n\n\treturn &PeriodicVestingAccount{\n\t\tBaseVestingAccount: baseVestingAcc,\n\t\tStartTime: startTime,\n\t\tVestingPeriods: periods,\n\t}\n}", "func (r Runner) AddAccount(ctx context.Context, name, mnemonic string) (Account, error) {\n\tb := &bytes.Buffer{}\n\n\t// check if account already exists.\n\tvar accounts []Account\n\tif err := r.run(ctx, runOptions{stdout: b}, r.cc.ListKeysCommand()); err != nil {\n\t\treturn Account{}, err\n\t}\n\tif err := json.NewDecoder(b).Decode(&accounts); err != nil {\n\t\treturn Account{}, err\n\t}\n\tfor _, account := range accounts {\n\t\tif account.Name == name {\n\t\t\treturn Account{}, ErrAccountAlreadyExists\n\t\t}\n\t}\n\tb.Reset()\n\n\taccount := Account{\n\t\tName: name,\n\t\tMnemonic: mnemonic,\n\t}\n\n\t// import the account when mnemonic is provided, otherwise create a new one.\n\tif mnemonic != \"\" {\n\t\tinput := &bytes.Buffer{}\n\t\tfmt.Fprintln(input, mnemonic)\n\n\t\tif r.cc.KeyringPassword != \"\" {\n\t\t\tfmt.Fprintln(input, r.cc.KeyringPassword)\n\t\t\tfmt.Fprintln(input, r.cc.KeyringPassword)\n\t\t}\n\n\t\tif err := r.run(\n\t\t\tctx,\n\t\t\trunOptions{},\n\t\t\tr.cc.ImportKeyCommand(name),\n\t\t\tstep.Write(input.Bytes()),\n\t\t); err != nil {\n\t\t\treturn Account{}, err\n\t\t}\n\t} else {\n\t\t// note that, launchpad prints account output from stderr.\n\t\tif err := r.run(ctx, runOptions{stdout: b, stderr: b}, r.cc.AddKeyCommand(name)); err != nil {\n\t\t\treturn Account{}, err\n\t\t}\n\t\tif err := json.NewDecoder(b).Decode(&account); err != nil {\n\t\t\treturn Account{}, err\n\t\t}\n\n\t\tb.Reset()\n\t}\n\n\t// get full details of the account.\n\topt := []step.Option{\n\t\tr.cc.ShowKeyAddressCommand(name),\n\t}\n\n\tif r.cc.KeyringPassword != \"\" {\n\t\tinput := &bytes.Buffer{}\n\t\tfmt.Fprintln(input, r.cc.KeyringPassword)\n\t\topt = append(opt, step.Write(input.Bytes()))\n\t}\n\n\tif err := r.run(ctx, runOptions{stdout: b}, opt...); err != nil {\n\t\treturn Account{}, err\n\t}\n\taccount.Address = strings.TrimSpace(b.String())\n\n\treturn account, nil\n}", "func Account(cluster string, tier toolchainv1alpha1.NSTemplateTier, modifiers ...UaInMurModifier) MurModifier {\n\treturn func(mur *toolchainv1alpha1.MasterUserRecord) error {\n\t\tmur.Spec.UserAccounts = []toolchainv1alpha1.UserAccountEmbedded{}\n\t\treturn AdditionalAccount(cluster, tier, modifiers...)(mur)\n\t}\n}", "func AdditionalAccount(cluster string, tier toolchainv1alpha1.NSTemplateTier, modifiers ...UaInMurModifier) MurModifier {\n\treturn func(mur *toolchainv1alpha1.MasterUserRecord) error {\n\t\ttemplates := nstemplateSetFromTier(tier)\n\t\tua := toolchainv1alpha1.UserAccountEmbedded{\n\t\t\tTargetCluster: cluster,\n\t\t\tSyncIndex: \"123abc\", // default value\n\t\t\tSpec: toolchainv1alpha1.UserAccountSpecEmbedded{\n\t\t\t\tUserAccountSpecBase: toolchainv1alpha1.UserAccountSpecBase{\n\t\t\t\t\tNSLimit: tier.Name,\n\t\t\t\t\tNSTemplateSet: templates,\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t\t// set the user account\n\t\tmur.Spec.UserAccounts = append(mur.Spec.UserAccounts, ua)\n\t\tfor _, modify := range modifiers {\n\t\t\tmodify(cluster, mur)\n\t\t}\n\t\t// set the labels for the tier templates in use\n\t\thash, err := computeTemplateRefsHash(tier)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tmur.ObjectMeta.Labels = map[string]string{\n\t\t\ttoolchainv1alpha1.LabelKeyPrefix + tier.Name + \"-tier-hash\": hash,\n\t\t}\n\t\treturn nil\n\t}\n}", "func create_account_ (stub shim.ChaincodeStubInterface, account *Account) error {\n var old_account Account\n row_was_found,err := util.InsertTableRow(stub, ACCOUNT_TABLE, row_keys_of_Account(account), account, util.FAIL_BEFORE_OVERWRITE, &old_account)\n if err != nil {\n return err\n }\n if row_was_found {\n return fmt.Errorf(\"Could not create account %v because an account with that Name already exists\", *account)\n }\n return nil // success\n}", "func newPeriodicVestingAccount(address sdk.AccAddress, periods vestingtypes.Periods, firstPeriodStartTimestamp int64) *vestingtypes.PeriodicVestingAccount {\n\tbaseAccount := authtypes.NewBaseAccount(address, nil, 0, 0)\n\n\toriginalVesting := sdk.NewCoins()\n\tfor _, p := range periods {\n\t\toriginalVesting = originalVesting.Add(p.Amount...)\n\t}\n\n\tvar totalPeriods int64\n\tfor _, p := range periods {\n\t\ttotalPeriods += p.Length\n\t}\n\tendTime := firstPeriodStartTimestamp + totalPeriods\n\n\tbaseVestingAccount := vestingtypes.NewBaseVestingAccount(baseAccount, originalVesting, endTime)\n\treturn vestingtypes.NewPeriodicVestingAccountRaw(baseVestingAccount, firstPeriodStartTimestamp, periods)\n}", "func (s *Service) AddAccount(acc *entity.Account) (*entity.Account, error) {\n\t_, err := govalidator.ValidateStruct(acc)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn s.repo.AddAccount(acc)\n}", "func AddAccount(ctx context.Context, tconn *chrome.TestConn, email, password string) error {\n\t// Set up keyboard.\n\tkb, err := input.VirtualKeyboard(ctx)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to get keyboard\")\n\t}\n\tdefer kb.Close()\n\n\tui := uiauto.New(tconn).WithTimeout(DefaultUITimeout)\n\n\tif err := startAddAccount(ctx, kb, ui, email); err != nil {\n\t\treturn errors.Wrap(err, \"failed to start account addition\")\n\t}\n\n\t// All nodes in the dialog should be inside the `root`.\n\troot := AddAccountDialog()\n\n\tpasswordField := nodewith.Name(\"Enter your password\").Role(role.TextField).Ancestor(root)\n\tnextButton := nodewith.Name(\"Next\").Role(role.Button).Ancestor(root)\n\tiAgreeButton := nodewith.Name(\"I agree\").Role(role.Button).Ancestor(root)\n\n\tif err := uiauto.Combine(\"Enter email and password\",\n\t\t// Enter the User Name.\n\t\tkb.TypeAction(email+\"\\n\"),\n\t\tui.WaitUntilExists(passwordField),\n\t\tui.LeftClick(passwordField),\n\t\t// Enter the Password.\n\t\tkb.TypeAction(password),\n\t\tui.LeftClick(nextButton),\n\t\t// We need to focus the button first to click at right location\n\t\t// as it returns wrong coordinates when button is offscreen.\n\t\tui.FocusAndWait(iAgreeButton),\n\t\tui.LeftClick(iAgreeButton),\n\t)(ctx); err != nil {\n\t\treturn errors.Wrap(err, \"failed to enter email and password\")\n\t}\n\n\treturn nil\n}", "func AccountGrant() GrantBuilder {\n\treturn &CurrentGrantBuilder{\n\t\tgrantType: accountType,\n\t}\n}", "func NewValidatorVestingAccountRaw(bva *vestingtypes.BaseVestingAccount,\n\tstartTime int64, periods vestingtypes.Periods, validatorAddress sdk.ConsAddress, returnAddress sdk.AccAddress, signingThreshold int64) *ValidatorVestingAccount {\n\n\tpva := &vestingtypes.PeriodicVestingAccount{\n\t\tBaseVestingAccount: bva,\n\t\tStartTime: startTime,\n\t\tVestingPeriods: periods,\n\t}\n\tvar vestingPeriodProgress []VestingProgress\n\tfor i := 0; i < len(periods); i++ {\n\t\tvestingPeriodProgress = append(vestingPeriodProgress, VestingProgress{false, false})\n\t}\n\n\treturn &ValidatorVestingAccount{\n\t\tPeriodicVestingAccount: pva,\n\t\tValidatorAddress: validatorAddress,\n\t\tReturnAddress: returnAddress,\n\t\tSigningThreshold: signingThreshold,\n\t\tCurrentPeriodProgress: CurrentPeriodProgress{0, 0},\n\t\tVestingPeriodProgress: vestingPeriodProgress,\n\t\tDebtAfterFailedVesting: sdk.NewCoins(),\n\t}\n}", "func (_PermInterface *PermInterfaceTransactorSession) AddAdminAccount(_acct common.Address) (*types.Transaction, error) {\n\treturn _PermInterface.Contract.AddAdminAccount(&_PermInterface.TransactOpts, _acct)\n}", "func CreateAccount(u usecase.UseCase) gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\t\tvar a presenter.Account\n\t\terr := c.BindJSON(&a)\n\t\tif err != nil {\n\t\t\tresponseFailure(c, http.StatusText(http.StatusInternalServerError),\n\t\t\t\t\"Account can't be created\",\n\t\t\t\t\"Error when converting the parameters sent to json\", \"\", http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\n\t\tacc, err := u.NewAccount(&account.Account{\n\t\t\tID: a.ID, DocumentNumber: a.DocumentNumber,\n\t\t\tAvailableCreditLimit: a.AvailableCreditLimit,\n\t\t})\n\t\tif err != nil {\n\t\t\tresponseFailure(c, http.StatusText(http.StatusInternalServerError),\n\t\t\t\t\"Account can't be created\",\n\t\t\t\tfmt.Sprintf(\"Internal server error when creating a new account - datails err: %s\", err.Error()), \"\", http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t\tc.JSON(http.StatusCreated, acc)\n\t}\n}", "func (mam *MockAccountModel) AddAccount(email, password string) error {\n\targs := mam.Called(email, password)\n\n\treturn args.Error(0)\n}", "func (_ERC20Pausable *ERC20PausableTransactor) AddPauser(opts *bind.TransactOpts, account common.Address) (*types.Transaction, error) {\n\treturn _ERC20Pausable.contract.Transact(opts, \"addPauser\", account)\n}", "func (s *Scim) SaveAccount(oldAcct, newAcct *cpb.Account, desc, subject, realm string, r *http.Request, tx storage.Tx) error {\n\tnewAcct.Revision++\n\tnewAcct.Properties.Modified = float64(time.Now().UnixNano()) / 1e9\n\tif newAcct.Properties.Created == 0 {\n\t\tif oldAcct != nil && oldAcct.Properties.Created != 0 {\n\t\t\tnewAcct.Properties.Created = oldAcct.Properties.Created\n\t\t} else {\n\t\t\tnewAcct.Properties.Created = newAcct.Properties.Modified\n\t\t}\n\t}\n\n\tif err := s.store.WriteTx(storage.AccountDatatype, realm, storage.DefaultUser, newAcct.Properties.Subject, newAcct.Revision, newAcct, storage.MakeConfigHistory(desc, storage.AccountDatatype, newAcct.Revision, newAcct.Properties.Modified, r, subject, oldAcct, newAcct), tx); err != nil {\n\t\treturn fmt.Errorf(\"service storage unavailable: %v, retry later\", err)\n\t}\n\treturn nil\n}", "func CreateAccount(w http.ResponseWriter, r *http.Request) {\n\tvar acc models.Account\n\t_ = json.NewDecoder(r.Body).Decode(&acc)\n\n\tracc, err := models.CreateAccount(acc)\n\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t_, _ = fmt.Fprintf(w, err.Error())\n\t} else {\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\t_ = json.NewEncoder(w).Encode(racc)\n\t}\n}", "func (e *copyS2SMigrationBlobEnumerator) addTransferFromAccount(ctx context.Context,\n\tsrcServiceURL azblob.ServiceURL, destBaseURL url.URL,\n\tcontainerPrefix, blobPrefix, blobNamePattern string, cca *cookedCopyCmdArgs) error {\n\treturn enumerateContainersInAccount(\n\t\tctx,\n\t\tsrcServiceURL,\n\t\tcontainerPrefix,\n\t\tfunc(containerItem azblob.ContainerItem) error {\n\t\t\t// Whatever the destination type is, it should be equivalent to account level,\n\t\t\t// so directly append container name to it.\n\t\t\ttmpDestURL := urlExtension{URL: destBaseURL}.generateObjectPath(containerItem.Name)\n\t\t\t// create bucket for destination, in case bucket doesn't exist.\n\t\t\tif err := e.createDestBucket(ctx, tmpDestURL, nil); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t// Two cases for exclude/include which need to match container names in account:\n\t\t\t// a. https://<blobservice>/container*/blob*.vhd\n\t\t\t// b. https://<blobservice>/ which equals to https://<blobservice>/*\n\t\t\treturn e.addTransfersFromContainer(\n\t\t\t\tctx,\n\t\t\t\tsrcServiceURL.NewContainerURL(containerItem.Name),\n\t\t\t\ttmpDestURL,\n\t\t\t\tblobPrefix,\n\t\t\t\tblobNamePattern,\n\t\t\t\t\"\",\n\t\t\t\ttrue,\n\t\t\t\ttrue,\n\t\t\t\tcca)\n\t\t})\n}", "func CreateAccount(ee engine.Exchange) sknet.HandlerFunc {\n\treturn func(c *sknet.Context) error {\n\t\terrRlt := &pp.EmptyRes{}\n\t\tfor {\n\t\t\treq := pp.CreateAccountReq{}\n\t\t\tif err := c.BindJSON(&req); err != nil {\n\t\t\t\tlogger.Error(err.Error())\n\t\t\t\terrRlt = pp.MakeErrResWithCode(pp.ErrCode_WrongRequest)\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\t// validate pubkey.\n\t\t\tif err := validatePubkey(req.GetPubkey()); err != nil {\n\t\t\t\tlogger.Error(err.Error())\n\t\t\t\terrRlt = pp.MakeErrResWithCode(pp.ErrCode_WrongPubkey)\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\t// create account with pubkey.\n\t\t\tif _, err := ee.CreateAccountWithPubkey(req.GetPubkey()); err != nil {\n\t\t\t\tlogger.Error(err.Error())\n\t\t\t\terrRlt = pp.MakeErrResWithCode(pp.ErrCode_WrongRequest)\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tres := pp.CreateAccountRes{\n\t\t\t\tResult: pp.MakeResultWithCode(pp.ErrCode_Success),\n\t\t\t\tPubkey: req.Pubkey,\n\t\t\t\tCreatedAt: pp.PtrInt64(time.Now().Unix()),\n\t\t\t}\n\n\t\t\treturn c.SendJSON(&res)\n\t\t}\n\n\t\treturn c.Error(errRlt)\n\t}\n}", "func (_ChpRegistry *ChpRegistryTransactorSession) AddPauser(account common.Address) (*types.Transaction, error) {\n\treturn _ChpRegistry.Contract.AddPauser(&_ChpRegistry.TransactOpts, account)\n}", "func (b *OGame) AddAccount(number int, lang string) (*AddAccountRes, error) {\n\treturn b.addAccount(number, lang)\n}", "func (client *Client) CreateResourceAccountWithOptions(request *CreateResourceAccountRequest, runtime *util.RuntimeOptions) (_result *CreateResourceAccountResponse, _err error) {\n\t_err = util.ValidateModel(request)\n\tif _err != nil {\n\t\treturn _result, _err\n\t}\n\tquery := map[string]interface{}{}\n\tif !tea.BoolValue(util.IsUnset(request.AccountNamePrefix)) {\n\t\tquery[\"AccountNamePrefix\"] = request.AccountNamePrefix\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.DisplayName)) {\n\t\tquery[\"DisplayName\"] = request.DisplayName\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.ParentFolderId)) {\n\t\tquery[\"ParentFolderId\"] = request.ParentFolderId\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.PayerAccountId)) {\n\t\tquery[\"PayerAccountId\"] = request.PayerAccountId\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.ResellAccountType)) {\n\t\tquery[\"ResellAccountType\"] = request.ResellAccountType\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.Tag)) {\n\t\tquery[\"Tag\"] = request.Tag\n\t}\n\n\treq := &openapi.OpenApiRequest{\n\t\tQuery: openapiutil.Query(query),\n\t}\n\tparams := &openapi.Params{\n\t\tAction: tea.String(\"CreateResourceAccount\"),\n\t\tVersion: tea.String(\"2020-03-31\"),\n\t\tProtocol: tea.String(\"HTTPS\"),\n\t\tPathname: tea.String(\"/\"),\n\t\tMethod: tea.String(\"POST\"),\n\t\tAuthType: tea.String(\"AK\"),\n\t\tStyle: tea.String(\"RPC\"),\n\t\tReqBodyType: tea.String(\"formData\"),\n\t\tBodyType: tea.String(\"json\"),\n\t}\n\t_result = &CreateResourceAccountResponse{}\n\t_body, _err := client.CallApi(params, req, runtime)\n\tif _err != nil {\n\t\treturn _result, _err\n\t}\n\t_err = tea.Convert(_body, &_result)\n\treturn _result, _err\n}", "func (s *Service) Create(newAccountDefinition *model.NewAccountDefinition) *CreateOp {\n\treturn &CreateOp{\n\t\tCredential: s.credential,\n\t\tMethod: \"POST\",\n\t\tPath: \"/v2/accounts\",\n\t\tPayload: newAccountDefinition,\n\t\tQueryOpts: make(url.Values),\n\t\tVersion: esign.APIv2,\n\t}\n}", "func (Mutation) UpsertAccount(\n\tctx context.Context,\n\tinput generated.UpsertAccountInput,\n) (*generated.UpsertAccountPayload, error) {\n\tdbi := db.GetDB(ctx)\n\ta := auth.GetAuth(ctx)\n\tif a == nil {\n\t\treturn nil, auth.ErrNoToken\n\t}\n\n\tmodel := models.Account{\n\t\tAuthID: a.AuthID,\n\t\tName: input.Name,\n\t\tSurname: input.Surname,\n\t\tEmail: input.Email,\n\t}\n\n\tif err := model.Upsert(ctx, dbi, true, []string{\"auth_id\"}, boil.Infer(), boil.Infer()); err != nil {\n\t\traven.CaptureError(err, nil)\n\t\treturn nil, db.ErrDefault\n\t}\n\n\tres := generated.UpsertAccountPayload{\n\t\tAccount: &schemas.Account{Account: model},\n\t\tClientMutationID: input.ClientMutationID,\n\t}\n\n\treturn &res, nil\n}", "func (a *Account) CreateAcct(password string) (*Account, *http.Response, []error) {\n\tk := kumoru.New()\n\n\tk.Put(fmt.Sprintf(\"%s/v1/accounts/%s\", k.EndPoint.Authorization, a.Email))\n\tk.Send(fmt.Sprintf(\"given_name=%s&surname=%s&password=%s\", a.GivenName, a.Surname, password))\n\n\tresp, body, errs := k.End()\n\n\tif len(errs) > 0 {\n\t\treturn a, resp, errs\n\t}\n\n\tif resp.StatusCode >= 400 {\n\t\terrs = append(errs, fmt.Errorf(\"%s\", resp.Status))\n\t}\n\n\terr := json.Unmarshal([]byte(body), &a)\n\n\tif err != nil {\n\t\terrs = append(errs, err)\n\t\treturn a, resp, errs\n\t}\n\n\treturn a, resp, nil\n}", "func (_TxRelay *TxRelayTransactor) AddToWhitelist(opts *bind.TransactOpts, addr common.Address) (*types.Transaction, error) {\n\treturn _TxRelay.contract.Transact(opts, \"addToWhitelist\", addr)\n}", "func (_PermInterface *PermInterfaceSession) AddAdminAccount(_acct common.Address) (*types.Transaction, error) {\n\treturn _PermInterface.Contract.AddAdminAccount(&_PermInterface.TransactOpts, _acct)\n}", "func (am *AccountManager) RegisterNewAccount(a *Account) error {\n\tam.AddAccount(a)\n\n\t// Ensure that the new account is written out to disk.\n\tam.ds.ScheduleWalletWrite(a)\n\tam.ds.ScheduleTxStoreWrite(a)\n\tif err := am.ds.FlushAccount(a); err != nil {\n\t\tam.RemoveAccount(a)\n\t\treturn err\n\t}\n\treturn nil\n}", "func (_ElvToken *ElvTokenTransactor) AddPauser(opts *bind.TransactOpts, account common.Address) (*types.Transaction, error) {\n\treturn _ElvToken.contract.Transact(opts, \"addPauser\", account)\n}", "func (_Pausable *PausableTransactor) AddPauser(opts *bind.TransactOpts, account common.Address) (*types.Transaction, error) {\n\treturn _Pausable.contract.Transact(opts, \"addPauser\", account)\n}", "func (s *Service) CreateAccount(budgetID string, accountPayload PayloadAccount) (*Account, error) {\n\tresModel := struct {\n\t\tData struct {\n\t\t\tAccount *Account `json:\"account\"`\n\t\t} `json:\"data\"`\n\t}{}\n\n\tpayload := struct {\n\t\tAccount PayloadAccount `json:\"account\"`\n\t}{\n\t\taccountPayload,\n\t}\n\n\tbuf, err := json.Marshal(&payload)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\turl := fmt.Sprintf(\"/budgets/%s/accounts/\", budgetID)\n\tif err := s.c.POST(url, &resModel, buf); err != nil {\n\t\treturn nil, err\n\t}\n\treturn resModel.Data.Account, nil\n}", "func (manager *OpenIdManager) RegisterAccount(providerId string, oauth2Token *oauth2.Token, oidToken *oidc.IDToken) (*models.UserAccount, error) {\n\tclient, err := manager.GetOIdClient(providerId)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpayload, err := client.FetchProfilePayload(oauth2Token)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\taccount, err := models.RegisterUser(payload)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t_, err = models.RegisterOIdAccount(providerId, oidToken.Subject, account.Id)\n\tif err != nil {\n\t\t_ = account.Delete()\n\t\treturn nil, err\n\t}\n\n\treturn account, nil\n}", "func AddAccountReference(user *jenkinsv1.User, gitProviderKey string, id string) *jenkinsv1.User {\n\tif user.Spec.Accounts == nil {\n\t\tuser.Spec.Accounts = make([]jenkinsv1.AccountReference, 0)\n\t}\n\tuser.Spec.Accounts = append(user.Spec.Accounts, jenkinsv1.AccountReference{\n\t\tProvider: gitProviderKey,\n\t\tID: id,\n\t})\n\tif user.ObjectMeta.Labels == nil {\n\t\tuser.ObjectMeta.Labels = make(map[string]string)\n\t}\n\tuser.ObjectMeta.Labels[gitProviderKey] = id\n\treturn user\n}", "func (tx *Tx) AddReportAccount(reportID string, accountID string) error {\n\tlog.Printf(\"Adding account %s under reportID: %s\", accountID, reportID)\n\t_, err := tx.Exec(\"INSERT INTO aws_account (report_id, aws_account_id, name) VALUES ($1, $2, $3)\", reportID, accountID, accountID)\n\tif err != nil {\n\t\tif strings.Contains(err.Error(), \"unique_account\") {\n\t\t\tlog.Printf(\"Account %s already exists in reportID %s\", accountID, reportID)\n\t\t\treturn nil\n\t\t}\n\t\treturn errors.InternalError(err)\n\t}\n\terr = tx.UpdateUserReportMtime(reportID)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlog.Printf(\"Successfully added account %s under reportID: %s\", accountID, reportID)\n\treturn nil\n}", "func (r *CompanyAccountsCollectionRequest) Add(ctx context.Context, reqObj *Account) (resObj *Account, err error) {\n\terr = r.JSONRequest(ctx, \"POST\", \"\", reqObj, &resObj)\n\treturn\n}", "func (s *Service) AccountCreate(c *gin.Context, roleID model.AccessRole) error {\n\treturn s.IsLowerRole(c, roleID)\n}", "func Create(w http.ResponseWriter, r *http.Request) {\n\tauthUser, err := auth.GetUserFromJWT(w, r)\n\tif err != nil {\n\t\tresponse.FormatStandardResponse(false, \"error-auth\", \"\", err.Error(), w)\n\t\treturn\n\t}\n\n\tdefer r.Body.Close()\n\n\t// Decode the JSON body\n\tacct := datastore.Account{}\n\terr = json.NewDecoder(r.Body).Decode(&acct)\n\tswitch {\n\t// Check we have some data\n\tcase err == io.EOF:\n\t\tresponse.FormatStandardResponse(false, \"error-account-data\", \"\", \"No account data supplied.\", w)\n\t\treturn\n\t\t// Check for parsing errors\n\tcase err != nil:\n\t\tresponse.FormatStandardResponse(false, \"error-decode-json\", \"\", err.Error(), w)\n\t\treturn\n\t}\n\n\tcreateHandler(w, authUser, false, acct)\n}", "func (_TokenVesting *TokenVestingTransactor) AddToken(opts *bind.TransactOpts, _token common.Address, _vestingBeneficiary common.Address, _vestingPeriodInWeeks *big.Int) (*types.Transaction, error) {\n\treturn _TokenVesting.contract.Transact(opts, \"addToken\", _token, _vestingBeneficiary, _vestingPeriodInWeeks)\n}", "func NewPeriodicGrantAction(\n\tsk StakingKeeper,\n\tgrantStartTime int64,\n\tgrantVestingPeriods []Period,\n\tgrantCoins sdk.Coins,\n) exported.AddGrantAction {\n\treturn periodicGrantAction{\n\t\tsk: sk,\n\t\tgrantStartTime: grantStartTime,\n\t\tgrantVestingPeriods: grantVestingPeriods,\n\t\tgrantCoins: grantCoins,\n\t}\n}", "func (_ChpRegistry *ChpRegistrySession) AddPauser(account common.Address) (*types.Transaction, error) {\n\treturn _ChpRegistry.Contract.AddPauser(&_ChpRegistry.TransactOpts, account)\n}", "func Create(w http.ResponseWriter, r *http.Request) {\n\n\taccountDecoder := json.NewDecoder(r.Body)\n\tvar accData Account\n\terr := accountDecoder.Decode(&accData)\n\tif err != nil {\n\t\tlog.Fatalln(\"error:\", err)\n\t}\n\taccData.CreateAccount()\n\tfmt.Fprintf(w, \"Account added successfully\")\n}", "func NewBaseVestingAccount(baseAccount *authtypes.BaseAccount, originalVesting sdk.Coins, endTime int64) *BaseVestingAccount {\n\treturn &BaseVestingAccount{\n\t\tBaseAccount: baseAccount,\n\t\tOriginalVesting: originalVesting,\n\t\tDelegatedFree: sdk.NewCoins(),\n\t\tDelegatedVesting: sdk.NewCoins(),\n\t\tEndTime: endTime,\n\t}\n}", "func (service AccountsService) Create(a Account) (*Response, Account, error) {\n\treq, err := service.client.newRequest(\"POST\", \"accounts\", nil, a)\n\tif err != nil {\n\t\treturn nil, Account{}, err\n\t}\n\n\tvar dest Account\n\tres, err := service.client.do(req, &dest)\n\n\tdest.BillingInfo = nil\n\n\treturn res, dest, err\n}", "func (repo *Repository) Create(ctx context.Context, claims auth.Claims, req UserAccountCreateRequest, now time.Time) (*UserAccount, error) {\n\tspan, ctx := tracer.StartSpanFromContext(ctx, \"internal.user_account.Create\")\n\tdefer span.Finish()\n\n\t// Validate the request.\n\tv := webcontext.Validator()\n\terr := v.Struct(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Ensure the claims can modify the account specified in the request.\n\terr = repo.CanModifyAccount(ctx, claims, req.AccountID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// If now empty set it to the current time.\n\tif now.IsZero() {\n\t\tnow = time.Now()\n\t}\n\n\t// Always store the time as UTC.\n\tnow = now.UTC()\n\n\t// Postgres truncates times to milliseconds when storing. We and do the same\n\t// here so the value we return is consistent with what we store.\n\tnow = now.Truncate(time.Millisecond)\n\n\t// Check to see if there is an existing user account, including archived.\n\texistQuery := selectQuery()\n\texistQuery.Where(existQuery.And(\n\t\texistQuery.Equal(\"account_id\", req.AccountID),\n\t\texistQuery.Equal(\"user_id\", req.UserID),\n\t))\n\texisting, err := find(ctx, claims, repo.DbConn, existQuery, []interface{}{}, true)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// If there is an existing entry, then update instead of insert.\n\tvar ua UserAccount\n\tif len(existing) > 0 {\n\t\tupReq := UserAccountUpdateRequest{\n\t\t\tUserID: req.UserID,\n\t\t\tAccountID: req.AccountID,\n\t\t\tRoles: &req.Roles,\n\t\t\tunArchive: true,\n\t\t}\n\t\terr = repo.Update(ctx, claims, upReq, now)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tua = *existing[0]\n\t\tua.Roles = req.Roles\n\t\tua.UpdatedAt = now\n\t\tua.ArchivedAt = nil\n\t} else {\n\t\tuaID := uuid.NewRandom().String()\n\n\t\tua = UserAccount{\n\t\t\t//ID: uaID,\n\t\t\tUserID: req.UserID,\n\t\t\tAccountID: req.AccountID,\n\t\t\tRoles: req.Roles,\n\t\t\tStatus: UserAccountStatus_Active,\n\t\t\tCreatedAt: now,\n\t\t\tUpdatedAt: now,\n\t\t}\n\n\t\tif req.Status != nil {\n\t\t\tua.Status = *req.Status\n\t\t}\n\n\t\t// Build the insert SQL statement.\n\t\tquery := sqlbuilder.NewInsertBuilder()\n\t\tquery.InsertInto(userAccountTableName)\n\t\tquery.Cols(\"id\", \"user_id\", \"account_id\", \"roles\", \"status\", \"created_at\", \"updated_at\")\n\t\tquery.Values(uaID, ua.UserID, ua.AccountID, ua.Roles, ua.Status.String(), ua.CreatedAt, ua.UpdatedAt)\n\n\t\t// Execute the query with the provided context.\n\t\tsql, args := query.Build()\n\t\tsql = repo.DbConn.Rebind(sql)\n\t\t_, err = repo.DbConn.ExecContext(ctx, sql, args...)\n\t\tif err != nil {\n\t\t\terr = errors.Wrapf(err, \"query - %s\", query.String())\n\t\t\terr = errors.WithMessagef(err, \"add account %s to user %s failed\", req.AccountID, req.UserID)\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn &ua, nil\n}", "func (s *Subscription) AttachAccount(a Account) (e error) {\n\tif s.UUID != \"\" {\n\t\treturn RecurlyError{statusCode: 400, Description: \"Subscription Already in Use and can't attach another account to it\"}\n\t}\n\ts.EmbedAccount = new(Account)\n\ta.CreatedAt = nil\n\ta.State = \"\"\n\t//some more may need to be blanked out\n\ta.HostedLoginToken = \"\"\n\ts.EmbedAccount = &a\n\treturn\n}", "func (p *Person) AddNameRaw(fullName string) error {\n\n\t// Do we have a valid name?\n\tif len(fullName) <= 5 {\n\t\treturn ErrNameTooShort\n\t}\n\n\t// Start the name\n\tnewName := new(Name)\n\tnewName.Raw = fullName\n\tp.Names = append(p.Names, *newName)\n\treturn nil\n}", "func AccountGrant() *TerraformGrantResource {\n\treturn &TerraformGrantResource{\n\t\tResource: &schema.Resource{\n\t\t\tCreate: CreateAccountGrant,\n\t\t\tRead: ReadAccountGrant,\n\t\t\tDelete: DeleteAccountGrant,\n\t\t\tUpdate: UpdateAccountGrant,\n\n\t\t\tSchema: accountGrantSchema,\n\t\t\tImporter: &schema.ResourceImporter{\n\t\t\t\tStateContext: schema.ImportStatePassthroughContext,\n\t\t\t},\n\t\t},\n\t\tValidPrivs: validAccountPrivileges,\n\t}\n}", "func addFoundryToAccount(state kv.KVStore, agentID isc.AgentID, sn uint32) {\n\tkey := codec.EncodeUint32(sn)\n\tfoundries := accountFoundriesMap(state, agentID)\n\tif foundries.HasAt(key) {\n\t\tpanic(ErrRepeatingFoundrySerialNumber)\n\t}\n\tfoundries.SetAt(key, codec.EncodeBool(true))\n}", "func HandleCreateTOTPAccount(w http.ResponseWriter, r *http.Request) {\n\n\tvar body CreateAccountRequest\n\terr := api.UnmarshalJSONFromRequest(r, &body)\n\tif err != nil {\n\t\tapi.WriteError(w, http.StatusBadRequest, err, false, nil)\n\t\treturn\n\t}\n\n\tvar req = totp.CreateAccountRequest{\n\t\tName: body.Name,\n\t\tPrivateKey: []byte(body.PrivateKey),\n\t}\n\n\t// Attempt login and get the token\n\ta, err := totp.CreateAccount(req)\n\tif err != nil {\n\t\tapi.WriteError(w, http.StatusBadRequest, err, false, nil)\n\t\treturn\n\t}\n\n\tapi.WriteResponse(w, http.StatusCreated, a.ID)\n\n}", "func (kb *Keybase) CreateAccount(name, mnemonic, bip39Passwd, encryptPasswd, hdPath string, algo keys.SigningAlgo) (keys.Info, error) {\n\tkb.mx.Lock()\n\tdefer kb.mx.Unlock()\n\treturn kb.kb.CreateAccount(name, mnemonic, bip39Passwd, encryptPasswd, hdPath, algo)\n}", "func handleACCOUNT(c *Client, e Event) {\n\tif len(e.Params) != 1 {\n\t\treturn\n\t}\n\n\taccount := e.Params[0]\n\tif account == \"*\" {\n\t\taccount = \"\"\n\t}\n\n\tc.state.Lock()\n\tuser := c.state.lookupUser(e.Source.Name)\n\tif user != nil {\n\t\tuser.Extras.Account = account\n\t}\n\tc.state.Unlock()\n\tc.state.notify(c, UPDATE_STATE)\n}", "func (c *Client) CreateAccount(ctx context.Context, js string) (*CreateResponse, error) {\n\n\tvar jsonStr = []byte(js)\n\treq, err := http.NewRequest(\"POST\", fmt.Sprintf(\"%sv1/organisation/accounts\", c.BaseURL), bytes.NewBuffer(jsonStr))\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tres := CreateResponse{}\n\n\tif rescode, err := c.sendRequest(ctx, req, &res); err != nil {\n\t\treturn nil, err\n\t} else {\n\t\tres.Code = rescode\n\t}\n\n\treturn &res, nil\n}", "func (tt *BlockTestTable) AddAccountBlock(priv *rsa.PrivateKey, b *tradeblocks.AccountBlock) *tradeblocks.AccountBlock {\n\tsignBlock(tt.t, priv, b)\n\ttt.AccountBlocks = append(tt.AccountBlocks, b)\n\treturn b\n}", "func (_Token *TokenTransactor) AddWhitelisted(opts *bind.TransactOpts, account common.Address) (*types.Transaction, error) {\n\treturn _Token.contract.Transact(opts, \"addWhitelisted\", account)\n}", "func (app *App) AddAccountsInBlock(accs ...sdk.AccAddress) {\n\tfor _, acc := range accs {\n\t\tapp.accsInBlock[acc.String()] = true\n\t}\n}", "func (inst *DeprecatedPopulateParticipationPrintingAccount) SetRentAccount(rent ag_solanago.PublicKey) *DeprecatedPopulateParticipationPrintingAccount {\n\tinst.AccountMetaSlice[17] = ag_solanago.Meta(rent)\n\treturn inst\n}", "func (repo *RevenueAccountRepository) Create(account *model.RevenueAccountModel) error {\n\tif err := repo.db.Create(account).Error; err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (cl *CustodianLedger) AddAccountToLedger(account *Bankaccount) {\n\tnewData := account\n\tcl.Ledger = append(cl.Ledger, newData)\n}", "func (s *Sender) assignAcct(ctx context.Context) {\n\tif s.acct != nil {\n\t\tamount, err := s.refund(ctx, *s.acct, s.nonce, *s.AccountStore.RandSeed())\n\t\tif ctx.Err() != nil {\n\t\t\treturn\n\t\t}\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Failed to refund account\\t%s err=%q\\n\", s, err)\n\t\t} else if amount > 0 {\n\t\t\ts.nonce++\n\t\t\tlog.Printf(\"Refunded account\\t%s amount=%d\", s, amount)\n\t\t}\n\t\ts.AccountStore.Return(s.acct, s.Node.Number, s.nonce)\n\t}\n\tbo := backOff{maxWait: 30 * time.Second, wait: 1 * time.Second}\n\n\tif !bo.do(ctx, func() (err error) {\n\t\ts.acct, s.nonce, err = s.AccountStore.Next(ctx, s.Node.Number)\n\t\tif err != nil {\n\t\t\terr = fmt.Errorf(\"failed to assign sender account\\tsender=%d err=%q\", s.Number, err)\n\t\t}\n\t\treturn\n\t}) {\n\t\treturn\n\t}\n\tif s.acct == nil {\n\t\tif !bo.do(ctx, func() (err error) {\n\t\t\ts.acct, err = s.AccountStore.New(ctx)\n\t\t\ts.nonce = 0\n\t\t\tif err != nil {\n\t\t\t\terr = fmt.Errorf(\"failed to create sender account\\tsender=%d err=%q\", s.Number, err)\n\t\t\t}\n\t\t\treturn\n\t\t}) {\n\t\t\treturn\n\t\t}\n\t} else {\n\t\tif !bo.doTimed(ctx, pendingNonceAtTimer, func() (err error) {\n\t\t\ts.nonce, err = s.Client.NonceAt(ctx, s.acct.Address, nil)\n\t\t\tif err != nil {\n\t\t\t\terr = fmt.Errorf(\"failed to get nonce\\t%s err=%q\", s, err)\n\t\t\t}\n\t\t\treturn\n\t\t}) {\n\t\t\treturn\n\t\t}\n\t}\n\n\tvar pb *big.Int\n\tif !bo.doTimed(ctx, pendingBalanceAtTimer, func() (err error) {\n\t\tpb, err = s.BalanceAt(ctx, s.acct.Address, nil)\n\t\tif err != nil {\n\t\t\terr = fmt.Errorf(\"failed to get sender balance\\t%s err=%q\", s, err)\n\t\t}\n\t\treturn\n\t}) {\n\t\treturn\n\t}\n\tbal := pb.Uint64()\n\n\tlog.Printf(\"Assigned sender account\\t%s balance=%d\\n\", s, bal)\n\n\tfee := new(big.Int).Mul(s.gasPrice, new(big.Int).SetUint64(s.gas))\n\tamt := fee.Mul(fee, new(big.Int).SetUint64(1000)).Uint64()\n\tif bal < amt {\n\t\tamt = amt - bal\n\t\ts.transition(senderSeedState)\n\t\tif !bo.do(ctx, func() error {\n\t\t\terr := s.requestSeed(ctx, amt)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to seed account\\t%s err=%q\", s, err)\n\t\t\t}\n\t\t\treturn nil\n\t\t}) {\n\t\t\treturn\n\t\t}\n\t\tif _, err := waitBlocks(ctx, s.Client, 0); err != nil {\n\t\t\treturn\n\t\t}\n\t\tlog.Printf(\"Seeded account\\t%s seed=%d balance=%d\\n\", s, amt, amt+bal)\n\t\ts.transition(senderAssignState)\n\t}\n\n\tif !bo.do(ctx, func() error {\n\t\ts.recv = s.AccountStore.NextRecv(s.acct.Address, rand.Intn(10)+1)\n\t\tif len(s.recv) == 0 {\n\t\t\treturn fmt.Errorf(\"failed to assign sender receivers\\t%s receivers=%v\", s, receivers(s.recv))\n\t\t}\n\t\treturn nil\n\t}) {\n\t\treturn\n\t}\n\tif s.verbose {\n\t\tlog.Printf(\"Assigned sender receivers\\t%s receivers=%s\\n\", s, receivers(s.recv))\n\t}\n}", "func (a *Client) AddWhitelist(params *AddWhitelistParams) (*AddWhitelistOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewAddWhitelistParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"addWhitelist\",\n\t\tMethod: \"POST\",\n\t\tPathPattern: \"/asset/tokens/{symbol}/forbidden/whitelist\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"http\", \"https\"},\n\t\tParams: params,\n\t\tReader: &AddWhitelistReader{formats: a.formats},\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsuccess, ok := result.(*AddWhitelistOK)\n\tif ok {\n\t\treturn success, nil\n\t}\n\t// unexpected success response\n\t// safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue\n\tmsg := fmt.Sprintf(\"unexpected success response for addWhitelist: API contract not enforced by server. Client expected to get an error, but got: %T\", result)\n\tpanic(msg)\n}", "func (s *Service) CreateAccount(request commons.CreateAccountRequest) (*commons.CreateAccountResponse, error) {\n\tif ok, err := request.Validate(); !ok {\n\t\treturn nil, err\n\t}\n\treturn &commons.CreateAccountResponse{\n\t\tAccountNo: \"90010062653\",\n\t\tAccountType: commons.MainAccountType,\n\t}, nil\n}", "func (sd *StateDB) CreateAccount(addr types.Address) {\n\tnewstate := NewStateObject(addr, sd)\n\toldstate := sd.getStateObject(addr)\n\tif oldstate != nil {\n\t\tsd.journal.append(&resetObjectChange{\n\t\t\tprev: oldstate,\n\t\t})\n\t} else {\n\t\tsd.journal.append(&createObjectChange{\n\t\t\taccount: &addr,\n\t\t})\n\t}\n\tsd.states[addr] = newstate\n\tsd.beats[addr] = time.Now()\n\n}", "func (act Account) Create(nr Application) (Resource, error) {\n\tvar r Resource\n\tif nr.Validate() != nil {\n\t\treturn r, nr.Validate()\n\t}\n\terr := common.SendPostRequest(fmt.Sprintf(applications.Create, act.AccountSid), nr, act, &r)\n\treturn r, err\n}", "func (a *AccountClient) Create(accountParams AccountParams) (*Resource, error) {\n\n\tresp, err := a.client.R().\n\t\tSetResult(&Resource{}).\n\t\tSetBody(map[string]AccountParams{\"data\": accountParams}).\n\t\tPost(\"/v1/organisation/accounts\")\n\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"create account failed: %s\", err)\n\t}\n\n\tif resp.Error() != nil {\n\t\treturn nil, getAPIError(resp)\n\t}\n\n\treturn resp.Result().(*Resource), nil\n}", "func (am *AccountManager) RecordSpendingTx(tx *btcutil.Tx, block *txstore.Block) error {\n\tfor _, a := range am.AllAccounts() {\n\t\t// TODO(jrick): This needs to iterate through each txout's\n\t\t// addresses and find whether this account's keystore contains\n\t\t// any of the addresses this tx sends to.\n\t\ttxr, err := a.TxStore.InsertTx(tx, block)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// When received as a notification, we don't know what the inputs are.\n\t\tif _, err := txr.AddDebits(nil); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tam.ds.ScheduleTxStoreWrite(a)\n\t}\n\treturn nil\n}", "func (me *AccountController) RegisterAccount(r *http.Request) (*account.Account, error) {\n\tvar registrant account.Registrant\n\terr := me.decoder.DecodeBodyAndValidate(r, &registrant)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tregisteredAccount, err := me.accountService.RegisterAccount(r.Context(), &registrant)\n\treturn registeredAccount, err\n}", "func (client *AccountsClient) createCreateRequest(ctx context.Context, resourceGroupName string, accountName string, account Account, options *AccountsClientBeginCreateOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}\"\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif accountName == \"\" {\n\t\treturn nil, errors.New(\"parameter accountName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{accountName}\", url.PathEscape(accountName))\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\treq, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2023-05-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\treturn req, runtime.MarshalAsJSON(req, account)\n}", "func CreateAccount(resp http.ResponseWriter, req *http.Request) {\n\tresp.Header().Add(\"Content-Type\", \"application/json\")\n\n\tvar account domain.Account\n\tdecoder := json.NewDecoder(req.Body)\n\n\terr := decoder.Decode(&account)\n\n\tif err != nil {\n\t\thttp.Error(resp, \"Bad Request\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tapiErr := service.CreateAccount(account)\n\n\tif apiErr != nil {\n\t\tresp.WriteHeader(http.StatusInternalServerError)\n\t\tencoder := json.NewEncoder(resp)\n\t\tencoder.Encode(apiErr)\n\t}\n\n\tresp.WriteHeader(http.StatusOK)\n\n\tjsonValue, _ := json.Marshal(utils.AppMsgs{http.StatusOK, \"Account was created\"})\n\n\tresp.Write(jsonValue)\n}", "func (client *Client) CreateAccountWithOptions(request *CreateAccountRequest, runtime *util.RuntimeOptions) (_result *CreateAccountResponse, _err error) {\n\t_err = util.ValidateModel(request)\n\tif _err != nil {\n\t\treturn _result, _err\n\t}\n\tquery := map[string]interface{}{}\n\tif !tea.BoolValue(util.IsUnset(request.AccountDescription)) {\n\t\tquery[\"AccountDescription\"] = request.AccountDescription\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.AccountName)) {\n\t\tquery[\"AccountName\"] = request.AccountName\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.AccountPassword)) {\n\t\tquery[\"AccountPassword\"] = request.AccountPassword\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.AccountPrivilege)) {\n\t\tquery[\"AccountPrivilege\"] = request.AccountPrivilege\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.AccountType)) {\n\t\tquery[\"AccountType\"] = request.AccountType\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.InstanceId)) {\n\t\tquery[\"InstanceId\"] = request.InstanceId\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.OwnerAccount)) {\n\t\tquery[\"OwnerAccount\"] = request.OwnerAccount\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.OwnerId)) {\n\t\tquery[\"OwnerId\"] = request.OwnerId\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.ResourceOwnerAccount)) {\n\t\tquery[\"ResourceOwnerAccount\"] = request.ResourceOwnerAccount\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.ResourceOwnerId)) {\n\t\tquery[\"ResourceOwnerId\"] = request.ResourceOwnerId\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.SecurityToken)) {\n\t\tquery[\"SecurityToken\"] = request.SecurityToken\n\t}\n\n\treq := &openapi.OpenApiRequest{\n\t\tQuery: openapiutil.Query(query),\n\t}\n\tparams := &openapi.Params{\n\t\tAction: tea.String(\"CreateAccount\"),\n\t\tVersion: tea.String(\"2015-01-01\"),\n\t\tProtocol: tea.String(\"HTTPS\"),\n\t\tPathname: tea.String(\"/\"),\n\t\tMethod: tea.String(\"POST\"),\n\t\tAuthType: tea.String(\"AK\"),\n\t\tStyle: tea.String(\"RPC\"),\n\t\tReqBodyType: tea.String(\"formData\"),\n\t\tBodyType: tea.String(\"json\"),\n\t}\n\t_result = &CreateAccountResponse{}\n\t_body, _err := client.CallApi(params, req, runtime)\n\tif _err != nil {\n\t\treturn _result, _err\n\t}\n\t_err = tea.Convert(_body, &_result)\n\treturn _result, _err\n}", "func (p *Person) AddAddressRaw(fullAddress string) error {\n\n\t// Must have a minimum length\n\tif len(fullAddress) < 5 {\n\t\treturn ErrAddressTooShort\n\t}\n\n\t// Set the address\n\tnewAddress := new(Address)\n\tnewAddress.Raw = fullAddress\n\tp.Addresses = append(p.Addresses, *newAddress)\n\treturn nil\n}", "func NewDelayedVestingAccountRaw(bva *BaseVestingAccount) *DelayedVestingAccount {\n\treturn &DelayedVestingAccount{\n\t\tBaseVestingAccount: bva,\n\t}\n}", "func (c *Client) AddAccount(ctx context.Context, id string) error {\n\tif id == \"\" {\n\t\treturn &ErrorMissingID{}\n\t}\n\n\tinput := &dynamodb.PutItemInput{\n\t\tItem: map[string]*dynamodb.AttributeValue{\n\t\t\taccountIDKey: {\n\t\t\t\tS: aws.String(id),\n\t\t\t},\n\t\t},\n\t\tTableName: aws.String(tableName),\n\t}\n\n\t_, err := c.dynamoDBClient.PutItem(input)\n\tif err != nil {\n\t\treturn &ErrorPutItem{err: err}\n\t}\n\n\treturn nil\n}", "func CreateAccount(w http.ResponseWriter, r *http.Request) {\n\n\tbodyR, erro := ioutil.ReadAll(r.Body)\n\tif erro != nil {\n\t\tresponses.Error(w, http.StatusUnprocessableEntity, erro)\n\t\treturn\n\t}\n\tvar account model.Account\n\tif erro = json.Unmarshal(bodyR, &account); erro != nil {\n\t\tresponses.Error(w, http.StatusBadRequest, erro)\n\t\treturn\n\t}\n\tfmt.Println(account)\n\tif erro = account.Prepare(\"cadastro\"); erro != nil {\n\t\tresponses.Error(w, http.StatusBadRequest, erro)\n\t\treturn\n\t}\n\n\tdb, erro := database.Connect()\n\tif erro != nil {\n\t\tresponses.Error(w, http.StatusInternalServerError, erro)\n\t\treturn\n\t}\n\tdefer db.Close()\n\n\trepository := repositories.NewAccountRepository(db)\n\t_, erro = repository.FindByCPF(account.Cpf)\n\tif erro != nil {\n\t\tresponses.Error(w, http.StatusConflict, erro)\n\t}\n\n\taccount.ID, erro = repository.Save(account)\n\tif erro != nil {\n\t\tresponses.Error(w, http.StatusInternalServerError, erro)\n\t\treturn\n\t}\n\n\tresponses.JSON(w, http.StatusCreated, account)\n}", "func CreateAccount(form form.Account) (model *Account, err error) {\n\tmodel = &Account{\n\t\tShareSize: \"\",\n\t\tShareExpires: 0,\n\t\tRetryLimit: 3,\n\t\tSyncStatus: AccountSyncStatusRefresh,\n\t}\n\n\terr = model.SaveForm(form)\n\n\treturn model, err\n}", "func (r *RPCKeyRing) ImportAccount(name string,\n\taccountPubKey *hdkeychain.ExtendedKey, masterKeyFingerprint uint32,\n\taddrType *waddrmgr.AddressType,\n\tdryRun bool) (*waddrmgr.AccountProperties, []btcutil.Address,\n\t[]btcutil.Address, error) {\n\n\tctxt, cancel := context.WithTimeout(context.Background(), r.rpcTimeout)\n\tdefer cancel()\n\n\tvar masterKeyFingerprintBytes [4]byte\n\tbinary.BigEndian.PutUint32(\n\t\tmasterKeyFingerprintBytes[:], masterKeyFingerprint,\n\t)\n\n\trpcAddrType, err := toRPCAddrType(addrType)\n\tif err != nil {\n\t\treturn nil, nil, nil, fmt.Errorf(\"error converting address \"+\n\t\t\t\"type: %v\", err)\n\t}\n\n\tremoteAcct, err := r.walletClient.ImportAccount(\n\t\tctxt, &walletrpc.ImportAccountRequest{\n\t\t\tName: name,\n\t\t\tExtendedPublicKey: accountPubKey.String(),\n\t\t\tMasterKeyFingerprint: masterKeyFingerprintBytes[:],\n\t\t\tAddressType: rpcAddrType,\n\t\t\tDryRun: dryRun,\n\t\t},\n\t)\n\tif err != nil {\n\t\treturn nil, nil, nil, fmt.Errorf(\"error importing account on \"+\n\t\t\t\"remote signer instance: %v\", err)\n\t}\n\n\tprops, extAddrs, intAddrs, err := r.WalletController.ImportAccount(\n\t\tname, accountPubKey, masterKeyFingerprint, addrType, dryRun,\n\t)\n\tif err != nil {\n\t\treturn nil, nil, nil, fmt.Errorf(\"error importing account on \"+\n\t\t\t\"local wallet instance: %v\", err)\n\t}\n\n\tmismatchErr := fmt.Errorf(\"error importing account on remote signing \"+\n\t\t\"instance, got different external addresses (%v) than on \"+\n\t\t\"local wallet instance (%s)\", remoteAcct.DryRunExternalAddrs,\n\t\textAddrs)\n\tif len(remoteAcct.DryRunExternalAddrs) != len(extAddrs) {\n\t\treturn nil, nil, nil, mismatchErr\n\t}\n\tfor idx, remoteExtAddr := range remoteAcct.DryRunExternalAddrs {\n\t\tif extAddrs[idx].String() != remoteExtAddr {\n\t\t\treturn nil, nil, nil, mismatchErr\n\t\t}\n\t}\n\n\tmismatchErr = fmt.Errorf(\"error importing account on remote signing \"+\n\t\t\"instance, got different internal addresses (%v) than on \"+\n\t\t\"local wallet instance (%s)\", remoteAcct.DryRunInternalAddrs,\n\t\tintAddrs)\n\tif len(remoteAcct.DryRunInternalAddrs) != len(intAddrs) {\n\t\treturn nil, nil, nil, mismatchErr\n\t}\n\tfor idx, remoteIntAddr := range remoteAcct.DryRunInternalAddrs {\n\t\tif intAddrs[idx].String() != remoteIntAddr {\n\t\t\treturn nil, nil, nil, mismatchErr\n\t\t}\n\t}\n\n\treturn props, extAddrs, intAddrs, nil\n}", "func (_SmartTgStats *SmartTgStatsTransactor) AddRequest(opts *bind.TransactOpts, _channel string, _postID uint32) (*types.Transaction, error) {\n\treturn _SmartTgStats.contract.Transact(opts, \"AddRequest\", _channel, _postID)\n}", "func (c *AccountController) Create(ctx echo.Context) error {\n\tmodel := account.Account{}\n\terr := ctx.Bind(&model)\n\tif err != nil {\n\t\treturn ctx.JSON(http.StatusUnprocessableEntity, err.Error())\n\t}\n\n\tres, err := c.AccountUsecase.Create(&model)\n\tif err != nil {\n\t\treturn ctx.JSON(http.StatusInternalServerError, err.Error())\n\t}\n\n\treturn ctx.JSON(http.StatusCreated, res)\n}", "func (m *MegaCorp) createAccount(firstName, lastName string) (acct *Account, err error) {\n\tacct = &Account{ID: util.UUID4(), FirstName: firstName, LastName: lastName}\n\t_, err = Me.Put(Ledger, fmt.Sprintf(\"account.%s\", acct.ID), ToJSON(acct))\n\treturn\n}", "func (_PauserRole *PauserRoleTransactor) AddPauser(opts *bind.TransactOpts, account common.Address) (*types.Transaction, error) {\n\treturn _PauserRole.contract.Transact(opts, \"addPauser\", account)\n}", "func (wc *WalletCreate) AddAccounts(a ...*Account) *WalletCreate {\n\tids := make([]uuid.UUID, len(a))\n\tfor i := range a {\n\t\tids[i] = a[i].ID\n\t}\n\treturn wc.AddAccountIDs(ids...)\n}" ]
[ "0.6673063", "0.6106532", "0.58922356", "0.5645127", "0.5491181", "0.54294187", "0.52670664", "0.52047217", "0.51024365", "0.5024481", "0.5017414", "0.49595973", "0.49293518", "0.48778266", "0.4868511", "0.48504722", "0.48359856", "0.48092648", "0.47958285", "0.47902265", "0.47751325", "0.47645047", "0.4759813", "0.46989658", "0.4692212", "0.46907523", "0.4674804", "0.46684435", "0.46668735", "0.4660511", "0.46384764", "0.46275455", "0.46080056", "0.46009886", "0.45839384", "0.45777422", "0.45598164", "0.45578986", "0.4551666", "0.45473254", "0.45453927", "0.4522851", "0.4520912", "0.45195514", "0.45185938", "0.45099193", "0.45076764", "0.45026332", "0.44997793", "0.44980857", "0.44933903", "0.44886494", "0.44878218", "0.44757706", "0.44641232", "0.44600704", "0.44560313", "0.44499597", "0.44483033", "0.44473493", "0.44471428", "0.4439601", "0.44081378", "0.4405907", "0.43972608", "0.43914995", "0.43887725", "0.43795213", "0.43544337", "0.4347755", "0.43361324", "0.43241447", "0.43220866", "0.43202192", "0.43176407", "0.43162122", "0.43128657", "0.429896", "0.42949885", "0.42887807", "0.42864737", "0.42857087", "0.42840463", "0.42728677", "0.4267304", "0.4266351", "0.42567408", "0.4255505", "0.425002", "0.42496917", "0.4243773", "0.42409742", "0.4239806", "0.42378134", "0.42363992", "0.4229644", "0.42296255", "0.42266053", "0.42265323", "0.42242533" ]
0.7897445
0
AddGrant implements the exported.GrantAccount interface.
func (pva *PeriodicVestingAccount) AddGrant(ctx sdk.Context, action exported.AddGrantAction) error { return action.AddToAccount(ctx, pva) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (pva *PeriodicVestingAccount) addGrant(ctx sdk.Context, sk StakingKeeper, grantStartTime int64, grantVestingPeriods []Period, grantCoins sdk.Coins) {\n\t// how much is really delegated?\n\tbondedAmt := sk.GetDelegatorBonded(ctx, pva.GetAddress())\n\tunbondingAmt := sk.GetDelegatorUnbonding(ctx, pva.GetAddress())\n\tdelegatedAmt := bondedAmt.Add(unbondingAmt)\n\tdelegated := sdk.NewCoins(sdk.NewCoin(sk.BondDenom(ctx), delegatedAmt))\n\n\t// discover what has been slashed\n\toldDelegated := pva.DelegatedVesting.Add(pva.DelegatedFree...)\n\tslashed := oldDelegated.Sub(coinsMin(oldDelegated, delegated))\n\n\t// rebase the DV+DF by capping slashed at the current unvested amount\n\tunvested := pva.GetVestingCoins(ctx.BlockTime())\n\tnewSlashed := coinsMin(unvested, slashed)\n\tnewTotalDelegated := delegated.Add(newSlashed...)\n\n\t// modify vesting schedule for the new grant\n\tnewStart, newEnd, newPeriods := DisjunctPeriods(pva.StartTime, grantStartTime,\n\t\tpva.GetVestingPeriods(), grantVestingPeriods)\n\tpva.StartTime = newStart\n\tpva.EndTime = newEnd\n\tpva.VestingPeriods = newPeriods\n\tpva.OriginalVesting = pva.OriginalVesting.Add(grantCoins...)\n\n\t// cap DV at the current unvested amount, DF rounds out to newTotalDelegated\n\tunvested2 := pva.GetVestingCoins(ctx.BlockTime())\n\tpva.DelegatedVesting = coinsMin(newTotalDelegated, unvested2)\n\tpva.DelegatedFree = newTotalDelegated.Sub(pva.DelegatedVesting)\n}", "func (va *ClawbackVestingAccount) addGrant(ctx sdk.Context, sk StakingKeeper, grantStartTime int64, grantLockupPeriods, grantVestingPeriods []Period, grantCoins sdk.Coins) {\n\t// how much is really delegated?\n\tbondedAmt := sk.GetDelegatorBonded(ctx, va.GetAddress())\n\tunbondingAmt := sk.GetDelegatorUnbonding(ctx, va.GetAddress())\n\tdelegatedAmt := bondedAmt.Add(unbondingAmt)\n\tdelegated := sdk.NewCoins(sdk.NewCoin(sk.BondDenom(ctx), delegatedAmt))\n\n\t// discover what has been slashed\n\toldDelegated := va.DelegatedVesting.Add(va.DelegatedFree...)\n\tslashed := oldDelegated.Sub(coinsMin(oldDelegated, delegated))\n\n\t// rebase the DV + DF by capping slashed at the current unvested amount\n\tunvested := va.OriginalVesting.Sub(va.GetVestedOnly(ctx.BlockTime()))\n\tnewSlashed := coinsMin(slashed, unvested)\n\tnewDelegated := delegated.Add(newSlashed...)\n\n\t// modify schedules for the new grant\n\tnewLockupStart, newLockupEnd, newLockupPeriods := DisjunctPeriods(va.StartTime, grantStartTime, va.LockupPeriods, grantLockupPeriods)\n\tnewVestingStart, newVestingEnd, newVestingPeriods := DisjunctPeriods(va.StartTime, grantStartTime,\n\t\tva.GetVestingPeriods(), grantVestingPeriods)\n\tif newLockupStart != newVestingStart {\n\t\tpanic(\"bad start time calculation\")\n\t}\n\tva.StartTime = newLockupStart\n\tva.EndTime = max64(newLockupEnd, newVestingEnd)\n\tva.LockupPeriods = newLockupPeriods\n\tva.VestingPeriods = newVestingPeriods\n\tva.OriginalVesting = va.OriginalVesting.Add(grantCoins...)\n\n\t// cap DV at the current unvested amount, DF rounds out to newDelegated\n\tunvested2 := va.GetVestingCoins(ctx.BlockTime())\n\tva.DelegatedVesting = coinsMin(newDelegated, unvested2)\n\tva.DelegatedFree = newDelegated.Sub(va.DelegatedVesting)\n}", "func (ge *CurrentGrantExecutable) Grant(p string) string {\n\tvar template string\n\tif p == `OWNERSHIP` {\n\t\ttemplate = `GRANT %v ON %v %v TO %v \"%v\" COPY CURRENT GRANTS`\n\t} else {\n\t\ttemplate = `GRANT %v ON %v %v TO %v \"%v\"`\n\t}\n\treturn fmt.Sprintf(template,\n\t\tp, ge.grantType, ge.grantName, ge.granteeType, ge.granteeName)\n}", "func AccountGrant() GrantBuilder {\n\treturn &CurrentGrantBuilder{\n\t\tgrantType: accountType,\n\t}\n}", "func Grant(ctx context.Context, i grantRequest) error {\n\tclient, err := New(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn client.Grant(ctx, i)\n}", "func (_LvRecording *LvRecordingTransactor) RunGrant(opts *bind.TransactOpts, arg0 *big.Int, arg1 bool) (*types.Transaction, error) {\n\treturn _LvRecording.contract.Transact(opts, \"runGrant\", arg0, arg1)\n}", "func (n *noopRules) Grant(rule *Rule) error {\n\treturn nil\n}", "func AccountGrant() *TerraformGrantResource {\n\treturn &TerraformGrantResource{\n\t\tResource: &schema.Resource{\n\t\t\tCreate: CreateAccountGrant,\n\t\t\tRead: ReadAccountGrant,\n\t\t\tDelete: DeleteAccountGrant,\n\t\t\tUpdate: UpdateAccountGrant,\n\n\t\t\tSchema: accountGrantSchema,\n\t\t\tImporter: &schema.ResourceImporter{\n\t\t\t\tStateContext: schema.ImportStatePassthroughContext,\n\t\t\t},\n\t\t},\n\t\tValidPrivs: validAccountPrivileges,\n\t}\n}", "func (r *jsiiProxy_RepositoryBase) Grant(grantee awsiam.IGrantable, actions ...*string) awsiam.Grant {\n\targs := []interface{}{grantee}\n\tfor _, a := range actions {\n\t\targs = append(args, a)\n\t}\n\n\tvar returns awsiam.Grant\n\n\t_jsii_.Invoke(\n\t\tr,\n\t\t\"grant\",\n\t\targs,\n\t\t&returns,\n\t)\n\n\treturn returns\n}", "func (r *jsiiProxy_Repository) Grant(grantee awsiam.IGrantable, actions ...*string) awsiam.Grant {\n\targs := []interface{}{grantee}\n\tfor _, a := range actions {\n\t\targs = append(args, a)\n\t}\n\n\tvar returns awsiam.Grant\n\n\t_jsii_.Invoke(\n\t\tr,\n\t\t\"grant\",\n\t\targs,\n\t\t&returns,\n\t)\n\n\treturn returns\n}", "func (_Content *ContentTransactor) RunGrant(opts *bind.TransactOpts, arg0 *big.Int, arg1 bool) (*types.Transaction, error) {\n\treturn _Content.contract.Transact(opts, \"runGrant\", arg0, arg1)\n}", "func (c *Client) Grant(ctx context.Context, i grantRequest) error {\n\tif i == nil {\n\t\treturn fmt.Errorf(\"missing request\")\n\t}\n\n\tswitch t := i.(type) {\n\tcase *SecretManagerGrantRequest:\n\t\treturn c.secretManagerGrant(ctx, t)\n\tcase *StorageGrantRequest:\n\t\treturn c.storageGrant(ctx, t)\n\tdefault:\n\t\treturn fmt.Errorf(\"unknown grant type %T\", t)\n\t}\n}", "func (r *refreshTokenGranter) Grant(_ context.Context, requestedScopes []string) grants.Grant {\n\treturn grants.Grant{\n\t\tSourceType: \"refresh_token\",\n\t\tSourceID: r.token.ID,\n\t\tScopes: requestedScopes,\n\t\tAccountID: r.token.AccountID,\n\t\tProfileID: r.token.ProfileID,\n\t\tClientID: r.token.ClientID,\n\t\tUsed: false,\n\t}\n}", "func (ag *AccessGrant) MergeAdd(other AccessGrant) error {\n\tif err := other.Validate(); err != nil {\n\t\treturn err\n\t}\n\tif other.Address != ag.Address {\n\t\treturn fmt.Errorf(\"cannot merge in AccessGrant for different address\")\n\t}\n\tfor _, p := range other.GetAccessList() {\n\t\tif !ag.HasAccess(p) {\n\t\t\tag.Permissions = append(ag.Permissions, p)\n\t\t}\n\t}\n\treturn nil\n}", "func (_TokenStakingEscrow *TokenStakingEscrowCaller) TokenGrant(opts *bind.CallOpts) (common.Address, error) {\n\tvar (\n\t\tret0 = new(common.Address)\n\t)\n\tout := ret0\n\terr := _TokenStakingEscrow.contract.Call(opts, out, \"tokenGrant\")\n\treturn *ret0, err\n}", "func (u *user) grant(ctx context.Context, db Database, access string) error {\n\tescapedDbName := pathEscape(db.Name())\n\treq, err := u.conn.NewRequest(\"PUT\", path.Join(u.relPath(), \"database\", escapedDbName))\n\tif err != nil {\n\t\treturn WithStack(err)\n\t}\n\tinput := struct {\n\t\tGrant string `arangodb:\"grant\" json:\"grant\"`\n\t}{\n\t\tGrant: access,\n\t}\n\tif _, err := req.SetBody(input); err != nil {\n\t\treturn WithStack(err)\n\t}\n\tresp, err := u.conn.Do(ctx, req)\n\tif err != nil {\n\t\treturn WithStack(err)\n\t}\n\tif err := resp.CheckStatus(200); err != nil {\n\t\treturn WithStack(err)\n\t}\n\treturn nil\n}", "func (_PermInterface *PermInterfaceTransactor) AddOrg(opts *bind.TransactOpts, _orgId string, _enodeId string, _ip string, _port uint16, _raftport uint16, _account common.Address) (*types.Transaction, error) {\n\treturn _PermInterface.contract.Transact(opts, \"addOrg\", _orgId, _enodeId, _ip, _port, _raftport, _account)\n}", "func (_LvRecordableStream *LvRecordableStreamTransactor) RunGrant(opts *bind.TransactOpts, arg0 *big.Int, arg1 bool) (*types.Transaction, error) {\n\treturn _LvRecordableStream.contract.Transact(opts, \"runGrant\", arg0, arg1)\n}", "func (s *Session) GrantDB(database, user, grant string) error {\n\tok, err := s.client.UserExists(context.Background(), user)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error in finding user %s\", err)\n\t}\n\tif !ok {\n\t\treturn fmt.Errorf(\"user %s does not exist\", user)\n\t}\n\tdbuser, err := s.client.User(context.Background(), user)\n\tif err != nil {\n\t\treturn fmt.Errorf(\n\t\t\t\"error in getting user %s from database %s\",\n\t\t\tuser,\n\t\t\terr,\n\t\t)\n\t}\n\tdbh, err := s.client.Database(context.Background(), database)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"cannot get a database instance %s\", err)\n\t}\n\terr = dbuser.SetDatabaseAccess(context.Background(), dbh, getGrant(grant))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error in setting database access %s\", err)\n\t}\n\n\treturn nil\n}", "func (client *Client) GrantAccountPrivilege(request *GrantAccountPrivilegeRequest) (_result *GrantAccountPrivilegeResponse, _err error) {\n\truntime := &util.RuntimeOptions{}\n\t_result = &GrantAccountPrivilegeResponse{}\n\t_body, _err := client.GrantAccountPrivilegeWithOptions(request, runtime)\n\tif _err != nil {\n\t\treturn _result, _err\n\t}\n\t_result = _body\n\treturn _result, _err\n}", "func (s *BasePlSqlParserListener) EnterGrant_statement(ctx *Grant_statementContext) {}", "func (k *Kerberos) Grant(encTGT, appID, encAuthenticator string) (*KerberosGrantResult, error) {\n\ttgt := &kerberosTGT{}\n\tif err := k.decrypt(encTGT, k.tgsSecretKey, tgt); err != nil {\n\t\treturn nil, errTGTInvalid\n\t}\n\tif tgt.Expired < time.Now().Unix() {\n\t\treturn nil, errTGTInvalid\n\t}\n\tauthenticator := &kerberosAuthenticator{}\n\tif err := k.decrypt(encAuthenticator, tgt.CTSK, authenticator); err != nil {\n\t\treturn nil, errAuthenticatorInvalid\n\t}\n\n\tvar appSecret string\n\tif appID == \"cell\" {\n\t\tappSecret = k.appSecretKey\n\t} else {\n\t\terr := k.db.QueryRowContext(\n\t\t\tdbCtx(),\n\t\t\t\"SELECT `secret` FROM `app` WHERE `app_id`=? LIMIT 1\",\n\t\t\tappID,\n\t\t).Scan(&appSecret)\n\t\tswitch {\n\t\tcase err == sql.ErrNoRows:\n\t\t\treturn nil, errAppNotExist\n\t\tcase err != nil:\n\t\t\tpanic(err)\n\t\t}\n\t}\n\n\tst := &kerberosServiceTicket{\n\t\tCSSK: RandToken(),\n\t\tUsername: authenticator.Username,\n\t\tExpired: time.Now().Add(2 * time.Hour).Unix(),\n\t}\n\n\tencCSSK := k.encrypt(st.CSSK, tgt.CTSK)\n\tencST := k.encrypt(st, appSecret)\n\n\tres := &KerberosGrantResult{\n\t\tencCSSK,\n\t\tencST,\n\t}\n\treturn res, nil\n}", "func StageGrant(db, schema, stage string) GrantBuilder {\n\treturn &CurrentGrantBuilder{\n\t\tname: stage,\n\t\tqualifiedName: fmt.Sprintf(`\"%v\".\"%v\".\"%v\"`, db, schema, stage),\n\t\tgrantType: stageType,\n\t}\n}", "func (ag *AccessGrant) AddAccess(access Access) error {\n\tupdated, err := addAccess(ag.Permissions, access)\n\tif err != nil {\n\t\treturn err\n\t}\n\tag.Permissions = updated\n\treturn nil\n}", "func (g *autoGrant) GrantNeeded(user user.Info, grant *api.Grant, w http.ResponseWriter, req *http.Request) (bool, bool, error) {\n\treturn true, false, nil\n}", "func (pga periodicGrantAction) AddToAccount(ctx sdk.Context, rawAccount exported.VestingAccount) error {\n\tpva, ok := rawAccount.(*PeriodicVestingAccount)\n\tif !ok {\n\t\treturn sdkerrors.Wrapf(sdkerrors.ErrNotSupported,\n\t\t\t\"account %s must be a PeriodicVestingAccount, got %T\",\n\t\t\trawAccount.GetAddress(), rawAccount)\n\t}\n\tpva.addGrant(ctx, pga.sk, pga.grantStartTime, pga.grantVestingPeriods, pga.grantCoins)\n\treturn nil\n}", "func (_Storage *StorageTransactor) AddAccount(opts *bind.TransactOpts, addr common.Address, kind uint8, isFrozen bool, parent common.Address) (*types.Transaction, error) {\n\treturn _Storage.contract.Transact(opts, \"addAccount\", addr, kind, isFrozen, parent)\n}", "func (_BaseContent *BaseContentTransactor) AccessGrant(opts *bind.TransactOpts, request_ID *big.Int, access_granted bool, re_key string, encrypted_AES_key string) (*types.Transaction, error) {\n\treturn _BaseContent.contract.Transact(opts, \"accessGrant\", request_ID, access_granted, re_key, encrypted_AES_key)\n}", "func (_LvStreamRightsHolder *LvStreamRightsHolderTransactor) RunGrant(opts *bind.TransactOpts, arg0 *big.Int, arg1 bool) (*types.Transaction, error) {\n\treturn _LvStreamRightsHolder.contract.Transact(opts, \"runGrant\", arg0, arg1)\n}", "func (_PermInterface *PermInterfaceTransactorSession) AddOrg(_orgId string, _enodeId string, _ip string, _port uint16, _raftport uint16, _account common.Address) (*types.Transaction, error) {\n\treturn _PermInterface.Contract.AddOrg(&_PermInterface.TransactOpts, _orgId, _enodeId, _ip, _port, _raftport, _account)\n}", "func (_PermInterface *PermInterfaceSession) AddOrg(_orgId string, _enodeId string, _ip string, _port uint16, _raftport uint16, _account common.Address) (*types.Transaction, error) {\n\treturn _PermInterface.Contract.AddOrg(&_PermInterface.TransactOpts, _orgId, _enodeId, _ip, _port, _raftport, _account)\n}", "func (emptyGrant) GrantNeeded(user user.Info, grant *api.Grant, w http.ResponseWriter, req *http.Request) (bool, bool, error) {\n\treturn false, false, nil\n}", "func (c *managementServiceClient) CreateProjectGrantUserGrant(ctx context.Context, in *ProjectGrantUserGrantCreate, opts ...grpc.CallOption) (*UserGrant, error) {\n\tout := new(UserGrant)\n\terr := c.cc.Invoke(ctx, \"/caos.zitadel.management.api.v1.ManagementService/CreateProjectGrantUserGrant\", in, out, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn out, nil\n}", "func (c *Client) Grant(email string) {\n\tif c.CI {\n\t\temail = strings.ToLower(email)\n\t}\n\tc.mu.Lock()\n\tc.whitelist[email] = struct{}{}\n\tc.mu.Unlock()\n}", "func (_BaseAccessControlGroup *BaseAccessControlGroupTransactor) GrantAccess(opts *bind.TransactOpts, candidate common.Address) (*types.Transaction, error) {\n\treturn _BaseAccessControlGroup.contract.Transact(opts, \"grantAccess\", candidate)\n}", "func (_SingleAuto *SingleAutoTransactor) Add(opts *bind.TransactOpts, _allocPoint *big.Int, _want common.Address, _withUpdate bool, _strat common.Address) (*types.Transaction, error) {\n\treturn _SingleAuto.contract.Transact(opts, \"add\", _allocPoint, _want, _withUpdate, _strat)\n}", "func (_TokenStakingEscrow *TokenStakingEscrowSession) TokenGrant() (common.Address, error) {\n\treturn _TokenStakingEscrow.Contract.TokenGrant(&_TokenStakingEscrow.CallOpts)\n}", "func (as AccountStorage) SetGrantPubKey(ctx sdk.Context, me types.AccountKey, pubKey crypto.PubKey, grantPubKey *GrantPubKey) sdk.Error {\n\tstore := ctx.KVStore(as.key)\n\tgrantPubKeyByte, err := as.cdc.MarshalJSON(*grantPubKey)\n\tif err != nil {\n\t\treturn ErrFailedToMarshalGrantPubKey(err)\n\t}\n\tstore.Set(getGrantPubKeyKey(me, pubKey), grantPubKeyByte)\n\treturn nil\n}", "func AddTenant(m *Tenant) (id int64, err error) {\n\to := orm.NewOrm()\n\tid, err = o.Insert(m)\n\treturn\n}", "func SchemaGrant(db, schema string) GrantBuilder {\n\treturn &CurrentGrantBuilder{\n\t\tname: schema,\n\t\tqualifiedName: fmt.Sprintf(`\"%v\".\"%v\"`, db, schema),\n\t\tgrantType: schemaType,\n\t}\n}", "func (_TokenStakingEscrow *TokenStakingEscrowCallerSession) TokenGrant() (common.Address, error) {\n\treturn _TokenStakingEscrow.Contract.TokenGrant(&_TokenStakingEscrow.CallOpts)\n}", "func (_ChpRegistry *ChpRegistryTransactor) AddPauser(opts *bind.TransactOpts, account common.Address) (*types.Transaction, error) {\n\treturn _ChpRegistry.contract.Transact(opts, \"addPauser\", account)\n}", "func DatabaseGrant() *TerraformGrantResource {\n\treturn &TerraformGrantResource{\n\t\tResource: &schema.Resource{\n\t\t\tCreate: CreateDatabaseGrant,\n\t\t\tRead: ReadDatabaseGrant,\n\t\t\tDelete: DeleteDatabaseGrant,\n\t\t\tUpdate: UpdateDatabaseGrant,\n\n\t\t\tSchema: databaseGrantSchema,\n\t\t\tImporter: &schema.ResourceImporter{\n\t\t\t\tStateContext: schema.ImportStatePassthroughContext,\n\t\t\t},\n\t\t},\n\t\tValidPrivs: validDatabasePrivileges,\n\t}\n}", "func (_Storage *StorageTransactor) GrantPermission(opts *bind.TransactOpts, kind uint8, addr common.Address) (*types.Transaction, error) {\n\treturn _Storage.contract.Transact(opts, \"grantPermission\", kind, addr)\n}", "func (p *jsiiProxy_ProfilingGroup) GrantPublish(grantee awsiam.IGrantable) awsiam.Grant {\n\tvar returns awsiam.Grant\n\n\t_jsii_.Invoke(\n\t\tp,\n\t\t\"grantPublish\",\n\t\t[]interface{}{grantee},\n\t\t&returns,\n\t)\n\n\treturn returns\n}", "func (s *Service) GrantAccessToken(client *models.OauthClient, user *models.OauthUser, expiresIn int, scope string) (*models.OauthAccessToken, error) {\n\t// Begin a transaction\n\ttx := s.db.Begin()\n\n\t// Delete expired access tokens\n\tquery := tx.Unscoped().Where(\"client_id = ?\", client.ID)\n\tif user != nil && len([]rune(user.ID)) > 0 {\n\t\tquery = query.Where(\"user_id = ?\", user.ID)\n\t} else {\n\t\tquery = query.Where(\"user_id IS NULL\")\n\t}\n\tif err := query.Where(\"expires_at <= ?\", time.Now()).Delete(new(models.OauthAccessToken)).Error; err != nil {\n\t\ttx.Rollback() // rollback the transaction\n\t\treturn nil, err\n\t}\n\n\t// Create a new access token\n\taccessToken := models.NewOauthAccessToken(client, user, expiresIn, scope)\n\tif err := tx.Create(accessToken).Error; err != nil {\n\t\ttx.Rollback() // rollback the transaction\n\t\treturn nil, err\n\t}\n\taccessToken.Client = client\n\taccessToken.User = user\n\n\t// Commit the transaction\n\tif err := tx.Commit().Error; err != nil {\n\t\ttx.Rollback() // rollback the transaction\n\t\treturn nil, err\n\t}\n\n\treturn accessToken, nil\n}", "func (_PermInterface *PermInterfaceTransactor) AddAdminAccount(opts *bind.TransactOpts, _acct common.Address) (*types.Transaction, error) {\n\treturn _PermInterface.contract.Transact(opts, \"addAdminAccount\", _acct)\n}", "func GrantByName(name string) Grant {\n\tfor g, grantName := range grantNameMap {\n\t\tif grantName == name {\n\t\t\treturn g\n\t\t}\n\t}\n\n\treturn GrantNone\n}", "func (n *Node) DeleteGrant(ctx context.Context, g *provider.Grant, acquireLock bool) (err error) {\n\n\tvar attr string\n\tif g.Grantee.Type == provider.GranteeType_GRANTEE_TYPE_GROUP {\n\t\tattr = prefixes.GrantGroupAcePrefix + g.Grantee.GetGroupId().OpaqueId\n\t} else {\n\t\tattr = prefixes.GrantUserAcePrefix + g.Grantee.GetUserId().OpaqueId\n\t}\n\n\tif err = n.RemoveXattr(ctx, attr, acquireLock); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (_PermInterface *PermInterfaceSession) AddNode(_orgId string, _enodeId string, _ip string, _port uint16, _raftport uint16) (*types.Transaction, error) {\n\treturn _PermInterface.Contract.AddNode(&_PermInterface.TransactOpts, _orgId, _enodeId, _ip, _port, _raftport)\n}", "func (k *Keeper) Add(ctx sdk.Context, address sdk.AccAddress, coins sdk.Coins) error {\n\tif err := k.bank.SendCoinsFromAccountToModule(ctx, address, types.ModuleName, coins); err != nil {\n\t\treturn err\n\t}\n\n\tdeposit, found := k.GetDeposit(ctx, address)\n\tif !found {\n\t\tdeposit = types.Deposit{\n\t\t\tAddress: address.String(),\n\t\t\tCoins: sdk.NewCoins(),\n\t\t}\n\t}\n\n\tdeposit.Coins = deposit.Coins.Add(coins...)\n\tif deposit.Coins.IsAnyNegative() {\n\t\treturn types.ErrorInsufficientDepositFunds\n\t}\n\n\tk.SetDeposit(ctx, deposit)\n\treturn nil\n}", "func (_PermInterface *PermInterfaceTransactor) AddNode(opts *bind.TransactOpts, _orgId string, _enodeId string, _ip string, _port uint16, _raftport uint16) (*types.Transaction, error) {\n\treturn _PermInterface.contract.Transact(opts, \"addNode\", _orgId, _enodeId, _ip, _port, _raftport)\n}", "func (c *managementServiceClient) CreateProjectUserGrant(ctx context.Context, in *UserGrantCreate, opts ...grpc.CallOption) (*UserGrant, error) {\n\tout := new(UserGrant)\n\terr := c.cc.Invoke(ctx, \"/caos.zitadel.management.api.v1.ManagementService/CreateProjectUserGrant\", in, out, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn out, nil\n}", "func (g *redirectGrant) GrantNeeded(user user.Info, grant *api.Grant, w http.ResponseWriter, req *http.Request) (bool, bool, error) {\n\tredirectURL, err := url.Parse(g.url)\n\tif err != nil {\n\t\treturn false, false, err\n\t}\n\tredirectURL.RawQuery = url.Values{\n\t\t\"then\": {req.URL.String()},\n\t\t\"client_id\": {grant.Client.GetId()},\n\t\t\"scope\": {grant.Scope},\n\t\t\"redirect_uri\": {grant.RedirectURI},\n\t}.Encode()\n\thttp.Redirect(w, req, redirectURL.String(), http.StatusFound)\n\treturn false, true, nil\n}", "func (m *MockupAccountProvider) Add(account entities.Account) derrors.Error {\n\tm.Lock()\n\tdefer m.Unlock()\n\n\tif !m.unsafeExists(account.AccountId) {\n\t\tm.accounts[account.AccountId] = account\n\t\tm.accountNames[account.Name] = true\n\t\treturn nil\n\t}\n\treturn derrors.NewAlreadyExistsError(account.AccountId)\n}", "func (service *Service) AddUser(accountId types.ID) error {\n\t// you can be delegate of a user after the user designate you as a delegate.\n\tif isDelegate, err := service.accounts.IsDelegateOf(service.addr, accountId); err != nil {\n\t\treturn errors.Wrapf(err, \"failed to call Accounts.IsDelegateOf\")\n\t} else if !isDelegate {\n\t\treturn ErrDelegationNotAllowed\n\t}\n\tservice.accountIds = append(service.accountIds, accountId)\n\treturn nil\n}", "func (_PermInterface *PermInterfaceTransactorSession) AddNode(_orgId string, _enodeId string, _ip string, _port uint16, _raftport uint16) (*types.Transaction, error) {\n\treturn _PermInterface.Contract.AddNode(&_PermInterface.TransactOpts, _orgId, _enodeId, _ip, _port, _raftport)\n}", "func (aaa *TierService) GrantUserExp(input *tier.GrantUserExpParams) (*seasonpassclientmodels.UserSeasonSummary, error) {\n\ttoken, err := aaa.TokenRepository.GetToken()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tok, badRequest, err := aaa.Client.Tier.GrantUserExp(input, client.BearerToken(*token.AccessToken))\n\tif badRequest != nil {\n\t\treturn nil, badRequest\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn ok.GetPayload(), nil\n}", "func ViewGrant(db, schema, view string) GrantBuilder {\n\treturn &CurrentGrantBuilder{\n\t\tname: view,\n\t\tqualifiedName: fmt.Sprintf(`\"%v\".\"%v\".\"%v\"`, db, schema, view),\n\t\tgrantType: viewType,\n\t}\n}", "func (o LookupGrantResultOutput) GrantName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v LookupGrantResult) *string { return v.GrantName }).(pulumi.StringPtrOutput)\n}", "func (s *BasePlSqlParserListener) EnterGrant_object_name(ctx *Grant_object_nameContext) {}", "func (_Contracts *ContractsTransactor) AddProposal(opts *bind.TransactOpts, _name [32]byte, _proposalId *big.Int, _endDate *big.Int) (*types.Transaction, error) {\n\treturn _Contracts.contract.Transact(opts, \"addProposal\", _name, _proposalId, _endDate)\n}", "func (m *Manager) Add(transfer *Transfer) {\n\tm.mu.Lock()\n\tdefer m.mu.Unlock()\n\n\tm.transfers[transfer.Server.ID()] = transfer\n}", "func (mr *MockFormatterMockRecorder) AccessGrant(e interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"AccessGrant\", reflect.TypeOf((*MockFormatter)(nil).AccessGrant), e)\n}", "func (mapper GovMapper) AddDeposit(ctx context.Context, proposalID uint64, depositorAddr btypes.Address, depositAmount uint64) (btypes.Error, bool) {\n\tproposal, ok := mapper.GetProposal(proposalID)\n\tif !ok {\n\t\treturn ErrUnknownProposal(proposalID), false\n\t}\n\n\taccountMapper := ctx.Mapper(account.AccountMapperName).(*account.AccountMapper)\n\taccount := accountMapper.GetAccount(depositorAddr).(*types.QOSAccount)\n\taccount.MustMinusQOS(btypes.NewInt(int64(depositAmount)))\n\taccountMapper.SetAccount(account)\n\n\t// Update proposal\n\tproposal.TotalDeposit = proposal.TotalDeposit + depositAmount\n\tmapper.SetProposal(proposal)\n\n\t// Check if deposit has provided sufficient total funds to transition the proposal into the voting period\n\tactivatedVotingPeriod := false\n\tif proposal.Status == gtypes.StatusDepositPeriod && proposal.TotalDeposit >= mapper.GetParams(ctx).MinDeposit {\n\t\tmapper.activateVotingPeriod(ctx, proposal)\n\t\tactivatedVotingPeriod = true\n\t}\n\n\t// Add or update deposit object\n\tcurrDeposit, found := mapper.GetDeposit(proposalID, depositorAddr)\n\tif !found {\n\t\tnewDeposit := gtypes.Deposit{depositorAddr, proposalID, depositAmount}\n\t\tmapper.setDeposit(proposalID, depositorAddr, newDeposit)\n\t} else {\n\t\tcurrDeposit.Amount = currDeposit.Amount + depositAmount\n\t\tmapper.setDeposit(proposalID, depositorAddr, currDeposit)\n\t}\n\n\treturn nil, activatedVotingPeriod\n}", "func Grant(uid int, ip, mac string) {\n\tif res, e := exec.Command(*iptables,\n\t\t\"-t mangle -I internet 1 -m mac --mac-source\", mac, \"-s\", ip,\n\t\t\"-j RETURN\").Output(); e != nil {\n\n\t\tlog.Printf(\"[EE] %s: %s\", e.Error(), string(res))\n\t\treturn\n\t}\n\n\tvar ttl time.Duration // TODO: calculate and set\n\ttimers[uid] = time.AfterFunc(ttl, func() {\n\t\tblock(uid, ip, mac)\n\t})\n}", "func (*ProjectGrantMemberAdd) Descriptor() ([]byte, []int) {\n\treturn file_management_proto_rawDescGZIP(), []int{119}\n}", "func (_Pausable *PausableTransactor) AddPauser(opts *bind.TransactOpts, account common.Address) (*types.Transaction, error) {\n\treturn _Pausable.contract.Transact(opts, \"addPauser\", account)\n}", "func DatabaseGrant(name string) GrantBuilder {\n\treturn &CurrentGrantBuilder{\n\t\tname: name,\n\t\tqualifiedName: fmt.Sprintf(`\"%v\"`, name),\n\t\tgrantType: databaseType,\n\t}\n}", "func (ssa *SharedSecretAuthorizer) AddUser(userId string, password string) {\n\tssa.mu.Lock()\n\tdefer ssa.mu.Unlock()\n\tssa.allowedUsers[userId] = password\n}", "func (*ProjectGrantMemberAdd) Descriptor() ([]byte, []int) {\n\treturn file_management_proto_rawDescGZIP(), []int{116}\n}", "func (_Rootchain *RootchainTransactor) AddToken(opts *bind.TransactOpts, _token common.Address) (*types.Transaction, error) {\n\treturn _Rootchain.contract.Transact(opts, \"addToken\", _token)\n}", "func (s *Server) AddPlant(ctx context.Context, plant *Plant) (*Feedback, error) {\n\t_, err := addPlantToDB(plant)\n\tif err != nil {\n\t\tlog.Fatalf(\"Failure adding this plant to the DB: %s\\n\", err)\n\t}\n\n\treturn &Feedback{Success: true, Message: \"added\"}, nil\n}", "func (_ERC20HecoManager *ERC20HecoManagerTransactor) AddToken(opts *bind.TransactOpts, tokenManager common.Address, hynTokenAddr common.Address, name string, symbol string, decimals uint8) (*types.Transaction, error) {\n\treturn _ERC20HecoManager.contract.Transact(opts, \"addToken\", tokenManager, hynTokenAddr, name, symbol, decimals)\n}", "func (_TokenVesting *TokenVestingTransactor) AddToken(opts *bind.TransactOpts, _token common.Address, _vestingBeneficiary common.Address, _vestingPeriodInWeeks *big.Int) (*types.Transaction, error) {\n\treturn _TokenVesting.contract.Transact(opts, \"addToken\", _token, _vestingBeneficiary, _vestingPeriodInWeeks)\n}", "func (cga clawbackGrantAction) AddToAccount(ctx sdk.Context, rawAccount exported.VestingAccount) error {\n\tcva, ok := rawAccount.(*ClawbackVestingAccount)\n\tif !ok {\n\t\treturn sdkerrors.Wrapf(sdkerrors.ErrNotSupported,\n\t\t\t\"account %s must be a ClawbackVestingAccount, got %T\",\n\t\t\trawAccount.GetAddress(), rawAccount)\n\t}\n\tif cga.funderAddress != cva.FunderAddress {\n\t\treturn sdkerrors.Wrapf(sdkerrors.ErrInvalidRequest, \"account %s can only accept grants from account %s\",\n\t\t\trawAccount.GetAddress(), cva.FunderAddress)\n\t}\n\tcva.addGrant(ctx, cga.sk, cga.grantStartTime, cga.grantLockupPeriods, cga.grantVestingPeriods, cga.grantCoins)\n\treturn nil\n}", "func (_ElvToken *ElvTokenTransactor) AddPauser(opts *bind.TransactOpts, account common.Address) (*types.Transaction, error) {\n\treturn _ElvToken.contract.Transact(opts, \"addPauser\", account)\n}", "func (_BaseLibrary *BaseLibraryTransactor) AddReviewerGroup(opts *bind.TransactOpts, group common.Address) (*types.Transaction, error) {\n\treturn _BaseLibrary.contract.Transact(opts, \"addReviewerGroup\", group)\n}", "func (_PoC *PoCTransactor) GrantAccess(opts *bind.TransactOpts, _to common.Address) (*types.Transaction, error) {\n\treturn _PoC.contract.Transact(opts, \"grantAccess\", _to)\n}", "func (c *managementServiceClient) ReactivateProjectGrantUserGrant(ctx context.Context, in *ProjectGrantUserGrantID, opts ...grpc.CallOption) (*UserGrant, error) {\n\tout := new(UserGrant)\n\terr := c.cc.Invoke(ctx, \"/caos.zitadel.management.api.v1.ManagementService/ReactivateProjectGrantUserGrant\", in, out, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn out, nil\n}", "func (_PermInterface *PermInterfaceSession) AddAdminAccount(_acct common.Address) (*types.Transaction, error) {\n\treturn _PermInterface.Contract.AddAdminAccount(&_PermInterface.TransactOpts, _acct)\n}", "func GrantUserPriv(db *sql.DB, dbname string) (int64, error) {\n\tres, err := db.Exec(fmt.Sprintf(\"GRANT ALL PRIVILEGES ON %s.* TO '%s'@'localhost' IDENTIFIED BY '%s';\", dbname, dbname, dbname))\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn res.RowsAffected()\n}", "func (_Storage *StorageTransactorSession) AddAccount(addr common.Address, kind uint8, isFrozen bool, parent common.Address) (*types.Transaction, error) {\n\treturn _Storage.Contract.AddAccount(&_Storage.TransactOpts, addr, kind, isFrozen, parent)\n}", "func (_PermInterface *PermInterfaceTransactorSession) AddAdminAccount(_acct common.Address) (*types.Transaction, error) {\n\treturn _PermInterface.Contract.AddAdminAccount(&_PermInterface.TransactOpts, _acct)\n}", "func (_Contracts *ContractsTransactorSession) AddProposal(_name [32]byte, _proposalId *big.Int, _endDate *big.Int) (*types.Transaction, error) {\n\treturn _Contracts.Contract.AddProposal(&_Contracts.TransactOpts, _name, _proposalId, _endDate)\n}", "func NewPeriodicGrantAction(\n\tsk StakingKeeper,\n\tgrantStartTime int64,\n\tgrantVestingPeriods []Period,\n\tgrantCoins sdk.Coins,\n) exported.AddGrantAction {\n\treturn periodicGrantAction{\n\t\tsk: sk,\n\t\tgrantStartTime: grantStartTime,\n\t\tgrantVestingPeriods: grantVestingPeriods,\n\t\tgrantCoins: grantCoins,\n\t}\n}", "func (a *ACCOUNT) Add(stmt *sql.Stmt) (string, error) {\n\tpk := GenerateUUID(UndashedUUID)\n\t_, err := stmt.Exec(pk, a.Email, a.APICode)\n\n\treturn pk, err\n}", "func (_BaseAccessControlGroup *BaseAccessControlGroupTransactor) GrantManagerAccess(opts *bind.TransactOpts, manager common.Address) (*types.Transaction, error) {\n\treturn _BaseAccessControlGroup.contract.Transact(opts, \"grantManagerAccess\", manager)\n}", "func (c *managementServiceClient) UpdateProjectGrantUserGrant(ctx context.Context, in *ProjectGrantUserGrantUpdate, opts ...grpc.CallOption) (*UserGrant, error) {\n\tout := new(UserGrant)\n\terr := c.cc.Invoke(ctx, \"/caos.zitadel.management.api.v1.ManagementService/UpdateProjectGrantUserGrant\", in, out, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn out, nil\n}", "func (_ERC20Pausable *ERC20PausableTransactor) AddPauser(opts *bind.TransactOpts, account common.Address) (*types.Transaction, error) {\n\treturn _ERC20Pausable.contract.Transact(opts, \"addPauser\", account)\n}", "func addTransaction(db meddler.DB, lender *User, debtor *User, amount int, expense *Expense) (*Transaction, error) {\n trans := new(Transaction)\n trans.LenderId = lender.Id\n trans.DebtorId = debtor.Id\n trans.Amount = amount\n trans.Date = expense.Date\n trans.ExpenseId = expense.Id\n\n err := meddler.Insert(db, \"transactions\", trans)\n if err != nil {\n return nil, err\n }\n\n lender.UpdateBalance(db, amount)\n debtor.UpdateBalance(db, -amount)\n\n return trans, nil\n}", "func (_Contracts *ContractsSession) AddProposal(_name [32]byte, _proposalId *big.Int, _endDate *big.Int) (*types.Transaction, error) {\n\treturn _Contracts.Contract.AddProposal(&_Contracts.TransactOpts, _name, _proposalId, _endDate)\n}", "func NewRedirectGrant(url string) GrantHandler {\n\treturn &redirectGrant{url}\n}", "func (_Storage *StorageTransactorSession) GrantPermission(kind uint8, addr common.Address) (*types.Transaction, error) {\n\treturn _Storage.Contract.GrantPermission(&_Storage.TransactOpts, kind, addr)\n}", "func (p *PubNub) GrantAccess(a *Authenticate, c ChannelManager) error {\n\t// read and write access can be optional later on.\n\tsettings := &pubnub.AuthSettings{\n\t\tChannelName: c.PrepareName(),\n\t\tCanRead: true,\n\t\tCanWrite: true,\n\t\tTTL: 0,\n\t\tToken: a.Account.Token,\n\t}\n\n\treturn p.grantAccess(settings)\n}", "func (_AnchorChain *AnchorChainTransactor) AddUser(opts *bind.TransactOpts, user common.Address) (*types.Transaction, error) {\n\treturn _AnchorChain.contract.Transact(opts, \"addUser\", user)\n}", "func AddVendor(\n\tt *testing.T,\n\tsim *backends.SimulatedBackend,\n\tauth *bind.TransactOpts,\n\tcontract *bindingsm.Vendingmachine,\n\tcontractAddress common.Address,\n) error {\n\ttx, err := contract.AddVendor(auth, \"lays\", contractAddress)\n\tif err != nil {\n\t\treturn err\n\t}\n\tsim.Commit()\n\tif _, err := bind.WaitMined(context.Background(), sim, tx); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (k *Oauth2CredsCollection) Add(oauth2Cred Oauth2Credential) error {\n\ttxn := k.db.Txn(true)\n\tdefer txn.Abort()\n\terr := txn.Insert(oauth2CredTableName, &oauth2Cred)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"insert failed\")\n\t}\n\ttxn.Commit()\n\treturn nil\n}", "func AddTenant(t Tenant, db *database.DB) (*Tenant, error) {\n\n\tvar temp Tenant\n\n\tsearchres := db.Client.Where(\"name = ?\", t.Name).First(&temp)\n\tif searchres.Error == nil {\n\t\t// setting tenant ID to object found in DB\n\t\t// for error handling\n\t\tfmt.Println(\"found %v\", temp)\n\n\t\treturn &temp, &TenantAlreadyExist{Err: errors.New(\"error creating tenant\"), FoundID: temp.ID.String()}\n\t}\n\n\t// Create new entry\n\tresult := db.Client.Create(&t)\n\tif result.Error != nil {\n\t\t// log.Fatal(result.Error)\n\t\treturn nil, result.Error\n\t}\n\treturn &t, nil\n}", "func (_Storage *StorageSession) GrantPermission(kind uint8, addr common.Address) (*types.Transaction, error) {\n\treturn _Storage.Contract.GrantPermission(&_Storage.TransactOpts, kind, addr)\n}" ]
[ "0.6638425", "0.63351303", "0.63263184", "0.60253334", "0.60100543", "0.5991094", "0.59736663", "0.5939039", "0.5906749", "0.5818377", "0.5752371", "0.5751387", "0.57154185", "0.5666535", "0.55915976", "0.5591315", "0.55844253", "0.55637395", "0.5555593", "0.5406534", "0.54049385", "0.5388819", "0.5380899", "0.53795195", "0.5370649", "0.5368041", "0.530638", "0.526977", "0.52629954", "0.5244913", "0.521221", "0.5170941", "0.51709217", "0.5168909", "0.51647264", "0.5133919", "0.51228136", "0.51092994", "0.51010257", "0.5093442", "0.50872844", "0.5081075", "0.507517", "0.5062546", "0.5038109", "0.5023695", "0.49890846", "0.49833968", "0.49709094", "0.49623662", "0.49489453", "0.49387747", "0.4934344", "0.49255168", "0.4924035", "0.49152964", "0.49121478", "0.49107894", "0.49100402", "0.49055827", "0.49029604", "0.48886913", "0.48777208", "0.4871244", "0.48687083", "0.48444605", "0.48326477", "0.4831198", "0.48301825", "0.48300314", "0.48226088", "0.48197687", "0.48169547", "0.47792187", "0.47763386", "0.47721824", "0.4768116", "0.47666234", "0.47627297", "0.47496438", "0.47488096", "0.47373638", "0.47295186", "0.47279605", "0.47276035", "0.47273508", "0.47272807", "0.4711448", "0.47030208", "0.46932167", "0.46925", "0.46900472", "0.46866703", "0.46843424", "0.4677941", "0.46685266", "0.46645215", "0.465921", "0.46515012", "0.46470106" ]
0.82359046
0
addGrant merges a new periodic vesting grant into an existing PeriodicVestingAccount.
func (pva *PeriodicVestingAccount) addGrant(ctx sdk.Context, sk StakingKeeper, grantStartTime int64, grantVestingPeriods []Period, grantCoins sdk.Coins) { // how much is really delegated? bondedAmt := sk.GetDelegatorBonded(ctx, pva.GetAddress()) unbondingAmt := sk.GetDelegatorUnbonding(ctx, pva.GetAddress()) delegatedAmt := bondedAmt.Add(unbondingAmt) delegated := sdk.NewCoins(sdk.NewCoin(sk.BondDenom(ctx), delegatedAmt)) // discover what has been slashed oldDelegated := pva.DelegatedVesting.Add(pva.DelegatedFree...) slashed := oldDelegated.Sub(coinsMin(oldDelegated, delegated)) // rebase the DV+DF by capping slashed at the current unvested amount unvested := pva.GetVestingCoins(ctx.BlockTime()) newSlashed := coinsMin(unvested, slashed) newTotalDelegated := delegated.Add(newSlashed...) // modify vesting schedule for the new grant newStart, newEnd, newPeriods := DisjunctPeriods(pva.StartTime, grantStartTime, pva.GetVestingPeriods(), grantVestingPeriods) pva.StartTime = newStart pva.EndTime = newEnd pva.VestingPeriods = newPeriods pva.OriginalVesting = pva.OriginalVesting.Add(grantCoins...) // cap DV at the current unvested amount, DF rounds out to newTotalDelegated unvested2 := pva.GetVestingCoins(ctx.BlockTime()) pva.DelegatedVesting = coinsMin(newTotalDelegated, unvested2) pva.DelegatedFree = newTotalDelegated.Sub(pva.DelegatedVesting) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (pva *PeriodicVestingAccount) AddGrant(ctx sdk.Context, action exported.AddGrantAction) error {\n\treturn action.AddToAccount(ctx, pva)\n}", "func (va *ClawbackVestingAccount) addGrant(ctx sdk.Context, sk StakingKeeper, grantStartTime int64, grantLockupPeriods, grantVestingPeriods []Period, grantCoins sdk.Coins) {\n\t// how much is really delegated?\n\tbondedAmt := sk.GetDelegatorBonded(ctx, va.GetAddress())\n\tunbondingAmt := sk.GetDelegatorUnbonding(ctx, va.GetAddress())\n\tdelegatedAmt := bondedAmt.Add(unbondingAmt)\n\tdelegated := sdk.NewCoins(sdk.NewCoin(sk.BondDenom(ctx), delegatedAmt))\n\n\t// discover what has been slashed\n\toldDelegated := va.DelegatedVesting.Add(va.DelegatedFree...)\n\tslashed := oldDelegated.Sub(coinsMin(oldDelegated, delegated))\n\n\t// rebase the DV + DF by capping slashed at the current unvested amount\n\tunvested := va.OriginalVesting.Sub(va.GetVestedOnly(ctx.BlockTime()))\n\tnewSlashed := coinsMin(slashed, unvested)\n\tnewDelegated := delegated.Add(newSlashed...)\n\n\t// modify schedules for the new grant\n\tnewLockupStart, newLockupEnd, newLockupPeriods := DisjunctPeriods(va.StartTime, grantStartTime, va.LockupPeriods, grantLockupPeriods)\n\tnewVestingStart, newVestingEnd, newVestingPeriods := DisjunctPeriods(va.StartTime, grantStartTime,\n\t\tva.GetVestingPeriods(), grantVestingPeriods)\n\tif newLockupStart != newVestingStart {\n\t\tpanic(\"bad start time calculation\")\n\t}\n\tva.StartTime = newLockupStart\n\tva.EndTime = max64(newLockupEnd, newVestingEnd)\n\tva.LockupPeriods = newLockupPeriods\n\tva.VestingPeriods = newVestingPeriods\n\tva.OriginalVesting = va.OriginalVesting.Add(grantCoins...)\n\n\t// cap DV at the current unvested amount, DF rounds out to newDelegated\n\tunvested2 := va.GetVestingCoins(ctx.BlockTime())\n\tva.DelegatedVesting = coinsMin(newDelegated, unvested2)\n\tva.DelegatedFree = newDelegated.Sub(va.DelegatedVesting)\n}", "func NewPeriodicGrantAction(\n\tsk StakingKeeper,\n\tgrantStartTime int64,\n\tgrantVestingPeriods []Period,\n\tgrantCoins sdk.Coins,\n) exported.AddGrantAction {\n\treturn periodicGrantAction{\n\t\tsk: sk,\n\t\tgrantStartTime: grantStartTime,\n\t\tgrantVestingPeriods: grantVestingPeriods,\n\t\tgrantCoins: grantCoins,\n\t}\n}", "func (ag *AccessGrant) MergeAdd(other AccessGrant) error {\n\tif err := other.Validate(); err != nil {\n\t\treturn err\n\t}\n\tif other.Address != ag.Address {\n\t\treturn fmt.Errorf(\"cannot merge in AccessGrant for different address\")\n\t}\n\tfor _, p := range other.GetAccessList() {\n\t\tif !ag.HasAccess(p) {\n\t\t\tag.Permissions = append(ag.Permissions, p)\n\t\t}\n\t}\n\treturn nil\n}", "func (pga periodicGrantAction) AddToAccount(ctx sdk.Context, rawAccount exported.VestingAccount) error {\n\tpva, ok := rawAccount.(*PeriodicVestingAccount)\n\tif !ok {\n\t\treturn sdkerrors.Wrapf(sdkerrors.ErrNotSupported,\n\t\t\t\"account %s must be a PeriodicVestingAccount, got %T\",\n\t\t\trawAccount.GetAddress(), rawAccount)\n\t}\n\tpva.addGrant(ctx, pga.sk, pga.grantStartTime, pga.grantVestingPeriods, pga.grantCoins)\n\treturn nil\n}", "func (ge *CurrentGrantExecutable) Grant(p string) string {\n\tvar template string\n\tif p == `OWNERSHIP` {\n\t\ttemplate = `GRANT %v ON %v %v TO %v \"%v\" COPY CURRENT GRANTS`\n\t} else {\n\t\ttemplate = `GRANT %v ON %v %v TO %v \"%v\"`\n\t}\n\treturn fmt.Sprintf(template,\n\t\tp, ge.grantType, ge.grantName, ge.granteeType, ge.granteeName)\n}", "func StageGrant(db, schema, stage string) GrantBuilder {\n\treturn &CurrentGrantBuilder{\n\t\tname: stage,\n\t\tqualifiedName: fmt.Sprintf(`\"%v\".\"%v\".\"%v\"`, db, schema, stage),\n\t\tgrantType: stageType,\n\t}\n}", "func AccountGrant() GrantBuilder {\n\treturn &CurrentGrantBuilder{\n\t\tgrantType: accountType,\n\t}\n}", "func (_LvRecording *LvRecordingTransactor) RunGrant(opts *bind.TransactOpts, arg0 *big.Int, arg1 bool) (*types.Transaction, error) {\n\treturn _LvRecording.contract.Transact(opts, \"runGrant\", arg0, arg1)\n}", "func (s *Session) GrantDB(database, user, grant string) error {\n\tok, err := s.client.UserExists(context.Background(), user)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error in finding user %s\", err)\n\t}\n\tif !ok {\n\t\treturn fmt.Errorf(\"user %s does not exist\", user)\n\t}\n\tdbuser, err := s.client.User(context.Background(), user)\n\tif err != nil {\n\t\treturn fmt.Errorf(\n\t\t\t\"error in getting user %s from database %s\",\n\t\t\tuser,\n\t\t\terr,\n\t\t)\n\t}\n\tdbh, err := s.client.Database(context.Background(), database)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"cannot get a database instance %s\", err)\n\t}\n\terr = dbuser.SetDatabaseAccess(context.Background(), dbh, getGrant(grant))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error in setting database access %s\", err)\n\t}\n\n\treturn nil\n}", "func (r *refreshTokenGranter) Grant(_ context.Context, requestedScopes []string) grants.Grant {\n\treturn grants.Grant{\n\t\tSourceType: \"refresh_token\",\n\t\tSourceID: r.token.ID,\n\t\tScopes: requestedScopes,\n\t\tAccountID: r.token.AccountID,\n\t\tProfileID: r.token.ProfileID,\n\t\tClientID: r.token.ClientID,\n\t\tUsed: false,\n\t}\n}", "func (u *user) grant(ctx context.Context, db Database, access string) error {\n\tescapedDbName := pathEscape(db.Name())\n\treq, err := u.conn.NewRequest(\"PUT\", path.Join(u.relPath(), \"database\", escapedDbName))\n\tif err != nil {\n\t\treturn WithStack(err)\n\t}\n\tinput := struct {\n\t\tGrant string `arangodb:\"grant\" json:\"grant\"`\n\t}{\n\t\tGrant: access,\n\t}\n\tif _, err := req.SetBody(input); err != nil {\n\t\treturn WithStack(err)\n\t}\n\tresp, err := u.conn.Do(ctx, req)\n\tif err != nil {\n\t\treturn WithStack(err)\n\t}\n\tif err := resp.CheckStatus(200); err != nil {\n\t\treturn WithStack(err)\n\t}\n\treturn nil\n}", "func ResourceMonitorGrant(w string) GrantBuilder {\n\treturn &CurrentGrantBuilder{\n\t\tname: w,\n\t\tqualifiedName: fmt.Sprintf(`\"%v\"`, w),\n\t\tgrantType: resourceMonitorType,\n\t}\n}", "func Grant(ctx context.Context, i grantRequest) error {\n\tclient, err := New(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn client.Grant(ctx, i)\n}", "func (_Content *ContentTransactor) RunGrant(opts *bind.TransactOpts, arg0 *big.Int, arg1 bool) (*types.Transaction, error) {\n\treturn _Content.contract.Transact(opts, \"runGrant\", arg0, arg1)\n}", "func (s *BasePlSqlParserListener) EnterGrant_statement(ctx *Grant_statementContext) {}", "func (_TokenStakingEscrow *TokenStakingEscrowCaller) TokenGrant(opts *bind.CallOpts) (common.Address, error) {\n\tvar (\n\t\tret0 = new(common.Address)\n\t)\n\tout := ret0\n\terr := _TokenStakingEscrow.contract.Call(opts, out, \"tokenGrant\")\n\treturn *ret0, err\n}", "func AccountGrant() *TerraformGrantResource {\n\treturn &TerraformGrantResource{\n\t\tResource: &schema.Resource{\n\t\t\tCreate: CreateAccountGrant,\n\t\t\tRead: ReadAccountGrant,\n\t\t\tDelete: DeleteAccountGrant,\n\t\t\tUpdate: UpdateAccountGrant,\n\n\t\t\tSchema: accountGrantSchema,\n\t\t\tImporter: &schema.ResourceImporter{\n\t\t\t\tStateContext: schema.ImportStatePassthroughContext,\n\t\t\t},\n\t\t},\n\t\tValidPrivs: validAccountPrivileges,\n\t}\n}", "func SchemaGrant(db, schema string) GrantBuilder {\n\treturn &CurrentGrantBuilder{\n\t\tname: schema,\n\t\tqualifiedName: fmt.Sprintf(`\"%v\".\"%v\"`, db, schema),\n\t\tgrantType: schemaType,\n\t}\n}", "func (_LvRecordableStream *LvRecordableStreamTransactor) RunGrant(opts *bind.TransactOpts, arg0 *big.Int, arg1 bool) (*types.Transaction, error) {\n\treturn _LvRecordableStream.contract.Transact(opts, \"runGrant\", arg0, arg1)\n}", "func ViewGrant(db, schema, view string) GrantBuilder {\n\treturn &CurrentGrantBuilder{\n\t\tname: view,\n\t\tqualifiedName: fmt.Sprintf(`\"%v\".\"%v\".\"%v\"`, db, schema, view),\n\t\tgrantType: viewType,\n\t}\n}", "func (_TokenVesting *TokenVestingTransactor) AddToken(opts *bind.TransactOpts, _token common.Address, _vestingBeneficiary common.Address, _vestingPeriodInWeeks *big.Int) (*types.Transaction, error) {\n\treturn _TokenVesting.contract.Transact(opts, \"addToken\", _token, _vestingBeneficiary, _vestingPeriodInWeeks)\n}", "func (n *noopRules) Grant(rule *Rule) error {\n\treturn nil\n}", "func (k *Kerberos) Grant(encTGT, appID, encAuthenticator string) (*KerberosGrantResult, error) {\n\ttgt := &kerberosTGT{}\n\tif err := k.decrypt(encTGT, k.tgsSecretKey, tgt); err != nil {\n\t\treturn nil, errTGTInvalid\n\t}\n\tif tgt.Expired < time.Now().Unix() {\n\t\treturn nil, errTGTInvalid\n\t}\n\tauthenticator := &kerberosAuthenticator{}\n\tif err := k.decrypt(encAuthenticator, tgt.CTSK, authenticator); err != nil {\n\t\treturn nil, errAuthenticatorInvalid\n\t}\n\n\tvar appSecret string\n\tif appID == \"cell\" {\n\t\tappSecret = k.appSecretKey\n\t} else {\n\t\terr := k.db.QueryRowContext(\n\t\t\tdbCtx(),\n\t\t\t\"SELECT `secret` FROM `app` WHERE `app_id`=? LIMIT 1\",\n\t\t\tappID,\n\t\t).Scan(&appSecret)\n\t\tswitch {\n\t\tcase err == sql.ErrNoRows:\n\t\t\treturn nil, errAppNotExist\n\t\tcase err != nil:\n\t\t\tpanic(err)\n\t\t}\n\t}\n\n\tst := &kerberosServiceTicket{\n\t\tCSSK: RandToken(),\n\t\tUsername: authenticator.Username,\n\t\tExpired: time.Now().Add(2 * time.Hour).Unix(),\n\t}\n\n\tencCSSK := k.encrypt(st.CSSK, tgt.CTSK)\n\tencST := k.encrypt(st, appSecret)\n\n\tres := &KerberosGrantResult{\n\t\tencCSSK,\n\t\tencST,\n\t}\n\treturn res, nil\n}", "func (p *jsiiProxy_ProfilingGroup) GrantPublish(grantee awsiam.IGrantable) awsiam.Grant {\n\tvar returns awsiam.Grant\n\n\t_jsii_.Invoke(\n\t\tp,\n\t\t\"grantPublish\",\n\t\t[]interface{}{grantee},\n\t\t&returns,\n\t)\n\n\treturn returns\n}", "func (r *jsiiProxy_RepositoryBase) Grant(grantee awsiam.IGrantable, actions ...*string) awsiam.Grant {\n\targs := []interface{}{grantee}\n\tfor _, a := range actions {\n\t\targs = append(args, a)\n\t}\n\n\tvar returns awsiam.Grant\n\n\t_jsii_.Invoke(\n\t\tr,\n\t\t\"grant\",\n\t\targs,\n\t\t&returns,\n\t)\n\n\treturn returns\n}", "func (c *Client) Grant(ctx context.Context, i grantRequest) error {\n\tif i == nil {\n\t\treturn fmt.Errorf(\"missing request\")\n\t}\n\n\tswitch t := i.(type) {\n\tcase *SecretManagerGrantRequest:\n\t\treturn c.secretManagerGrant(ctx, t)\n\tcase *StorageGrantRequest:\n\t\treturn c.storageGrant(ctx, t)\n\tdefault:\n\t\treturn fmt.Errorf(\"unknown grant type %T\", t)\n\t}\n}", "func WarehouseGrant(w string) GrantBuilder {\n\treturn &CurrentGrantBuilder{\n\t\tname: w,\n\t\tqualifiedName: fmt.Sprintf(`\"%v\"`, w),\n\t\tgrantType: warehouseType,\n\t}\n}", "func (c *managementServiceClient) UpdateProjectGrantUserGrant(ctx context.Context, in *ProjectGrantUserGrantUpdate, opts ...grpc.CallOption) (*UserGrant, error) {\n\tout := new(UserGrant)\n\terr := c.cc.Invoke(ctx, \"/caos.zitadel.management.api.v1.ManagementService/UpdateProjectGrantUserGrant\", in, out, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn out, nil\n}", "func (r *jsiiProxy_Repository) Grant(grantee awsiam.IGrantable, actions ...*string) awsiam.Grant {\n\targs := []interface{}{grantee}\n\tfor _, a := range actions {\n\t\targs = append(args, a)\n\t}\n\n\tvar returns awsiam.Grant\n\n\t_jsii_.Invoke(\n\t\tr,\n\t\t\"grant\",\n\t\targs,\n\t\t&returns,\n\t)\n\n\treturn returns\n}", "func (_LvStreamRightsHolder *LvStreamRightsHolderTransactor) RunGrant(opts *bind.TransactOpts, arg0 *big.Int, arg1 bool) (*types.Transaction, error) {\n\treturn _LvStreamRightsHolder.contract.Transact(opts, \"runGrant\", arg0, arg1)\n}", "func IntegrationGrant(w string) GrantBuilder {\n\treturn &CurrentGrantBuilder{\n\t\tname: w,\n\t\tqualifiedName: fmt.Sprintf(`\"%v\"`, w),\n\t\tgrantType: integrationType,\n\t}\n}", "func AddTenant(m *Tenant) (id int64, err error) {\n\to := orm.NewOrm()\n\tid, err = o.Insert(m)\n\treturn\n}", "func GrantByName(name string) Grant {\n\tfor g, grantName := range grantNameMap {\n\t\tif grantName == name {\n\t\t\treturn g\n\t\t}\n\t}\n\n\treturn GrantNone\n}", "func (c *managementServiceClient) ReactivateProjectGrantUserGrant(ctx context.Context, in *ProjectGrantUserGrantID, opts ...grpc.CallOption) (*UserGrant, error) {\n\tout := new(UserGrant)\n\terr := c.cc.Invoke(ctx, \"/caos.zitadel.management.api.v1.ManagementService/ReactivateProjectGrantUserGrant\", in, out, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn out, nil\n}", "func DatabaseGrant(name string) GrantBuilder {\n\treturn &CurrentGrantBuilder{\n\t\tname: name,\n\t\tqualifiedName: fmt.Sprintf(`\"%v\"`, name),\n\t\tgrantType: databaseType,\n\t}\n}", "func (_TokenStakingEscrow *TokenStakingEscrowSession) TokenGrant() (common.Address, error) {\n\treturn _TokenStakingEscrow.Contract.TokenGrant(&_TokenStakingEscrow.CallOpts)\n}", "func (m *Manager) AddPlanToMonitor(plan *entities.DeploymentPlan) {\n\tm.pendingPlans.AddPendingPlan(plan)\n}", "func DatabaseGrant() *TerraformGrantResource {\n\treturn &TerraformGrantResource{\n\t\tResource: &schema.Resource{\n\t\t\tCreate: CreateDatabaseGrant,\n\t\t\tRead: ReadDatabaseGrant,\n\t\t\tDelete: DeleteDatabaseGrant,\n\t\t\tUpdate: UpdateDatabaseGrant,\n\n\t\t\tSchema: databaseGrantSchema,\n\t\t\tImporter: &schema.ResourceImporter{\n\t\t\t\tStateContext: schema.ImportStatePassthroughContext,\n\t\t\t},\n\t\t},\n\t\tValidPrivs: validDatabasePrivileges,\n\t}\n}", "func (n *Node) DeleteGrant(ctx context.Context, g *provider.Grant, acquireLock bool) (err error) {\n\n\tvar attr string\n\tif g.Grantee.Type == provider.GranteeType_GRANTEE_TYPE_GROUP {\n\t\tattr = prefixes.GrantGroupAcePrefix + g.Grantee.GetGroupId().OpaqueId\n\t} else {\n\t\tattr = prefixes.GrantUserAcePrefix + g.Grantee.GetUserId().OpaqueId\n\t}\n\n\tif err = n.RemoveXattr(ctx, attr, acquireLock); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (gq *GrantQuery) addPredicate(pred func(s *sql.Selector)) {\n\tgq.predicates = append(gq.predicates, pred)\n}", "func (_TokenVesting *TokenVestingTransactorSession) AddToken(_token common.Address, _vestingBeneficiary common.Address, _vestingPeriodInWeeks *big.Int) (*types.Transaction, error) {\n\treturn _TokenVesting.Contract.AddToken(&_TokenVesting.TransactOpts, _token, _vestingBeneficiary, _vestingPeriodInWeeks)\n}", "func (_BaseContent *BaseContentTransactor) AccessGrant(opts *bind.TransactOpts, request_ID *big.Int, access_granted bool, re_key string, encrypted_AES_key string) (*types.Transaction, error) {\n\treturn _BaseContent.contract.Transact(opts, \"accessGrant\", request_ID, access_granted, re_key, encrypted_AES_key)\n}", "func (s *BasePlSqlParserListener) EnterGrant_object_name(ctx *Grant_object_nameContext) {}", "func (_TokenVesting *TokenVestingSession) AddToken(_token common.Address, _vestingBeneficiary common.Address, _vestingPeriodInWeeks *big.Int) (*types.Transaction, error) {\n\treturn _TokenVesting.Contract.AddToken(&_TokenVesting.TransactOpts, _token, _vestingBeneficiary, _vestingPeriodInWeeks)\n}", "func (mapper GovMapper) AddDeposit(ctx context.Context, proposalID uint64, depositorAddr btypes.Address, depositAmount uint64) (btypes.Error, bool) {\n\tproposal, ok := mapper.GetProposal(proposalID)\n\tif !ok {\n\t\treturn ErrUnknownProposal(proposalID), false\n\t}\n\n\taccountMapper := ctx.Mapper(account.AccountMapperName).(*account.AccountMapper)\n\taccount := accountMapper.GetAccount(depositorAddr).(*types.QOSAccount)\n\taccount.MustMinusQOS(btypes.NewInt(int64(depositAmount)))\n\taccountMapper.SetAccount(account)\n\n\t// Update proposal\n\tproposal.TotalDeposit = proposal.TotalDeposit + depositAmount\n\tmapper.SetProposal(proposal)\n\n\t// Check if deposit has provided sufficient total funds to transition the proposal into the voting period\n\tactivatedVotingPeriod := false\n\tif proposal.Status == gtypes.StatusDepositPeriod && proposal.TotalDeposit >= mapper.GetParams(ctx).MinDeposit {\n\t\tmapper.activateVotingPeriod(ctx, proposal)\n\t\tactivatedVotingPeriod = true\n\t}\n\n\t// Add or update deposit object\n\tcurrDeposit, found := mapper.GetDeposit(proposalID, depositorAddr)\n\tif !found {\n\t\tnewDeposit := gtypes.Deposit{depositorAddr, proposalID, depositAmount}\n\t\tmapper.setDeposit(proposalID, depositorAddr, newDeposit)\n\t} else {\n\t\tcurrDeposit.Amount = currDeposit.Amount + depositAmount\n\t\tmapper.setDeposit(proposalID, depositorAddr, currDeposit)\n\t}\n\n\treturn nil, activatedVotingPeriod\n}", "func NewGrantDBDriver(store kv.Storage) *GrantDBDriver {\n\treturn &GrantDBDriver{\n\t\tstore: store,\n\t}\n}", "func (_TokenStakingEscrow *TokenStakingEscrowCallerSession) TokenGrant() (common.Address, error) {\n\treturn _TokenStakingEscrow.Contract.TokenGrant(&_TokenStakingEscrow.CallOpts)\n}", "func (c *managementServiceClient) ProjectGrantUserGrantByID(ctx context.Context, in *ProjectGrantUserGrantID, opts ...grpc.CallOption) (*UserGrantView, error) {\n\tout := new(UserGrantView)\n\terr := c.cc.Invoke(ctx, \"/caos.zitadel.management.api.v1.ManagementService/ProjectGrantUserGrantByID\", in, out, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn out, nil\n}", "func ParseGrant(s string) (Grant, error) {\n\tu, err := url.Parse(s)\n\tif err != nil {\n\t\treturn Grant{}, err\n\t}\n\n\tg := Grant{}\n\tg.Provider = u.Scheme\n\tg.Values = []string{u.Opaque}\n\n\tfor key := range u.Query() {\n\t\tval := u.Query().Get(key)\n\t\tswitch key {\n\t\tcase \"ttl\":\n\t\t\td, err := time.ParseDuration(val)\n\t\t\tif err != nil {\n\t\t\t\treturn Grant{}, err\n\t\t\t}\n\t\t\tg.Expires = time.Now().Add(d)\n\t\t}\n\t}\n\treturn g, nil\n}", "func Add(mgr manager.Manager) error {\n\tr := newReconciler(mgr)\n\treturn add(mgr, r, r.SecretTriggerCertMerge)\n}", "func (c *managementServiceClient) UpdateProjectUserGrant(ctx context.Context, in *ProjectUserGrantUpdate, opts ...grpc.CallOption) (*UserGrant, error) {\n\tout := new(UserGrant)\n\terr := c.cc.Invoke(ctx, \"/caos.zitadel.management.api.v1.ManagementService/UpdateProjectUserGrant\", in, out, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn out, nil\n}", "func (client *Client) GrantAccountPrivilege(request *GrantAccountPrivilegeRequest) (_result *GrantAccountPrivilegeResponse, _err error) {\n\truntime := &util.RuntimeOptions{}\n\t_result = &GrantAccountPrivilegeResponse{}\n\t_body, _err := client.GrantAccountPrivilegeWithOptions(request, runtime)\n\tif _err != nil {\n\t\treturn _result, _err\n\t}\n\t_result = _body\n\treturn _result, _err\n}", "func Grant(uid int, ip, mac string) {\n\tif res, e := exec.Command(*iptables,\n\t\t\"-t mangle -I internet 1 -m mac --mac-source\", mac, \"-s\", ip,\n\t\t\"-j RETURN\").Output(); e != nil {\n\n\t\tlog.Printf(\"[EE] %s: %s\", e.Error(), string(res))\n\t\treturn\n\t}\n\n\tvar ttl time.Duration // TODO: calculate and set\n\ttimers[uid] = time.AfterFunc(ttl, func() {\n\t\tblock(uid, ip, mac)\n\t})\n}", "func (p *IssuingAuthorizationApproveParams) AddExpand(f string) {\n\tp.Expand = append(p.Expand, &f)\n}", "func NewRedirectGrant(url string) GrantHandler {\n\treturn &redirectGrant{url}\n}", "func (pm *PendingMgr) addTx(tx *types.Transaction, maxPending uint32) error {\n\n\tpm.Lock()\n\tdefer pm.Unlock()\n\n\tif uint32(len(pm.pendingTxs)) > maxPending {\n\t\treturn errors.ERR_TXPOOL_OUTOFMAX\n\t}\n\n\tpm.pendingTxs[tx.Hash()] = tx\n\treturn nil\n}", "func (c *managementServiceClient) CreateProjectGrantUserGrant(ctx context.Context, in *ProjectGrantUserGrantCreate, opts ...grpc.CallOption) (*UserGrant, error) {\n\tout := new(UserGrant)\n\terr := c.cc.Invoke(ctx, \"/caos.zitadel.management.api.v1.ManagementService/CreateProjectGrantUserGrant\", in, out, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn out, nil\n}", "func (c *Client) Grant(email string) {\n\tif c.CI {\n\t\temail = strings.ToLower(email)\n\t}\n\tc.mu.Lock()\n\tc.whitelist[email] = struct{}{}\n\tc.mu.Unlock()\n}", "func (m *GrantMutation) addPredicate(pred func(s *sql.Selector)) {\n\tm.predicates = append(m.predicates, pred)\n}", "func (client GovernanceClient) addGovernance(ctx context.Context, request common.OCIRequest, binaryReqBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (common.OCIResponse, error) {\n\n\thttpRequest, err := request.HTTPRequest(http.MethodPost, \"/organizations/{organizationId}/tenancies/{organizationTenancyId}/actions/addGovernance\", binaryReqBody, extraHeaders)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar response AddGovernanceResponse\n\tvar httpResponse *http.Response\n\thttpResponse, err = client.Call(ctx, &httpRequest)\n\tdefer common.CloseBodyIfValid(httpResponse)\n\tresponse.RawResponse = httpResponse\n\tif err != nil {\n\t\tapiReferenceLink := \"https://docs.oracle.com/iaas/api/#/en/organizations/20230401/OrganizationTenancy/AddGovernance\"\n\t\terr = common.PostProcessServiceError(err, \"Governance\", \"AddGovernance\", apiReferenceLink)\n\t\treturn response, err\n\t}\n\n\terr = common.UnmarshalResponse(httpResponse, &response)\n\treturn response, err\n}", "func (as AccountStorage) SetGrantPubKey(ctx sdk.Context, me types.AccountKey, pubKey crypto.PubKey, grantPubKey *GrantPubKey) sdk.Error {\n\tstore := ctx.KVStore(as.key)\n\tgrantPubKeyByte, err := as.cdc.MarshalJSON(*grantPubKey)\n\tif err != nil {\n\t\treturn ErrFailedToMarshalGrantPubKey(err)\n\t}\n\tstore.Set(getGrantPubKeyKey(me, pubKey), grantPubKeyByte)\n\treturn nil\n}", "func (g *autoGrant) GrantNeeded(user user.Info, grant *api.Grant, w http.ResponseWriter, req *http.Request) (bool, bool, error) {\n\treturn true, false, nil\n}", "func (_BaseContent *BaseContentFilterer) WatchAccessGrant(opts *bind.WatchOpts, sink chan<- *BaseContentAccessGrant) (event.Subscription, error) {\n\n\tlogs, sub, err := _BaseContent.contract.WatchLogs(opts, \"AccessGrant\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn event.NewSubscription(func(quit <-chan struct{}) error {\n\t\tdefer sub.Unsubscribe()\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase log := <-logs:\n\t\t\t\t// New log arrived, parse the event and forward to the user\n\t\t\t\tevent := new(BaseContentAccessGrant)\n\t\t\t\tif err := _BaseContent.contract.UnpackLog(event, \"AccessGrant\", log); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tevent.Raw = log\n\n\t\t\t\tselect {\n\t\t\t\tcase sink <- event:\n\t\t\t\tcase err := <-sub.Err():\n\t\t\t\t\treturn err\n\t\t\t\tcase <-quit:\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\tcase err := <-sub.Err():\n\t\t\t\treturn err\n\t\t\tcase <-quit:\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t}), nil\n}", "func (o *PostOauthTokenParams) WithGrantType(grantType string) *PostOauthTokenParams {\n\to.SetGrantType(grantType)\n\treturn o\n}", "func (r ResourceGrantsType) Extend(ac AccessControl, subject SubjectType) ResourceGrantsType {\n\tif !subject.IsZero() && ac.Grants[subject] == nil {\n\t\tac.Grants[subject] = make(ResourceGrantsType)\n\t}\n\tac.Grants[subject] = r\n\treturn r\n}", "func appendToLedger(record *LedgerRecord) error {\n\n\t// mad skillz at distributed concurrency\n\ttheLock.Lock()\n\tdefer theLock.Unlock()\n\n\tswitch record.RecType {\n\tcase ClaimBID:\n\t\tclaimingPID := record.PIDs[0]\n\n\t\t// is this BID available?\n\t\t_, ok := PIDsForBID[record.BID]\n\t\tif ok {\n\t\t\treturn errors.New(\"BID '\" + record.BID + \"' has already been claimed by another account\")\n\t\t}\n\n\t\t// map from BID to PID\n\t\tPIDsForBID[record.BID] = map[string]bool{claimingPID: true}\n\n\t\t// map from PID to BID\n\t\tbidsForClaimingPID, ok := BIDsForPID[claimingPID]\n\t\tif !ok {\n\t\t\tbidsForClaimingPID = make(map[string]bool)\n\t\t\tBIDsForPID[claimingPID] = bidsForClaimingPID\n\t\t}\n\t\tbidsForClaimingPID[record.BID] = true\n\n\tcase GrantBID:\n\t\tgranter := record.PIDs[0]\n\t\taccepter := record.PIDs[1]\n\t\tpidsForGrantedBID, ok := PIDsForBID[record.BID]\n\n\t\t// granter has to own PID\n\t\tif !ok {\n\t\t\treturn errors.New(\"no such BID: \" + record.BID)\n\t\t}\n\t\t_, ok = pidsForGrantedBID[granter]\n\t\tif !ok {\n\t\t\treturn errors.New(\"this account is not mapped to BID \" + record.BID)\n\t\t}\n\n\t\t// has key been used?\n\t\t_, ok = KeysUsed[record.Key]\n\t\tif ok {\n\t\t\treturn errors.New(\"public key has been used in a previous grant transaction\")\n\t\t}\n\t\tKeysUsed[record.Key] = true\n\n\t\t// map from BID to accepter PID\n\t\tpidsForGrantedBID[accepter] = true\n\n\t\t// map from accepter PID to BID\n\t\tbidsForAccepter, ok := BIDsForPID[accepter]\n\t\tif !ok {\n\t\t\tbidsForAccepter = make(map[string]bool)\n\t\t\tBIDsForPID[accepter] = bidsForAccepter\n\t\t}\n\t\tbidsForAccepter[record.BID] = true\n\n\tcase UnclaimBID:\n\t\t// can only do this if this BID exists and I'm mapped to it\n\t\tcurrentPIDs, ok := PIDsForBID[record.BID]\n\t\tif !ok {\n\t\t\treturn errors.New(\"no such BID: \" + record.BID)\n\t\t}\n\t\t_, ok = currentPIDs[record.PIDs[0]]\n\t\tif !ok {\n\t\t\treturn errors.New(\"this account is not mapped to BID \" + record.BID)\n\t\t}\n\n\t\t// remove the mapping between PID to BID\n\t\t// note - the pidsForGrantedBID map may now be empty but we won't free up the BID, because they probably\n\t\t// shouldn't be re-used.\n\t\tdelete(currentPIDs, record.PIDs[0])\n\n\t\tcurrentBIDs, _ := BIDsForPID[record.PIDs[0]]\n\t\tdelete(currentBIDs, record.BID)\n\t}\n\n\ttheLedger.Records = append(theLedger.Records, record)\n\treturn nil\n}", "func (c *managementServiceClient) ReactivateProjectUserGrant(ctx context.Context, in *ProjectUserGrantID, opts ...grpc.CallOption) (*UserGrant, error) {\n\tout := new(UserGrant)\n\terr := c.cc.Invoke(ctx, \"/caos.zitadel.management.api.v1.ManagementService/ReactivateProjectUserGrant\", in, out, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn out, nil\n}", "func NewAutoGrant() GrantHandler {\n\treturn &autoGrant{}\n}", "func AddTenant(t Tenant, db *database.DB) (*Tenant, error) {\n\n\tvar temp Tenant\n\n\tsearchres := db.Client.Where(\"name = ?\", t.Name).First(&temp)\n\tif searchres.Error == nil {\n\t\t// setting tenant ID to object found in DB\n\t\t// for error handling\n\t\tfmt.Println(\"found %v\", temp)\n\n\t\treturn &temp, &TenantAlreadyExist{Err: errors.New(\"error creating tenant\"), FoundID: temp.ID.String()}\n\t}\n\n\t// Create new entry\n\tresult := db.Client.Create(&t)\n\tif result.Error != nil {\n\t\t// log.Fatal(result.Error)\n\t\treturn nil, result.Error\n\t}\n\treturn &t, nil\n}", "func (o LookupGrantResultOutput) GrantName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v LookupGrantResult) *string { return v.GrantName }).(pulumi.StringPtrOutput)\n}", "func (aaa *TierService) GrantUserExp(input *tier.GrantUserExpParams) (*seasonpassclientmodels.UserSeasonSummary, error) {\n\ttoken, err := aaa.TokenRepository.GetToken()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tok, badRequest, err := aaa.Client.Tier.GrantUserExp(input, client.BearerToken(*token.AccessToken))\n\tif badRequest != nil {\n\t\treturn nil, badRequest\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn ok.GetPayload(), nil\n}", "func (p *program) addCost(cost types.Currency) error {\n\tif !p.staticBudget.Withdraw(cost) {\n\t\treturn modules.ErrMDMInsufficientBudget\n\t}\n\tp.executionCost = p.executionCost.Add(cost)\n\treturn nil\n}", "func (_ChpRegistry *ChpRegistryTransactor) AddPauser(opts *bind.TransactOpts, account common.Address) (*types.Transaction, error) {\n\treturn _ChpRegistry.contract.Transact(opts, \"addPauser\", account)\n}", "func (s *Statement) AddWorkingGrpahClause() {\n\ts.pattern = append(s.pattern, s.workingClause)\n\ts.ResetWorkingGraphClause()\n}", "func (emptyGrant) GrantNeeded(user user.Info, grant *api.Grant, w http.ResponseWriter, req *http.Request) (bool, bool, error) {\n\treturn false, false, nil\n}", "func (p *IssuingAuthorizationParams) AddExpand(f string) {\n\tp.Expand = append(p.Expand, &f)\n}", "func add(mgr manager.Manager, r reconcile.Reconciler) error {\n\t// Create a new controller\n\tc, err := controller.New(\"projectclaim-controller\", mgr, controller.Options{Reconciler: r})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Watch for changes to primary resource ProjectClaim\n\terr = c.Watch(&source.Kind{Type: &gcpv1alpha1.ProjectClaim{}}, &handler.EnqueueRequestForObject{})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func add(mgr manager.Manager, r reconcile.Reconciler) error {\n\n \t// minimumRefreshRate = os.Getenv(\"MINIMUM_REFRESH_RATE\")\n\n\t// Create a new controller\n\tc, err := controller.New(\"vaultsecret-controller\", mgr, controller.Options{Reconciler: r})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Watch for changes to primary resource VaultSecret\n\terr = c.Watch(&source.Kind{Type: &crdv1alpha1.VaultSecret{}}, &handler.EnqueueRequestForObject{})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// TODO(user): Modify this to be the types you create that are owned by the primary resource\n\t// Watch for changes to secondary resource Secrets and requeue the owner VaultSecret\n\terr = c.Watch(&source.Kind{Type: &corev1.Secret{}}, &handler.EnqueueRequestForOwner{\n\t\tIsController: true,\n\t\tOwnerType: &crdv1alpha1.VaultSecret{},\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (o *PostOauthTokenParams) SetGrantType(grantType string) {\n\to.GrantType = grantType\n}", "func NewAuthorizationGrant(authorization Authorization, expiration time.Time) AuthorizationGrant {\n\treturn AuthorizationGrant{Authorization: authorization, Expiration: expiration}\n}", "func addBinding(crmService *cloudresourcemanager.Service, projectID, member, role string) {\n\n\tpolicy := getPolicy(crmService, projectID)\n\n\t// Find the policy binding for role. Only one binding can have the role.\n\tvar binding *cloudresourcemanager.Binding\n\tfor _, b := range policy.Bindings {\n\t\tif b.Role == role {\n\t\t\tbinding = b\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif binding != nil {\n\t\t// If the binding exists, adds the member to the binding\n\t\tbinding.Members = append(binding.Members, member)\n\t} else {\n\t\t// If the binding does not exist, adds a new binding to the policy\n\t\tbinding = &cloudresourcemanager.Binding{\n\t\t\tRole: role,\n\t\t\tMembers: []string{member},\n\t\t}\n\t\tpolicy.Bindings = append(policy.Bindings, binding)\n\t}\n\n\tsetPolicy(crmService, projectID, policy)\n\n}", "func (s *Service) GrantAccessToken(client *models.OauthClient, user *models.OauthUser, expiresIn int, scope string) (*models.OauthAccessToken, error) {\n\t// Begin a transaction\n\ttx := s.db.Begin()\n\n\t// Delete expired access tokens\n\tquery := tx.Unscoped().Where(\"client_id = ?\", client.ID)\n\tif user != nil && len([]rune(user.ID)) > 0 {\n\t\tquery = query.Where(\"user_id = ?\", user.ID)\n\t} else {\n\t\tquery = query.Where(\"user_id IS NULL\")\n\t}\n\tif err := query.Where(\"expires_at <= ?\", time.Now()).Delete(new(models.OauthAccessToken)).Error; err != nil {\n\t\ttx.Rollback() // rollback the transaction\n\t\treturn nil, err\n\t}\n\n\t// Create a new access token\n\taccessToken := models.NewOauthAccessToken(client, user, expiresIn, scope)\n\tif err := tx.Create(accessToken).Error; err != nil {\n\t\ttx.Rollback() // rollback the transaction\n\t\treturn nil, err\n\t}\n\taccessToken.Client = client\n\taccessToken.User = user\n\n\t// Commit the transaction\n\tif err := tx.Commit().Error; err != nil {\n\t\ttx.Rollback() // rollback the transaction\n\t\treturn nil, err\n\t}\n\n\treturn accessToken, nil\n}", "func AddGigasecond(t time.Time) time.Time {\n\n\treturn t.Add(GIGASECOND)\n}", "func TableGrant(db, schema, table string) GrantBuilder {\n\treturn &CurrentGrantBuilder{\n\t\tname: table,\n\t\tqualifiedName: fmt.Sprintf(`\"%v\".\"%v\".\"%v\"`, db, schema, table),\n\t\tgrantType: tableType,\n\t}\n}", "func (m *Manager) Add(transfer *Transfer) {\n\tm.mu.Lock()\n\tdefer m.mu.Unlock()\n\n\tm.transfers[transfer.Server.ID()] = transfer\n}", "func (p *IssuingAuthorizationDeclineParams) AddExpand(f string) {\n\tp.Expand = append(p.Expand, &f)\n}", "func (r *GroupPolicyMigrationReportGroupPolicySettingMappingsCollectionRequest) Add(ctx context.Context, reqObj *GroupPolicySettingMapping) (resObj *GroupPolicySettingMapping, err error) {\n\terr = r.JSONRequest(ctx, \"POST\", \"\", reqObj, &resObj)\n\treturn\n}", "func (f Fraction) Plus(summand Fraction) (sum Fraction) {\n\ttmp := f.normalize()\n\tif tmp.denominator == summand.denominator {\n\t\tsum = Fraction{\n\t\t\ttmp.numerator + summand.numerator,\n\t\t\ttmp.denominator,\n\t\t}\n\t} else {\n\t\tdenominator := tmp.denominator * summand.denominator\n\t\tsum = Fraction{\n\t\t\ttmp.numerator*summand.denominator + summand.numerator*tmp.denominator,\n\t\t\tdenominator,\n\t\t}\n\t}\n\treturn sum.normalize()\n}", "func AddGigasecond(t time.Time) time.Time {\n\treturn t.Add(GIGASECOND)\n}", "func (vua vserverUserAccess) grantAccess(vserver, username, reason string) {\n\tvs, ok := vua[vserver]\n\tif !ok {\n\t\tvs = make(map[string]string)\n\t\tvua[vserver] = vs\n\t}\n\tvs[username] = reason\n}", "func (c *context) WgAdd(delta int) {\n\tc.waitGroup.Add(delta)\n}", "func AddGuestTransaction(m *Guests, o orm.Ormer) (id int64, err error) {\n\tid, err = o.Insert(m)\n\treturn\n}", "func (mt *MetaTable) SelectGrant(tenant string, entity *milvuspb.GrantEntity) ([]*milvuspb.GrantEntity, error) {\n\tvar entities []*milvuspb.GrantEntity\n\tif entity == nil {\n\t\treturn entities, fmt.Errorf(\"the grant entity is nil\")\n\t}\n\n\tif entity.Role == nil || funcutil.IsEmptyString(entity.Role.Name) {\n\t\treturn entities, fmt.Errorf(\"the role entity in the grant entity is invalid\")\n\t}\n\tif entity.DbName == \"\" {\n\t\tentity.DbName = util.DefaultDBName\n\t}\n\n\tmt.permissionLock.RLock()\n\tdefer mt.permissionLock.RUnlock()\n\n\treturn mt.catalog.ListGrant(mt.ctx, tenant, entity)\n}", "func (b *backend) addUserToPaywallPoolLock(user *database.User, paywallType string) {\n\tif !b.paywallIsEnabled() {\n\t\treturn\n\t}\n\n\tb.Lock()\n\tdefer b.Unlock()\n\n\tb.addUserToPaywallPool(user, paywallType)\n}", "func TestLessorGrant(t *testing.T) {\n\tlg := zap.NewNop()\n\tdir, be := NewTestBackend(t)\n\tdefer os.RemoveAll(dir)\n\tdefer be.Close()\n\n\tle := newLessor(lg, be, clusterLatest(), LessorConfig{MinLeaseTTL: minLeaseTTL})\n\tdefer le.Stop()\n\tle.Promote(0)\n\n\tl, err := le.Grant(1, 1)\n\tif err != nil {\n\t\tt.Fatalf(\"could not grant lease 1 (%v)\", err)\n\t}\n\tif l.ttl != minLeaseTTL {\n\t\tt.Fatalf(\"ttl = %v, expect minLeaseTTL %v\", l.ttl, minLeaseTTL)\n\t}\n\n\tgl := le.Lookup(l.ID)\n\n\tif !reflect.DeepEqual(gl, l) {\n\t\tt.Errorf(\"lease = %v, want %v\", gl, l)\n\t}\n\tif l.Remaining() < minLeaseTTLDuration-time.Second {\n\t\tt.Errorf(\"term = %v, want at least %v\", l.Remaining(), minLeaseTTLDuration-time.Second)\n\t}\n\n\t_, err = le.Grant(1, 1)\n\tif err == nil {\n\t\tt.Errorf(\"allocated the same lease\")\n\t}\n\n\tvar nl *Lease\n\tnl, err = le.Grant(2, 1)\n\tif err != nil {\n\t\tt.Errorf(\"could not grant lease 2 (%v)\", err)\n\t}\n\tif nl.ID == l.ID {\n\t\tt.Errorf(\"new lease.id = %x, want != %x\", nl.ID, l.ID)\n\t}\n\n\tlss := []*Lease{gl, nl}\n\tleases := le.Leases()\n\tfor i := range lss {\n\t\tif lss[i].ID != leases[i].ID {\n\t\t\tt.Fatalf(\"lease ID expected %d, got %d\", lss[i].ID, leases[i].ID)\n\t\t}\n\t\tif lss[i].ttl != leases[i].ttl {\n\t\t\tt.Fatalf(\"ttl expected %d, got %d\", lss[i].ttl, leases[i].ttl)\n\t\t}\n\t}\n\n\ttx := be.BatchTx()\n\ttx.Lock()\n\tdefer tx.Unlock()\n\tlpb := schema.MustUnsafeGetLease(tx, int64(l.ID))\n\tif lpb == nil {\n\t\tt.Errorf(\"lpb = %d, want not nil\", lpb)\n\t}\n}", "func (client *Client) GrantAccountPrivilegeWithOptions(request *GrantAccountPrivilegeRequest, runtime *util.RuntimeOptions) (_result *GrantAccountPrivilegeResponse, _err error) {\n\t_err = util.ValidateModel(request)\n\tif _err != nil {\n\t\treturn _result, _err\n\t}\n\tquery := map[string]interface{}{}\n\tif !tea.BoolValue(util.IsUnset(request.AccountName)) {\n\t\tquery[\"AccountName\"] = request.AccountName\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.AccountPrivilege)) {\n\t\tquery[\"AccountPrivilege\"] = request.AccountPrivilege\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.InstanceId)) {\n\t\tquery[\"InstanceId\"] = request.InstanceId\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.OwnerAccount)) {\n\t\tquery[\"OwnerAccount\"] = request.OwnerAccount\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.OwnerId)) {\n\t\tquery[\"OwnerId\"] = request.OwnerId\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.ResourceOwnerAccount)) {\n\t\tquery[\"ResourceOwnerAccount\"] = request.ResourceOwnerAccount\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.ResourceOwnerId)) {\n\t\tquery[\"ResourceOwnerId\"] = request.ResourceOwnerId\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.SecurityToken)) {\n\t\tquery[\"SecurityToken\"] = request.SecurityToken\n\t}\n\n\treq := &openapi.OpenApiRequest{\n\t\tQuery: openapiutil.Query(query),\n\t}\n\tparams := &openapi.Params{\n\t\tAction: tea.String(\"GrantAccountPrivilege\"),\n\t\tVersion: tea.String(\"2015-01-01\"),\n\t\tProtocol: tea.String(\"HTTPS\"),\n\t\tPathname: tea.String(\"/\"),\n\t\tMethod: tea.String(\"POST\"),\n\t\tAuthType: tea.String(\"AK\"),\n\t\tStyle: tea.String(\"RPC\"),\n\t\tReqBodyType: tea.String(\"formData\"),\n\t\tBodyType: tea.String(\"json\"),\n\t}\n\t_result = &GrantAccountPrivilegeResponse{}\n\t_body, _err := client.CallApi(params, req, runtime)\n\tif _err != nil {\n\t\treturn _result, _err\n\t}\n\t_err = tea.Convert(_body, &_result)\n\treturn _result, _err\n}", "func InvalidGrant() ErrorBuilder {\n\treturn &defaultErrorBuilder{\n\t\terr: \"invalid_grant\",\n\t\terrorDescription: \"The provided authorization grant (e.g., authorization code, resource owner credentials) or refresh token is invalid, expired, revoked, does not match the redirection URI used in the authorization request, or was issued to another client.\",\n\t}\n}", "func (m *GraphBaseServiceClient) PermissionGrantsById(id string)(*i23bab38fb8688d4bab0b6ffc533eb085d40e58af49a27ab228a8d1ad3e0ab203.ResourceSpecificPermissionGrantItemRequestBuilder) {\n urlTplParams := make(map[string]string)\n for idx, item := range m.pathParameters {\n urlTplParams[idx] = item\n }\n if id != \"\" {\n urlTplParams[\"resourceSpecificPermissionGrant%2Did\"] = id\n }\n return i23bab38fb8688d4bab0b6ffc533eb085d40e58af49a27ab228a8d1ad3e0ab203.NewResourceSpecificPermissionGrantItemRequestBuilderInternal(urlTplParams, m.requestAdapter);\n}", "func (m *GraphBaseServiceClient) PermissionGrantsById(id string)(*i23bab38fb8688d4bab0b6ffc533eb085d40e58af49a27ab228a8d1ad3e0ab203.ResourceSpecificPermissionGrantItemRequestBuilder) {\n urlTplParams := make(map[string]string)\n for idx, item := range m.pathParameters {\n urlTplParams[idx] = item\n }\n if id != \"\" {\n urlTplParams[\"resourceSpecificPermissionGrant%2Did\"] = id\n }\n return i23bab38fb8688d4bab0b6ffc533eb085d40e58af49a27ab228a8d1ad3e0ab203.NewResourceSpecificPermissionGrantItemRequestBuilderInternal(urlTplParams, m.requestAdapter);\n}" ]
[ "0.8021465", "0.70819193", "0.5704787", "0.557793", "0.5520405", "0.5516304", "0.54987746", "0.54319793", "0.54234326", "0.5198178", "0.5190612", "0.516897", "0.51671606", "0.5102042", "0.50500983", "0.5033243", "0.50264156", "0.50088483", "0.49463457", "0.4917783", "0.49124628", "0.4898419", "0.4896466", "0.48926166", "0.48544726", "0.48544413", "0.47441095", "0.47365117", "0.47274438", "0.47010127", "0.46948484", "0.46268535", "0.46073988", "0.45868516", "0.4531453", "0.45207357", "0.45002723", "0.44769964", "0.44691423", "0.4466653", "0.4443727", "0.4440009", "0.4407788", "0.44055533", "0.4390275", "0.43807685", "0.43779254", "0.43693826", "0.43425453", "0.43370163", "0.43332997", "0.43300465", "0.4324707", "0.43085307", "0.43026915", "0.4294378", "0.42937014", "0.42900026", "0.4288786", "0.4281059", "0.42683357", "0.4261212", "0.42575976", "0.4225412", "0.4211585", "0.4207805", "0.41819063", "0.41757905", "0.41733545", "0.41688365", "0.41673985", "0.41662025", "0.41279066", "0.4125894", "0.41216803", "0.41184625", "0.4102664", "0.40980124", "0.40960956", "0.40928906", "0.40864074", "0.40805367", "0.408004", "0.4079824", "0.4078647", "0.4073363", "0.40712085", "0.40679523", "0.40677577", "0.40669504", "0.40656167", "0.40637067", "0.40576744", "0.40548065", "0.40519384", "0.40511847", "0.405031", "0.4045072", "0.40424263", "0.40424263" ]
0.78557765
1
NewDelayedVestingAccountRaw creates a new DelayedVestingAccount object from BaseVestingAccount
func NewDelayedVestingAccountRaw(bva *BaseVestingAccount) *DelayedVestingAccount { return &DelayedVestingAccount{ BaseVestingAccount: bva, } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func NewDelayedVestingAccount(baseAcc *authtypes.BaseAccount, originalVesting sdk.Coins, endTime int64) *DelayedVestingAccount {\n\tbaseVestingAcc := &BaseVestingAccount{\n\t\tBaseAccount: baseAcc,\n\t\tOriginalVesting: originalVesting,\n\t\tEndTime: endTime,\n\t}\n\n\treturn &DelayedVestingAccount{baseVestingAcc}\n}", "func NewPeriodicVestingAccountRaw(bva *BaseVestingAccount, startTime int64, periods Periods) *PeriodicVestingAccount {\n\treturn &PeriodicVestingAccount{\n\t\tBaseVestingAccount: bva,\n\t\tStartTime: startTime,\n\t\tVestingPeriods: periods,\n\t}\n}", "func NewValidatorVestingAccountRaw(bva *vestingtypes.BaseVestingAccount,\n\tstartTime int64, periods vestingtypes.Periods, validatorAddress sdk.ConsAddress, returnAddress sdk.AccAddress, signingThreshold int64) *ValidatorVestingAccount {\n\n\tpva := &vestingtypes.PeriodicVestingAccount{\n\t\tBaseVestingAccount: bva,\n\t\tStartTime: startTime,\n\t\tVestingPeriods: periods,\n\t}\n\tvar vestingPeriodProgress []VestingProgress\n\tfor i := 0; i < len(periods); i++ {\n\t\tvestingPeriodProgress = append(vestingPeriodProgress, VestingProgress{false, false})\n\t}\n\n\treturn &ValidatorVestingAccount{\n\t\tPeriodicVestingAccount: pva,\n\t\tValidatorAddress: validatorAddress,\n\t\tReturnAddress: returnAddress,\n\t\tSigningThreshold: signingThreshold,\n\t\tCurrentPeriodProgress: CurrentPeriodProgress{0, 0},\n\t\tVestingPeriodProgress: vestingPeriodProgress,\n\t\tDebtAfterFailedVesting: sdk.NewCoins(),\n\t}\n}", "func NewBaseVestingAccount(baseAccount *authtypes.BaseAccount, originalVesting sdk.Coins, endTime int64) *BaseVestingAccount {\n\treturn &BaseVestingAccount{\n\t\tBaseAccount: baseAccount,\n\t\tOriginalVesting: originalVesting,\n\t\tDelegatedFree: sdk.NewCoins(),\n\t\tDelegatedVesting: sdk.NewCoins(),\n\t\tEndTime: endTime,\n\t}\n}", "func NewContinuousVestingAccountRaw(bva *BaseVestingAccount, startTime int64) *ContinuousVestingAccount {\n\treturn &ContinuousVestingAccount{\n\t\tBaseVestingAccount: bva,\n\t\tStartTime: startTime,\n\t}\n}", "func newPeriodicVestingAccount(address sdk.AccAddress, periods vestingtypes.Periods, firstPeriodStartTimestamp int64) *vestingtypes.PeriodicVestingAccount {\n\tbaseAccount := authtypes.NewBaseAccount(address, nil, 0, 0)\n\n\toriginalVesting := sdk.NewCoins()\n\tfor _, p := range periods {\n\t\toriginalVesting = originalVesting.Add(p.Amount...)\n\t}\n\n\tvar totalPeriods int64\n\tfor _, p := range periods {\n\t\ttotalPeriods += p.Length\n\t}\n\tendTime := firstPeriodStartTimestamp + totalPeriods\n\n\tbaseVestingAccount := vestingtypes.NewBaseVestingAccount(baseAccount, originalVesting, endTime)\n\treturn vestingtypes.NewPeriodicVestingAccountRaw(baseVestingAccount, firstPeriodStartTimestamp, periods)\n}", "func newAccount() *Account {\n\treturn &Account{\n\t\tblocks: make(map[string]uint64),\n\t}\n}", "func NewPeriodicVestingAccount(baseAcc *authtypes.BaseAccount, originalVesting sdk.Coins, startTime int64, periods Periods) *PeriodicVestingAccount {\n\tendTime := startTime\n\tfor _, p := range periods {\n\t\tendTime += p.Length\n\t}\n\tbaseVestingAcc := &BaseVestingAccount{\n\t\tBaseAccount: baseAcc,\n\t\tOriginalVesting: originalVesting,\n\t\tEndTime: endTime,\n\t}\n\n\treturn &PeriodicVestingAccount{\n\t\tBaseVestingAccount: baseVestingAcc,\n\t\tStartTime: startTime,\n\t\tVestingPeriods: periods,\n\t}\n}", "func NewValidatorVestingAccount(baseAcc *authtypes.BaseAccount, startTime int64, periods vestingtypes.Periods, validatorAddress sdk.ConsAddress, returnAddress sdk.AccAddress, signingThreshold int64) *ValidatorVestingAccount {\n\n\tendTime := startTime\n\tfor _, p := range periods {\n\t\tendTime += p.Length\n\t}\n\tbaseVestingAcc := &vestingtypes.BaseVestingAccount{\n\t\tBaseAccount: baseAcc,\n\t\tOriginalVesting: baseAcc.Coins,\n\t\tEndTime: endTime,\n\t}\n\tpva := &vestingtypes.PeriodicVestingAccount{\n\t\tBaseVestingAccount: baseVestingAcc,\n\t\tStartTime: startTime,\n\t\tVestingPeriods: periods,\n\t}\n\tvar vestingPeriodProgress []VestingProgress\n\tfor i := 0; i < len(periods); i++ {\n\t\tvestingPeriodProgress = append(vestingPeriodProgress, VestingProgress{false, false})\n\t}\n\n\treturn &ValidatorVestingAccount{\n\t\tPeriodicVestingAccount: pva,\n\t\tValidatorAddress: validatorAddress,\n\t\tReturnAddress: returnAddress,\n\t\tSigningThreshold: signingThreshold,\n\t\tCurrentPeriodProgress: CurrentPeriodProgress{0, 0},\n\t\tVestingPeriodProgress: vestingPeriodProgress,\n\t\tDebtAfterFailedVesting: sdk.NewCoins(),\n\t}\n}", "func NewContinuousVestingAccount(baseAcc *authtypes.BaseAccount, originalVesting sdk.Coins, startTime, endTime int64) *ContinuousVestingAccount {\n\tbaseVestingAcc := &BaseVestingAccount{\n\t\tBaseAccount: baseAcc,\n\t\tOriginalVesting: originalVesting,\n\t\tEndTime: endTime,\n\t}\n\n\treturn &ContinuousVestingAccount{\n\t\tStartTime: startTime,\n\t\tBaseVestingAccount: baseVestingAcc,\n\t}\n}", "func NewAccount(val string) AccountField {\n\treturn AccountField{quickfix.FIXString(val)}\n}", "func NewClawbackVestingAccount(baseAcc *authtypes.BaseAccount, funder sdk.AccAddress, originalVesting sdk.Coins, startTime int64, lockupPeriods, vestingPeriods Periods) *ClawbackVestingAccount {\n\t// copy and align schedules to avoid mutating inputs\n\tlp := make(Periods, len(lockupPeriods))\n\tcopy(lp, lockupPeriods)\n\tvp := make(Periods, len(vestingPeriods))\n\tcopy(vp, vestingPeriods)\n\t_, endTime := AlignSchedules(startTime, startTime, lp, vp)\n\tbaseVestingAcc := &BaseVestingAccount{\n\t\tBaseAccount: baseAcc,\n\t\tOriginalVesting: originalVesting,\n\t\tEndTime: endTime,\n\t}\n\n\treturn &ClawbackVestingAccount{\n\t\tBaseVestingAccount: baseVestingAcc,\n\t\tFunderAddress: funder.String(),\n\t\tStartTime: startTime,\n\t\tLockupPeriods: lp,\n\t\tVestingPeriods: vp,\n\t}\n}", "func (c *CoinTest) newAccount(stub shim.ChaincodeStubInterface, args []string) pb.Response {\r\n\tvar id string\r\n\tvar asset int\r\n\tvar err error\r\n\r\n\tif len(args) == 1{\r\n\t\tid = args[0]\r\n\t\tasset = 0\r\n\t}else if len(args) == 2{\r\n\t\tid = args[0]\r\n\t\t//asset, err = strconv.Atoi(args[1])\r\n\t\t//if err != nil{\r\n\t\t//\treturn shim.Error(\"Invalid asset amount, expecting a integer value\")\r\n\t\t//}\r\n\t\tasset = 0;\r\n\t}else{\r\n\t\treturn shim.Error(\"Incorrect number of arguments.\")\r\n\t}\r\n\r\n\t//deliver 0 number of TolakCoin to user\r\n\ttolakCoin.Token.Deliver(token.Address(id), int(asset))\r\n\r\n\t//write to ledger\r\n\terr = stub.PutState(id, []byte(strconv.Itoa(asset)))\r\n\tif err != nil{\r\n\t\treturn shim.Error(err.Error())\r\n\t}\r\n\r\n\treturn shim.Success(nil)\r\n}", "func (e Account) EntNew() ent.Ent { return &Account{} }", "func (e Account) EntNew() ent.Ent { return &Account{} }", "func (account *Account) New() {\n\n\tparams, _ := pbc.NewParamsFromString(crypto.Params)\n\tpairing := params.NewPairing()\n\n\tA := pairing.NewG1()\n\tAT := pairing.NewG1()\n\ta := pairing.NewZr()\n\n\ta.Rand()\n\n\tG := pairing.NewG1()\n\tT := pairing.NewG1()\n\tG.SetString(crypto.G, 10)\n\tT.SetString(crypto.T, 10)\n\n\tA.PowZn(G, a)\n\tAT.PowZn(T, a)\n\n\taccount.a = a.String()\n\taccount.A = A.String()\n\taccount.AT = AT.String()\n}", "func NewAllocAccount(val string) AllocAccountField {\n\treturn AllocAccountField{quickfix.FIXString(val)}\n}", "func newBase() *base {\n\treturn &base{shared.NewUUID(), time.Now().UTC(), time.Now().UTC(), false/*, shared.NewUUID()*/}\n}", "func NewMsgCreatePeriodicVestingAccount(fromAddr, toAddr sdk.AccAddress, startTime int64, periods []Period) *MsgCreatePeriodicVestingAccount {\n\treturn &MsgCreatePeriodicVestingAccount{\n\t\tFromAddress: fromAddr.String(),\n\t\tToAddress: toAddr.String(),\n\t\tStartTime: startTime,\n\t\tVestingPeriods: periods,\n\t}\n}", "func tNewUser(lbl string) *tUser {\n\tintBytes := make([]byte, 4)\n\tbinary.BigEndian.PutUint32(intBytes, acctCounter)\n\tacctID := account.AccountID{}\n\tcopy(acctID[:], acctTemplate[:])\n\tcopy(acctID[account.HashSize-4:], intBytes)\n\taddr := strconv.Itoa(int(acctCounter))\n\tsig := []byte{0xab} // Just to differentiate from the addr.\n\tsig = append(sig, intBytes...)\n\tsigHex := hex.EncodeToString(sig)\n\tacctCounter++\n\treturn &tUser{\n\t\tsig: sig,\n\t\tsigHex: sigHex,\n\t\tacct: acctID,\n\t\taddr: addr,\n\t\tlbl: lbl,\n\t}\n}", "func (*tenantR) NewStruct() *tenantR {\n\treturn &tenantR{}\n}", "func NewAccount(txr *repository.Transactioner) repository.Account {\n\treturn &account{txr: txr}\n}", "func NewMsgCreateVestingAccount(fromAddr, toAddr sdk.AccAddress, amount sdk.Coins, endTime int64, delayed bool) *MsgCreateVestingAccount {\n\treturn &MsgCreateVestingAccount{\n\t\tFromAddress: fromAddr.String(),\n\t\tToAddress: toAddr.String(),\n\t\tAmount: amount,\n\t\tEndTime: endTime,\n\t\tDelayed: delayed,\n\t}\n}", "func New(from, to string, amount float64, opts TransactionOptions) Transaction {\n\treturn Transaction{\n\t\tFromID: from,\n\t\tToID: to,\n\t\tAmount: amount,\n\t\tStatus: \"pending\",\n\t\tDescription: opts.Description,\n\t\tCurrency: opts.Currency,\n\t\tCreationTime: time.Now(),\n\t\tUUID: uuid.New().String(),\n\t}\n}", "func NewAccount(owner string) *Account {\n\treturn &Account{owner: owner, balance: 0}\n}", "func (c *Jrpc) CreateRawTransaction(in *pty.ReqCreatePrivacyTx, result *interface{}) error {\n\treply, err := c.cli.CreateRawTransaction(context.Background(), in)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t*result = hex.EncodeToString(types.Encode(reply))\n\treturn err\n}", "func NewAccount() *Account {\n\n\tcreatedAccount := Account{}\n\n\tnewPrivateKey, err := generatePrivateKey(4096)\n\tif err != nil {\n\t\tlog.Fatal(\"Error generating rsa private key \", err)\n\t}\n\tnewPublicKey, err := generatePublicKey(&newPrivateKey.PublicKey)\n\tif err != nil {\n\t\tlog.Fatal(\"Error generating rsa public key \", err)\n\t}\n\tcreatedAccount.privateKey = newPrivateKey\n\tcreatedAccount.Address = string(newPublicKey)\n\tcreatedAccount.Amount = 0\n\n\treturn &createdAccount\n}", "func MakeNewAccount(name string) (*MyAccount, error) {\n\tkeys, err := NewKeypair()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &MyAccount{\n\t\tFields: make(map[string]string),\n\t\tKeys: keys,\n\t\tName: name,\n\t}, nil\n}", "func NewAccount(user, apiKey string) *Account {\n\treturn &Account{user: user, apiKey: apiKey}\n}", "func (dva *DelayedVestingAccount) UnmarshalJSON(bz []byte) error {\n\tvar alias vestingAccountJSON\n\tif err := legacy.Cdc.UnmarshalJSON(bz, &alias); err != nil {\n\t\treturn err\n\t}\n\n\tdva.BaseVestingAccount = &BaseVestingAccount{\n\t\tBaseAccount: NewBaseAccount(alias.Address, alias.Coins, alias.PubKey, alias.AccountNumber, alias.Sequence),\n\t\tOriginalVesting: alias.OriginalVesting,\n\t\tDelegatedFree: alias.DelegatedFree,\n\t\tDelegatedVesting: alias.DelegatedVesting,\n\t\tEndTime: alias.EndTime,\n\t}\n\n\treturn nil\n}", "func newJWTBase(ctx context.Context, cfg Config) (string, error) {\n\tserviceAccount, project, tokenSource, err := getServiceAccountInfo(ctx, cfg)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"unable to get service account from environment\")\n\t}\n\n\tpayload, err := json.Marshal(map[string]interface{}{\n\t\t\"aud\": \"vault/\" + cfg.Role,\n\t\t\"sub\": serviceAccount,\n\t\t\"exp\": time.Now().UTC().Add(5 * time.Minute).Unix(),\n\t})\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"unable to encode JWT payload\")\n\t}\n\n\thc := getHTTPClient(ctx, cfg)\n\t// reuse base transport and timeout but sprinkle on the token source for IAM access\n\thcIAM := &http.Client{\n\t\tTimeout: hc.Timeout,\n\t\tTransport: &oauth2.Transport{\n\t\t\tSource: tokenSource,\n\t\t\tBase: hc.Transport,\n\t\t},\n\t}\n\tiamClient, err := iam.New(hcIAM)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"unable to init IAM client\")\n\t}\n\n\tif cfg.IAMAddress != \"\" {\n\t\tiamClient.BasePath = cfg.IAMAddress\n\t}\n\n\tresp, err := iamClient.Projects.ServiceAccounts.SignJwt(\n\t\tfmt.Sprintf(\"projects/%s/serviceAccounts/%s\",\n\t\t\tproject, serviceAccount),\n\t\t&iam.SignJwtRequest{Payload: string(payload)}).Context(ctx).Do()\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"unable to sign JWT\")\n\t}\n\treturn resp.SignedJwt, nil\n}", "func NewAccount(addr, amount string) *Account {\n\tam := big.NewInt(0)\n\tam.SetString(amount, 0)\n\treturn &Account{Address: addr, Amount: am}\n}", "func NewAccount(instanceID uuid.UUID, name, aud string) (*Account, error) {\n\tid, err := uuid.NewV4()\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"Error generating unique id\")\n\t}\n\n\taccount := &Account{\n\t\tInstanceID: instanceID,\n\t\tID: id,\n\t\tAud: aud,\n\t\tName: name,\n\t}\n\treturn account, nil\n}", "func newBlockchain(opts ...emulator.Option) *emulator.Blockchain {\n\tb, err := emulator.NewBlockchain(\n\t\tappend(\n\t\t\t[]emulator.Option{\n\t\t\t\temulator.WithStorageLimitEnabled(false),\n\t\t\t},\n\t\t\topts...,\n\t\t)...,\n\t)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn b\n}", "func newBlockchain(opts ...emulator.Option) *emulator.Blockchain {\n\tb, err := emulator.NewBlockchain(\n\t\tappend(\n\t\t\t[]emulator.Option{\n\t\t\t\temulator.WithStorageLimitEnabled(false),\n\t\t\t},\n\t\t\topts...,\n\t\t)...,\n\t)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn b\n}", "func NewMockAVR(quote []byte, nonce string) ([]byte, error) {\n\tmockAVR := &mockAVR{\n\t\tVersion: 4,\n\t\tTimestamp: time.Now().UTC().Format(TimestampFormat),\n\t\tISVEnclaveQuoteStatus: \"OK\",\n\t\tISVEnclaveQuoteBody: quote[:quoteLen],\n\t\tNonce: nonce,\n\t}\n\n\tvar q Quote\n\terr := q.UnmarshalBinary(mockAVR.ISVEnclaveQuoteBody)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif err = q.Verify(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn json.Marshal(mockAVR)\n}", "func newTransportRecord() *TransportRecord {\n\ttr := TransportRecord{}\n\ttr.id = messages.RandTransportId()\n\ttr.status = DISCONNECTED\n\tif messages.IsDebug() {\n\t\tlog.Printf(\"Created TransportRecord: %d\\n\", tr.id)\n\t}\n\treturn &tr\n}", "func NewAccount(address string) *Account {\n\treturn &Account{\n\t\tAddress: address,\n\t\tHeight: \"0\",\n\t\tGoldTokenBalance: \"0\",\n\t\tTotalLockedGoldBalance: \"0\",\n\t\tNonVotingLockedGoldBalance: \"0\",\n\t\tVotingLockedGoldBalance: \"0\",\n\t\tPendingWithdrawalBalance: \"0\",\n\t\tCeloUSDValue: \"0\",\n\t\tDelegations: []*Delegation{},\n\t}\n\n}", "func NewAgedAccountsPayable()(*AgedAccountsPayable) {\n m := &AgedAccountsPayable{\n }\n m.backingStore = ie8677ce2c7e1b4c22e9c3827ecd078d41185424dd9eeb92b7d971ed2d49a392e.BackingStoreFactoryInstance();\n m.SetAdditionalData(make(map[string]any))\n return m\n}", "func NewFundedAccount() *keypair.Full {\n\tkp, err := keypair.Random()\n\tif err != nil {\n\t\tlog.Fatal(err, \"generating random keypair\")\n\t}\n\terr = FundAccount(kp.Address())\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tlog.Printf(\"successfully funded %s\", kp.Address())\n\treturn kp\n}", "func newRawAuthentication(value string) httpAuthentication {\n\treturn &basicAuthentication{\n\t\tauthorizationValue: value,\n\t}\n}", "func (c Client) New(params *stripe.TreasuryOutboundPaymentParams) (*stripe.TreasuryOutboundPayment, error) {\n\toutboundpayment := &stripe.TreasuryOutboundPayment{}\n\terr := c.B.Call(\n\t\thttp.MethodPost,\n\t\t\"/v1/treasury/outbound_payments\",\n\t\tc.Key,\n\t\tparams,\n\t\toutboundpayment,\n\t)\n\treturn outboundpayment, err\n}", "func New(params ...rune) SuperSpin {\n\tsp := SuperSpin{\n\t\topenToken: '{',\n\t\tcloseToken: '}',\n\t\torToken: '|',\n\t}\n\n\tif len(params) == 1 {\n\t\tsp.openToken = params[0]\n\t}\n\n\tif len(params) == 2 {\n\t\tsp.closeToken = params[1]\n\t}\n\n\tif len(params) == 3 {\n\t\tsp.orToken = params[2]\n\t}\n\n\treturn sp\n}", "func (w *Wallet) NewAccount(index *uint32) (a *Account, err error) {\n\tindex2 := w.nextIndex\n\tif index != nil {\n\t\tindex2 = *index\n\t}\n\ta = &Account{w: w, index: index2}\n\tif err = w.impl.deriveAccount(a); err != nil {\n\t\treturn\n\t}\n\tpubkeyToAddress := util.PubkeyToAddress\n\tif w.isBanano {\n\t\tpubkeyToAddress = util.PubkeyToBananoAddress\n\t}\n\tif a.address, err = pubkeyToAddress(a.pubkey); err != nil {\n\t\treturn\n\t}\n\tif index == nil {\n\t\tw.nextIndex++\n\t}\n\tif _, ok := w.accounts[a.address]; !ok {\n\t\tw.accounts[a.address] = a\n\t} else if index == nil {\n\t\treturn w.NewAccount(nil)\n\t}\n\treturn\n}", "func (dva DelayedVestingAccount) Validate() error {\n\treturn dva.BaseVestingAccount.Validate()\n}", "func (a API) CreateRawTransaction(cmd *btcjson.CreateRawTransactionCmd) (e error) {\n\tRPCHandlers[\"createrawtransaction\"].Call <-API{a.Ch, cmd, nil}\n\treturn\n}", "func NewRaw(id, netID string, args ...string) *CmdMsg {\n\tcmd := NewCmd(id, \"raw\", args...)\n\tcmd.Network.Init(netID, \"net\")\n\treturn cmd\n}", "func (d *Db) CreateRawRecord(length int64) (*Record, error) {\n\tr := &Record{rec: C.wg_create_raw_record(d.db, C.wg_int(length))}\n\tif r.rec == nil {\n\t\treturn nil, WDBError(\"Could not create record\")\n\t}\n\treturn r, nil\n}", "func NewAccount() *Account {\n\tpriv, _ := ecdsa.GenerateKey(crypto.S256(), cryptorand.Reader)\n\tpub := base64.URLEncoding.EncodeToString(\n\t\tcrypto.FromECDSAPub(&priv.PublicKey))\n\taddr := hex.EncodeToString(crypto.PubkeyToAddress(priv.PublicKey).Bytes())\n\treturn &Account{\n\t\tID: NewUUID(),\n\t\tEthAddr: addr,\n\t\tPublicKey: pub,\n\t\tPrivateKey: base64.URLEncoding.EncodeToString(crypto.FromECDSA(priv)),\n\t}\n}", "func NewAccount(id, entityID string) *Account {\n\treturn &Account{\n\t\tID: id,\n\t\tEntityID: entityID,\n\t\tWallets: make([]Wallet, 0),\n\t}\n}", "func newTestChain(t testing.TB) *Blockchain {\n\treturn newTestChainWithCustomCfg(t, nil)\n}", "func NewTestAccount(sb *collections.SchemaBuilder) (TestAccount, error) {\n\tta := TestAccount{\n\t\tItem: collections.NewItem(sb, itemPrefix, \"test\", collections.Uint64Value),\n\t}\n\treturn ta, nil\n}", "func mkdummytx() *Transaction {\n\ttx := &Transaction{\n\t\tBlockHeight: 42,\n\t\tName: \"dummy\",\n\t\tTimestamp: func() time.Time {\n\t\t\tt, _ := time.Parse(\"2006-Jan-02 15:04\", \"1988-Jan-02 10:00\")\n\t\t\treturn t\n\t\t}(),\n\t\tTotalInputs: 13,\n\t\tTotalOutputs: 12,\n\t\tTotalECOutputs: 1,\n\t}\n\treturn tx\n}", "func NewAccount(id string, name string, primary bool, type_ string, currency Currency, balance AccountBalance, createdAt time.Time, updatedAt time.Time, resource string, resourcePath string, ready bool) *Account {\n\tthis := Account{}\n\tthis.Id = id\n\tthis.Name = name\n\tthis.Primary = primary\n\tthis.Type = type_\n\tthis.Currency = currency\n\tthis.Balance = balance\n\tthis.CreatedAt = createdAt\n\tthis.UpdatedAt = updatedAt\n\tthis.Resource = resource\n\tthis.ResourcePath = resourcePath\n\tthis.Ready = ready\n\treturn &this\n}", "func NewAccount(addr *Address) *Account {\n\treturn &Account{\n\t\taccount: common.NewAccount(common.BytesToAddress(addr.Bytes())),\n\t}\n}", "func NewTransaction(p *requestParams) {\n\tw, r, c, u := p.w, p.r, p.c, p.u\n\n\td := json.NewDecoder(r.Body)\n\tvar request TransactionRequest\n\tif err := d.Decode(&request); err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tif len(request.Amounts) != len(request.Accounts) {\n\t\thttp.Error(w, \"Amounts and accounts of different lengths\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tdate, err := time.Parse(dateStringFormat, request.Date)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tuserKey := userKey(c, u)\n\ttransactionId := uuid.NewRandom().String()\n\taccountKeys := make([]*datastore.Key, len(request.Accounts))\n\tsplitKeys := make([]*datastore.Key, len(request.Accounts))\n\tsplits := make([]*transaction.Split, len(request.Accounts))\n\n\tfor i := range request.Accounts {\n\t\taccountKeys[i] = datastore.NewKey(c, \"Account\", \"\", request.Accounts[i], userKey)\n\t\tsplitKeys[i] = datastore.NewKey(c, \"Split\", transactionId, 0, accountKeys[i])\n\t\tsplits[i] = &transaction.Split{\n\t\t\tAmount: request.Amounts[i],\n\t\t\tAccount: request.Accounts[i],\n\t\t\tMemo: request.Memo,\n\t\t\tDate: date,\n\t\t}\n\t}\n\n\tx := transaction.NewTransaction()\n\tx.AddSplits(splits)\n\n\tif err := x.ValidateAmount(); err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\terr = datastore.RunInTransaction(c, func(c appengine.Context) error {\n\t\taccounts := make([]transaction.Account, len(accountKeys))\n\t\tif err := datastore.GetMulti(c, accountKeys, accounts); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfor i := range accounts {\n\t\t\tx.AddAccount(&accounts[i], accountKeys[i].IntID())\n\t\t}\n\n\t\tif err := x.Commit(); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tputStatus := make(chan error)\n\n\t\tgo func() {\n\t\t\t_, err := datastore.PutMulti(c, accountKeys, accounts)\n\t\t\tputStatus <- err\n\t\t}()\n\t\tgo func() {\n\t\t\t_, err := datastore.PutMulti(c, splitKeys, splits)\n\t\t\tputStatus <- err\n\t\t}()\n\n\t\terr := <-putStatus\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn <-putStatus\n\t}, nil)\n\tif err != nil {\n\t\t// TODO(cjc25): This might not be a 400: if e.g. datastore failed it should\n\t\t// be a 500. Interpret err and return the right thing.\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n}", "func NewPermanentLockedAccount(baseAcc *authtypes.BaseAccount, coins sdk.Coins) *PermanentLockedAccount {\n\tbaseVestingAcc := &BaseVestingAccount{\n\t\tBaseAccount: baseAcc,\n\t\tOriginalVesting: coins,\n\t\tEndTime: 0, // ensure EndTime is set to 0, as PermanentLockedAccount's do not have an EndTime\n\t}\n\n\treturn &PermanentLockedAccount{baseVestingAcc}\n}", "func NewAccount(\n\tconfig *accounts.AccountConfig,\n\taccountCoin *Coin,\n\thttpClient *http.Client,\n\tlog *logrus.Entry,\n) *Account {\n\tlog = log.WithField(\"group\", \"eth\").\n\t\tWithFields(logrus.Fields{\"coin\": accountCoin.String(), \"code\": config.Config.Code, \"name\": config.Config.Name})\n\tlog.Debug(\"Creating new account\")\n\n\taccount := &Account{\n\t\tBaseAccount: accounts.NewBaseAccount(config, accountCoin, log),\n\t\tcoin: accountCoin,\n\t\tdbSubfolder: \"\", // set in Initialize()\n\t\tsigningConfiguration: nil,\n\t\thttpClient: httpClient,\n\t\tbalance: coin.NewAmountFromInt64(0),\n\n\t\tenqueueUpdateCh: make(chan struct{}),\n\t\tquitChan: make(chan struct{}),\n\n\t\tlog: log,\n\t}\n\n\treturn account\n}", "func (pva *PeriodicVestingAccount) UnmarshalJSON(bz []byte) error {\n\tvar alias vestingAccountJSON\n\tif err := legacy.Cdc.UnmarshalJSON(bz, &alias); err != nil {\n\t\treturn err\n\t}\n\n\tpva.BaseVestingAccount = &BaseVestingAccount{\n\t\tBaseAccount: NewBaseAccount(alias.Address, alias.Coins, alias.PubKey, alias.AccountNumber, alias.Sequence),\n\t\tOriginalVesting: alias.OriginalVesting,\n\t\tDelegatedFree: alias.DelegatedFree,\n\t\tDelegatedVesting: alias.DelegatedVesting,\n\t\tEndTime: alias.EndTime,\n\t}\n\tpva.StartTime = alias.StartTime\n\tpva.VestingPeriods = alias.VestingPeriods\n\n\treturn nil\n}", "func New(chainID uint32, payload []byte) Address {\n\tvar pkHash hash.PKHash\n\tcopy(pkHash[:], payload)\n\treturn V1.New(chainID, pkHash)\n}", "func New(ctx context.Context, backupTables tablesmap.TablesMapInterface, cfg *config.Config) *basebackup {\n\tb := basebackup{\n\t\tctx: ctx,\n\t\tcfg: cfg,\n\t\twg: &sync.WaitGroup{},\n\t\tbackupTables: backupTables,\n\t\tqueue: queue.New(ctx),\n\t}\n\n\treturn &b\n}", "func NewStorageDataRaw(b []byte) StorageDataRaw {\n\treturn StorageDataRaw(b)\n}", "func CreateWithdrawRawTxCmd() *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse: \"withdraw\",\n\t\tShort: \"one key get withdraw proof input data\",\n\t\tRun: withdrawSecret,\n\t}\n\twithdrawSecretCmdFlags(cmd)\n\treturn cmd\n}", "func (ba *BankAccount) New() Resource {\n\tvar obj = &BankAccount{}\n\treturn obj\n}", "func NewRawClient(ctx sdkclient.Context, key string) RawClient {\n\treturn &rawclient{ctx: ctx, key: key}\n}", "func newTestRawNode(id uint64, peers []uint64, election, heartbeat int, storage Storage) *RawNode {\n\tcfg := newTestConfig(id, peers, election, heartbeat, storage)\n\trn, err := NewRawNode(cfg)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn rn\n}", "func (*withdrawalCryptoR) NewStruct() *withdrawalCryptoR {\n\treturn &withdrawalCryptoR{}\n}", "func newBlockInventory(instance *BlockInstance, inv IInventory, ejectOnUnsubscribe bool, invTypeId InvTypeId) *blockInventory {\n blkInv := &blockInventory{\n inv: inv,\n subscribers: make(map[EntityId]IPlayerClient),\n ejectOnUnsubscribe: ejectOnUnsubscribe,\n invTypeId: invTypeId,\n }\n\n if instance != nil {\n blkInv.chunk = instance.Chunk\n blkInv.blockLoc = instance.BlockLoc\n }\n\n blkInv.inv.SetSubscriber(blkInv)\n\n return blkInv\n}", "func New(raw []byte) (*BytesObj, error) {\n\tbo := new(BytesObj)\n\tif err := bo.UnmarshalJSON(raw); err != nil {\n\t\treturn nil, err\n\t}\n\treturn bo, nil\n}", "func NewRawCardSignerWithCtx(pointer unsafe.Pointer) *RawCardSigner {\n\tctx := (*C.vssc_raw_card_signer_t /*ct2*/)(pointer)\n\tobj := &RawCardSigner{\n\t\tcCtx: ctx,\n\t}\n\truntime.SetFinalizer(obj, (*RawCardSigner).Delete)\n\treturn obj\n}", "func New(OrganisationID string, BaseURL string) *Client {\n\tconfig := config{\n\t\tURL: BaseURL,\n\t\tOrganisationID: OrganisationID,\n\t\tclient: &http.Client{},\n\t}\n\treturn &Client{\n\t\tAccount: AccountEndpoint{\n\t\t\tconfig: &config,\n\t\t},\n\t}\n}", "func (s SecureValueTypeUtilityBill) construct() SecureValueTypeClass { return &s }", "func (c Client) New(params *stripe.TreasuryCreditReversalParams) (*stripe.TreasuryCreditReversal, error) {\n\tcreditreversal := &stripe.TreasuryCreditReversal{}\n\terr := c.B.Call(\n\t\thttp.MethodPost,\n\t\t\"/v1/treasury/credit_reversals\",\n\t\tc.Key,\n\t\tparams,\n\t\tcreditreversal,\n\t)\n\treturn creditreversal, err\n}", "func NewCustomAccounting(h modules.Host, m modules.Miner, r modules.Renter, w modules.Wallet, persistDir string, deps modules.Dependencies) (*Accounting, error) {\n\t// Check that at least the wallet is not nil\n\tif w == nil {\n\t\treturn nil, errNilWallet\n\t}\n\n\t// Check required parameters\n\tif persistDir == \"\" {\n\t\treturn nil, errNilPersistDir\n\t}\n\tif deps == nil {\n\t\treturn nil, errNilDeps\n\t}\n\n\t// Initialize the accounting\n\ta := &Accounting{\n\t\tstaticHost: h,\n\t\tstaticMiner: m,\n\t\tstaticRenter: r,\n\t\tstaticWallet: w,\n\n\t\tstaticPersistDir: persistDir,\n\n\t\tstaticDeps: deps,\n\t}\n\n\t// Initialize the persistence\n\terr := a.initPersist()\n\tif err != nil {\n\t\treturn nil, errors.AddContext(err, \"unable to initialize the persistence\")\n\t}\n\n\t// Launch background thread to persist the accounting information\n\tif !a.staticDeps.Disrupt(\"DisablePersistLoop\") {\n\t\tgo a.callThreadedPersistAccounting()\n\t}\n\treturn a, nil\n}", "func newTx(ctx context.Context, drv dialect.Driver) (*txDriver, error) {\n\ttx, err := drv.Tx(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &txDriver{tx: tx, drv: drv}, nil\n}", "func newTx(ctx context.Context, drv dialect.Driver) (*txDriver, error) {\n\ttx, err := drv.Tx(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &txDriver{tx: tx, drv: drv}, nil\n}", "func NewAccount(opts ...AccountCreationOption) (*Account, error) {\n\taccount := &Account{\n\t\tBalance: big.NewInt(0),\n\t\tvotingWeight: big.NewInt(0),\n\t\taccountType: 1,\n\t}\n\tfor _, opt := range opts {\n\t\tif err := opt(account); err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"failed to apply account creation option\")\n\t\t}\n\t}\n\treturn account, nil\n}", "func CreateDepositRawTxCmd() *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse: \"deposit\",\n\t\tShort: \"one key get deposit input data\",\n\t\tRun: depositSecret,\n\t}\n\tdepositSecretCmdFlags(cmd)\n\treturn cmd\n}", "func New(transport runtime.ClientTransport, formats strfmt.Registry) *OpenbankingPaymentsClient {\n\t// ensure nullable parameters have default\n\tif formats == nil {\n\t\tformats = strfmt.Default\n\t}\n\n\tcli := new(OpenbankingPaymentsClient)\n\tcli.Transport = transport\n\tcli.DomesticPayments = domestic_payments.New(transport, formats)\n\tcli.DomesticScheduledPayments = domestic_scheduled_payments.New(transport, formats)\n\tcli.DomesticStandingOrders = domestic_standing_orders.New(transport, formats)\n\tcli.FilePayments = file_payments.New(transport, formats)\n\tcli.InternationalPayments = international_payments.New(transport, formats)\n\tcli.InternationalScheduledPayments = international_scheduled_payments.New(transport, formats)\n\tcli.InternationalStandingOrders = international_standing_orders.New(transport, formats)\n\tcli.PaymentDetails = payment_details.New(transport, formats)\n\treturn cli\n}", "func (client *Client) CreateRawSendFromWithData(watchAddress, destinationAddress string, assets map[string]float64, data []string) (Response, error) {\n\n\tmsg := client.Command(\n\t\t\"createrawsendfrom\",\n\t\t[]interface{}{\n\t\t\twatchAddress,\n\t\t\tmap[string]interface{}{\n\t\t\t\tdestinationAddress: assets,\n\t\t\t},\n\t\t\tdata,\n\t\t},\n\t)\n\n\treturn client.Post(msg)\n}", "func New(url string, username string, password string) TransmissionClient {\n\tapiclient := NewClient(url, username, password)\n\ttc := TransmissionClient{apiclient: apiclient}\n\treturn tc\n}", "func newTransaction(kvScheduler scheduler_api.KVScheduler) *kvSchedulerTxn {\n\treturn &kvSchedulerTxn{\n\t\tkvScheduler: kvScheduler,\n\t\tvalues: make(api.KeyValuePairs),\n\t\tmerged: make(api.KeyValuePairs),\n\t}\n}", "func New(config Config, root *Account) (*Thereum, error) {\n\t// init the configured db\n\tdb := config.DB()\n\t// delay := config.Delayer()\n\n\t// init the genesis block + any accounts designated in config.Allocaiton\n\tgenesis, accounts, err := config.Genesis()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tgenBlock := genesis.MustCommit(db)\n\n\tif root == nil {\n\t\troot, _ = NewAccount(\"defaultRoot\", big.NewInt(100))\n\t}\n\tchainConfig := params.AllEthashProtocolChanges\n\tchainConfig.ChainID = big.NewInt(1)\n\tbc, _ := core.NewBlockChain(db, nil, chainConfig, ethash.NewFaker(), vm.Config{}, nil)\n\tt := &Thereum{\n\t\ttxPool: txpool.NewLinkedPool(),\n\t\tdatabase: db,\n\t\tblockchain: bc,\n\t\tsigner: types.NewEIP155Signer(big.NewInt(1)),\n\t\troot: root,\n\t\tgasLimit: config.GasLimit, // TODO: config and make more flexible\n\t\tDelay: int(config.Delay),\n\t\tEvents: filters.NewEventSystem(&filterBackend{db: db, bc: bc}, false),\n\t\tAccounts: accounts,\n\t}\n\tt.pendingBlock = genBlock\n\tt.chainConfig = chainConfig\n\treturn t, nil\n}", "func NewTxRecord(serializedTx []byte, received time.Time) (*TxRecord, er.R) {\n\trec := &TxRecord{\n\t\tReceived: received,\n\t\tSerializedTx: serializedTx,\n\t}\n\terr := rec.MsgTx.Deserialize(bytes.NewReader(serializedTx))\n\tif err != nil {\n\t\tstr := \"failed to deserialize transaction\"\n\t\treturn nil, storeError(ErrInput, str, err)\n\t}\n\tcopy(rec.Hash[:], chainhash.DoubleHashB(serializedTx))\n\treturn rec, nil\n}", "func NewTxRecord(serializedTx []byte, received time.Time) (*TxRecord, error) {\n\trec := &TxRecord{\n\t\tReceived: received,\n\t\tSerializedTx: serializedTx,\n\t}\n\terr := rec.MsgTx.Deserialize(bytes.NewReader(serializedTx))\n\tif err != nil {\n\t\tstr := \"failed to deserialize transaction\"\n\t\treturn nil, storeError(ErrInput, str, err)\n\t}\n\tcopy(rec.Hash[:], chainhash.DoubleHashB(serializedTx))\n\treturn rec, nil\n}", "func CreateRawTransaction(amount_s string, fee_s string, from_ucs_s string, to_ucs_s string, refund_ucs_s string, spendingTxs_s string) (string, error) {\n\tamount, ok := scanAmount(amount_s)\n\tif !ok {\n\t\treturn \"\", errors.New(\"could not read amount from '\" + amount_s + \"'\")\n\t}\n\tfee, ok := scanAmount(fee_s)\n\tif !ok {\n\t\treturn \"\", errors.New(\"could not read fee from '\" + fee_s + \"'\")\n\t}\n\n\tvar spendingTx []SpendingTransaction\n\terr := json.Unmarshal([]byte(spendingTxs_s), &spendingTx)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tvar from_ucs types.UnlockConditions\n\terr = json.Unmarshal([]byte(from_ucs_s), &from_ucs)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tvar to_ucs types.UnlockConditions\n\terr = json.Unmarshal([]byte(to_ucs_s), &to_ucs)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tvar refund_ucs *types.UnlockConditions = nil\n\tif len(refund_ucs_s) != 0 {\n\t\trefund_ucs = &types.UnlockConditions{}\n\t\terr = json.Unmarshal([]byte(refund_ucs_s), &refund_ucs)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t}\n\n\toutput := types.SiacoinOutput{\n\t\tValue: amount,\n\t\tUnlockHash: to_ucs.UnlockHash(),\n\t}\n\n\ttxnBuilder, err := startTransaction()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\terr = txnBuilder.FundSiacoins(amount.Add(fee), spendingTx, from_ucs, refund_ucs)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\ttxnBuilder.AddMinerFee(fee)\n\ttxnBuilder.AddSiacoinOutput(output)\n\n\tresult, err := json.Marshal(txnBuilder)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(result), nil\n}", "func NewRPCCtx(embed Ctx) *RPCCtx {\n\tret := &RPCCtx{\n\t\tembed: embed,\n\t\tServices: finder.New(),\n\t\tLog: &ggt.VoidLog{},\n\t\tSession: &ggt.VoidSession{},\n\t\tUpload: &ggt.FileProvider{},\n\t}\n\tret.Log.Handle(nil, nil, nil, \"constructor\", \"RPCCtx\")\n\treturn ret\n}", "func newPRSignedBaseLayer(baseLayerIdentity PolicyReferenceMatch) (*prSignedBaseLayer, error) {\n\tif baseLayerIdentity == nil {\n\t\treturn nil, InvalidPolicyFormatError(\"baseLayerIdentity not specified\")\n\t}\n\treturn &prSignedBaseLayer{\n\t\tprCommon: prCommon{Type: prTypeSignedBaseLayer},\n\t\tBaseLayerIdentity: baseLayerIdentity,\n\t}, nil\n}", "func NewBase() Base {\r\n\treturn Base{\r\n\t\tActive: \"\",\r\n\t\tTitle: \"Lemonade Stand Supply\",\r\n\t}\r\n}", "func (ws *WebServer) NewAccount(c *gin.Context) {\n\tnetwork := ws.nodeConfig.GetNetwork()\n\tif network == \"\" {\n\t\tReturnError(c, 500, ErrorNoNetwork.Error())\n\t\treturn\n\t}\n\tn := sdk.Testnet\n\tif network == \"bitmark\" {\n\t\tn = sdk.Livenet\n\t}\n\tseedFile := filepath.Join(ws.rootPath, \"bitmarkd\", network, \"proof.sign\")\n\tif _, err := os.Stat(seedFile); err == nil {\n\t\tReturnError(c, 500, ErrorNoSeedFile.Error())\n\t\treturn\n\t}\n\n\ta, err := sdk.NewAccount(n)\n\tif err != nil {\n\t\tReturnError(c, 500, ErrorCreateAccount.Error())\n\t\treturn\n\t}\n\tseed := a.Seed()\n\n\tf, err := os.OpenFile(seedFile, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0600)\n\tif err != nil {\n\t\tReturnError(c, 500, ErrorOpenSeedFile.Error())\n\t\treturn\n\t}\n\tdefer f.Close()\n\n\t_, err = f.WriteString(fmt.Sprintf(\"SEED:%s\", seed))\n\tif err != nil {\n\t\tReturnError(c, 500, ErrorToWriteSeedFile.Error())\n\t\treturn\n\t}\n\tws.SetAccount(a.AccountNumber(), seed, network) // Record in AccountInfo in memory\n\terr = ws.saveAcct()\n\tif nil != err {\n\t\tReturnError(c, 500, ErrorAutoSaveAccount.Error())\n\t\treturn\n\n\t}\n\tc.JSON(200, map[string]interface{}{\n\t\t\"ok\": 1,\n\t})\n}", "func New(ctx context.Context, now NowFunc) *Blockchain {\n\tvar b = Blockchain{\n\t\tnow: now,\n\t}\n\n\tgenesisBlock := Block{\n\t\t0,\n\t\tb.now().String(),\n\t\t0,\n\t\t\"\",\n\t\t\"\",\n\t}\n\n\tb.Blocks = append(b.Blocks, genesisBlock)\n\n\treturn &b\n}", "func (s SecureValueTypeRentalAgreement) construct() SecureValueTypeClass { return &s }", "func NewTrimmedTX(hash util.Uint256) *Transaction {\n\treturn &Transaction{\n\t\thash: hash,\n\t\thashed: true,\n\t\tTrimmed: true,\n\t}\n}", "func New(conn *bindings.Conn, id uint64) *Txn {\n\treturn &Txn{\n\t\tconn: conn,\n\t\tid: id,\n\t\tmachine: newMachine(),\n\t}\n}", "func (ak AccountKeeper) NewAccount(ctx sdk.Context, acc exported.Account) exported.Account {\n\t// FIXME: update account number\n\treturn acc\n}", "func New(params *stripe.UsageRecordParams) (*stripe.UsageRecord, error) {\n\treturn getC().New(params)\n}", "func New(token string) (*GAB, error) {\n\tbot, err := tapi.NewBotAPI(token)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Could not create new bot with provided token: %v\", err)\n\t}\n\tlog.Printf(\"Authorized on account %s\", bot.Self.UserName)\n\treturn &GAB{\n\t\tTelBot: bot,\n\t}, nil\n}", "func NewCoinbaseTX(to, data string) *Transaction {\n\tif data == \"\" {\n\t\trandData := make([]byte, 20)\n\t\t_, err := rand.Read(randData)\n\t\tif err != nil {\n\t\t\tlog.Panic(err)\n\t\t}\n\t\tdata = fmt.Sprintf(\"%x\", randData)\n\t}\n\ttxin := TXInput{[]byte{}, -1, nil, []byte(data)} // remember this tx need no previous tx output\n\ttxout := NewTXOutput(subsidy, to)\n\ttx := Transaction{nil, []TXInput{txin}, []TXOutput{*txout}}\n\ttx.ID = tx.Hash() // New way\n\treturn &tx\n}", "func (c Client) New(params *stripe.TestHelpersTreasuryReceivedDebitParams) (*stripe.TreasuryReceivedDebit, error) {\n\treceiveddebit := &stripe.TreasuryReceivedDebit{}\n\terr := c.B.Call(\n\t\thttp.MethodPost,\n\t\t\"/v1/test_helpers/treasury/received_debits\",\n\t\tc.Key,\n\t\tparams,\n\t\treceiveddebit,\n\t)\n\treturn receiveddebit, err\n}", "func newRandomAccountPersistence() accountPersistence {\n\taid, sk := modules.NewAccountID()\n\treturn accountPersistence{\n\t\tAccountID: aid,\n\t\tBalance: types.NewCurrency64(fastrand.Uint64n(1e3)),\n\t\tHostKey: types.SiaPublicKey{},\n\t\tSecretKey: sk,\n\t}\n}" ]
[ "0.70239556", "0.7022922", "0.6753236", "0.6679299", "0.644923", "0.6337664", "0.62031996", "0.6165785", "0.56279266", "0.5534443", "0.5452274", "0.54449195", "0.52648777", "0.52131265", "0.52131265", "0.5204797", "0.5139948", "0.5122591", "0.5079009", "0.5059517", "0.503759", "0.5005238", "0.4977278", "0.4969858", "0.4964585", "0.49636662", "0.49478373", "0.49011165", "0.48790994", "0.48741758", "0.48611256", "0.48528954", "0.48420322", "0.4836913", "0.4836913", "0.48207515", "0.48094273", "0.48073936", "0.4806476", "0.48009056", "0.47892365", "0.477907", "0.47627556", "0.4726182", "0.4717712", "0.47093782", "0.46825004", "0.4675469", "0.46567455", "0.46566668", "0.4649242", "0.4646849", "0.46374443", "0.46295452", "0.46269292", "0.4623907", "0.46183765", "0.46110687", "0.4604068", "0.45944983", "0.45933083", "0.4590322", "0.45898435", "0.45873755", "0.4584808", "0.45837495", "0.4582209", "0.4577678", "0.4575311", "0.45716223", "0.4569976", "0.45696563", "0.45657814", "0.45498478", "0.45458606", "0.45458606", "0.45441183", "0.45412928", "0.45388284", "0.45367798", "0.4530983", "0.45152572", "0.45144427", "0.45119584", "0.4510944", "0.4508748", "0.45063728", "0.4504158", "0.45030057", "0.45008403", "0.4494306", "0.44908804", "0.44881508", "0.4484404", "0.4483953", "0.4481197", "0.44790542", "0.44767871", "0.44703016", "0.44635046" ]
0.81710976
0
NewDelayedVestingAccount returns a DelayedVestingAccount
func NewDelayedVestingAccount(baseAcc *authtypes.BaseAccount, originalVesting sdk.Coins, endTime int64) *DelayedVestingAccount { baseVestingAcc := &BaseVestingAccount{ BaseAccount: baseAcc, OriginalVesting: originalVesting, EndTime: endTime, } return &DelayedVestingAccount{baseVestingAcc} }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func NewDelayedVestingAccountRaw(bva *BaseVestingAccount) *DelayedVestingAccount {\n\treturn &DelayedVestingAccount{\n\t\tBaseVestingAccount: bva,\n\t}\n}", "func newPeriodicVestingAccount(address sdk.AccAddress, periods vestingtypes.Periods, firstPeriodStartTimestamp int64) *vestingtypes.PeriodicVestingAccount {\n\tbaseAccount := authtypes.NewBaseAccount(address, nil, 0, 0)\n\n\toriginalVesting := sdk.NewCoins()\n\tfor _, p := range periods {\n\t\toriginalVesting = originalVesting.Add(p.Amount...)\n\t}\n\n\tvar totalPeriods int64\n\tfor _, p := range periods {\n\t\ttotalPeriods += p.Length\n\t}\n\tendTime := firstPeriodStartTimestamp + totalPeriods\n\n\tbaseVestingAccount := vestingtypes.NewBaseVestingAccount(baseAccount, originalVesting, endTime)\n\treturn vestingtypes.NewPeriodicVestingAccountRaw(baseVestingAccount, firstPeriodStartTimestamp, periods)\n}", "func NewPeriodicVestingAccount(baseAcc *authtypes.BaseAccount, originalVesting sdk.Coins, startTime int64, periods Periods) *PeriodicVestingAccount {\n\tendTime := startTime\n\tfor _, p := range periods {\n\t\tendTime += p.Length\n\t}\n\tbaseVestingAcc := &BaseVestingAccount{\n\t\tBaseAccount: baseAcc,\n\t\tOriginalVesting: originalVesting,\n\t\tEndTime: endTime,\n\t}\n\n\treturn &PeriodicVestingAccount{\n\t\tBaseVestingAccount: baseVestingAcc,\n\t\tStartTime: startTime,\n\t\tVestingPeriods: periods,\n\t}\n}", "func newAccount() *Account {\n\treturn &Account{\n\t\tblocks: make(map[string]uint64),\n\t}\n}", "func NewBaseVestingAccount(baseAccount *authtypes.BaseAccount, originalVesting sdk.Coins, endTime int64) *BaseVestingAccount {\n\treturn &BaseVestingAccount{\n\t\tBaseAccount: baseAccount,\n\t\tOriginalVesting: originalVesting,\n\t\tDelegatedFree: sdk.NewCoins(),\n\t\tDelegatedVesting: sdk.NewCoins(),\n\t\tEndTime: endTime,\n\t}\n}", "func (e Account) EntNew() ent.Ent { return &Account{} }", "func (e Account) EntNew() ent.Ent { return &Account{} }", "func NewValidatorVestingAccount(baseAcc *authtypes.BaseAccount, startTime int64, periods vestingtypes.Periods, validatorAddress sdk.ConsAddress, returnAddress sdk.AccAddress, signingThreshold int64) *ValidatorVestingAccount {\n\n\tendTime := startTime\n\tfor _, p := range periods {\n\t\tendTime += p.Length\n\t}\n\tbaseVestingAcc := &vestingtypes.BaseVestingAccount{\n\t\tBaseAccount: baseAcc,\n\t\tOriginalVesting: baseAcc.Coins,\n\t\tEndTime: endTime,\n\t}\n\tpva := &vestingtypes.PeriodicVestingAccount{\n\t\tBaseVestingAccount: baseVestingAcc,\n\t\tStartTime: startTime,\n\t\tVestingPeriods: periods,\n\t}\n\tvar vestingPeriodProgress []VestingProgress\n\tfor i := 0; i < len(periods); i++ {\n\t\tvestingPeriodProgress = append(vestingPeriodProgress, VestingProgress{false, false})\n\t}\n\n\treturn &ValidatorVestingAccount{\n\t\tPeriodicVestingAccount: pva,\n\t\tValidatorAddress: validatorAddress,\n\t\tReturnAddress: returnAddress,\n\t\tSigningThreshold: signingThreshold,\n\t\tCurrentPeriodProgress: CurrentPeriodProgress{0, 0},\n\t\tVestingPeriodProgress: vestingPeriodProgress,\n\t\tDebtAfterFailedVesting: sdk.NewCoins(),\n\t}\n}", "func (c *CoinTest) newAccount(stub shim.ChaincodeStubInterface, args []string) pb.Response {\r\n\tvar id string\r\n\tvar asset int\r\n\tvar err error\r\n\r\n\tif len(args) == 1{\r\n\t\tid = args[0]\r\n\t\tasset = 0\r\n\t}else if len(args) == 2{\r\n\t\tid = args[0]\r\n\t\t//asset, err = strconv.Atoi(args[1])\r\n\t\t//if err != nil{\r\n\t\t//\treturn shim.Error(\"Invalid asset amount, expecting a integer value\")\r\n\t\t//}\r\n\t\tasset = 0;\r\n\t}else{\r\n\t\treturn shim.Error(\"Incorrect number of arguments.\")\r\n\t}\r\n\r\n\t//deliver 0 number of TolakCoin to user\r\n\ttolakCoin.Token.Deliver(token.Address(id), int(asset))\r\n\r\n\t//write to ledger\r\n\terr = stub.PutState(id, []byte(strconv.Itoa(asset)))\r\n\tif err != nil{\r\n\t\treturn shim.Error(err.Error())\r\n\t}\r\n\r\n\treturn shim.Success(nil)\r\n}", "func NewContinuousVestingAccount(baseAcc *authtypes.BaseAccount, originalVesting sdk.Coins, startTime, endTime int64) *ContinuousVestingAccount {\n\tbaseVestingAcc := &BaseVestingAccount{\n\t\tBaseAccount: baseAcc,\n\t\tOriginalVesting: originalVesting,\n\t\tEndTime: endTime,\n\t}\n\n\treturn &ContinuousVestingAccount{\n\t\tStartTime: startTime,\n\t\tBaseVestingAccount: baseVestingAcc,\n\t}\n}", "func NewClawbackVestingAccount(baseAcc *authtypes.BaseAccount, funder sdk.AccAddress, originalVesting sdk.Coins, startTime int64, lockupPeriods, vestingPeriods Periods) *ClawbackVestingAccount {\n\t// copy and align schedules to avoid mutating inputs\n\tlp := make(Periods, len(lockupPeriods))\n\tcopy(lp, lockupPeriods)\n\tvp := make(Periods, len(vestingPeriods))\n\tcopy(vp, vestingPeriods)\n\t_, endTime := AlignSchedules(startTime, startTime, lp, vp)\n\tbaseVestingAcc := &BaseVestingAccount{\n\t\tBaseAccount: baseAcc,\n\t\tOriginalVesting: originalVesting,\n\t\tEndTime: endTime,\n\t}\n\n\treturn &ClawbackVestingAccount{\n\t\tBaseVestingAccount: baseVestingAcc,\n\t\tFunderAddress: funder.String(),\n\t\tStartTime: startTime,\n\t\tLockupPeriods: lp,\n\t\tVestingPeriods: vp,\n\t}\n}", "func NewDelayedWithdrawal(address common.Address, backend bind.ContractBackend) (*DelayedWithdrawal, error) {\n\tcontract, err := bindDelayedWithdrawal(address, backend, backend, backend)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &DelayedWithdrawal{DelayedWithdrawalCaller: DelayedWithdrawalCaller{contract: contract}, DelayedWithdrawalTransactor: DelayedWithdrawalTransactor{contract: contract}, DelayedWithdrawalFilterer: DelayedWithdrawalFilterer{contract: contract}}, nil\n}", "func NewAccount(val string) AccountField {\n\treturn AccountField{quickfix.FIXString(val)}\n}", "func NewMsgCreateVestingAccount(fromAddr, toAddr sdk.AccAddress, amount sdk.Coins, endTime int64, delayed bool) *MsgCreateVestingAccount {\n\treturn &MsgCreateVestingAccount{\n\t\tFromAddress: fromAddr.String(),\n\t\tToAddress: toAddr.String(),\n\t\tAmount: amount,\n\t\tEndTime: endTime,\n\t\tDelayed: delayed,\n\t}\n}", "func NewMsgCreatePeriodicVestingAccount(fromAddr, toAddr sdk.AccAddress, startTime int64, periods []Period) *MsgCreatePeriodicVestingAccount {\n\treturn &MsgCreatePeriodicVestingAccount{\n\t\tFromAddress: fromAddr.String(),\n\t\tToAddress: toAddr.String(),\n\t\tStartTime: startTime,\n\t\tVestingPeriods: periods,\n\t}\n}", "func NewAccount(txr *repository.Transactioner) repository.Account {\n\treturn &account{txr: txr}\n}", "func NewPeriodicVestingAccountRaw(bva *BaseVestingAccount, startTime int64, periods Periods) *PeriodicVestingAccount {\n\treturn &PeriodicVestingAccount{\n\t\tBaseVestingAccount: bva,\n\t\tStartTime: startTime,\n\t\tVestingPeriods: periods,\n\t}\n}", "func NewAllocAccount(val string) AllocAccountField {\n\treturn AllocAccountField{quickfix.FIXString(val)}\n}", "func tNewUser(lbl string) *tUser {\n\tintBytes := make([]byte, 4)\n\tbinary.BigEndian.PutUint32(intBytes, acctCounter)\n\tacctID := account.AccountID{}\n\tcopy(acctID[:], acctTemplate[:])\n\tcopy(acctID[account.HashSize-4:], intBytes)\n\taddr := strconv.Itoa(int(acctCounter))\n\tsig := []byte{0xab} // Just to differentiate from the addr.\n\tsig = append(sig, intBytes...)\n\tsigHex := hex.EncodeToString(sig)\n\tacctCounter++\n\treturn &tUser{\n\t\tsig: sig,\n\t\tsigHex: sigHex,\n\t\tacct: acctID,\n\t\taddr: addr,\n\t\tlbl: lbl,\n\t}\n}", "func MakeNewAccount(name string) (*MyAccount, error) {\n\tkeys, err := NewKeypair()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &MyAccount{\n\t\tFields: make(map[string]string),\n\t\tKeys: keys,\n\t\tName: name,\n\t}, nil\n}", "func NewFundedAccount() *keypair.Full {\n\tkp, err := keypair.Random()\n\tif err != nil {\n\t\tlog.Fatal(err, \"generating random keypair\")\n\t}\n\terr = FundAccount(kp.Address())\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tlog.Printf(\"successfully funded %s\", kp.Address())\n\treturn kp\n}", "func NewAccount(user, apiKey string) *Account {\n\treturn &Account{user: user, apiKey: apiKey}\n}", "func newTrial(\n\tlogCtx logger.Context,\n\ttaskID model.TaskID,\n\tjobID model.JobID,\n\tjobSubmissionTime time.Time,\n\texperimentID int,\n\tinitialState model.State,\n\tsearcher trialSearcherState,\n\trm rm.ResourceManager,\n\tdb db.DB,\n\tconfig expconf.ExperimentConfig,\n\twarmStartCheckpoint *model.Checkpoint,\n\ttaskSpec *tasks.TaskSpec,\n\tgeneratedKeys ssh.PrivateAndPublicKeys,\n\trestored bool,\n) *trial {\n\treturn &trial{\n\t\ttaskID: taskID,\n\t\tjobID: jobID,\n\t\tjobSubmissionTime: jobSubmissionTime,\n\t\texperimentID: experimentID,\n\t\tstate: initialState,\n\t\tsearcher: searcher,\n\n\t\tdb: db,\n\t\trm: rm,\n\n\t\tconfig: config,\n\t\ttaskSpec: taskSpec,\n\t\tgeneratedKeys: generatedKeys,\n\t\twarmStartCheckpoint: warmStartCheckpoint,\n\n\t\tlogCtx: logger.MergeContexts(logCtx, logger.Context{\n\t\t\t\"task-id\": taskID,\n\t\t\t\"task-type\": model.TaskTypeTrial,\n\t\t}),\n\t\trestored: restored,\n\t}\n}", "func newServiceAccount(cr *storagev1.CSIPowerMaxRevProxy) *v1.ServiceAccount {\n\treturn &v1.ServiceAccount{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: ReverseProxyName,\n\t\t\tNamespace: cr.Namespace,\n\t\t\tOwnerReferences: getOwnerReferences(cr),\n\t\t},\n\t}\n}", "func NewDelayedWithdrawalCaller(address common.Address, caller bind.ContractCaller) (*DelayedWithdrawalCaller, error) {\n\tcontract, err := bindDelayedWithdrawal(address, caller, nil, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &DelayedWithdrawalCaller{contract: contract}, nil\n}", "func NewValidatorVestingAccountRaw(bva *vestingtypes.BaseVestingAccount,\n\tstartTime int64, periods vestingtypes.Periods, validatorAddress sdk.ConsAddress, returnAddress sdk.AccAddress, signingThreshold int64) *ValidatorVestingAccount {\n\n\tpva := &vestingtypes.PeriodicVestingAccount{\n\t\tBaseVestingAccount: bva,\n\t\tStartTime: startTime,\n\t\tVestingPeriods: periods,\n\t}\n\tvar vestingPeriodProgress []VestingProgress\n\tfor i := 0; i < len(periods); i++ {\n\t\tvestingPeriodProgress = append(vestingPeriodProgress, VestingProgress{false, false})\n\t}\n\n\treturn &ValidatorVestingAccount{\n\t\tPeriodicVestingAccount: pva,\n\t\tValidatorAddress: validatorAddress,\n\t\tReturnAddress: returnAddress,\n\t\tSigningThreshold: signingThreshold,\n\t\tCurrentPeriodProgress: CurrentPeriodProgress{0, 0},\n\t\tVestingPeriodProgress: vestingPeriodProgress,\n\t\tDebtAfterFailedVesting: sdk.NewCoins(),\n\t}\n}", "func newTransportRecord() *TransportRecord {\n\ttr := TransportRecord{}\n\ttr.id = messages.RandTransportId()\n\ttr.status = DISCONNECTED\n\tif messages.IsDebug() {\n\t\tlog.Printf(\"Created TransportRecord: %d\\n\", tr.id)\n\t}\n\treturn &tr\n}", "func makeAccount(){\n\toperatorSecret, err := hedera.SecretKeyFromString(secret)\n\tif err != nil{\n\t\tpanic(err)\n\t}\n\n\tsecretKey, _ := hedera.GenerateSecretKey()\n\tpublic := secretKey.Public()\n\n\tfmt.Printf(\"secret = %v\\n\", secretKey)\n\tfmt.Printf(\"public = %v\\n\", public)\n\n\tclient, err := hedera.Dial(server)\n\tif err !=nil{\n\t\tpanic(err)\n\t}\n\tdefer client.Close()\n\n\tnodeAccountID := hedera.AccountID{Account: 3}\n\toperatorAccountID := hedera.AccountID{Account: 1001}\n\ttime.Sleep(2* time.Second)\n\tresponse, err := client.CreateAccount().Key(public).InitialBalance(0).Operator(operatorAccountID).Node(nodeAccountID).Memo(\"Test make Account\").Sign(operatorSecret).Execute()\n\tif err != nil{\n\t\tpanic(err)\n\t}\n\n\ttransactionID := response.ID\n\tfmt.Printf(\"Created account; transaction = %v\\n\", transactionID)\n\ttime.Sleep(2* time.Second)\n \n\treceipt,err := client.Transaction(*transactionID).Receipt().Get()\n\tif err != nil{\n\t\tpanic(err)\n\t}\n\tfmt.Printf(\"Account = %v\\n\", *receipt.AccountID)\n\n}", "func (dva DelayedVestingAccount) Validate() error {\n\treturn dva.BaseVestingAccount.Validate()\n}", "func NewAccount(instanceID uuid.UUID, name, aud string) (*Account, error) {\n\tid, err := uuid.NewV4()\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"Error generating unique id\")\n\t}\n\n\taccount := &Account{\n\t\tInstanceID: instanceID,\n\t\tID: id,\n\t\tAud: aud,\n\t\tName: name,\n\t}\n\treturn account, nil\n}", "func newRandomAccountPersistence() accountPersistence {\n\taid, sk := modules.NewAccountID()\n\treturn accountPersistence{\n\t\tAccountID: aid,\n\t\tBalance: types.NewCurrency64(fastrand.Uint64n(1e3)),\n\t\tHostKey: types.SiaPublicKey{},\n\t\tSecretKey: sk,\n\t}\n}", "func (ws *WebServer) NewAccount(c *gin.Context) {\n\tnetwork := ws.nodeConfig.GetNetwork()\n\tif network == \"\" {\n\t\tReturnError(c, 500, ErrorNoNetwork.Error())\n\t\treturn\n\t}\n\tn := sdk.Testnet\n\tif network == \"bitmark\" {\n\t\tn = sdk.Livenet\n\t}\n\tseedFile := filepath.Join(ws.rootPath, \"bitmarkd\", network, \"proof.sign\")\n\tif _, err := os.Stat(seedFile); err == nil {\n\t\tReturnError(c, 500, ErrorNoSeedFile.Error())\n\t\treturn\n\t}\n\n\ta, err := sdk.NewAccount(n)\n\tif err != nil {\n\t\tReturnError(c, 500, ErrorCreateAccount.Error())\n\t\treturn\n\t}\n\tseed := a.Seed()\n\n\tf, err := os.OpenFile(seedFile, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0600)\n\tif err != nil {\n\t\tReturnError(c, 500, ErrorOpenSeedFile.Error())\n\t\treturn\n\t}\n\tdefer f.Close()\n\n\t_, err = f.WriteString(fmt.Sprintf(\"SEED:%s\", seed))\n\tif err != nil {\n\t\tReturnError(c, 500, ErrorToWriteSeedFile.Error())\n\t\treturn\n\t}\n\tws.SetAccount(a.AccountNumber(), seed, network) // Record in AccountInfo in memory\n\terr = ws.saveAcct()\n\tif nil != err {\n\t\tReturnError(c, 500, ErrorAutoSaveAccount.Error())\n\t\treturn\n\n\t}\n\tc.JSON(200, map[string]interface{}{\n\t\t\"ok\": 1,\n\t})\n}", "func NewAccount() *Account {\n\n\tcreatedAccount := Account{}\n\n\tnewPrivateKey, err := generatePrivateKey(4096)\n\tif err != nil {\n\t\tlog.Fatal(\"Error generating rsa private key \", err)\n\t}\n\tnewPublicKey, err := generatePublicKey(&newPrivateKey.PublicKey)\n\tif err != nil {\n\t\tlog.Fatal(\"Error generating rsa public key \", err)\n\t}\n\tcreatedAccount.privateKey = newPrivateKey\n\tcreatedAccount.Address = string(newPublicKey)\n\tcreatedAccount.Amount = 0\n\n\treturn &createdAccount\n}", "func NewAccount(owner string) *Account {\n\treturn &Account{owner: owner, balance: 0}\n}", "func newServiceAccount(cr *argoprojv1a1.ArgoCD) *corev1.ServiceAccount {\n\treturn &corev1.ServiceAccount{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: cr.Name,\n\t\t\tNamespace: cr.Namespace,\n\t\t\tLabels: argoutil.LabelsForCluster(cr),\n\t\t},\n\t}\n}", "func (e Department) EntNew() ent.Ent { return &Department{} }", "func New(ds ds.Datastore, delay delay.D) ds.Datastore {\n\treturn &delayed{ds: ds, delay: delay}\n}", "func (as *Service) Create(name, iamRole, externalID string) (*Account, error) {\n\n\tbody := map[string]map[string]string{\n\t\t\"account\": {\"name\": name},\n\t}\n\n\tlog.Printf(\"Making request %v\\n\", body)\n\treq, err := as.httpClient.NewRequest(http.MethodPost, \"/setup/account\", &body)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar v common.Response\n\t_, err = as.httpClient.Do(req, &v)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(v.Response.Items) == 0 {\n\t\treturn nil, errors.New(\"Couldn't create account\")\n\t}\n\tvar account Account\n\n\tfmt.Println(string(v.Response.Items[0]))\n\n\terr = json.Unmarshal(v.Response.Items[0], &account)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttime.Sleep(time.Second * 5)\n\n\terr = as.setupCloudCredentials(account.ID, iamRole, externalID)\n\n\tif err != nil {\n\t\t_ = as.Delete(account.ID)\n\t\treturn nil, err\n\t}\n\n\treturn &account, nil\n}", "func (msg MsgCreatePeriodicVestingAccount) Type() string { return TypeMsgCreatePeriodicVestingAccount }", "func NewAccount(opts ...AccountCreationOption) (*Account, error) {\n\taccount := &Account{\n\t\tBalance: big.NewInt(0),\n\t\tvotingWeight: big.NewInt(0),\n\t\taccountType: 1,\n\t}\n\tfor _, opt := range opts {\n\t\tif err := opt(account); err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"failed to apply account creation option\")\n\t\t}\n\t}\n\treturn account, nil\n}", "func NewAccount(addr, amount string) *Account {\n\tam := big.NewInt(0)\n\tam.SetString(amount, 0)\n\treturn &Account{Address: addr, Amount: am}\n}", "func (ak AccountKeeper) NewAccount(ctx sdk.Context, acc exported.Account) exported.Account {\n\t// FIXME: update account number\n\treturn acc\n}", "func New(from, to string, amount float64, opts TransactionOptions) Transaction {\n\treturn Transaction{\n\t\tFromID: from,\n\t\tToID: to,\n\t\tAmount: amount,\n\t\tStatus: \"pending\",\n\t\tDescription: opts.Description,\n\t\tCurrency: opts.Currency,\n\t\tCreationTime: time.Now(),\n\t\tUUID: uuid.New().String(),\n\t}\n}", "func (va *ClawbackVestingAccount) addGrant(ctx sdk.Context, sk StakingKeeper, grantStartTime int64, grantLockupPeriods, grantVestingPeriods []Period, grantCoins sdk.Coins) {\n\t// how much is really delegated?\n\tbondedAmt := sk.GetDelegatorBonded(ctx, va.GetAddress())\n\tunbondingAmt := sk.GetDelegatorUnbonding(ctx, va.GetAddress())\n\tdelegatedAmt := bondedAmt.Add(unbondingAmt)\n\tdelegated := sdk.NewCoins(sdk.NewCoin(sk.BondDenom(ctx), delegatedAmt))\n\n\t// discover what has been slashed\n\toldDelegated := va.DelegatedVesting.Add(va.DelegatedFree...)\n\tslashed := oldDelegated.Sub(coinsMin(oldDelegated, delegated))\n\n\t// rebase the DV + DF by capping slashed at the current unvested amount\n\tunvested := va.OriginalVesting.Sub(va.GetVestedOnly(ctx.BlockTime()))\n\tnewSlashed := coinsMin(slashed, unvested)\n\tnewDelegated := delegated.Add(newSlashed...)\n\n\t// modify schedules for the new grant\n\tnewLockupStart, newLockupEnd, newLockupPeriods := DisjunctPeriods(va.StartTime, grantStartTime, va.LockupPeriods, grantLockupPeriods)\n\tnewVestingStart, newVestingEnd, newVestingPeriods := DisjunctPeriods(va.StartTime, grantStartTime,\n\t\tva.GetVestingPeriods(), grantVestingPeriods)\n\tif newLockupStart != newVestingStart {\n\t\tpanic(\"bad start time calculation\")\n\t}\n\tva.StartTime = newLockupStart\n\tva.EndTime = max64(newLockupEnd, newVestingEnd)\n\tva.LockupPeriods = newLockupPeriods\n\tva.VestingPeriods = newVestingPeriods\n\tva.OriginalVesting = va.OriginalVesting.Add(grantCoins...)\n\n\t// cap DV at the current unvested amount, DF rounds out to newDelegated\n\tunvested2 := va.GetVestingCoins(ctx.BlockTime())\n\tva.DelegatedVesting = coinsMin(newDelegated, unvested2)\n\tva.DelegatedFree = newDelegated.Sub(va.DelegatedVesting)\n}", "func newDelayedRouteUpdater(az *Cloud, interval time.Duration) *delayedRouteUpdater {\n\treturn &delayedRouteUpdater{\n\t\taz: az,\n\t\tinterval: interval,\n\t\troutesToUpdate: make([]*delayedRouteOperation, 0),\n\t}\n}", "func (policy *ticketPolicy) OnCreateNewAccount(acc *types.Account) {\n}", "func createRequestAccount() *data.Account {\n\taccount := test.NewAccountDataFromFile(\"create-request.json\")\n\treturn &account.Account\n}", "func NewAccount(id, entityID string) *Account {\n\treturn &Account{\n\t\tID: id,\n\t\tEntityID: entityID,\n\t\tWallets: make([]Wallet, 0),\n\t}\n}", "func newRateLimiter(delay time.Duration) *rateLimiter {\n\treturn &rateLimiter{\n\t\tdelay: delay,\n\t\tops: make(map[string]time.Time),\n\t}\n}", "func NewPermanentLockedAccount(baseAcc *authtypes.BaseAccount, coins sdk.Coins) *PermanentLockedAccount {\n\tbaseVestingAcc := &BaseVestingAccount{\n\t\tBaseAccount: baseAcc,\n\t\tOriginalVesting: coins,\n\t\tEndTime: 0, // ensure EndTime is set to 0, as PermanentLockedAccount's do not have an EndTime\n\t}\n\n\treturn &PermanentLockedAccount{baseVestingAcc}\n}", "func (pva *PeriodicVestingAccount) addGrant(ctx sdk.Context, sk StakingKeeper, grantStartTime int64, grantVestingPeriods []Period, grantCoins sdk.Coins) {\n\t// how much is really delegated?\n\tbondedAmt := sk.GetDelegatorBonded(ctx, pva.GetAddress())\n\tunbondingAmt := sk.GetDelegatorUnbonding(ctx, pva.GetAddress())\n\tdelegatedAmt := bondedAmt.Add(unbondingAmt)\n\tdelegated := sdk.NewCoins(sdk.NewCoin(sk.BondDenom(ctx), delegatedAmt))\n\n\t// discover what has been slashed\n\toldDelegated := pva.DelegatedVesting.Add(pva.DelegatedFree...)\n\tslashed := oldDelegated.Sub(coinsMin(oldDelegated, delegated))\n\n\t// rebase the DV+DF by capping slashed at the current unvested amount\n\tunvested := pva.GetVestingCoins(ctx.BlockTime())\n\tnewSlashed := coinsMin(unvested, slashed)\n\tnewTotalDelegated := delegated.Add(newSlashed...)\n\n\t// modify vesting schedule for the new grant\n\tnewStart, newEnd, newPeriods := DisjunctPeriods(pva.StartTime, grantStartTime,\n\t\tpva.GetVestingPeriods(), grantVestingPeriods)\n\tpva.StartTime = newStart\n\tpva.EndTime = newEnd\n\tpva.VestingPeriods = newPeriods\n\tpva.OriginalVesting = pva.OriginalVesting.Add(grantCoins...)\n\n\t// cap DV at the current unvested amount, DF rounds out to newTotalDelegated\n\tunvested2 := pva.GetVestingCoins(ctx.BlockTime())\n\tpva.DelegatedVesting = coinsMin(newTotalDelegated, unvested2)\n\tpva.DelegatedFree = newTotalDelegated.Sub(pva.DelegatedVesting)\n}", "func (account *Account) New() {\n\n\tparams, _ := pbc.NewParamsFromString(crypto.Params)\n\tpairing := params.NewPairing()\n\n\tA := pairing.NewG1()\n\tAT := pairing.NewG1()\n\ta := pairing.NewZr()\n\n\ta.Rand()\n\n\tG := pairing.NewG1()\n\tT := pairing.NewG1()\n\tG.SetString(crypto.G, 10)\n\tT.SetString(crypto.T, 10)\n\n\tA.PowZn(G, a)\n\tAT.PowZn(T, a)\n\n\taccount.a = a.String()\n\taccount.A = A.String()\n\taccount.AT = AT.String()\n}", "func New(token string) (*GAB, error) {\n\tbot, err := tapi.NewBotAPI(token)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Could not create new bot with provided token: %v\", err)\n\t}\n\tlog.Printf(\"Authorized on account %s\", bot.Self.UserName)\n\treturn &GAB{\n\t\tTelBot: bot,\n\t}, nil\n}", "func (c Client) NewAccount(privateKey crypto.Signer, onlyReturnExisting, termsOfServiceAgreed bool, contact ...string) (Account, error) {\n\tvar opts []NewAccountOptionFunc\n\tif onlyReturnExisting {\n\t\topts = append(opts, NewAcctOptOnlyReturnExisting())\n\t}\n\tif termsOfServiceAgreed {\n\t\topts = append(opts, NewAcctOptAgreeTOS())\n\t}\n\tif contact != nil && len(contact) > 0 {\n\t\topts = append(opts, NewAcctOptWithContacts(contact...))\n\t}\n\n\treturn c.NewAccountOptions(privateKey, opts...)\n}", "func newExponentialBackoff() *exponentialBackoff {\n\tb := &backoff.Backoff{\n\t\tMin: DefaultMinBackoff,\n\t\tMax: DefaultMaxBackoff,\n\t\tJitter: true,\n\t}\n\treturn &exponentialBackoff{b: *b, currentDelay: b.Duration()}\n}", "func (dva *DelayedVestingAccount) UnmarshalJSON(bz []byte) error {\n\tvar alias vestingAccountJSON\n\tif err := legacy.Cdc.UnmarshalJSON(bz, &alias); err != nil {\n\t\treturn err\n\t}\n\n\tdva.BaseVestingAccount = &BaseVestingAccount{\n\t\tBaseAccount: NewBaseAccount(alias.Address, alias.Coins, alias.PubKey, alias.AccountNumber, alias.Sequence),\n\t\tOriginalVesting: alias.OriginalVesting,\n\t\tDelegatedFree: alias.DelegatedFree,\n\t\tDelegatedVesting: alias.DelegatedVesting,\n\t\tEndTime: alias.EndTime,\n\t}\n\n\treturn nil\n}", "func (*ACMEIssuer) newAccount(email string) (acme.Account, error) {\n\tvar acct acme.Account\n\tif email != \"\" {\n\t\tacct.Contact = []string{\"mailto:\" + email} // TODO: should we abstract the contact scheme?\n\t}\n\tprivateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)\n\tif err != nil {\n\t\treturn acct, fmt.Errorf(\"generating private key: %v\", err)\n\t}\n\tacct.PrivateKey = privateKey\n\treturn acct, nil\n}", "func NewBilling(ctx context.Context, dbc cosmosdb.DatabaseClient, dbName string) (Billing, error) {\n\tcollc := cosmosdb.NewCollectionClient(dbc, dbName)\n\n\ttriggers := []*cosmosdb.Trigger{\n\t\t{\n\t\t\tID: \"setCreationBillingTimeStamp\",\n\t\t\tTriggerOperation: cosmosdb.TriggerOperationCreate,\n\t\t\tTriggerType: cosmosdb.TriggerTypePre,\n\t\t\tBody: `function trigger() {\n\tvar request = getContext().getRequest();\n\tvar body = request.getBody();\n\tvar date = new Date();\n\tvar now = Math.floor(date.getTime() / 1000);\n\tvar billingBody = body[\"billing\"];\n\tif (!billingBody[\"creationTime\"]) {\n\t\tbillingBody[\"creationTime\"] = now;\n\t}\n\trequest.setBody(body);\n}`,\n\t\t},\n\t\t{\n\t\t\tID: \"setDeletionBillingTimeStamp\",\n\t\t\tTriggerOperation: cosmosdb.TriggerOperationReplace,\n\t\t\tTriggerType: cosmosdb.TriggerTypePre,\n\t\t\tBody: `function trigger() {\n\tvar request = getContext().getRequest();\n\tvar body = request.getBody();\n\tvar date = new Date();\n\tvar now = Math.floor(date.getTime() / 1000);\n\tvar billingBody = body[\"billing\"];\n\tif (!billingBody[\"deletionTime\"]) {\n\t\tbillingBody[\"deletionTime\"] = now;\n\t}\n\trequest.setBody(body);\n}`,\n\t\t},\n\t}\n\n\ttriggerc := cosmosdb.NewTriggerClient(collc, collBilling)\n\tfor _, trigger := range triggers {\n\t\t_, err := triggerc.Create(ctx, trigger)\n\t\tif err != nil && !cosmosdb.IsErrorStatusCode(err, http.StatusConflict) {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tdocumentClient := cosmosdb.NewBillingDocumentClient(collc, collBilling)\n\treturn NewBillingWithProvidedClient(documentClient), nil\n}", "func (w *Wallet) NewAccount(index *uint32) (a *Account, err error) {\n\tindex2 := w.nextIndex\n\tif index != nil {\n\t\tindex2 = *index\n\t}\n\ta = &Account{w: w, index: index2}\n\tif err = w.impl.deriveAccount(a); err != nil {\n\t\treturn\n\t}\n\tpubkeyToAddress := util.PubkeyToAddress\n\tif w.isBanano {\n\t\tpubkeyToAddress = util.PubkeyToBananoAddress\n\t}\n\tif a.address, err = pubkeyToAddress(a.pubkey); err != nil {\n\t\treturn\n\t}\n\tif index == nil {\n\t\tw.nextIndex++\n\t}\n\tif _, ok := w.accounts[a.address]; !ok {\n\t\tw.accounts[a.address] = a\n\t} else if index == nil {\n\t\treturn w.NewAccount(nil)\n\t}\n\treturn\n}", "func NewAccount(firstName string) *Account {\n\tthis := Account{}\n\tthis.FirstName = firstName\n\treturn &this\n}", "func NewDelayedWithdrawalTransactor(address common.Address, transactor bind.ContractTransactor) (*DelayedWithdrawalTransactor, error) {\n\tcontract, err := bindDelayedWithdrawal(address, nil, transactor, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &DelayedWithdrawalTransactor{contract: contract}, nil\n}", "func newServiceAccountWithName(name string, cr *argoprojv1a1.ArgoCD) *corev1.ServiceAccount {\n\tsa := newServiceAccount(cr)\n\tsa.ObjectMeta.Name = getServiceAccountName(cr.Name, name)\n\n\tlbls := sa.ObjectMeta.Labels\n\tlbls[common.ArgoCDKeyName] = name\n\tsa.ObjectMeta.Labels = lbls\n\n\treturn sa\n}", "func NewTrial(\n\texperimentID int,\n\thparams JSONObj,\n\twarmStartCheckpointID *int,\n\ttrialSeed int64) *Trial {\n\treturn &Trial{\n\t\tExperimentID: experimentID,\n\t\tState: ActiveState,\n\t\tStartTime: time.Now().UTC(),\n\t\tHParams: hparams,\n\t\tWarmStartCheckpointID: warmStartCheckpointID,\n\t\tSeed: trialSeed,\n\t}\n}", "func NewAccount(email string) *Account {\n\treturn &Account{email: email}\n}", "func newAtomicBased(rate int, opts ...Option) *atomicLimiter {\r\n\tconfig := buildConfig(opts)\r\n\tl := &atomicLimiter{\r\n\t\tperRequest: config.per / time.Duration(rate),\r\n\t\tmaxSlack: -1 * config.maxSlack * time.Second / time.Duration(rate),\r\n\t\tclock: config.clock,\r\n\t}\r\n\r\n\tinitialState := state{\r\n\t\tlast: time.Time{},\r\n\t\tsleepFor: 0,\r\n\t}\r\n\tatomic.StorePointer(&l.state, unsafe.Pointer(&initialState))\r\n\treturn l\r\n}", "func NewBookingNamedEntity()(*BookingNamedEntity) {\n m := &BookingNamedEntity{\n Entity: *NewEntity(),\n }\n return m\n}", "func NewAccount(newid AccountIDType, newemail string) *Account {\n\treturn &Account{\n\t\tid: newid,\n\t\temail: newemail,\n\t}\n}", "func generateNewAccount() string {\n\taccount := crypto.GenerateAccount()\n\tpassphrase, err := mnemonic.FromPrivateKey(account.PrivateKey)\n\tif err != nil {\n\t\tfmt.Printf(\"Error creating new account: %s\\n\", err)\n\t} else {\n\t\tfmt.Printf(\"Created new account: %s\\n\", account.Address)\n\t\tfmt.Printf(\"Generated mnemonic: \\\"%s\\\"\\n\", passphrase)\n\t}\n\treturn account.Address.String()\n}", "func newTransactorSetup(t *testing.T, prng *rand.Rand, hideSignHash bool, signer types.Signer, chainID int64) test.TransactorSetup {\n\twalletSeed := make([]byte, 20)\n\tprng.Read(walletSeed)\n\tmnemonic, err := hdwallet.NewMnemonicFromEntropy(walletSeed)\n\trequire.NoError(t, err)\n\n\trawHDWallet, err := hdwallet.NewFromMnemonic(mnemonic)\n\trequire.NoError(t, err)\n\trequire.NotNil(t, rawHDWallet)\n\n\tvar wrappedWallet accounts.Wallet = rawHDWallet\n\tif hideSignHash {\n\t\twrappedWallet = &noSignHash{rawHDWallet}\n\t}\n\thdWallet, err := hd.NewWallet(wrappedWallet, hd.DefaultRootDerivationPath.String(), 0)\n\trequire.NoError(t, err)\n\trequire.NotNil(t, hdWallet)\n\n\tvalidAcc, err := hdWallet.NewAccount()\n\trequire.NoError(t, err)\n\trequire.NotNil(t, validAcc)\n\n\treturn test.TransactorSetup{\n\t\tSigner: signer,\n\t\tChainID: chainID,\n\t\tTr: hd.NewTransactor(hdWallet.Wallet(), signer),\n\t\tValidAcc: accounts.Account{Address: wallet.AsEthAddr(validAcc.Address())},\n\t\tMissingAcc: accounts.Account{Address: common.HexToAddress(missingAddr)},\n\t}\n}", "func NewAccount() *Account {\n\tpriv, _ := ecdsa.GenerateKey(crypto.S256(), cryptorand.Reader)\n\tpub := base64.URLEncoding.EncodeToString(\n\t\tcrypto.FromECDSAPub(&priv.PublicKey))\n\taddr := hex.EncodeToString(crypto.PubkeyToAddress(priv.PublicKey).Bytes())\n\treturn &Account{\n\t\tID: NewUUID(),\n\t\tEthAddr: addr,\n\t\tPublicKey: pub,\n\t\tPrivateKey: base64.URLEncoding.EncodeToString(crypto.FromECDSA(priv)),\n\t}\n}", "func NewAgedAccountsPayable()(*AgedAccountsPayable) {\n m := &AgedAccountsPayable{\n }\n m.backingStore = ie8677ce2c7e1b4c22e9c3827ecd078d41185424dd9eeb92b7d971ed2d49a392e.BackingStoreFactoryInstance();\n m.SetAdditionalData(make(map[string]any))\n return m\n}", "func NewAccount(\n\tconfig *accounts.AccountConfig,\n\taccountCoin *Coin,\n\thttpClient *http.Client,\n\tlog *logrus.Entry,\n) *Account {\n\tlog = log.WithField(\"group\", \"eth\").\n\t\tWithFields(logrus.Fields{\"coin\": accountCoin.String(), \"code\": config.Config.Code, \"name\": config.Config.Name})\n\tlog.Debug(\"Creating new account\")\n\n\taccount := &Account{\n\t\tBaseAccount: accounts.NewBaseAccount(config, accountCoin, log),\n\t\tcoin: accountCoin,\n\t\tdbSubfolder: \"\", // set in Initialize()\n\t\tsigningConfiguration: nil,\n\t\thttpClient: httpClient,\n\t\tbalance: coin.NewAmountFromInt64(0),\n\n\t\tenqueueUpdateCh: make(chan struct{}),\n\t\tquitChan: make(chan struct{}),\n\n\t\tlog: log,\n\t}\n\n\treturn account\n}", "func NewPlanner()(*Planner) {\n m := &Planner{\n Entity: *NewEntity(),\n }\n return m\n}", "func NewAccount(address string) *Account {\n\treturn &Account{\n\t\tAddress: address,\n\t\tHeight: \"0\",\n\t\tGoldTokenBalance: \"0\",\n\t\tTotalLockedGoldBalance: \"0\",\n\t\tNonVotingLockedGoldBalance: \"0\",\n\t\tVotingLockedGoldBalance: \"0\",\n\t\tPendingWithdrawalBalance: \"0\",\n\t\tCeloUSDValue: \"0\",\n\t\tDelegations: []*Delegation{},\n\t}\n\n}", "func New(ccHost, username, password, clusterID, clusterToken string) *ContrailCommand {\n\treturn &ContrailCommand{\n\t\tAuthHost: ccHost,\n\t\tUsername: username,\n\t\tPassword: password,\n\t\tClusterID: clusterID,\n\t\tClusterToken: clusterToken,\n\t\tAuthPath: \"/keystone/v3/auth/tokens\",\n\t\tUserDomain: \"default\",\n\t\tProjectName: \"admin\",\n\t\tProjectDomain: \"default\",\n\t}\n}", "func NewUserTeamwork()(*UserTeamwork) {\n m := &UserTeamwork{\n Entity: *NewEntity(),\n }\n return m\n}", "func NewTransaction(opts *Opts, log logging.Logger) *Transaction {\n\tt := Transaction{\n\t\tattempts: opts.MaxTransactionAttempts,\n\t}\n\n\tt.Transaction.Starter = &t\n\tt.Transaction.Stopper = &t\n\treturn &t\n}", "func NewSynchronizationJob()(*SynchronizationJob) {\n m := &SynchronizationJob{\n Entity: *NewEntity(),\n }\n return m\n}", "func NewContinuousVestingAccountRaw(bva *BaseVestingAccount, startTime int64) *ContinuousVestingAccount {\n\treturn &ContinuousVestingAccount{\n\t\tBaseVestingAccount: bva,\n\t\tStartTime: startTime,\n\t}\n}", "func NewAccount(id string, name string, primary bool, type_ string, currency Currency, balance AccountBalance, createdAt time.Time, updatedAt time.Time, resource string, resourcePath string, ready bool) *Account {\n\tthis := Account{}\n\tthis.Id = id\n\tthis.Name = name\n\tthis.Primary = primary\n\tthis.Type = type_\n\tthis.Currency = currency\n\tthis.Balance = balance\n\tthis.CreatedAt = createdAt\n\tthis.UpdatedAt = updatedAt\n\tthis.Resource = resource\n\tthis.ResourcePath = resourcePath\n\tthis.Ready = ready\n\treturn &this\n}", "func newReconciledServiceAccount() *corev1.ServiceAccount {\n\treturn NewServiceAccount(newEventSource())()\n}", "func CreateAccount(t *testing.T) (priv *rsa.PrivateKey, address string) {\n\tvar err error\n\tpriv, err = rsa.GenerateKey(rand.Reader, 1024)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\taddress, err = PrivateKeyToAddress(priv)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\treturn\n}", "func newTestingWallet(testdir string, cs modules.ConsensusSet, tp modules.TransactionPool) (modules.Wallet, error) {\n\tw, err := modWallet.New(cs, tp, filepath.Join(testdir, modules.WalletDir), modules.DefaultAddressGapLimit, false)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tkey := crypto.GenerateSiaKey(crypto.TypeDefaultWallet)\n\tencrypted, err := w.Encrypted()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !encrypted {\n\t\t_, err = w.Encrypt(key)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\terr = w.Unlock(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// give it some money\n\tm, err := miner.New(cs, tp, w, filepath.Join(testdir, modules.MinerDir))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor i := types.BlockHeight(0); i <= types.MaturityDelay; i++ {\n\t\t_, err := m.AddBlock()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn w, nil\n}", "func (lw *Manager) NewWaiter(startTS, lockTS, keyHash uint64, timeout time.Duration) *Waiter {\n\t// allocate memory before hold the lock.\n\tq := new(queue)\n\tq.waiters = make([]*Waiter, 0, 8)\n\twaiter := &Waiter{\n\t\ttimeout: timeout,\n\t\tch: make(chan Result, 1),\n\t\tstartTS: startTS,\n\t\tLockTS: lockTS,\n\t\tKeyHash: keyHash,\n\t}\n\tq.waiters = append(q.waiters, waiter)\n\tlw.mu.Lock()\n\tif old, ok := lw.waitingQueues[lockTS]; ok {\n\t\told.waiters = append(old.waiters, waiter)\n\t} else {\n\t\tlw.waitingQueues[lockTS] = q\n\t}\n\tlw.mu.Unlock()\n\treturn waiter\n}", "func NewAccount() *Account {\n\tacc := &Account{}\n\tpriv, pub := newKeyPair()\n\tacc.PriKey = priv\n\tacc.PubKey = pub\n\treturn acc\n}", "func NewCustomAccounting(h modules.Host, m modules.Miner, r modules.Renter, w modules.Wallet, persistDir string, deps modules.Dependencies) (*Accounting, error) {\n\t// Check that at least the wallet is not nil\n\tif w == nil {\n\t\treturn nil, errNilWallet\n\t}\n\n\t// Check required parameters\n\tif persistDir == \"\" {\n\t\treturn nil, errNilPersistDir\n\t}\n\tif deps == nil {\n\t\treturn nil, errNilDeps\n\t}\n\n\t// Initialize the accounting\n\ta := &Accounting{\n\t\tstaticHost: h,\n\t\tstaticMiner: m,\n\t\tstaticRenter: r,\n\t\tstaticWallet: w,\n\n\t\tstaticPersistDir: persistDir,\n\n\t\tstaticDeps: deps,\n\t}\n\n\t// Initialize the persistence\n\terr := a.initPersist()\n\tif err != nil {\n\t\treturn nil, errors.AddContext(err, \"unable to initialize the persistence\")\n\t}\n\n\t// Launch background thread to persist the accounting information\n\tif !a.staticDeps.Disrupt(\"DisablePersistLoop\") {\n\t\tgo a.callThreadedPersistAccounting()\n\t}\n\treturn a, nil\n}", "func NewAccount(acc *types.Account) *Account {\n\treturn &Account{\n\t\tAccount: *acc,\n\t}\n}", "func (msg MsgCreateVestingAccount) Type() string { return TypeMsgCreateVestingAccount }", "func NewTransaction(p *requestParams) {\n\tw, r, c, u := p.w, p.r, p.c, p.u\n\n\td := json.NewDecoder(r.Body)\n\tvar request TransactionRequest\n\tif err := d.Decode(&request); err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tif len(request.Amounts) != len(request.Accounts) {\n\t\thttp.Error(w, \"Amounts and accounts of different lengths\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tdate, err := time.Parse(dateStringFormat, request.Date)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tuserKey := userKey(c, u)\n\ttransactionId := uuid.NewRandom().String()\n\taccountKeys := make([]*datastore.Key, len(request.Accounts))\n\tsplitKeys := make([]*datastore.Key, len(request.Accounts))\n\tsplits := make([]*transaction.Split, len(request.Accounts))\n\n\tfor i := range request.Accounts {\n\t\taccountKeys[i] = datastore.NewKey(c, \"Account\", \"\", request.Accounts[i], userKey)\n\t\tsplitKeys[i] = datastore.NewKey(c, \"Split\", transactionId, 0, accountKeys[i])\n\t\tsplits[i] = &transaction.Split{\n\t\t\tAmount: request.Amounts[i],\n\t\t\tAccount: request.Accounts[i],\n\t\t\tMemo: request.Memo,\n\t\t\tDate: date,\n\t\t}\n\t}\n\n\tx := transaction.NewTransaction()\n\tx.AddSplits(splits)\n\n\tif err := x.ValidateAmount(); err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\terr = datastore.RunInTransaction(c, func(c appengine.Context) error {\n\t\taccounts := make([]transaction.Account, len(accountKeys))\n\t\tif err := datastore.GetMulti(c, accountKeys, accounts); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfor i := range accounts {\n\t\t\tx.AddAccount(&accounts[i], accountKeys[i].IntID())\n\t\t}\n\n\t\tif err := x.Commit(); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tputStatus := make(chan error)\n\n\t\tgo func() {\n\t\t\t_, err := datastore.PutMulti(c, accountKeys, accounts)\n\t\t\tputStatus <- err\n\t\t}()\n\t\tgo func() {\n\t\t\t_, err := datastore.PutMulti(c, splitKeys, splits)\n\t\t\tputStatus <- err\n\t\t}()\n\n\t\terr := <-putStatus\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn <-putStatus\n\t}, nil)\n\tif err != nil {\n\t\t// TODO(cjc25): This might not be a 400: if e.g. datastore failed it should\n\t\t// be a 500. Interpret err and return the right thing.\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n}", "func MakeAccount(owner string) *Account {\n\taccount := Account{owner: owner, balance: 0}\n\treturn &account\n}", "func WithAccount(name string) TokenOption {\n return func(t *tokenOpts) {\n t.account = name\n }\n}", "func newTestChain(t testing.TB) *Blockchain {\n\treturn newTestChainWithCustomCfg(t, nil)\n}", "func accountCreate(ctx *cli.Context) error {\n\n\tdataDir := ctx.GlobalString(utils.DataDirFlag.Name)\n\t//get keyStoreDir from KeyStoreDirFlag, if not use the default value\n\tkeyStoreDir := ctx.GlobalString(utils.KeyStoreDirFlag.Name)\n\tif keyStoreDir == \"\" {\n\t\tkeyStoreDir = keystore.KeyStoreScheme\n\t}\n\tkeyStoreDir = filepath.Join(dataDir, keyStoreDir)\n\tpassword := getPassPhrase(\"Your new account is locked with a password. Please give a password. Do not forget this password.\", true, 0, utils.MakePasswordList(ctx))\n\t_, err := utils.NewAccount(keyStoreDir, password)\n\n\treturn err\n}", "func New(url string, username string, password string) TransmissionClient {\n\tapiclient := NewClient(url, username, password)\n\ttc := TransmissionClient{apiclient: apiclient}\n\treturn tc\n}", "func NewAccount(addr *Address) *Account {\n\treturn &Account{\n\t\taccount: common.NewAccount(common.BytesToAddress(addr.Bytes())),\n\t}\n}", "func newScheduledJobs(c *BatchClient, namespace string) *scheduledJobs {\n\treturn &scheduledJobs{c, namespace}\n}", "func MakeStandaloneBudget(capacity int64) BoundAccount {\n\treturn BoundAccount{used: capacity}\n}", "func NewOffer(sup Supplier) *Transaction {\n\treturn &Transaction{\n\t\ttp: Offer,\n\t\tSup: sup,\n\t}\n}", "func newJobRunner(logger *persist.Logger, ant *Ant, siadirectory string, existingWalletSeed string) (*JobRunner, error) {\n\tjr := &JobRunner{\n\t\tstaticLogger: logger,\n\t\tstaticAntsSyncWG: ant.staticAntsSyncWG,\n\t\tstaticAnt: ant,\n\t\tstaticClient: ant.StaticClient,\n\t\tstaticDataDir: ant.Config.DataDir,\n\t}\n\n\t// Get the wallet\n\twg, err := jr.staticClient.WalletGet()\n\tif err != nil {\n\t\treturn nil, errors.AddContext(err, \"can't get wallet info\")\n\t}\n\tif wg.Unlocked && existingWalletSeed == \"\" {\n\t\t// Set the wallet seed in the jobrunner and return. This case happens\n\t\t// when newJobRunner() is called multiple times (by purpose or by\n\t\t// mistake) on the ant.\n\t\twsg, err := jr.staticClient.WalletSeedsGet()\n\t\tif err != nil {\n\t\t\treturn nil, errors.AddContext(err, \"can't get wallet seeds\")\n\t\t}\n\t\tjr.StaticWalletSeed = wsg.PrimarySeed\n\t\treturn jr, nil\n\t}\n\n\t// Init the wallet when needed and save seed\n\tvar checkSeed bool\n\tif existingWalletSeed == \"\" && !wg.Encrypted {\n\t\t// No wallet seed was specified and wallet is encrypted. Initialize a\n\t\t// new wallet.\n\t\tjr.staticLogger.Debugf(\"%v: init wallet\", jr.staticDataDir)\n\t\twalletParams, err := jr.staticClient.WalletInitPost(\"\", false)\n\t\tif err != nil {\n\t\t\ter := errors.AddContext(err, \"can't init wallet\")\n\t\t\tjr.staticLogger.Errorf(\"%v: %v\", jr.staticDataDir, er)\n\t\t\treturn nil, er\n\t\t}\n\t\tjr.StaticWalletSeed = walletParams.PrimarySeed\n\t} else if existingWalletSeed == \"\" && wg.Encrypted {\n\t\t// Nothing to do. Not sure if or when this case can happen.\n\t} else if existingWalletSeed != \"\" && !wg.Encrypted {\n\t\t// A wallet seed was specified, but wallet is not encrypted. Initialize\n\t\t// the wallet with the existing seed.\n\t\tjr.staticLogger.Debugf(\"%v: init wallet using existing seed\", jr.staticDataDir)\n\t\terr := jr.staticClient.WalletInitSeedPost(existingWalletSeed, \"\", false)\n\t\tif err != nil {\n\t\t\ter := errors.AddContext(err, \"can't init wallet using existing seed\")\n\t\t\tjr.staticLogger.Errorf(\"%v: %v\", jr.staticDataDir, er)\n\t\t\treturn nil, er\n\t\t}\n\t\tjr.StaticWalletSeed = existingWalletSeed\n\t} else if existingWalletSeed != \"\" && wg.Encrypted {\n\t\t// A wallet seed was specified, wallet is encrypted. Just save seed.\n\t\t// Executed e.g. during siad upgrade with job runner re-creation.\n\t\tcheckSeed = true\n\t\tjr.staticLogger.Debugf(\"%v: use existing initialized wallet\", jr.staticDataDir)\n\t\tjr.StaticWalletSeed = existingWalletSeed\n\t}\n\n\t// Unlock the wallet\n\terr = jr.staticClient.WalletUnlockPost(jr.StaticWalletSeed)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Check that actual seed equals existingWalletSeed.\n\tif checkSeed {\n\t\twsg, err := jr.staticClient.WalletSeedsGet()\n\t\tif err != nil {\n\t\t\treturn nil, errors.AddContext(err, \"can't get wallet seeds\")\n\t\t}\n\t\tif wsg.PrimarySeed != existingWalletSeed {\n\t\t\treturn nil, errors.New(\"wallet primary seed doesn't equal expected existing seed\")\n\t\t}\n\t}\n\n\treturn jr, nil\n}", "func NewBookingBusiness()(*BookingBusiness) {\n m := &BookingBusiness{\n Entity: *NewEntity(),\n }\n return m\n}" ]
[ "0.69552976", "0.6662628", "0.6262276", "0.59880567", "0.58953786", "0.57377744", "0.57377744", "0.5700749", "0.54910743", "0.5422893", "0.5391255", "0.5373617", "0.53433174", "0.53415126", "0.53125954", "0.53034943", "0.5293382", "0.5290742", "0.52859324", "0.5257186", "0.525304", "0.5251386", "0.5246119", "0.5224901", "0.5135589", "0.51142204", "0.50721186", "0.50603443", "0.50592774", "0.5047483", "0.50465035", "0.5036375", "0.5026448", "0.5023146", "0.50063705", "0.49996242", "0.4996115", "0.49840334", "0.4983567", "0.49586603", "0.49532372", "0.49204987", "0.49136448", "0.49088976", "0.4891227", "0.48627836", "0.48474783", "0.48467386", "0.48406616", "0.48250872", "0.48173133", "0.48031792", "0.48024738", "0.4799226", "0.47966594", "0.4792917", "0.47925848", "0.47849557", "0.47710952", "0.47700572", "0.47660598", "0.47606853", "0.47548544", "0.47499883", "0.4749588", "0.4748427", "0.47320288", "0.4726744", "0.4726682", "0.4718602", "0.4698316", "0.46965945", "0.46928373", "0.46920687", "0.46905023", "0.46887207", "0.46879244", "0.46818", "0.46768484", "0.46658954", "0.46339467", "0.46303082", "0.4629557", "0.46276277", "0.4621424", "0.46189108", "0.46155176", "0.46124938", "0.4602977", "0.46003368", "0.4593804", "0.45925653", "0.45922306", "0.45838162", "0.45717072", "0.4565175", "0.45639232", "0.45611197", "0.4560066", "0.45544195" ]
0.80419785
0
GetVestedCoins returns the total amount of vested coins for a delayed vesting account. All coins are only vested once the schedule has elapsed.
func (dva DelayedVestingAccount) GetVestedCoins(blockTime time.Time) sdk.Coins { if blockTime.Unix() >= dva.EndTime { return dva.OriginalVesting } return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (pva PeriodicVestingAccount) GetVestedCoins(blockTime time.Time) sdk.Coins {\n\tcoins := ReadSchedule(pva.StartTime, pva.EndTime, pva.VestingPeriods, pva.OriginalVesting, blockTime.Unix())\n\tif coins.IsZero() {\n\t\treturn nil\n\t}\n\treturn coins\n}", "func (plva PermanentLockedAccount) GetVestedCoins(_ time.Time) sdk.Coins {\n\treturn nil\n}", "func (dva DelayedVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn dva.OriginalVesting.Sub(dva.GetVestedCoins(blockTime))\n}", "func (cva ContinuousVestingAccount) GetVestedCoins(blockTime time.Time) sdk.Coins {\n\tvar vestedCoins sdk.Coins\n\n\t// We must handle the case where the start time for a vesting account has\n\t// been set into the future or when the start of the chain is not exactly\n\t// known.\n\tif blockTime.Unix() <= cva.StartTime {\n\t\treturn vestedCoins\n\t} else if blockTime.Unix() >= cva.EndTime {\n\t\treturn cva.OriginalVesting\n\t}\n\n\t// calculate the vesting scalar\n\tx := blockTime.Unix() - cva.StartTime\n\ty := cva.EndTime - cva.StartTime\n\ts := sdk.NewDec(x).Quo(sdk.NewDec(y))\n\n\tfor _, ovc := range cva.OriginalVesting {\n\t\tvestedAmt := ovc.Amount.ToDec().Mul(s).RoundInt()\n\t\tvestedCoins = append(vestedCoins, sdk.NewCoin(ovc.Denom, vestedAmt))\n\t}\n\n\treturn vestedCoins\n}", "func (va ClawbackVestingAccount) GetVestedCoins(blockTime time.Time) sdk.Coins {\n\t// It's likely that one or the other schedule will be nearly trivial,\n\t// so there should be little overhead in recomputing the conjunction each time.\n\tcoins := coinsMin(va.GetUnlockedOnly(blockTime), va.GetVestedOnly(blockTime))\n\tif coins.IsZero() {\n\t\treturn nil\n\t}\n\treturn coins\n}", "func (vva ValidatorVestingAccount) GetVestedCoins(blockTime time.Time) sdk.Coins {\n\tvar vestedCoins sdk.Coins\n\tif blockTime.Unix() <= vva.StartTime {\n\t\treturn vestedCoins\n\t}\n\tcurrentPeriodStartTime := vva.StartTime\n\tnumberPeriods := len(vva.VestingPeriods)\n\tfor i := 0; i < numberPeriods; i++ {\n\t\tx := blockTime.Unix() - currentPeriodStartTime\n\t\tif x >= vva.VestingPeriods[i].Length {\n\t\t\tif vva.VestingPeriodProgress[i].PeriodComplete {\n\t\t\t\tvestedCoins = vestedCoins.Add(vva.VestingPeriods[i].Amount)\n\t\t\t}\n\t\t\tcurrentPeriodStartTime += vva.VestingPeriods[i].Length\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn vestedCoins\n\n}", "func (cva ContinuousVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn cva.OriginalVesting.Sub(cva.GetVestedCoins(blockTime))\n}", "func (pva PeriodicVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn pva.OriginalVesting.Sub(pva.GetVestedCoins(blockTime))\n}", "func (va ClawbackVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn va.OriginalVesting.Sub(va.GetVestedCoins(blockTime))\n}", "func (vva ValidatorVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn vva.OriginalVesting.Sub(vva.GetVestedCoins(blockTime))\n}", "func (plva PermanentLockedAccount) GetVestingCoins(_ time.Time) sdk.Coins {\n\treturn plva.OriginalVesting\n}", "func (vva ValidatorVestingAccount) GetFailedVestedCoins() sdk.Coins {\n\tvar failedVestedCoins sdk.Coins\n\tnumberPeriods := len(vva.VestingPeriods)\n\tfor i := 0; i < numberPeriods; i++ {\n\t\tif vva.VestingPeriodProgress[i].PeriodComplete {\n\t\t\tif !vva.VestingPeriodProgress[i].VestingSuccessful {\n\t\t\t\tfailedVestedCoins = failedVestedCoins.Add(vva.VestingPeriods[i].Amount)\n\t\t\t}\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn failedVestedCoins\n}", "func (dva DelayedVestingAccount) LockedCoins(ctx sdk.Context) sdk.Coins {\n\treturn dva.BaseVestingAccount.LockedCoinsFromVesting(dva.GetVestingCoins(ctx.BlockTime()))\n}", "func (va ClawbackVestingAccount) GetVestedOnly(blockTime time.Time) sdk.Coins {\n\treturn ReadSchedule(va.StartTime, va.EndTime, va.VestingPeriods, va.OriginalVesting, blockTime.Unix())\n}", "func (cva ContinuousVestingAccount) LockedCoins(ctx sdk.Context) sdk.Coins {\n\treturn cva.BaseVestingAccount.LockedCoinsFromVesting(cva.GetVestingCoins(ctx.BlockTime()))\n}", "func (pva PeriodicVestingAccount) LockedCoins(ctx sdk.Context) sdk.Coins {\n\treturn pva.BaseVestingAccount.LockedCoinsFromVesting(pva.GetVestingCoins(ctx.BlockTime()))\n}", "func (va ClawbackVestingAccount) LockedCoins(ctx sdk.Context) sdk.Coins {\n\treturn va.BaseVestingAccount.LockedCoinsFromVesting(va.GetVestingCoins(ctx.BlockTime()))\n}", "func (vva ValidatorVestingAccount) SpendableCoins(blockTime time.Time) sdk.Coins {\n\treturn vva.BaseVestingAccount.SpendableCoinsVestingAccount(vva.GetVestingCoins(blockTime))\n}", "func (bva BaseVestingAccount) LockedCoinsFromVesting(vestingCoins sdk.Coins) sdk.Coins {\n\tlockedCoins := vestingCoins.Sub(vestingCoins.Min(bva.DelegatedVesting))\n\tif lockedCoins == nil {\n\t\treturn sdk.Coins{}\n\t}\n\treturn lockedCoins\n}", "func (plva PermanentLockedAccount) LockedCoins(_ sdk.Context) sdk.Coins {\n\treturn plva.BaseVestingAccount.LockedCoinsFromVesting(plva.OriginalVesting)\n}", "func (keeper ViewKeeper) GetCoins(ctx sdk.Context, addr sdk.Address) sdk.Coins {\n\treturn getCoins(ctx, keeper.am, addr)\n}", "func (keeper SendKeeper) GetCoins(ctx sdk.Context, addr sdk.Address) sdk.Coins {\n\treturn getCoins(ctx, keeper.am, addr)\n}", "func (keeper BaseViewKeeper) GetCoins(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins {\n\treturn getCoins(ctx, keeper.am, addr)\n}", "func (ck CoinKeeper) GetCoins(ctx sdk.Context, addr sdk.Address, amt sdk.Coins) sdk.Coins {\n\tacc := ck.am.GetAccount(ctx, addr)\n\treturn acc.GetCoins()\n}", "func (keeper Keeper) GetCoins(ctx sdk.Context, addr sdk.Address) sdk.Coins {\n\treturn getCoins(ctx, keeper.am, addr)\n}", "func GetCoins() (coins []Coin, error error) {\n\tvar c = []Coin{}\n\tvar d struct {\n\t\tCrypto []Coin `json:\"crypto\"`\n\t}\n\tjsonData, err := doTauRequest(1, \"GET\", \"data/coins\", nil)\n\tif err != nil {\n\t\treturn c, err\n\t}\n\tif err := json.Unmarshal(jsonData, &d); err != nil {\n\t\treturn c, err\n\t}\n\treturn d.Crypto, nil\n}", "func (t *TauAPI) GetCoins() (coins []Coin, error error) {\n\tvar c = []Coin{}\n\tvar d struct {\n\t\tCrypto []Coin `json:\"cryto\"` //typo from api\n\t\tFiat []Coin `json:\"fiat\"`\n\t}\n\tjsonData, err := t.doTauRequest(&TauReq{\n\t\tVersion: 2,\n\t\tMethod: \"GET\",\n\t\tPath: \"coins\",\n\t})\n\tif err != nil {\n\t\treturn c, err\n\t}\n\tif err := json.Unmarshal(jsonData, &d); err != nil {\n\t\treturn c, err\n\t}\n\tc = append(d.Crypto, d.Fiat...)\n\treturn c, nil\n}", "func (_TokenVesting *TokenVestingCaller) VestedAmount(opts *bind.CallOpts, _token common.Address) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _TokenVesting.contract.Call(opts, out, \"vestedAmount\", _token)\n\treturn *ret0, err\n}", "func (_TokenVesting *TokenVestingCallerSession) VestedAmount(_token common.Address) (*big.Int, error) {\n\treturn _TokenVesting.Contract.VestedAmount(&_TokenVesting.CallOpts, _token)\n}", "func (_TokenVesting *TokenVestingSession) VestedAmount(_token common.Address) (*big.Int, error) {\n\treturn _TokenVesting.Contract.VestedAmount(&_TokenVesting.CallOpts, _token)\n}", "func (m *Client) GetCoins() ([]string, error) {\n\tresp, err := m.Service.GetCoins()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error requesting coin list: %s\", err)\n\t}\n\tdefer resp.Body.Close()\n\n\tvar response []string\n\terr = json.NewDecoder(resp.Body).Decode(&response)\n\tif err != nil {\n\t\tmsg, _ := ioutil.ReadAll(resp.Body)\n\t\treturn nil, fmt.Errorf(\"error decoding coin list: %s: %s\", msg, err)\n\t}\n\n\treturn response, nil\n}", "func (n Network) VestingAccounts(ctx context.Context, launchID uint64) (vestingAccs []networktypes.VestingAccount, err error) {\n\tn.ev.Send(events.New(events.StatusOngoing, \"Fetching genesis vesting accounts\"))\n\tres, err := n.launchQuery.\n\t\tVestingAccountAll(ctx,\n\t\t\t&launchtypes.QueryAllVestingAccountRequest{\n\t\t\t\tLaunchID: launchID,\n\t\t\t},\n\t\t)\n\tif err != nil {\n\t\treturn vestingAccs, err\n\t}\n\n\tfor i, acc := range res.VestingAccount {\n\t\tparsedAcc, err := networktypes.ToVestingAccount(acc)\n\t\tif err != nil {\n\t\t\treturn vestingAccs, errors.Wrapf(err, \"error parsing vesting account %d\", i)\n\t\t}\n\n\t\tvestingAccs = append(vestingAccs, parsedAcc)\n\t}\n\n\treturn vestingAccs, nil\n}", "func (b *rpcVestingBalance) delegated() (sdk.Coins, sdk.Coins, error) {\n\tdelegatedCoins, err := b.totalDelegated()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tunbondingCoins, err := b.totalUnbondingDelegations()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tdelegated := delegatedCoins.AmountOf(stakingDenom)\n\tunbonding := unbondingCoins.AmountOf(stakingDenom)\n\ttotalStaked := delegated.Add(unbonding)\n\tdelegatedFree := b.vacc.GetDelegatedFree().AmountOf(stakingDenom)\n\n\t// total number of staked and unbonding tokens considered to be liquid\n\ttotalFree := sdk.MinInt(totalStaked, delegatedFree)\n\t// any coins that are not considered liquid, are vesting up to a maximum of delegated\n\tstakedVesting := sdk.MinInt(totalStaked.Sub(totalFree), delegated)\n\t// staked free coins are left over\n\tstakedFree := delegated.Sub(stakedVesting)\n\n\tliquidCoins := sdk.NewCoins(newKavaCoin(stakedFree))\n\tvestingCoins := sdk.NewCoins(newKavaCoin(stakedVesting))\n\treturn liquidCoins, vestingCoins, nil\n}", "func (dcr *ExchangeWallet) ReturnCoins(unspents asset.Coins) error {\n\tdcr.fundingMtx.Lock()\n\tdefer dcr.fundingMtx.Unlock()\n\treturn dcr.returnCoins(unspents)\n}", "func (o *Transaction) GetCounterparties() []TransactionCounterparty {\n\tif o == nil || o.Counterparties == nil {\n\t\tvar ret []TransactionCounterparty\n\t\treturn ret\n\t}\n\treturn *o.Counterparties\n}", "func (dcr *ExchangeWallet) FundingCoins(ids []dex.Bytes) (asset.Coins, error) {\n\t// First check if we have the coins in cache.\n\tcoins := make(asset.Coins, 0, len(ids))\n\tnotFound := make(map[outPoint]bool)\n\tdcr.fundingMtx.Lock()\n\tdefer dcr.fundingMtx.Unlock() // stay locked until we update the map and lock them in the wallet\n\tfor _, id := range ids {\n\t\ttxHash, vout, err := decodeCoinID(id)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tpt := newOutPoint(txHash, vout)\n\t\tfundingCoin, found := dcr.fundingCoins[pt]\n\t\tif found {\n\t\t\tcoins = append(coins, fundingCoin.op)\n\t\t\tcontinue\n\t\t}\n\t\tnotFound[pt] = true\n\t}\n\tif len(notFound) == 0 {\n\t\treturn coins, nil\n\t}\n\n\t// Check locked outputs for not found coins.\n\tlockedOutputs, err := dcr.lockedOutputs()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor _, output := range lockedOutputs {\n\t\ttxHash, err := chainhash.NewHashFromStr(output.Txid)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error decoding txid from rpc server %s: %w\", output.Txid, err)\n\t\t}\n\t\tpt := newOutPoint(txHash, output.Vout)\n\t\tif !notFound[pt] {\n\t\t\tcontinue\n\t\t}\n\t\ttxOut, err := dcr.node.GetTxOut(dcr.ctx, txHash, output.Vout, true)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"gettxout error for locked output %v: %w\", pt.String(), translateRPCCancelErr(err))\n\t\t}\n\t\tvar address string\n\t\tif len(txOut.ScriptPubKey.Addresses) > 0 {\n\t\t\taddress = txOut.ScriptPubKey.Addresses[0]\n\t\t}\n\t\tcoin := newOutput(txHash, output.Vout, toAtoms(output.Amount), output.Tree)\n\t\tcoins = append(coins, coin)\n\t\tdcr.fundingCoins[pt] = &fundingCoin{\n\t\t\top: coin,\n\t\t\taddr: address,\n\t\t}\n\t\tdelete(notFound, pt)\n\t\tif len(notFound) == 0 {\n\t\t\treturn coins, nil\n\t\t}\n\t}\n\n\t// Some funding coins still not found after checking locked outputs.\n\t// Check wallet unspent outputs as last resort. Lock the coins if found.\n\tunspents, err := dcr.unspents()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcoinsToLock := make([]*wire.OutPoint, 0, len(notFound))\n\tfor _, txout := range unspents {\n\t\ttxHash, err := chainhash.NewHashFromStr(txout.TxID)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error decoding txid from rpc server %s: %w\", txout.TxID, err)\n\t\t}\n\t\tpt := newOutPoint(txHash, txout.Vout)\n\t\tif !notFound[pt] {\n\t\t\tcontinue\n\t\t}\n\t\tcoinsToLock = append(coinsToLock, wire.NewOutPoint(txHash, txout.Vout, txout.Tree))\n\t\tcoin := newOutput(txHash, txout.Vout, toAtoms(txout.Amount), txout.Tree)\n\t\tcoins = append(coins, coin)\n\t\tdcr.fundingCoins[pt] = &fundingCoin{\n\t\t\top: coin,\n\t\t\taddr: txout.Address,\n\t\t}\n\t\tdelete(notFound, pt)\n\t\tif len(notFound) == 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\tif len(notFound) != 0 {\n\t\tids := make([]string, 0, len(notFound))\n\t\tfor pt := range notFound {\n\t\t\tids = append(ids, pt.String())\n\t\t}\n\t\treturn nil, fmt.Errorf(\"funding coins not found: %s\", strings.Join(ids, \", \"))\n\t}\n\tdcr.log.Debugf(\"Locking funding coins that were unlocked %v\", coinsToLock)\n\terr = dcr.node.LockUnspent(dcr.ctx, false, coinsToLock)\n\tif err != nil {\n\t\treturn nil, translateRPCCancelErr(err)\n\t}\n\n\treturn coins, nil\n}", "func subtractCoins(ctx sdk.Context, am sdk.AccountMapper, addr sdk.Address, amt sdk.Coins) (sdk.Coins, sdk.Error) {\n\toldCoins := getCoins(ctx, am, addr)\n\tnewCoins := oldCoins.Minus(amt)\n\tif !newCoins.IsNotNegative() {\n\t\treturn amt, sdk.ErrInsufficientCoins(fmt.Sprintf(\"%s < %s\", oldCoins, amt))\n\t}\n\terr := setCoins(ctx, am, addr, newCoins)\n\treturn newCoins, err\n}", "func (bva BaseVestingAccount) GetDelegatedVesting() sdk.Coins {\n\treturn bva.DelegatedVesting\n}", "func (dcr *ExchangeWallet) FundingCoins(ids []dex.Bytes) (asset.Coins, error) {\n\t// First check if we have the coins in cache.\n\tcoins := make(asset.Coins, 0, len(ids))\n\tnotFound := make(map[outPoint]bool)\n\tdcr.fundingMtx.Lock()\n\tdefer dcr.fundingMtx.Unlock() // stay locked until we update the map and lock them in the wallet\n\tfor _, id := range ids {\n\t\ttxHash, vout, err := decodeCoinID(id)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tpt := newOutPoint(txHash, vout)\n\t\tfundingCoin, found := dcr.fundingCoins[pt]\n\t\tif found {\n\t\t\tcoins = append(coins, fundingCoin.op)\n\t\t\tcontinue\n\t\t}\n\t\tnotFound[pt] = true\n\t}\n\tif len(notFound) == 0 {\n\t\treturn coins, nil\n\t}\n\n\t// Check locked outputs for not found coins.\n\tfor _, acct := range dcr.fundingAccounts() {\n\t\tlockedOutputs, err := dcr.wallet.LockedOutputs(dcr.ctx, acct)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfor _, output := range lockedOutputs {\n\t\t\ttxHash, err := chainhash.NewHashFromStr(output.Txid)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"error decoding txid from rpc server %s: %w\", output.Txid, err)\n\t\t\t}\n\t\t\tpt := newOutPoint(txHash, output.Vout)\n\t\t\tif !notFound[pt] {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ttxOut, err := dcr.wallet.UnspentOutput(dcr.ctx, txHash, output.Vout, output.Tree)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"gettxout error for locked output %v: %w\", pt.String(), err)\n\t\t\t}\n\t\t\tvar address string\n\t\t\tif len(txOut.Addresses) > 0 {\n\t\t\t\taddress = txOut.Addresses[0]\n\t\t\t}\n\t\t\tcoin := newOutput(txHash, output.Vout, toAtoms(output.Amount), output.Tree)\n\t\t\tcoins = append(coins, coin)\n\t\t\tdcr.fundingCoins[pt] = &fundingCoin{\n\t\t\t\top: coin,\n\t\t\t\taddr: address,\n\t\t\t}\n\t\t\tdelete(notFound, pt)\n\t\t\tif len(notFound) == 0 {\n\t\t\t\treturn coins, nil\n\t\t\t}\n\t\t}\n\t}\n\n\t// Some funding coins still not found after checking locked outputs.\n\t// Check wallet unspent outputs as last resort. Lock the coins if found.\n\tcoinsToLock := make([]*wire.OutPoint, 0, len(notFound))\n\tfor _, acct := range dcr.fundingAccounts() {\n\t\tunspents, err := dcr.wallet.Unspents(dcr.ctx, acct)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfor _, txout := range unspents {\n\t\t\ttxHash, err := chainhash.NewHashFromStr(txout.TxID)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"error decoding txid from rpc server %s: %w\", txout.TxID, err)\n\t\t\t}\n\t\t\tpt := newOutPoint(txHash, txout.Vout)\n\t\t\tif !notFound[pt] {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tcoinsToLock = append(coinsToLock, wire.NewOutPoint(txHash, txout.Vout, txout.Tree))\n\t\t\tcoin := newOutput(txHash, txout.Vout, toAtoms(txout.Amount), txout.Tree)\n\t\t\tcoins = append(coins, coin)\n\t\t\tdcr.fundingCoins[pt] = &fundingCoin{\n\t\t\t\top: coin,\n\t\t\t\taddr: txout.Address,\n\t\t\t}\n\t\t\tdelete(notFound, pt)\n\t\t\tif len(notFound) == 0 {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\t// Return an error if some coins are still not found.\n\tif len(notFound) != 0 {\n\t\tids := make([]string, 0, len(notFound))\n\t\tfor pt := range notFound {\n\t\t\tids = append(ids, pt.String())\n\t\t}\n\t\treturn nil, fmt.Errorf(\"funding coins not found: %s\", strings.Join(ids, \", \"))\n\t}\n\n\tdcr.log.Debugf(\"Locking funding coins that were unlocked %v\", coinsToLock)\n\terr := dcr.wallet.LockUnspent(dcr.ctx, false, coinsToLock)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn coins, nil\n}", "func makeSpendTxWithHoursBurned(t *testing.T, uxs coin.UxArray, keys []cipher.SecKey, toAddr cipher.Address, coins, hoursBurned uint64) coin.Transaction {\n\tspendTx := coin.Transaction{}\n\tvar totalHours uint64\n\tvar totalCoins uint64\n\tfor _, ux := range uxs {\n\t\tspendTx.PushInput(ux.Hash())\n\t\ttotalHours += ux.Body.Hours\n\t\ttotalCoins += ux.Body.Coins\n\t}\n\n\trequire.True(t, coins <= totalCoins)\n\trequire.True(t, hoursBurned <= totalHours, \"hoursBurned must be <= totalHours\")\n\n\tspendHours := totalHours - hoursBurned\n\n\tspendTx.PushOutput(toAddr, coins, spendHours)\n\tif totalCoins != coins {\n\t\tspendTx.PushOutput(uxs[0].Body.Address, totalCoins-coins, 0)\n\t}\n\tspendTx.SignInputs(keys)\n\tspendTx.UpdateHeader()\n\treturn spendTx\n}", "func (c Cart) GetVoucherSavings() domain.Price {\n\tprice := domain.Price{}\n\tvar err error\n\n\tfor _, item := range c.Totalitems {\n\t\tif item.Type == TotalsTypeVoucher {\n\t\t\tprice, err = price.Add(item.Price)\n\t\t\tif err != nil {\n\t\t\t\treturn price\n\t\t\t}\n\t\t}\n\t}\n\n\tif price.IsNegative() {\n\t\treturn domain.Price{}\n\t}\n\n\treturn price\n}", "func GetCoins(accCoins []types.Coin) AccountCoins {\n\tcoins := make(AccountCoins, 0)\n\tfor _, coin := range accCoins {\n\t\tcoins = append(coins, AccountCoin{Amount: uint64(coin.Amount), Denom: coin.Denom})\n\t}\n\treturn coins\n}", "func (keeper Keeper) SubtractCoins(ctx sdk.Context, addr sdk.Address, amt sdk.Coins) (sdk.Coins, sdk.Error) {\n\treturn subtractCoins(ctx, keeper.am, addr, amt)\n}", "func (c *CoordinatorHelper) Coins(\n\tctx context.Context,\n\tdbTx storage.DatabaseTransaction,\n\taccountIdentifier *types.AccountIdentifier,\n\tcurrency *types.Currency,\n) ([]*types.Coin, error) {\n\tcoins, _, err := c.coinStorage.GetCoinsTransactional(\n\t\tctx,\n\t\tdbTx,\n\t\taccountIdentifier,\n\t)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"%w: unable to get coins\", err)\n\t}\n\n\tcoinsToReturn := []*types.Coin{}\n\tfor _, coin := range coins {\n\t\tif types.Hash(coin.Amount.Currency) != types.Hash(currency) {\n\t\t\tcontinue\n\t\t}\n\n\t\tcoinsToReturn = append(coinsToReturn, coin)\n\t}\n\n\treturn coinsToReturn, nil\n}", "func (o *AvailableBudget) GetSpentInBudgets() []BudgetSpent {\n\tif o == nil || o.SpentInBudgets == nil {\n\t\tvar ret []BudgetSpent\n\t\treturn ret\n\t}\n\treturn *o.SpentInBudgets\n}", "func (o *AllocationList) GetInvested() float64 {\n\tif o == nil {\n\t\tvar ret float64\n\t\treturn ret\n\t}\n\n\treturn o.Invested\n}", "func (_DelegationController *DelegationControllerTransactor) GetAndUpdateLockedAmount(opts *bind.TransactOpts, wallet common.Address) (*types.Transaction, error) {\n\treturn _DelegationController.contract.Transact(opts, \"getAndUpdateLockedAmount\", wallet)\n}", "func (b *BlockChain) FetchSpendJournal(targetBlock *asiutil.Block, targetvblock *asiutil.VBlock) ([]txo.SpentTxOut, error) {\n\tb.chainLock.RLock()\n\tdefer b.chainLock.RUnlock()\n\n\tvar spendEntries []txo.SpentTxOut\n\terr := b.db.View(func(dbTx database.Tx) error {\n\t\tvar err error\n\t\tspendEntries, err = dbFetchSpendJournalEntry(dbTx, targetBlock, targetvblock)\n\t\treturn err\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn spendEntries, nil\n}", "func (dcr *ExchangeWallet) sendCoins(addr stdaddr.Address, coins asset.Coins, val, feeRate uint64, subtract bool) (*wire.MsgTx, uint64, error) {\n\tbaseTx := wire.NewMsgTx()\n\t_, err := dcr.addInputCoins(baseTx, coins)\n\tif err != nil {\n\t\treturn nil, 0, err\n\t}\n\tpayScriptVer, payScript := addr.PaymentScript()\n\ttxOut := newTxOut(int64(val), payScriptVer, payScript)\n\tbaseTx.AddTxOut(txOut)\n\n\tvar feeSource int32 // subtract from vout 0\n\tif !subtract {\n\t\tfeeSource = -1 // subtract from change\n\t}\n\n\ttx, err := dcr.sendWithReturn(baseTx, feeRate, feeSource)\n\tif err != nil {\n\t\treturn nil, 0, err\n\t}\n\treturn tx, uint64(tx.TxOut[0].Value), err\n}", "func (va ClawbackVestingAccount) GetVestingPeriods() Periods {\n\treturn va.VestingPeriods\n}", "func (b *Byzcoin) Watch(ctx context.Context) <-chan *ledger.TransactionResult {\n\tc := make(chan *ledger.TransactionResult, 100)\n\tb.bc.Watch(ctx, observer{ch: c})\n\n\treturn c\n}", "func GetCmdFreezeCoins(cdc *codec.Codec) *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse: `freeze --amount [amount] --symbol [ABC-123] --from [account]`,\n\t\tShort: \"move specified amount of token/coins into frozen status, preventing their sale\",\n\t\t// Args: cobra.ExactArgs(1),\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tcliCtx := context.NewCLIContext().WithCodec(cdc)\n\n\t\t\ttxBldr := auth.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(cdc))\n\n\t\t\taddress, symbol, amount := getCommonParameters(cliCtx, cmd)\n\n\t\t\tmsg := types.NewMsgFreezeCoins(amount, symbol, address)\n\t\t\terr := msg.ValidateBasic()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t// return utils.CompleteAndBroadcastTxCLI(txBldr, cliCtx, msgs)\n\t\t\treturn utils.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg})\n\t\t},\n\t}\n\n\tsetupInt64Flag(cmd, \"amount\", \"\", -1,\n\t\t\"what is the total amount of coins to freeze for the given token\", true)\n\tsetupStringFlag(cmd, \"symbol\", \"\", \"\",\n\t\t\"what is the shorthand symbol, eg ABC-123, for the existing token\", true)\n\n\treturn cmd\n}", "func (_DelegationController *DelegationControllerTransactorSession) GetAndUpdateLockedAmount(wallet common.Address) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.GetAndUpdateLockedAmount(&_DelegationController.TransactOpts, wallet)\n}", "func (candidate *Candidate) GetTotalBipStake() *big.Int {\n\tcandidate.lock.RLock()\n\tdefer candidate.lock.RUnlock()\n\n\treturn big.NewInt(0).Set(candidate.totalBipStake)\n}", "func (btc *ExchangeWallet) FundingCoins(ids []dex.Bytes) (asset.Coins, error) {\n\t// First check if we have the coins in cache.\n\tcoins := make(asset.Coins, 0, len(ids))\n\tnotFound := make(map[string]struct{})\n\tbtc.fundingMtx.RLock()\n\tfor _, id := range ids {\n\t\ttxHash, vout, err := decodeCoinID(id)\n\t\tif err != nil {\n\t\t\tbtc.fundingMtx.RUnlock()\n\t\t\treturn nil, err\n\t\t}\n\t\topID := outpointID(txHash.String(), vout)\n\t\tfundingCoin, found := btc.fundingCoins[opID]\n\t\tif found {\n\t\t\tcoins = append(coins, newOutput(btc.node, txHash, vout, fundingCoin.amount, fundingCoin.redeemScript))\n\t\t\tcontinue\n\t\t}\n\t\tnotFound[opID] = struct{}{}\n\t}\n\tbtc.fundingMtx.RUnlock()\n\tif len(notFound) == 0 {\n\t\treturn coins, nil\n\t}\n\t_, utxoMap, _, err := btc.spendableUTXOs(0)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlockers := make([]*output, 0, len(ids))\n\tbtc.fundingMtx.Lock()\n\tdefer btc.fundingMtx.Unlock()\n\tfor _, id := range ids {\n\t\ttxHash, vout, err := decodeCoinID(id)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\topID := outpointID(txHash.String(), vout)\n\t\tutxo, found := utxoMap[opID]\n\t\tif !found {\n\t\t\treturn nil, fmt.Errorf(\"funding coin %s not found\", opID)\n\t\t}\n\t\tbtc.fundingCoins[opID] = utxo\n\t\tcoin := newOutput(btc.node, utxo.txHash, utxo.vout, utxo.amount, utxo.redeemScript)\n\t\tcoins = append(coins, coin)\n\t\tlockers = append(lockers, coin)\n\t\tdelete(notFound, opID)\n\t\tif len(notFound) == 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\tif len(notFound) != 0 {\n\t\tids := make([]string, 0, len(notFound))\n\t\tfor opID := range notFound {\n\t\t\tids = append(ids, opID)\n\t\t}\n\t\treturn nil, fmt.Errorf(\"coins not found: %s\", strings.Join(ids, \", \"))\n\t}\n\terr = btc.wallet.LockUnspent(false, lockers)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn coins, nil\n}", "func (k Keeper) GetStakedTokens(ctx sdk.Ctx) sdk.BigInt {\n\tstakedPool := k.GetStakedPool(ctx)\n\treturn stakedPool.GetCoins().AmountOf(k.StakeDenom(ctx))\n}", "func (_DelegationController *DelegationControllerSession) GetAndUpdateLockedAmount(wallet common.Address) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.GetAndUpdateLockedAmount(&_DelegationController.TransactOpts, wallet)\n}", "func (pva PeriodicVestingAccount) GetVestingPeriods() Periods {\n\treturn pva.VestingPeriods\n}", "func (_CrToken *CrTokenCallerSession) TotalReserves() (*big.Int, error) {\n\treturn _CrToken.Contract.TotalReserves(&_CrToken.CallOpts)\n}", "func (cm *ConnectionManager) sumDeposits() *big.Int {\n\tchs := cm.openChannels()\n\tvar sum = big.NewInt(0)\n\tfor _, c := range chs {\n\t\tsum.Add(sum, c.OurContractBalance)\n\t}\n\treturn sum\n}", "func (_Bindings *BindingsCallerSession) TotalReserves() (*big.Int, error) {\n\treturn _Bindings.Contract.TotalReserves(&_Bindings.CallOpts)\n}", "func sendCoins(ctx sdk.Context, am sdk.AccountMapper, fromAddr sdk.Address, toAddr sdk.Address, amt sdk.Coins) sdk.Error {\n\t_, err := subtractCoins(ctx, am, fromAddr, amt)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = addCoins(ctx, am, toAddr, amt)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (m *Machine) ReturnCoins() {\n\tcoins := m.cashEngine.DropCoins()\n\n\ts := fmt.Sprintf(\"-> \")\n\tfor i, c := range coins {\n\t\tif i == len(coins)-1 {\n\t\t\ts += fmt.Sprintf(\"%s\", c.value.String())\n\t\t\tcontinue\n\t\t}\n\t\ts += fmt.Sprintf(\"%s, \", c.value.String())\n\t}\n\n\tm.logger.Println(s)\n}", "func (p *Player) CashSpentTotal() int {\n\treturn p.AdditionalPlayerInformation.TotalCashSpent\n}", "func (keeper ViewKeeper) HasCoins(ctx sdk.Context, addr sdk.Address, amt sdk.Coins) bool {\n\treturn hasCoins(ctx, keeper.am, addr, amt)\n}", "func (gw *Gateway) Spend(wltID string, password []byte, coins uint64, dest cipher.Address) (*coin.Transaction, error) {\n\tlogger.Warning(\"Calling deprecated method Gateway.Spend\")\n\n\tif !gw.Config.EnableSpendMethod {\n\t\treturn nil, ErrSpendMethodDisabled\n\t}\n\n\tif !gw.Config.EnableWalletAPI {\n\t\treturn nil, wallet.ErrWalletAPIDisabled\n\t}\n\n\tvar txn *coin.Transaction\n\tvar err error\n\tgw.strand(\"Spend\", func() {\n\t\ttxn, err = gw.v.CreateTransactionDeprecated(wltID, password, coins, dest)\n\t\tif err != nil {\n\t\t\tlogger.WithError(err).Error(\"CreateTransactionDeprecated failed\")\n\t\t\treturn\n\t\t}\n\n\t\t// WARNING: This is not safe from races once we remove strand\n\t\t_, err = gw.v.InjectUserTransaction(*txn)\n\t\tif err != nil {\n\t\t\tlogger.WithError(err).Error(\"InjectUserTransaction failed\")\n\t\t\treturn\n\t\t}\n\n\t\terr = gw.d.BroadcastTransaction(*txn)\n\t\tif err != nil {\n\t\t\tlogger.WithError(err).Error(\"BroadcastTransaction failed\")\n\t\t\treturn\n\t\t}\n\t})\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn txn, nil\n}", "func (k Keeper) GetWinnerIncentives(ctx sdk.Context) float32 {\n\tgames := float32(k.GetGames(ctx))\n\tvotes := float32(k.GetVotes(ctx))\n\tgVR := float32(k.GetParams(ctx).GameVoteRatio) / 100\n\treturn games / (votes*gVR + games)\n}", "func (_CrToken *CrTokenSession) TotalReserves() (*big.Int, error) {\n\treturn _CrToken.Contract.TotalReserves(&_CrToken.CallOpts)\n}", "func (o *AllocationList) SetInvested(v float64) {\n\to.Invested = v\n}", "func (_Distributor *DistributorTransactor) GetAndUpdateEarnedBountyAmountOf(opts *bind.TransactOpts, wallet common.Address, validatorId *big.Int) (*types.Transaction, error) {\n\treturn _Distributor.contract.Transact(opts, \"getAndUpdateEarnedBountyAmountOf\", wallet, validatorId)\n}", "func (keeper BaseViewKeeper) HasCoins(ctx sdk.Context, addr sdk.AccAddress, amt sdk.Coins) bool {\n\treturn hasCoins(ctx, keeper.am, addr, amt)\n}", "func (dcr *ExchangeWallet) ReturnCoins(unspents asset.Coins) error {\n\tdcr.fundingMtx.Lock()\n\treturnedCoins, err := dcr.returnCoins(unspents)\n\tdcr.fundingMtx.Unlock()\n\tif err != nil || dcr.unmixedAccount == \"\" {\n\t\treturn err\n\t}\n\n\t// If any of these coins belong to the trading account, transfer them to the\n\t// unmixed account to be re-mixed into the primary account before being\n\t// re-selected for funding future orders. This doesn't apply to unspent\n\t// split tx outputs, which should remain in the trading account and be\n\t// selected from there for funding future orders.\n\tvar coinsToTransfer []asset.Coin\n\tfor _, coin := range returnedCoins {\n\t\tif coin.addr == \"\" {\n\t\t\ttxOut, err := dcr.wallet.UnspentOutput(dcr.ctx, coin.op.txHash(), coin.op.vout(), coin.op.tree)\n\t\t\tif err != nil {\n\t\t\t\tdcr.log.Errorf(\"wallet.UnspentOutput error for returned coin %s: %v\", coin.op, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif len(txOut.Addresses) == 0 {\n\t\t\t\tdcr.log.Errorf(\"no address in gettxout response for returned coin %s\", coin.op)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tcoin.addr = txOut.Addresses[0]\n\t\t}\n\t\taddrInfo, err := dcr.wallet.AddressInfo(dcr.ctx, coin.addr)\n\t\tif err != nil {\n\t\t\tdcr.log.Errorf(\"wallet.AddressInfo error for returned coin %s: %v\", coin.op, err)\n\t\t\tcontinue\n\t\t}\n\t\t// Move this coin to the unmixed account if it was sent to the internal\n\t\t// branch of the trading account. This excludes unspent split tx outputs\n\t\t// which are sent to the external branch of the trading account.\n\t\tif addrInfo.Branch == acctInternalBranch && addrInfo.Account == dcr.tradingAccount {\n\t\t\tcoinsToTransfer = append(coinsToTransfer, coin.op)\n\t\t}\n\t}\n\n\tif len(coinsToTransfer) > 0 {\n\t\ttx, totalSent, err := dcr.sendAll(coinsToTransfer, dcr.unmixedAccount)\n\t\tif err != nil {\n\t\t\tdcr.log.Errorf(\"unable to transfer unlocked swapped change from temp trading \"+\n\t\t\t\t\"account to unmixed account: %v\", err)\n\t\t} else {\n\t\t\tdcr.log.Infof(\"Transferred %s from temp trading account to unmixed account in tx %s.\",\n\t\t\t\tdcrutil.Amount(totalSent), tx.TxHash())\n\t\t}\n\t}\n\n\treturn nil\n}", "func (dcr *ExchangeWallet) sendCoins(addr dcrutil.Address, coins asset.Coins, val, feeRate uint64, subtract bool) (*wire.MsgTx, uint64, error) {\n\tbaseTx := wire.NewMsgTx()\n\t_, err := dcr.addInputCoins(baseTx, coins)\n\tif err != nil {\n\t\treturn nil, 0, err\n\t}\n\tpayScript, err := txscript.PayToAddrScript(addr)\n\tif err != nil {\n\t\treturn nil, 0, fmt.Errorf(\"error creating P2SH script: %w\", err)\n\t}\n\n\ttxOut := wire.NewTxOut(int64(val), payScript)\n\tbaseTx.AddTxOut(txOut)\n\n\tvar feeSource int32 // subtract from vout 0\n\tif !subtract {\n\t\tfeeSource = -1 // subtract from change\n\t}\n\n\ttx, _, _, _, err := dcr.sendWithReturn(baseTx, feeRate, feeSource)\n\treturn tx, uint64(txOut.Value), err\n}", "func (_DayLimit *DayLimitCaller) SpentToday(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _DayLimit.contract.Call(opts, out, \"spentToday\")\n\treturn *ret0, err\n}", "func (tb *transactionBuilder) FundCoins(amount types.Currency, refundAddress *types.UnlockHash, reuseRefundAddress bool) error {\n\ttb.wallet.mu.Lock()\n\tdefer tb.wallet.mu.Unlock()\n\n\tif !tb.wallet.unlocked {\n\t\treturn modules.ErrLockedWallet\n\t}\n\n\t// prepare fulfillable context\n\tctx := tb.wallet.getFulfillableContextForLatestBlock()\n\n\t// Collect a value-sorted set of fulfillable coin outputs.\n\tvar so sortedOutputs\n\tfor scoid, sco := range tb.wallet.coinOutputs {\n\t\tif !sco.Condition.Fulfillable(ctx) {\n\t\t\tcontinue\n\t\t}\n\t\tso.ids = append(so.ids, scoid)\n\t\tso.outputs = append(so.outputs, sco)\n\t}\n\t// Add all of the unconfirmed outputs as well.\n\tfor _, upt := range tb.wallet.unconfirmedProcessedTransactions {\n\t\tfor i, sco := range upt.Transaction.CoinOutputs {\n\t\t\tuh := sco.Condition.UnlockHash()\n\t\t\t// Determine if the output belongs to the wallet.\n\t\t\texists, err := tb.wallet.keyExists(uh)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif !exists || !sco.Condition.Fulfillable(ctx) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tso.ids = append(so.ids, upt.Transaction.CoinOutputID(uint64(i)))\n\t\t\tso.outputs = append(so.outputs, sco)\n\t\t}\n\t}\n\tsort.Sort(sort.Reverse(so))\n\n\t// Create a transaction that will add the correct amount of coins to the\n\t// transaction.\n\tvar fund types.Currency\n\t// potentialFund tracks the balance of the wallet including outputs that\n\t// have been spent in other unconfirmed transactions recently. This is to\n\t// provide the user with a more useful error message in the event that they\n\t// are overspending.\n\tvar potentialFund types.Currency\n\tvar spentScoids []types.CoinOutputID\n\tfor i := range so.ids {\n\t\tscoid := so.ids[i]\n\t\tsco := so.outputs[i]\n\t\t// Check that this output has not recently been spent by the wallet.\n\t\tspendHeight := tb.wallet.spentOutputs[types.OutputID(scoid)]\n\t\t// Prevent an underflow error.\n\t\tallowedHeight := tb.wallet.consensusSetHeight - RespendTimeout\n\t\tif tb.wallet.consensusSetHeight < RespendTimeout {\n\t\t\tallowedHeight = 0\n\t\t}\n\t\tif spendHeight > allowedHeight {\n\t\t\tpotentialFund = potentialFund.Add(sco.Value)\n\t\t\tcontinue\n\t\t}\n\n\t\t// prepare fulfillment, matching the output\n\t\tuh := sco.Condition.UnlockHash()\n\t\tvar ff types.MarshalableUnlockFulfillment\n\t\tswitch sco.Condition.ConditionType() {\n\t\tcase types.ConditionTypeUnlockHash, types.ConditionTypeTimeLock:\n\t\t\t// ConditionTypeTimeLock is fine, as we know it's fulfillable,\n\t\t\t// and that can only mean for now that it is using an internal unlockHashCondition or nilCondition\n\t\t\tpk, _, err := tb.wallet.getKey(uh)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tff = types.NewSingleSignatureFulfillment(pk)\n\t\tdefault:\n\t\t\tbuild.Severe(fmt.Errorf(\"unexpected condition type: %[1]v (%[1]T)\", sco.Condition))\n\t\t\treturn types.ErrUnexpectedUnlockCondition\n\t\t}\n\t\t// Add a coin input for this output.\n\t\tsci := types.CoinInput{\n\t\t\tParentID: scoid,\n\t\t\tFulfillment: types.NewFulfillment(ff),\n\t\t}\n\t\ttb.coinInputs = append(tb.coinInputs, inputSignContext{\n\t\t\tInputIndex: len(tb.transaction.CoinInputs),\n\t\t\tUnlockHash: uh,\n\t\t})\n\t\ttb.transaction.CoinInputs = append(tb.transaction.CoinInputs, sci)\n\n\t\tspentScoids = append(spentScoids, scoid)\n\n\t\t// Add the output to the total fund\n\t\tfund = fund.Add(sco.Value)\n\t\tpotentialFund = potentialFund.Add(sco.Value)\n\t\tif fund.Cmp(amount) >= 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\tif potentialFund.Cmp(amount) >= 0 && fund.Cmp(amount) < 0 {\n\t\treturn modules.ErrIncompleteTransactions\n\t}\n\tif fund.Cmp(amount) < 0 {\n\t\treturn modules.ErrLowBalance\n\t}\n\n\t// Create a refund output if needed.\n\tif !amount.Equals(fund) {\n\t\tvar refundUnlockHash types.UnlockHash\n\t\tif refundAddress != nil {\n\t\t\t// use specified refund address\n\t\t\trefundUnlockHash = *refundAddress\n\t\t} else if reuseRefundAddress {\n\t\t\t// use the fist coin input of this tx as refund address\n\t\t\tvar maxCoinAmount types.Currency\n\t\t\tfor _, ci := range tb.transaction.CoinInputs {\n\t\t\t\tco, exists := tb.wallet.coinOutputs[ci.ParentID]\n\t\t\t\tif !exists {\n\t\t\t\t\tco = tb.getCoFromUnconfirmedProcessedTransactions(ci.ParentID)\n\t\t\t\t}\n\t\t\t\tif maxCoinAmount.Cmp(co.Value) < 0 {\n\t\t\t\t\tmaxCoinAmount = co.Value\n\t\t\t\t\trefundUnlockHash = co.Condition.UnlockHash()\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\t// generate a new address\n\t\t\tvar err error\n\t\t\trefundUnlockHash, err = tb.wallet.nextPrimarySeedAddress()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\trefundOutput := types.CoinOutput{\n\t\t\tValue: fund.Sub(amount),\n\t\t\tCondition: types.NewCondition(types.NewUnlockHashCondition(refundUnlockHash)),\n\t\t}\n\t\ttb.transaction.CoinOutputs = append(tb.transaction.CoinOutputs, refundOutput)\n\t}\n\n\t// Mark all outputs that were spent as spent.\n\tfor _, scoid := range spentScoids {\n\t\ttb.wallet.spentOutputs[types.OutputID(scoid)] = tb.wallet.consensusSetHeight\n\t}\n\treturn nil\n}", "func (cm *ConnectionManager) fundsRemaining() *big.Int {\n\tif cm.funds.Cmp(utils.BigInt0) > 0 {\n\t\tremaining := new(big.Int)\n\t\tremaining.Sub(cm.funds, cm.sumDeposits())\n\t\treturn remaining\n\t}\n\treturn utils.BigInt0\n}", "func coins(a int) int {\n\tif a == 0 {\n\t\treturn 0\n\t}\n\treturn doCoins(a, 25)\n}", "func (k Keeper) BurnCoins(ctx sdk.Context, moduleName string, amt sdk.Coins) error {\n\tacc := k.GetModuleAccount(ctx, moduleName)\n\tif acc == nil {\n\t\tpanic(sdkerrors.Wrapf(sdkerrors.ErrUnknownAddress, \"module account %s does not exist\", moduleName))\n\t}\n\n\tif !acc.HasPermission(types.Burner) {\n\t\tpanic(sdkerrors.Wrapf(sdkerrors.ErrUnauthorized, \"module account %s does not have permissions to burn tokens\", moduleName))\n\t}\n\n\t_, err := k.bk.SubtractCoins(ctx, acc.GetAddress(), amt)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// update total supply\n\tsupply := k.GetSupply(ctx)\n\tsupply = supply.Deflate(amt)\n\tk.SetSupply(ctx, supply)\n\n\tlogger := k.Logger(ctx)\n\tlogger.Info(fmt.Sprintf(\"burned %s from %s module account\", amt.String(), moduleName))\n\n\treturn nil\n}", "func (_Bindings *BindingsSession) TotalReserves() (*big.Int, error) {\n\treturn _Bindings.Contract.TotalReserves(&_Bindings.CallOpts)\n}", "func (va *ClawbackVestingAccount) computeClawback(clawbackTime int64) sdk.Coins {\n\t// Compute the truncated vesting schedule and amounts.\n\t// Work with the schedule as the primary data and recompute derived fields, e.g. OriginalVesting.\n\tvestTime := va.StartTime\n\ttotalVested := sdk.NewCoins()\n\ttotalUnvested := sdk.NewCoins()\n\tunvestedIdx := 0\n\tfor i, period := range va.VestingPeriods {\n\t\tvestTime += period.Length\n\t\t// tie in time goes to clawback\n\t\tif vestTime < clawbackTime {\n\t\t\ttotalVested = totalVested.Add(period.Amount...)\n\t\t\tunvestedIdx = i + 1\n\t\t} else {\n\t\t\ttotalUnvested = totalUnvested.Add(period.Amount...)\n\t\t}\n\t}\n\tlastVestTime := vestTime\n\tnewVestingPeriods := va.VestingPeriods[:unvestedIdx]\n\n\t// To cap the unlocking schedule to the new total vested, conjunct with a limiting schedule\n\tcapPeriods := []Period{\n\t\t{\n\t\t\tLength: 0,\n\t\t\tAmount: totalVested,\n\t\t},\n\t}\n\t_, lastLockTime, newLockupPeriods := ConjunctPeriods(va.StartTime, va.StartTime, va.LockupPeriods, capPeriods)\n\n\t// Now construct the new account state\n\tva.OriginalVesting = totalVested\n\tva.EndTime = max64(lastVestTime, lastLockTime)\n\tva.LockupPeriods = newLockupPeriods\n\tva.VestingPeriods = newVestingPeriods\n\t// DelegatedVesting and DelegatedFree will be adjusted elsewhere\n\n\treturn totalUnvested\n}", "func (bva BaseVestingAccount) GetOriginalVesting() sdk.Coins {\n\treturn bva.OriginalVesting\n}", "func (btc *ExchangeWallet) ReturnCoins(unspents asset.Coins) error {\n\tif len(unspents) == 0 {\n\t\treturn fmt.Errorf(\"cannot return zero coins\")\n\t}\n\tops := make([]*output, 0, len(unspents))\n\tbtc.fundingMtx.Lock()\n\tdefer btc.fundingMtx.Unlock()\n\tfor _, unspent := range unspents {\n\t\top, err := btc.convertCoin(unspent)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error converting coin: %v\", err)\n\t\t}\n\t\tops = append(ops, op)\n\t\tdelete(btc.fundingCoins, outpointID(op.txHash.String(), op.vout))\n\t}\n\treturn btc.wallet.LockUnspent(true, ops)\n}", "func (a *Account) TotalReceived(confirms int) (float64, error) {\n\tbs, err := GetCurBlock()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tvar totalSatoshis int64\n\tfor _, record := range a.TxStore.SortedRecords() {\n\t\ttxout, ok := record.(*tx.RecvTxOut)\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Ignore change.\n\t\tif txout.Change() {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Tally if the appropiate number of block confirmations have passed.\n\t\tif confirmed(confirms, txout.Height(), bs.Height) {\n\t\t\ttotalSatoshis += txout.Value()\n\t\t}\n\t}\n\n\treturn float64(totalSatoshis) / float64(btcutil.SatoshiPerBitcoin), nil\n}", "func (keeper SendKeeper) HasCoins(ctx sdk.Context, addr sdk.Address, amt sdk.Coins) bool {\n\treturn hasCoins(ctx, keeper.am, addr, amt)\n}", "func (_Bindings *BindingsCaller) TotalReserves(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _Bindings.contract.Call(opts, out, \"totalReserves\")\n\treturn *ret0, err\n}", "func (_DayLimitMock *DayLimitMockCaller) SpentToday(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _DayLimitMock.contract.Call(opts, out, \"spentToday\")\n\treturn *ret0, err\n}", "func GetBeneficiaryCmts(ctx iris.Context) {\n\tbID, err := ctx.Params().GetInt64(\"beneficiaryID\")\n\tif err != nil {\n\t\tctx.StatusCode(http.StatusBadRequest)\n\t\tctx.JSON(jsonError{\"Engagement d'un bénéficiaire, paramètre : \" + err.Error()})\n\t\treturn\n\t}\n\tvar resp models.BeneficiaryCmts\n\tdb := ctx.Values().Get(\"db\").(*sql.DB)\n\tif err = resp.GetAll(bID, db); err != nil {\n\t\tctx.StatusCode(http.StatusInternalServerError)\n\t\tctx.JSON(jsonError{\"Engagement d'un bénéficiaire, requête : \" + err.Error()})\n\t}\n\tctx.StatusCode(http.StatusOK)\n\tctx.JSON(resp)\n}", "func hasCoins(ctx sdk.Context, am sdk.AccountMapper, addr sdk.Address, amt sdk.Coins) bool {\n\treturn getCoins(ctx, am, addr).IsGTE(amt)\n}", "func (k Keeper) BurnDebtCoins(ctx sdk.Context, moduleAccount string, denom string, paymentCoins sdk.Coins) error {\n\tcoinsToBurn := sdk.NewCoins()\n\tfor _, pc := range paymentCoins {\n\t\tcoinsToBurn = coinsToBurn.Add(sdk.NewCoin(denom, pc.Amount))\n\t}\n\terr := k.supplyKeeper.BurnCoins(ctx, moduleAccount, coinsToBurn)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (r *Repository) GetAmountsOfManageCandidates(ctx context.Context, companyID string) (int32, int32, error) {\n\tobjCompanyID, err := primitive.ObjectIDFromHex(companyID)\n\tif err != nil {\n\t\treturn 0, 0, errors.New(`wrong_id`)\n\t}\n\n\tamount := struct {\n\t\tSaved int32 `bson:\"saved_candidates\"`\n\t\tSkipped int32 `bson:\"skipped_candidates\"`\n\t\t// Alerts int32 `bson:\"alerts\"`\n\t}{}\n\n\tcursor, err := r.companiesCollection.Aggregate(\n\t\tctx,\n\t\t[]bson.M{\n\t\t\t{\n\t\t\t\t\"$match\": bson.M{\n\t\t\t\t\t\"company_id\": objCompanyID,\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\t\"$addFields\": bson.M{\n\t\t\t\t\t\"saved_candidates\": bson.M{\n\t\t\t\t\t\t\"$size\": \"$saved_candidates\",\n\t\t\t\t\t},\n\t\t\t\t\t\"skipped_candidates\": bson.M{\n\t\t\t\t\t\t\"$size\": \"$skipped_candidates\",\n\t\t\t\t\t},\n\t\t\t\t\t// \"alerts\": bson.M{\n\t\t\t\t\t// \t\"$size\": \"$alerts\", // TODO:\n\t\t\t\t\t// },\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\t\"$project\": bson.M{\n\t\t\t\t\t\"saved_candidates\": 1,\n\t\t\t\t\t\"skipped_candidates\": 1,\n\t\t\t\t\t// \"alerts\": 1,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t)\n\tif err != nil {\n\t\tif err == mongo.ErrNoDocuments {\n\t\t\treturn 0, 0, errors.New(`not_found`)\n\t\t}\n\t\treturn 0, 0, err\n\t}\n\tdefer cursor.Close(ctx)\n\n\tif cursor.Next(ctx) {\n\t\terr = cursor.Decode(&amount)\n\t\tif err != nil {\n\t\t\treturn 0, 0, err\n\t\t}\n\t}\n\n\treturn amount.Saved, amount.Skipped, nil\n}", "func (_Bindings *BindingsTransactorSession) ReduceReserves(reduceAmount *big.Int) (*types.Transaction, error) {\n\treturn _Bindings.Contract.ReduceReserves(&_Bindings.TransactOpts, reduceAmount)\n}", "func SendFunds(ctx fsm.Context, environment ClientDealEnvironment, deal rm.ClientDealState) error {\n\ttotalBytesToPayFor := deal.TotalReceived\n\n\t// If unsealing has been paid for, and not all blocks have been received,\n\t// and the number of bytes received is less than the number required\n\t// for the current payment interval, no need to send a payment\n\tif deal.UnsealFundsPaid.GreaterThanEqual(deal.UnsealPrice) &&\n\t\t!deal.AllBlocksReceived &&\n\t\ttotalBytesToPayFor < deal.CurrentInterval {\n\n\t\tlog.Debugf(\"client: ignoring payment request for %d: total bytes to pay for %d < interval %d\",\n\t\t\tdeal.PaymentRequested, totalBytesToPayFor, deal.CurrentInterval)\n\t\treturn ctx.Trigger(rm.ClientEventPaymentNotSent)\n\t}\n\n\ttok, _, err := environment.Node().GetChainHead(ctx.Context())\n\tif err != nil {\n\t\treturn ctx.Trigger(rm.ClientEventCreateVoucherFailed, err)\n\t}\n\n\t// Calculate the payment amount due for data received\n\ttransferPrice := big.Mul(abi.NewTokenAmount(int64(totalBytesToPayFor)), deal.PricePerByte)\n\t// Calculate the total amount including the unsealing cost\n\ttotalPrice := big.Add(transferPrice, deal.UnsealPrice)\n\n\t// If we've already sent at or above the amount due, no need to send funds\n\tif totalPrice.LessThanEqual(deal.FundsSpent) {\n\t\tlog.Debugf(\"client: not sending voucher: funds spent %d >= total price %d: transfer price %d + unseal price %d (payment requested %d)\",\n\t\t\tdeal.FundsSpent, totalPrice, transferPrice, deal.UnsealPrice, deal.PaymentRequested)\n\t\treturn ctx.Trigger(rm.ClientEventPaymentNotSent)\n\t}\n\n\tlog.Debugf(\"client: sending voucher for %d = transfer price %d + unseal price %d (payment requested %d)\",\n\t\ttotalPrice, transferPrice, deal.UnsealPrice, deal.PaymentRequested)\n\n\t// Create a payment voucher\n\tvoucher, err := environment.Node().CreatePaymentVoucher(ctx.Context(), deal.PaymentInfo.PayCh, totalPrice, deal.PaymentInfo.Lane, tok)\n\tif err != nil {\n\t\tshortfallErr, ok := err.(rm.ShortfallError)\n\t\tif ok {\n\t\t\t// There were not enough funds in the payment channel to create a\n\t\t\t// voucher of this amount, so the client needs to add more funds to\n\t\t\t// the payment channel\n\t\t\tlog.Debugf(\"client: voucher shortfall of %d when creating voucher for %d\",\n\t\t\t\tshortfallErr.Shortfall(), totalPrice)\n\t\t\treturn ctx.Trigger(rm.ClientEventVoucherShortfall, shortfallErr.Shortfall())\n\t\t}\n\t\treturn ctx.Trigger(rm.ClientEventCreateVoucherFailed, err)\n\t}\n\n\t// Send the payment voucher\n\terr = environment.SendDataTransferVoucher(ctx.Context(), *deal.ChannelID, &rm.DealPayment{\n\t\tID: deal.DealProposal.ID,\n\t\tPaymentChannel: deal.PaymentInfo.PayCh,\n\t\tPaymentVoucher: voucher,\n\t})\n\tif err != nil {\n\t\treturn ctx.Trigger(rm.ClientEventWriteDealPaymentErrored, err)\n\t}\n\n\treturn ctx.Trigger(rm.ClientEventPaymentSent, totalPrice)\n}", "func NewDelayedVestingAccount(baseAcc *authtypes.BaseAccount, originalVesting sdk.Coins, endTime int64) *DelayedVestingAccount {\n\tbaseVestingAcc := &BaseVestingAccount{\n\t\tBaseAccount: baseAcc,\n\t\tOriginalVesting: originalVesting,\n\t\tEndTime: endTime,\n\t}\n\n\treturn &DelayedVestingAccount{baseVestingAcc}\n}", "func (k Keeper) BurnCoinsForChallenges(ctx sdk.Ctx, relays int64, toAddr sdk.Address) {\n\tk.posKeeper.BurnForChallenge(ctx, sdk.NewInt(relays), toAddr)\n}", "func (t *PendingTransaction) Get(input *PendingTransactionInput) (*PendingTransactions, error) {\n\tresp, err := t.c.Request(http.MethodGet, fmt.Sprintf(\"/pending_transactions/%s\", input.ID), new(bytes.Buffer), nil)\n\tif err != nil {\n\t\treturn &PendingTransactions{}, err\n\t}\n\tdefer resp.Body.Close()\n\n\tvar pendingTransactions *PendingTransactions\n\terr = json.NewDecoder(resp.Body).Decode(&pendingTransactions)\n\tif err != nil {\n\t\treturn &PendingTransactions{}, err\n\t}\n\treturn pendingTransactions, nil\n}", "func (s *skill) currentCoolDown() float64 {\n\ts.m.Lock()\n\tdefer s.m.Unlock()\n\treturn s.internalCD\n}", "func (_Cakevault *CakevaultSession) CalculateTotalPendingCakeRewards() (*big.Int, error) {\n\treturn _Cakevault.Contract.CalculateTotalPendingCakeRewards(&_Cakevault.CallOpts)\n}", "func (bc *BlockChain) FindUnspentTransactions(addr string) []Transaction {\n\tvar unspentTXs []Transaction\n\tspentTXOutputs := make(map[string][]int)\n\titerator := bc.Iterator()\n\n\tfor {\n\t\t_block := iterator.Next()\n\n\t\tfor _, tx := range _block.Transactions {\n\t\t\ttxID := hex.EncodeToString(tx.ID)\n\n\t\tOutputs:\n\t\t\tfor outIdx, out := range tx.VOut {\n\t\t\t\tif spentTXOutputs[txID] != nil {\n\t\t\t\t\tfor _, spentOut := range spentTXOutputs[txID] {\n\t\t\t\t\t\tif spentOut == outIdx {\n\t\t\t\t\t\t\tcontinue Outputs\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif out.CanBeUnlockedWith(addr) {\n\t\t\t\t\tunspentTXs = append(unspentTXs, *tx)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif !tx.isCoinBaseTx() {\n\t\t\t\tfor _, in := range tx.VIn {\n\t\t\t\t\tif in.CanUnlockOutputWith(addr) {\n\t\t\t\t\t\tinTxID := hex.EncodeToString(in.TxID)\n\t\t\t\t\t\tspentTXOutputs[inTxID] = append(spentTXOutputs[inTxID], in.VOut)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif len(_block.Prev) == 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn unspentTXs\n}", "func (va ClawbackVestingAccount) GetUnlockedOnly(blockTime time.Time) sdk.Coins {\n\treturn ReadSchedule(va.StartTime, va.EndTime, va.LockupPeriods, va.OriginalVesting, blockTime.Unix())\n}", "func (_Univ2 *Univ2CallerSession) GetReserves() (struct {\n\tReserve0 *big.Int\n\tReserve1 *big.Int\n\tBlockTimestampLast uint32\n}, error) {\n\treturn _Univ2.Contract.GetReserves(&_Univ2.CallOpts)\n}" ]
[ "0.78821915", "0.77730745", "0.7757383", "0.7747683", "0.77116185", "0.7681964", "0.73974156", "0.7347046", "0.72746074", "0.7222658", "0.71943384", "0.6369909", "0.6271219", "0.62576747", "0.6158414", "0.60933256", "0.59755814", "0.5791374", "0.5568287", "0.5336186", "0.522356", "0.51964056", "0.51309437", "0.5022051", "0.49525416", "0.49019387", "0.47204635", "0.46871337", "0.4622861", "0.45959532", "0.44876584", "0.4468089", "0.44558918", "0.4431778", "0.44053763", "0.43615958", "0.43233162", "0.42950004", "0.42834812", "0.42556605", "0.42336354", "0.42203602", "0.42139298", "0.4196689", "0.4189148", "0.41891086", "0.41722628", "0.41487077", "0.41391748", "0.41330418", "0.41196808", "0.41123435", "0.41082346", "0.4079394", "0.4069867", "0.4055867", "0.405051", "0.403225", "0.4027977", "0.4024206", "0.4021154", "0.39872533", "0.3983968", "0.39636633", "0.39430767", "0.3935672", "0.39343905", "0.39249867", "0.39235806", "0.39206472", "0.3902161", "0.39002824", "0.38982892", "0.38911334", "0.38901398", "0.38890108", "0.38855055", "0.38812923", "0.38765833", "0.38670784", "0.38607147", "0.38549536", "0.38513985", "0.38477427", "0.38473716", "0.38464025", "0.38452086", "0.38442126", "0.38418096", "0.38417026", "0.38352513", "0.38282913", "0.3826036", "0.38240886", "0.38191628", "0.38163346", "0.38157395", "0.38150048", "0.3809542", "0.38051668" ]
0.81205183
0
GetVestingCoins returns the total number of vesting coins for a delayed vesting account.
func (dva DelayedVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins { return dva.OriginalVesting.Sub(dva.GetVestedCoins(blockTime)) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (vva ValidatorVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn vva.OriginalVesting.Sub(vva.GetVestedCoins(blockTime))\n}", "func (pva PeriodicVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn pva.OriginalVesting.Sub(pva.GetVestedCoins(blockTime))\n}", "func (va ClawbackVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn va.OriginalVesting.Sub(va.GetVestedCoins(blockTime))\n}", "func (cva ContinuousVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn cva.OriginalVesting.Sub(cva.GetVestedCoins(blockTime))\n}", "func (plva PermanentLockedAccount) GetVestingCoins(_ time.Time) sdk.Coins {\n\treturn plva.OriginalVesting\n}", "func (dva DelayedVestingAccount) GetVestedCoins(blockTime time.Time) sdk.Coins {\n\tif blockTime.Unix() >= dva.EndTime {\n\t\treturn dva.OriginalVesting\n\t}\n\n\treturn nil\n}", "func (vva ValidatorVestingAccount) GetVestedCoins(blockTime time.Time) sdk.Coins {\n\tvar vestedCoins sdk.Coins\n\tif blockTime.Unix() <= vva.StartTime {\n\t\treturn vestedCoins\n\t}\n\tcurrentPeriodStartTime := vva.StartTime\n\tnumberPeriods := len(vva.VestingPeriods)\n\tfor i := 0; i < numberPeriods; i++ {\n\t\tx := blockTime.Unix() - currentPeriodStartTime\n\t\tif x >= vva.VestingPeriods[i].Length {\n\t\t\tif vva.VestingPeriodProgress[i].PeriodComplete {\n\t\t\t\tvestedCoins = vestedCoins.Add(vva.VestingPeriods[i].Amount)\n\t\t\t}\n\t\t\tcurrentPeriodStartTime += vva.VestingPeriods[i].Length\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn vestedCoins\n\n}", "func (cva ContinuousVestingAccount) GetVestedCoins(blockTime time.Time) sdk.Coins {\n\tvar vestedCoins sdk.Coins\n\n\t// We must handle the case where the start time for a vesting account has\n\t// been set into the future or when the start of the chain is not exactly\n\t// known.\n\tif blockTime.Unix() <= cva.StartTime {\n\t\treturn vestedCoins\n\t} else if blockTime.Unix() >= cva.EndTime {\n\t\treturn cva.OriginalVesting\n\t}\n\n\t// calculate the vesting scalar\n\tx := blockTime.Unix() - cva.StartTime\n\ty := cva.EndTime - cva.StartTime\n\ts := sdk.NewDec(x).Quo(sdk.NewDec(y))\n\n\tfor _, ovc := range cva.OriginalVesting {\n\t\tvestedAmt := ovc.Amount.ToDec().Mul(s).RoundInt()\n\t\tvestedCoins = append(vestedCoins, sdk.NewCoin(ovc.Denom, vestedAmt))\n\t}\n\n\treturn vestedCoins\n}", "func (pva PeriodicVestingAccount) GetVestedCoins(blockTime time.Time) sdk.Coins {\n\tcoins := ReadSchedule(pva.StartTime, pva.EndTime, pva.VestingPeriods, pva.OriginalVesting, blockTime.Unix())\n\tif coins.IsZero() {\n\t\treturn nil\n\t}\n\treturn coins\n}", "func (plva PermanentLockedAccount) GetVestedCoins(_ time.Time) sdk.Coins {\n\treturn nil\n}", "func (va ClawbackVestingAccount) GetVestedCoins(blockTime time.Time) sdk.Coins {\n\t// It's likely that one or the other schedule will be nearly trivial,\n\t// so there should be little overhead in recomputing the conjunction each time.\n\tcoins := coinsMin(va.GetUnlockedOnly(blockTime), va.GetVestedOnly(blockTime))\n\tif coins.IsZero() {\n\t\treturn nil\n\t}\n\treturn coins\n}", "func (dva DelayedVestingAccount) LockedCoins(ctx sdk.Context) sdk.Coins {\n\treturn dva.BaseVestingAccount.LockedCoinsFromVesting(dva.GetVestingCoins(ctx.BlockTime()))\n}", "func (bva BaseVestingAccount) LockedCoinsFromVesting(vestingCoins sdk.Coins) sdk.Coins {\n\tlockedCoins := vestingCoins.Sub(vestingCoins.Min(bva.DelegatedVesting))\n\tif lockedCoins == nil {\n\t\treturn sdk.Coins{}\n\t}\n\treturn lockedCoins\n}", "func (vva ValidatorVestingAccount) GetFailedVestedCoins() sdk.Coins {\n\tvar failedVestedCoins sdk.Coins\n\tnumberPeriods := len(vva.VestingPeriods)\n\tfor i := 0; i < numberPeriods; i++ {\n\t\tif vva.VestingPeriodProgress[i].PeriodComplete {\n\t\t\tif !vva.VestingPeriodProgress[i].VestingSuccessful {\n\t\t\t\tfailedVestedCoins = failedVestedCoins.Add(vva.VestingPeriods[i].Amount)\n\t\t\t}\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn failedVestedCoins\n}", "func (pva PeriodicVestingAccount) LockedCoins(ctx sdk.Context) sdk.Coins {\n\treturn pva.BaseVestingAccount.LockedCoinsFromVesting(pva.GetVestingCoins(ctx.BlockTime()))\n}", "func (cva ContinuousVestingAccount) LockedCoins(ctx sdk.Context) sdk.Coins {\n\treturn cva.BaseVestingAccount.LockedCoinsFromVesting(cva.GetVestingCoins(ctx.BlockTime()))\n}", "func (va ClawbackVestingAccount) LockedCoins(ctx sdk.Context) sdk.Coins {\n\treturn va.BaseVestingAccount.LockedCoinsFromVesting(va.GetVestingCoins(ctx.BlockTime()))\n}", "func (vva ValidatorVestingAccount) SpendableCoins(blockTime time.Time) sdk.Coins {\n\treturn vva.BaseVestingAccount.SpendableCoinsVestingAccount(vva.GetVestingCoins(blockTime))\n}", "func (keeper ViewKeeper) GetCoins(ctx sdk.Context, addr sdk.Address) sdk.Coins {\n\treturn getCoins(ctx, keeper.am, addr)\n}", "func (keeper SendKeeper) GetCoins(ctx sdk.Context, addr sdk.Address) sdk.Coins {\n\treturn getCoins(ctx, keeper.am, addr)\n}", "func (va ClawbackVestingAccount) GetVestedOnly(blockTime time.Time) sdk.Coins {\n\treturn ReadSchedule(va.StartTime, va.EndTime, va.VestingPeriods, va.OriginalVesting, blockTime.Unix())\n}", "func (keeper BaseViewKeeper) GetCoins(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins {\n\treturn getCoins(ctx, keeper.am, addr)\n}", "func GetCoins() (coins []Coin, error error) {\n\tvar c = []Coin{}\n\tvar d struct {\n\t\tCrypto []Coin `json:\"crypto\"`\n\t}\n\tjsonData, err := doTauRequest(1, \"GET\", \"data/coins\", nil)\n\tif err != nil {\n\t\treturn c, err\n\t}\n\tif err := json.Unmarshal(jsonData, &d); err != nil {\n\t\treturn c, err\n\t}\n\treturn d.Crypto, nil\n}", "func (plva PermanentLockedAccount) LockedCoins(_ sdk.Context) sdk.Coins {\n\treturn plva.BaseVestingAccount.LockedCoinsFromVesting(plva.OriginalVesting)\n}", "func (keeper Keeper) GetCoins(ctx sdk.Context, addr sdk.Address) sdk.Coins {\n\treturn getCoins(ctx, keeper.am, addr)\n}", "func (t *TauAPI) GetCoins() (coins []Coin, error error) {\n\tvar c = []Coin{}\n\tvar d struct {\n\t\tCrypto []Coin `json:\"cryto\"` //typo from api\n\t\tFiat []Coin `json:\"fiat\"`\n\t}\n\tjsonData, err := t.doTauRequest(&TauReq{\n\t\tVersion: 2,\n\t\tMethod: \"GET\",\n\t\tPath: \"coins\",\n\t})\n\tif err != nil {\n\t\treturn c, err\n\t}\n\tif err := json.Unmarshal(jsonData, &d); err != nil {\n\t\treturn c, err\n\t}\n\tc = append(d.Crypto, d.Fiat...)\n\treturn c, nil\n}", "func (n Network) VestingAccounts(ctx context.Context, launchID uint64) (vestingAccs []networktypes.VestingAccount, err error) {\n\tn.ev.Send(events.New(events.StatusOngoing, \"Fetching genesis vesting accounts\"))\n\tres, err := n.launchQuery.\n\t\tVestingAccountAll(ctx,\n\t\t\t&launchtypes.QueryAllVestingAccountRequest{\n\t\t\t\tLaunchID: launchID,\n\t\t\t},\n\t\t)\n\tif err != nil {\n\t\treturn vestingAccs, err\n\t}\n\n\tfor i, acc := range res.VestingAccount {\n\t\tparsedAcc, err := networktypes.ToVestingAccount(acc)\n\t\tif err != nil {\n\t\t\treturn vestingAccs, errors.Wrapf(err, \"error parsing vesting account %d\", i)\n\t\t}\n\n\t\tvestingAccs = append(vestingAccs, parsedAcc)\n\t}\n\n\treturn vestingAccs, nil\n}", "func (bva BaseVestingAccount) GetOriginalVesting() sdk.Coins {\n\treturn bva.OriginalVesting\n}", "func (ck CoinKeeper) GetCoins(ctx sdk.Context, addr sdk.Address, amt sdk.Coins) sdk.Coins {\n\tacc := ck.am.GetAccount(ctx, addr)\n\treturn acc.GetCoins()\n}", "func (bva BaseVestingAccount) GetDelegatedVesting() sdk.Coins {\n\treturn bva.DelegatedVesting\n}", "func (_TokenVesting *TokenVestingCaller) VestedAmount(opts *bind.CallOpts, _token common.Address) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _TokenVesting.contract.Call(opts, out, \"vestedAmount\", _token)\n\treturn *ret0, err\n}", "func (m *Client) GetCoins() ([]string, error) {\n\tresp, err := m.Service.GetCoins()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error requesting coin list: %s\", err)\n\t}\n\tdefer resp.Body.Close()\n\n\tvar response []string\n\terr = json.NewDecoder(resp.Body).Decode(&response)\n\tif err != nil {\n\t\tmsg, _ := ioutil.ReadAll(resp.Body)\n\t\treturn nil, fmt.Errorf(\"error decoding coin list: %s: %s\", msg, err)\n\t}\n\n\treturn response, nil\n}", "func coins(a int) int {\n\tif a == 0 {\n\t\treturn 0\n\t}\n\treturn doCoins(a, 25)\n}", "func (o *Transaction) GetCounterparties() []TransactionCounterparty {\n\tif o == nil || o.Counterparties == nil {\n\t\tvar ret []TransactionCounterparty\n\t\treturn ret\n\t}\n\treturn *o.Counterparties\n}", "func (_TokenVesting *TokenVestingSession) VestedAmount(_token common.Address) (*big.Int, error) {\n\treturn _TokenVesting.Contract.VestedAmount(&_TokenVesting.CallOpts, _token)\n}", "func (_TokenVesting *TokenVestingCallerSession) VestedAmount(_token common.Address) (*big.Int, error) {\n\treturn _TokenVesting.Contract.VestedAmount(&_TokenVesting.CallOpts, _token)\n}", "func (va ClawbackVestingAccount) GetVestingPeriods() Periods {\n\treturn va.VestingPeriods\n}", "func GetCoins(accCoins []types.Coin) AccountCoins {\n\tcoins := make(AccountCoins, 0)\n\tfor _, coin := range accCoins {\n\t\tcoins = append(coins, AccountCoin{Amount: uint64(coin.Amount), Denom: coin.Denom})\n\t}\n\treturn coins\n}", "func (b *rpcVestingBalance) delegated() (sdk.Coins, sdk.Coins, error) {\n\tdelegatedCoins, err := b.totalDelegated()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tunbondingCoins, err := b.totalUnbondingDelegations()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tdelegated := delegatedCoins.AmountOf(stakingDenom)\n\tunbonding := unbondingCoins.AmountOf(stakingDenom)\n\ttotalStaked := delegated.Add(unbonding)\n\tdelegatedFree := b.vacc.GetDelegatedFree().AmountOf(stakingDenom)\n\n\t// total number of staked and unbonding tokens considered to be liquid\n\ttotalFree := sdk.MinInt(totalStaked, delegatedFree)\n\t// any coins that are not considered liquid, are vesting up to a maximum of delegated\n\tstakedVesting := sdk.MinInt(totalStaked.Sub(totalFree), delegated)\n\t// staked free coins are left over\n\tstakedFree := delegated.Sub(stakedVesting)\n\n\tliquidCoins := sdk.NewCoins(newKavaCoin(stakedFree))\n\tvestingCoins := sdk.NewCoins(newKavaCoin(stakedVesting))\n\treturn liquidCoins, vestingCoins, nil\n}", "func newCoins() sdk.Coins {\n\treturn sdk.Coins{\n\t\tsdk.NewInt64Coin(\"atom\", 10000000),\n\t}\n}", "func (dcr *ExchangeWallet) FundingCoins(ids []dex.Bytes) (asset.Coins, error) {\n\t// First check if we have the coins in cache.\n\tcoins := make(asset.Coins, 0, len(ids))\n\tnotFound := make(map[outPoint]bool)\n\tdcr.fundingMtx.Lock()\n\tdefer dcr.fundingMtx.Unlock() // stay locked until we update the map and lock them in the wallet\n\tfor _, id := range ids {\n\t\ttxHash, vout, err := decodeCoinID(id)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tpt := newOutPoint(txHash, vout)\n\t\tfundingCoin, found := dcr.fundingCoins[pt]\n\t\tif found {\n\t\t\tcoins = append(coins, fundingCoin.op)\n\t\t\tcontinue\n\t\t}\n\t\tnotFound[pt] = true\n\t}\n\tif len(notFound) == 0 {\n\t\treturn coins, nil\n\t}\n\n\t// Check locked outputs for not found coins.\n\tlockedOutputs, err := dcr.lockedOutputs()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor _, output := range lockedOutputs {\n\t\ttxHash, err := chainhash.NewHashFromStr(output.Txid)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error decoding txid from rpc server %s: %w\", output.Txid, err)\n\t\t}\n\t\tpt := newOutPoint(txHash, output.Vout)\n\t\tif !notFound[pt] {\n\t\t\tcontinue\n\t\t}\n\t\ttxOut, err := dcr.node.GetTxOut(dcr.ctx, txHash, output.Vout, true)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"gettxout error for locked output %v: %w\", pt.String(), translateRPCCancelErr(err))\n\t\t}\n\t\tvar address string\n\t\tif len(txOut.ScriptPubKey.Addresses) > 0 {\n\t\t\taddress = txOut.ScriptPubKey.Addresses[0]\n\t\t}\n\t\tcoin := newOutput(txHash, output.Vout, toAtoms(output.Amount), output.Tree)\n\t\tcoins = append(coins, coin)\n\t\tdcr.fundingCoins[pt] = &fundingCoin{\n\t\t\top: coin,\n\t\t\taddr: address,\n\t\t}\n\t\tdelete(notFound, pt)\n\t\tif len(notFound) == 0 {\n\t\t\treturn coins, nil\n\t\t}\n\t}\n\n\t// Some funding coins still not found after checking locked outputs.\n\t// Check wallet unspent outputs as last resort. Lock the coins if found.\n\tunspents, err := dcr.unspents()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcoinsToLock := make([]*wire.OutPoint, 0, len(notFound))\n\tfor _, txout := range unspents {\n\t\ttxHash, err := chainhash.NewHashFromStr(txout.TxID)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error decoding txid from rpc server %s: %w\", txout.TxID, err)\n\t\t}\n\t\tpt := newOutPoint(txHash, txout.Vout)\n\t\tif !notFound[pt] {\n\t\t\tcontinue\n\t\t}\n\t\tcoinsToLock = append(coinsToLock, wire.NewOutPoint(txHash, txout.Vout, txout.Tree))\n\t\tcoin := newOutput(txHash, txout.Vout, toAtoms(txout.Amount), txout.Tree)\n\t\tcoins = append(coins, coin)\n\t\tdcr.fundingCoins[pt] = &fundingCoin{\n\t\t\top: coin,\n\t\t\taddr: txout.Address,\n\t\t}\n\t\tdelete(notFound, pt)\n\t\tif len(notFound) == 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\tif len(notFound) != 0 {\n\t\tids := make([]string, 0, len(notFound))\n\t\tfor pt := range notFound {\n\t\t\tids = append(ids, pt.String())\n\t\t}\n\t\treturn nil, fmt.Errorf(\"funding coins not found: %s\", strings.Join(ids, \", \"))\n\t}\n\tdcr.log.Debugf(\"Locking funding coins that were unlocked %v\", coinsToLock)\n\terr = dcr.node.LockUnspent(dcr.ctx, false, coinsToLock)\n\tif err != nil {\n\t\treturn nil, translateRPCCancelErr(err)\n\t}\n\n\treturn coins, nil\n}", "func TestGetSupportCoins(t *testing.T) {\n\tt.Parallel()\n\tif _, err := ok.GetSupportCoins(context.Background()); err != nil {\n\t\tt.Error(\"Okx GetSupportCoins() error\", err)\n\t}\n}", "func (dcr *ExchangeWallet) FundingCoins(ids []dex.Bytes) (asset.Coins, error) {\n\t// First check if we have the coins in cache.\n\tcoins := make(asset.Coins, 0, len(ids))\n\tnotFound := make(map[outPoint]bool)\n\tdcr.fundingMtx.Lock()\n\tdefer dcr.fundingMtx.Unlock() // stay locked until we update the map and lock them in the wallet\n\tfor _, id := range ids {\n\t\ttxHash, vout, err := decodeCoinID(id)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tpt := newOutPoint(txHash, vout)\n\t\tfundingCoin, found := dcr.fundingCoins[pt]\n\t\tif found {\n\t\t\tcoins = append(coins, fundingCoin.op)\n\t\t\tcontinue\n\t\t}\n\t\tnotFound[pt] = true\n\t}\n\tif len(notFound) == 0 {\n\t\treturn coins, nil\n\t}\n\n\t// Check locked outputs for not found coins.\n\tfor _, acct := range dcr.fundingAccounts() {\n\t\tlockedOutputs, err := dcr.wallet.LockedOutputs(dcr.ctx, acct)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfor _, output := range lockedOutputs {\n\t\t\ttxHash, err := chainhash.NewHashFromStr(output.Txid)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"error decoding txid from rpc server %s: %w\", output.Txid, err)\n\t\t\t}\n\t\t\tpt := newOutPoint(txHash, output.Vout)\n\t\t\tif !notFound[pt] {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ttxOut, err := dcr.wallet.UnspentOutput(dcr.ctx, txHash, output.Vout, output.Tree)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"gettxout error for locked output %v: %w\", pt.String(), err)\n\t\t\t}\n\t\t\tvar address string\n\t\t\tif len(txOut.Addresses) > 0 {\n\t\t\t\taddress = txOut.Addresses[0]\n\t\t\t}\n\t\t\tcoin := newOutput(txHash, output.Vout, toAtoms(output.Amount), output.Tree)\n\t\t\tcoins = append(coins, coin)\n\t\t\tdcr.fundingCoins[pt] = &fundingCoin{\n\t\t\t\top: coin,\n\t\t\t\taddr: address,\n\t\t\t}\n\t\t\tdelete(notFound, pt)\n\t\t\tif len(notFound) == 0 {\n\t\t\t\treturn coins, nil\n\t\t\t}\n\t\t}\n\t}\n\n\t// Some funding coins still not found after checking locked outputs.\n\t// Check wallet unspent outputs as last resort. Lock the coins if found.\n\tcoinsToLock := make([]*wire.OutPoint, 0, len(notFound))\n\tfor _, acct := range dcr.fundingAccounts() {\n\t\tunspents, err := dcr.wallet.Unspents(dcr.ctx, acct)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfor _, txout := range unspents {\n\t\t\ttxHash, err := chainhash.NewHashFromStr(txout.TxID)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"error decoding txid from rpc server %s: %w\", txout.TxID, err)\n\t\t\t}\n\t\t\tpt := newOutPoint(txHash, txout.Vout)\n\t\t\tif !notFound[pt] {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tcoinsToLock = append(coinsToLock, wire.NewOutPoint(txHash, txout.Vout, txout.Tree))\n\t\t\tcoin := newOutput(txHash, txout.Vout, toAtoms(txout.Amount), txout.Tree)\n\t\t\tcoins = append(coins, coin)\n\t\t\tdcr.fundingCoins[pt] = &fundingCoin{\n\t\t\t\top: coin,\n\t\t\t\taddr: txout.Address,\n\t\t\t}\n\t\t\tdelete(notFound, pt)\n\t\t\tif len(notFound) == 0 {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\t// Return an error if some coins are still not found.\n\tif len(notFound) != 0 {\n\t\tids := make([]string, 0, len(notFound))\n\t\tfor pt := range notFound {\n\t\t\tids = append(ids, pt.String())\n\t\t}\n\t\treturn nil, fmt.Errorf(\"funding coins not found: %s\", strings.Join(ids, \", \"))\n\t}\n\n\tdcr.log.Debugf(\"Locking funding coins that were unlocked %v\", coinsToLock)\n\terr := dcr.wallet.LockUnspent(dcr.ctx, false, coinsToLock)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn coins, nil\n}", "func (gc *GovernanceContract) TotalVotingPower() (hexutil.Big, error) {\n\treturn gc.repo.GovernanceTotalWeight(&gc.Address)\n}", "func (pva PeriodicVestingAccount) GetVestingPeriods() Periods {\n\treturn pva.VestingPeriods\n}", "func (_Vault *VaultCaller) WithdrawRequests(opts *bind.CallOpts, arg0 common.Address, arg1 common.Address) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _Vault.contract.Call(opts, out, \"withdrawRequests\", arg0, arg1)\n\treturn *ret0, err\n}", "func (candidate *Candidate) GetTotalBipStake() *big.Int {\n\tcandidate.lock.RLock()\n\tdefer candidate.lock.RUnlock()\n\n\treturn big.NewInt(0).Set(candidate.totalBipStake)\n}", "func (k Keeper) GetStakedTokens(ctx sdk.Ctx) sdk.BigInt {\n\tstakedPool := k.GetStakedPool(ctx)\n\treturn stakedPool.GetCoins().AmountOf(k.StakeDenom(ctx))\n}", "func drawCoins() int {\n\treturn rand.Intn(maxCoins+1-minCoins) + minCoins\n}", "func (c Cart) GetVoucherSavings() domain.Price {\n\tprice := domain.Price{}\n\tvar err error\n\n\tfor _, item := range c.Totalitems {\n\t\tif item.Type == TotalsTypeVoucher {\n\t\t\tprice, err = price.Add(item.Price)\n\t\t\tif err != nil {\n\t\t\t\treturn price\n\t\t\t}\n\t\t}\n\t}\n\n\tif price.IsNegative() {\n\t\treturn domain.Price{}\n\t}\n\n\treturn price\n}", "func (a API) GetBlockCountWait(cmd *None) (out *int64, e error) {\n\tRPCHandlers[\"getblockcount\"].Call <-API{a.Ch, cmd, nil}\n\tselect {\n\tcase <-time.After(time.Second*5):\n\t\tbreak\n\tcase o := <-a.Ch.(chan GetBlockCountRes):\n\t\tout, e = o.Res, o.Err\n\t}\n\treturn\n}", "func subtractCoins(ctx sdk.Context, am sdk.AccountMapper, addr sdk.Address, amt sdk.Coins) (sdk.Coins, sdk.Error) {\n\toldCoins := getCoins(ctx, am, addr)\n\tnewCoins := oldCoins.Minus(amt)\n\tif !newCoins.IsNotNegative() {\n\t\treturn amt, sdk.ErrInsufficientCoins(fmt.Sprintf(\"%s < %s\", oldCoins, amt))\n\t}\n\terr := setCoins(ctx, am, addr, newCoins)\n\treturn newCoins, err\n}", "func sendCoins(ctx sdk.Context, am sdk.AccountMapper, fromAddr sdk.Address, toAddr sdk.Address, amt sdk.Coins) sdk.Error {\n\t_, err := subtractCoins(ctx, am, fromAddr, amt)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = addCoins(ctx, am, toAddr, amt)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func NewDelayedVestingAccount(baseAcc *authtypes.BaseAccount, originalVesting sdk.Coins, endTime int64) *DelayedVestingAccount {\n\tbaseVestingAcc := &BaseVestingAccount{\n\t\tBaseAccount: baseAcc,\n\t\tOriginalVesting: originalVesting,\n\t\tEndTime: endTime,\n\t}\n\n\treturn &DelayedVestingAccount{baseVestingAcc}\n}", "func (c *CoordinatorHelper) Coins(\n\tctx context.Context,\n\tdbTx storage.DatabaseTransaction,\n\taccountIdentifier *types.AccountIdentifier,\n\tcurrency *types.Currency,\n) ([]*types.Coin, error) {\n\tcoins, _, err := c.coinStorage.GetCoinsTransactional(\n\t\tctx,\n\t\tdbTx,\n\t\taccountIdentifier,\n\t)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"%w: unable to get coins\", err)\n\t}\n\n\tcoinsToReturn := []*types.Coin{}\n\tfor _, coin := range coins {\n\t\tif types.Hash(coin.Amount.Currency) != types.Hash(currency) {\n\t\t\tcontinue\n\t\t}\n\n\t\tcoinsToReturn = append(coinsToReturn, coin)\n\t}\n\n\treturn coinsToReturn, nil\n}", "func (tx *Transaction) GetNewFromCoins() []FromCoin {\n\tnfcs := make([]FromCoin, 0)\n\tfor index, c := range tx.To.Coins {\n\t\tticket := Ticket{}\n\t\tticket.SetTxid(*tx.GetTxID())\n\t\tticket.SetIndex(uint32(index))\n\n\t\tnfc := FromCoin{}\n\t\tnfc.SetId(c.Id)\n\t\tnfc.AddTicket(&ticket)\n\n\t\tnfcs = append(nfcs, nfc)\n\t}\n\n\treturn nfcs\n}", "func (btc *ExchangeWallet) FundingCoins(ids []dex.Bytes) (asset.Coins, error) {\n\t// First check if we have the coins in cache.\n\tcoins := make(asset.Coins, 0, len(ids))\n\tnotFound := make(map[string]struct{})\n\tbtc.fundingMtx.RLock()\n\tfor _, id := range ids {\n\t\ttxHash, vout, err := decodeCoinID(id)\n\t\tif err != nil {\n\t\t\tbtc.fundingMtx.RUnlock()\n\t\t\treturn nil, err\n\t\t}\n\t\topID := outpointID(txHash.String(), vout)\n\t\tfundingCoin, found := btc.fundingCoins[opID]\n\t\tif found {\n\t\t\tcoins = append(coins, newOutput(btc.node, txHash, vout, fundingCoin.amount, fundingCoin.redeemScript))\n\t\t\tcontinue\n\t\t}\n\t\tnotFound[opID] = struct{}{}\n\t}\n\tbtc.fundingMtx.RUnlock()\n\tif len(notFound) == 0 {\n\t\treturn coins, nil\n\t}\n\t_, utxoMap, _, err := btc.spendableUTXOs(0)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlockers := make([]*output, 0, len(ids))\n\tbtc.fundingMtx.Lock()\n\tdefer btc.fundingMtx.Unlock()\n\tfor _, id := range ids {\n\t\ttxHash, vout, err := decodeCoinID(id)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\topID := outpointID(txHash.String(), vout)\n\t\tutxo, found := utxoMap[opID]\n\t\tif !found {\n\t\t\treturn nil, fmt.Errorf(\"funding coin %s not found\", opID)\n\t\t}\n\t\tbtc.fundingCoins[opID] = utxo\n\t\tcoin := newOutput(btc.node, utxo.txHash, utxo.vout, utxo.amount, utxo.redeemScript)\n\t\tcoins = append(coins, coin)\n\t\tlockers = append(lockers, coin)\n\t\tdelete(notFound, opID)\n\t\tif len(notFound) == 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\tif len(notFound) != 0 {\n\t\tids := make([]string, 0, len(notFound))\n\t\tfor opID := range notFound {\n\t\t\tids = append(ids, opID)\n\t\t}\n\t\treturn nil, fmt.Errorf(\"coins not found: %s\", strings.Join(ids, \", \"))\n\t}\n\terr = btc.wallet.LockUnspent(false, lockers)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn coins, nil\n}", "func (dcr *ExchangeWallet) sendCoins(addr stdaddr.Address, coins asset.Coins, val, feeRate uint64, subtract bool) (*wire.MsgTx, uint64, error) {\n\tbaseTx := wire.NewMsgTx()\n\t_, err := dcr.addInputCoins(baseTx, coins)\n\tif err != nil {\n\t\treturn nil, 0, err\n\t}\n\tpayScriptVer, payScript := addr.PaymentScript()\n\ttxOut := newTxOut(int64(val), payScriptVer, payScript)\n\tbaseTx.AddTxOut(txOut)\n\n\tvar feeSource int32 // subtract from vout 0\n\tif !subtract {\n\t\tfeeSource = -1 // subtract from change\n\t}\n\n\ttx, err := dcr.sendWithReturn(baseTx, feeRate, feeSource)\n\tif err != nil {\n\t\treturn nil, 0, err\n\t}\n\treturn tx, uint64(tx.TxOut[0].Value), err\n}", "func (cs *Coins) CoinSelect(amount uint64, asset string) (unspents []explorer.Utxo, change uint64, err error) {\n\tchange = 0\n\tunspents = []explorer.Utxo{}\n\tavailableSats := uint64(0)\n\n\tfor index, unspent := range cs.Utxos {\n\t\tu := unspent\n\t\tassetHash := u.Asset()\n\t\tamountSatoshis := u.Value()\n\t\tif len(u.AssetCommitment()) > 0 && len(u.ValueCommitment()) > 0 {\n\t\t\tbk := cs.BlindingKey\n\t\t\tif len(cs.BlindingKeys) > 0 {\n\t\t\t\tbk = cs.BlindingKeys[index]\n\t\t\t}\n\t\t\tav, err := unblindUxto(u, bk)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, 0, err\n\t\t\t}\n\t\t\tassetHash = av.asset\n\t\t\tamountSatoshis = av.value\n\t\t}\n\t\tif asset == assetHash {\n\t\t\tunspents = append(unspents, unspent)\n\t\t\tavailableSats += amountSatoshis\n\n\t\t\tif availableSats >= amount {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\tif availableSats < amount {\n\t\treturn nil, 0, errors.New(\"You do not have enough coins\")\n\t}\n\n\tchange = availableSats - amount\n\n\treturn unspents, change, nil\n}", "func (r *Repository) GetAmountsOfManageCandidates(ctx context.Context, companyID string) (int32, int32, error) {\n\tobjCompanyID, err := primitive.ObjectIDFromHex(companyID)\n\tif err != nil {\n\t\treturn 0, 0, errors.New(`wrong_id`)\n\t}\n\n\tamount := struct {\n\t\tSaved int32 `bson:\"saved_candidates\"`\n\t\tSkipped int32 `bson:\"skipped_candidates\"`\n\t\t// Alerts int32 `bson:\"alerts\"`\n\t}{}\n\n\tcursor, err := r.companiesCollection.Aggregate(\n\t\tctx,\n\t\t[]bson.M{\n\t\t\t{\n\t\t\t\t\"$match\": bson.M{\n\t\t\t\t\t\"company_id\": objCompanyID,\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\t\"$addFields\": bson.M{\n\t\t\t\t\t\"saved_candidates\": bson.M{\n\t\t\t\t\t\t\"$size\": \"$saved_candidates\",\n\t\t\t\t\t},\n\t\t\t\t\t\"skipped_candidates\": bson.M{\n\t\t\t\t\t\t\"$size\": \"$skipped_candidates\",\n\t\t\t\t\t},\n\t\t\t\t\t// \"alerts\": bson.M{\n\t\t\t\t\t// \t\"$size\": \"$alerts\", // TODO:\n\t\t\t\t\t// },\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\t\"$project\": bson.M{\n\t\t\t\t\t\"saved_candidates\": 1,\n\t\t\t\t\t\"skipped_candidates\": 1,\n\t\t\t\t\t// \"alerts\": 1,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t)\n\tif err != nil {\n\t\tif err == mongo.ErrNoDocuments {\n\t\t\treturn 0, 0, errors.New(`not_found`)\n\t\t}\n\t\treturn 0, 0, err\n\t}\n\tdefer cursor.Close(ctx)\n\n\tif cursor.Next(ctx) {\n\t\terr = cursor.Decode(&amount)\n\t\tif err != nil {\n\t\t\treturn 0, 0, err\n\t\t}\n\t}\n\n\treturn amount.Saved, amount.Skipped, nil\n}", "func (cm *ConnectionManager) sumDeposits() *big.Int {\n\tchs := cm.openChannels()\n\tvar sum = big.NewInt(0)\n\tfor _, c := range chs {\n\t\tsum.Add(sum, c.OurContractBalance)\n\t}\n\treturn sum\n}", "func NewContinuousVestingAccount(baseAcc *authtypes.BaseAccount, originalVesting sdk.Coins, startTime, endTime int64) *ContinuousVestingAccount {\n\tbaseVestingAcc := &BaseVestingAccount{\n\t\tBaseAccount: baseAcc,\n\t\tOriginalVesting: originalVesting,\n\t\tEndTime: endTime,\n\t}\n\n\treturn &ContinuousVestingAccount{\n\t\tStartTime: startTime,\n\t\tBaseVestingAccount: baseVestingAcc,\n\t}\n}", "func makeSpendTxWithHoursBurned(t *testing.T, uxs coin.UxArray, keys []cipher.SecKey, toAddr cipher.Address, coins, hoursBurned uint64) coin.Transaction {\n\tspendTx := coin.Transaction{}\n\tvar totalHours uint64\n\tvar totalCoins uint64\n\tfor _, ux := range uxs {\n\t\tspendTx.PushInput(ux.Hash())\n\t\ttotalHours += ux.Body.Hours\n\t\ttotalCoins += ux.Body.Coins\n\t}\n\n\trequire.True(t, coins <= totalCoins)\n\trequire.True(t, hoursBurned <= totalHours, \"hoursBurned must be <= totalHours\")\n\n\tspendHours := totalHours - hoursBurned\n\n\tspendTx.PushOutput(toAddr, coins, spendHours)\n\tif totalCoins != coins {\n\t\tspendTx.PushOutput(uxs[0].Body.Address, totalCoins-coins, 0)\n\t}\n\tspendTx.SignInputs(keys)\n\tspendTx.UpdateHeader()\n\treturn spendTx\n}", "func arrangeCoins(n int) int {\n\tcount := 1\n\tfor n >= count {\n\t\tn -= count\n\t\tcount++\n\t}\n\treturn count - 1\n}", "func (_DelegationController *DelegationControllerTransactor) GetAndUpdateLockedAmount(opts *bind.TransactOpts, wallet common.Address) (*types.Transaction, error) {\n\treturn _DelegationController.contract.Transact(opts, \"getAndUpdateLockedAmount\", wallet)\n}", "func getOVMETHTotalSupply(inStateDB *state.StateDB) *big.Int {\n\tposition := common.Big2\n\tkey := common.BytesToHash(common.LeftPadBytes(position.Bytes(), 32))\n\treturn inStateDB.GetState(OVMETHAddress, key).Big()\n}", "func (keeper Keeper) SubtractCoins(ctx sdk.Context, addr sdk.Address, amt sdk.Coins) (sdk.Coins, sdk.Error) {\n\treturn subtractCoins(ctx, keeper.am, addr, amt)\n}", "func (_Distributor *DistributorTransactor) GetAndUpdateEarnedBountyAmountOf(opts *bind.TransactOpts, wallet common.Address, validatorId *big.Int) (*types.Transaction, error) {\n\treturn _Distributor.contract.Transact(opts, \"getAndUpdateEarnedBountyAmountOf\", wallet, validatorId)\n}", "func (dcr *ExchangeWallet) ReturnCoins(unspents asset.Coins) error {\n\tdcr.fundingMtx.Lock()\n\tdefer dcr.fundingMtx.Unlock()\n\treturn dcr.returnCoins(unspents)\n}", "func getBudgetCredits(e *httpexpect.Expect, t *testing.T) {\n\ttestCases := []testCase{\n\t\tnotLoggedTestCase, // 0 : missing token\n\t\t{\n\t\t\tToken: testCtx.User.Token,\n\t\t\tStatus: http.StatusOK,\n\t\t\tBodyContains: []string{\"BudgetCredits\", \"BudgetChapter\"},\n\t\t\tArraySize: 78,\n\t\t\tCountItemName: `\"id\"`,\n\t\t}, // 1 : ok\n\t}\n\n\tf := func(tc testCase) *httpexpect.Response {\n\t\treturn e.GET(\"/api/budget_credits\").\n\t\t\tWithHeader(\"Authorization\", \"Bearer \"+tc.Token).Expect()\n\t}\n\tfor _, r := range chkTestCases(testCases, f, \"GetBudgetCredits\") {\n\t\tt.Error(r)\n\t}\n}", "func (b *Byzcoin) Watch(ctx context.Context) <-chan *ledger.TransactionResult {\n\tc := make(chan *ledger.TransactionResult, 100)\n\tb.bc.Watch(ctx, observer{ch: c})\n\n\treturn c\n}", "func listCoins(ctx sdk.Context, k Keeper) ([]byte, error) {\n\tvar coinsList types.QueryResCoins\n\n\titerator := k.GetCoinsIterator(ctx)\n\n\tfor ; iterator.Valid(); iterator.Next() {\n\t\tvar coin types.Coin\n\n\t\t_ = k.cdc.UnmarshalBinaryLengthPrefixed(iterator.Value(), &coin)\n\n\t\tcoinsList = append(coinsList, coin)\n\t}\n\n\tres, err := codec.MarshalJSONIndent(k.cdc, coinsList)\n\n\tif err != nil {\n\t\treturn res, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error())\n\t}\n\n\treturn res, nil\n}", "func getMoneyAmount(n int) int {\n \n}", "func (dcr *ExchangeWallet) sendCoins(addr dcrutil.Address, coins asset.Coins, val, feeRate uint64, subtract bool) (*wire.MsgTx, uint64, error) {\n\tbaseTx := wire.NewMsgTx()\n\t_, err := dcr.addInputCoins(baseTx, coins)\n\tif err != nil {\n\t\treturn nil, 0, err\n\t}\n\tpayScript, err := txscript.PayToAddrScript(addr)\n\tif err != nil {\n\t\treturn nil, 0, fmt.Errorf(\"error creating P2SH script: %w\", err)\n\t}\n\n\ttxOut := wire.NewTxOut(int64(val), payScript)\n\tbaseTx.AddTxOut(txOut)\n\n\tvar feeSource int32 // subtract from vout 0\n\tif !subtract {\n\t\tfeeSource = -1 // subtract from change\n\t}\n\n\ttx, _, _, _, err := dcr.sendWithReturn(baseTx, feeRate, feeSource)\n\treturn tx, uint64(txOut.Value), err\n}", "func (k Keeper) IncrementBorrowedCoins(ctx sdk.Context, newCoins sdk.Coins) {\n\tborrowedCoins, found := k.GetBorrowedCoins(ctx)\n\tif !found {\n\t\tk.SetBorrowedCoins(ctx, newCoins)\n\t} else {\n\t\tk.SetBorrowedCoins(ctx, borrowedCoins.Add(newCoins...))\n\t}\n}", "func (m *Machine) ReturnCoins() {\n\tcoins := m.cashEngine.DropCoins()\n\n\ts := fmt.Sprintf(\"-> \")\n\tfor i, c := range coins {\n\t\tif i == len(coins)-1 {\n\t\t\ts += fmt.Sprintf(\"%s\", c.value.String())\n\t\t\tcontinue\n\t\t}\n\t\ts += fmt.Sprintf(\"%s, \", c.value.String())\n\t}\n\n\tm.logger.Println(s)\n}", "func (ds *DepositToStake) Amount() *big.Int { return ds.amount }", "func (_DelegationController *DelegationControllerTransactorSession) GetAndUpdateLockedAmount(wallet common.Address) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.GetAndUpdateLockedAmount(&_DelegationController.TransactOpts, wallet)\n}", "func (s *Store) kvsGetTxn(tx *memdb.Txn, ws memdb.WatchSet, key string) (uint64, *structs.DirEntry, error) {\n\t// Get the table index.\n\tidx := maxIndexTxn(tx, \"kvs\", \"tombstones\")\n\n\t// Retrieve the key.\n\twatchCh, entry, err := tx.FirstWatch(\"kvs\", \"id\", key)\n\tif err != nil {\n\t\treturn 0, nil, fmt.Errorf(\"failed kvs lookup: %s\", err)\n\t}\n\tws.Add(watchCh)\n\tif entry != nil {\n\t\treturn idx, entry.(*structs.DirEntry), nil\n\t}\n\treturn idx, nil, nil\n}", "func (_Gatekeeper *GatekeeperCaller) GetCurrentTransactionAmountForBlock(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _Gatekeeper.contract.Call(opts, out, \"GetCurrentTransactionAmountForBlock\")\n\treturn *ret0, err\n}", "func (_Contracts *ContractsCaller) VotersCount(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _Contracts.contract.Call(opts, out, \"votersCount\")\n\treturn *ret0, err\n}", "func (tb *transactionBuilder) FundCoins(amount types.Currency, refundAddress *types.UnlockHash, reuseRefundAddress bool) error {\n\ttb.wallet.mu.Lock()\n\tdefer tb.wallet.mu.Unlock()\n\n\tif !tb.wallet.unlocked {\n\t\treturn modules.ErrLockedWallet\n\t}\n\n\t// prepare fulfillable context\n\tctx := tb.wallet.getFulfillableContextForLatestBlock()\n\n\t// Collect a value-sorted set of fulfillable coin outputs.\n\tvar so sortedOutputs\n\tfor scoid, sco := range tb.wallet.coinOutputs {\n\t\tif !sco.Condition.Fulfillable(ctx) {\n\t\t\tcontinue\n\t\t}\n\t\tso.ids = append(so.ids, scoid)\n\t\tso.outputs = append(so.outputs, sco)\n\t}\n\t// Add all of the unconfirmed outputs as well.\n\tfor _, upt := range tb.wallet.unconfirmedProcessedTransactions {\n\t\tfor i, sco := range upt.Transaction.CoinOutputs {\n\t\t\tuh := sco.Condition.UnlockHash()\n\t\t\t// Determine if the output belongs to the wallet.\n\t\t\texists, err := tb.wallet.keyExists(uh)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif !exists || !sco.Condition.Fulfillable(ctx) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tso.ids = append(so.ids, upt.Transaction.CoinOutputID(uint64(i)))\n\t\t\tso.outputs = append(so.outputs, sco)\n\t\t}\n\t}\n\tsort.Sort(sort.Reverse(so))\n\n\t// Create a transaction that will add the correct amount of coins to the\n\t// transaction.\n\tvar fund types.Currency\n\t// potentialFund tracks the balance of the wallet including outputs that\n\t// have been spent in other unconfirmed transactions recently. This is to\n\t// provide the user with a more useful error message in the event that they\n\t// are overspending.\n\tvar potentialFund types.Currency\n\tvar spentScoids []types.CoinOutputID\n\tfor i := range so.ids {\n\t\tscoid := so.ids[i]\n\t\tsco := so.outputs[i]\n\t\t// Check that this output has not recently been spent by the wallet.\n\t\tspendHeight := tb.wallet.spentOutputs[types.OutputID(scoid)]\n\t\t// Prevent an underflow error.\n\t\tallowedHeight := tb.wallet.consensusSetHeight - RespendTimeout\n\t\tif tb.wallet.consensusSetHeight < RespendTimeout {\n\t\t\tallowedHeight = 0\n\t\t}\n\t\tif spendHeight > allowedHeight {\n\t\t\tpotentialFund = potentialFund.Add(sco.Value)\n\t\t\tcontinue\n\t\t}\n\n\t\t// prepare fulfillment, matching the output\n\t\tuh := sco.Condition.UnlockHash()\n\t\tvar ff types.MarshalableUnlockFulfillment\n\t\tswitch sco.Condition.ConditionType() {\n\t\tcase types.ConditionTypeUnlockHash, types.ConditionTypeTimeLock:\n\t\t\t// ConditionTypeTimeLock is fine, as we know it's fulfillable,\n\t\t\t// and that can only mean for now that it is using an internal unlockHashCondition or nilCondition\n\t\t\tpk, _, err := tb.wallet.getKey(uh)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tff = types.NewSingleSignatureFulfillment(pk)\n\t\tdefault:\n\t\t\tbuild.Severe(fmt.Errorf(\"unexpected condition type: %[1]v (%[1]T)\", sco.Condition))\n\t\t\treturn types.ErrUnexpectedUnlockCondition\n\t\t}\n\t\t// Add a coin input for this output.\n\t\tsci := types.CoinInput{\n\t\t\tParentID: scoid,\n\t\t\tFulfillment: types.NewFulfillment(ff),\n\t\t}\n\t\ttb.coinInputs = append(tb.coinInputs, inputSignContext{\n\t\t\tInputIndex: len(tb.transaction.CoinInputs),\n\t\t\tUnlockHash: uh,\n\t\t})\n\t\ttb.transaction.CoinInputs = append(tb.transaction.CoinInputs, sci)\n\n\t\tspentScoids = append(spentScoids, scoid)\n\n\t\t// Add the output to the total fund\n\t\tfund = fund.Add(sco.Value)\n\t\tpotentialFund = potentialFund.Add(sco.Value)\n\t\tif fund.Cmp(amount) >= 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\tif potentialFund.Cmp(amount) >= 0 && fund.Cmp(amount) < 0 {\n\t\treturn modules.ErrIncompleteTransactions\n\t}\n\tif fund.Cmp(amount) < 0 {\n\t\treturn modules.ErrLowBalance\n\t}\n\n\t// Create a refund output if needed.\n\tif !amount.Equals(fund) {\n\t\tvar refundUnlockHash types.UnlockHash\n\t\tif refundAddress != nil {\n\t\t\t// use specified refund address\n\t\t\trefundUnlockHash = *refundAddress\n\t\t} else if reuseRefundAddress {\n\t\t\t// use the fist coin input of this tx as refund address\n\t\t\tvar maxCoinAmount types.Currency\n\t\t\tfor _, ci := range tb.transaction.CoinInputs {\n\t\t\t\tco, exists := tb.wallet.coinOutputs[ci.ParentID]\n\t\t\t\tif !exists {\n\t\t\t\t\tco = tb.getCoFromUnconfirmedProcessedTransactions(ci.ParentID)\n\t\t\t\t}\n\t\t\t\tif maxCoinAmount.Cmp(co.Value) < 0 {\n\t\t\t\t\tmaxCoinAmount = co.Value\n\t\t\t\t\trefundUnlockHash = co.Condition.UnlockHash()\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\t// generate a new address\n\t\t\tvar err error\n\t\t\trefundUnlockHash, err = tb.wallet.nextPrimarySeedAddress()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\trefundOutput := types.CoinOutput{\n\t\t\tValue: fund.Sub(amount),\n\t\t\tCondition: types.NewCondition(types.NewUnlockHashCondition(refundUnlockHash)),\n\t\t}\n\t\ttb.transaction.CoinOutputs = append(tb.transaction.CoinOutputs, refundOutput)\n\t}\n\n\t// Mark all outputs that were spent as spent.\n\tfor _, scoid := range spentScoids {\n\t\ttb.wallet.spentOutputs[types.OutputID(scoid)] = tb.wallet.consensusSetHeight\n\t}\n\treturn nil\n}", "func (_DelegationController *DelegationControllerSession) GetAndUpdateLockedAmount(wallet common.Address) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.GetAndUpdateLockedAmount(&_DelegationController.TransactOpts, wallet)\n}", "func (_BtlCoin *BtlCoinSession) TotalSupply() (*big.Int, error) {\n\treturn _BtlCoin.Contract.TotalSupply(&_BtlCoin.CallOpts)\n}", "func (_Vault *VaultCaller) GetDecimals(opts *bind.CallOpts, token common.Address) (uint8, error) {\n\tvar (\n\t\tret0 = new(uint8)\n\t)\n\tout := ret0\n\terr := _Vault.contract.Call(opts, out, \"getDecimals\", token)\n\treturn *ret0, err\n}", "func (_DayLimitMock *DayLimitMockCaller) SpentToday(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _DayLimitMock.contract.Call(opts, out, \"spentToday\")\n\treturn *ret0, err\n}", "func (rpcServer HttpServer) chooseBestOutCoinsToSpent(outCoins []*privacy.OutputCoin, amount uint64) (resultOutputCoins []*privacy.OutputCoin, remainOutputCoins []*privacy.OutputCoin, totalResultOutputCoinAmount uint64, err error) {\n\tresultOutputCoins = make([]*privacy.OutputCoin, 0)\n\tremainOutputCoins = make([]*privacy.OutputCoin, 0)\n\ttotalResultOutputCoinAmount = uint64(0)\n\n\t// either take the smallest coins, or a single largest one\n\tvar outCoinOverLimit *privacy.OutputCoin\n\toutCoinsUnderLimit := make([]*privacy.OutputCoin, 0)\n\n\tfor _, outCoin := range outCoins {\n\t\tif outCoin.CoinDetails.GetValue() < amount {\n\t\t\toutCoinsUnderLimit = append(outCoinsUnderLimit, outCoin)\n\t\t} else if outCoinOverLimit == nil {\n\t\t\toutCoinOverLimit = outCoin\n\t\t} else if outCoinOverLimit.CoinDetails.GetValue() > outCoin.CoinDetails.GetValue() {\n\t\t\tremainOutputCoins = append(remainOutputCoins, outCoin)\n\t\t} else {\n\t\t\tremainOutputCoins = append(remainOutputCoins, outCoinOverLimit)\n\t\t\toutCoinOverLimit = outCoin\n\t\t}\n\t}\n\n\tsort.Slice(outCoinsUnderLimit, func(i, j int) bool {\n\t\treturn outCoinsUnderLimit[i].CoinDetails.GetValue() < outCoinsUnderLimit[j].CoinDetails.GetValue()\n\t})\n\n\tfor _, outCoin := range outCoinsUnderLimit {\n\t\tif totalResultOutputCoinAmount < amount {\n\t\t\ttotalResultOutputCoinAmount += outCoin.CoinDetails.GetValue()\n\t\t\tresultOutputCoins = append(resultOutputCoins, outCoin)\n\t\t} else {\n\t\t\tremainOutputCoins = append(remainOutputCoins, outCoin)\n\t\t}\n\t}\n\n\tif outCoinOverLimit != nil && (outCoinOverLimit.CoinDetails.GetValue() > 2*amount || totalResultOutputCoinAmount < amount) {\n\t\tremainOutputCoins = append(remainOutputCoins, resultOutputCoins...)\n\t\tresultOutputCoins = []*privacy.OutputCoin{outCoinOverLimit}\n\t\ttotalResultOutputCoinAmount = outCoinOverLimit.CoinDetails.GetValue()\n\t} else if outCoinOverLimit != nil {\n\t\tremainOutputCoins = append(remainOutputCoins, outCoinOverLimit)\n\t}\n\n\tif totalResultOutputCoinAmount < amount {\n\t\treturn resultOutputCoins, remainOutputCoins, totalResultOutputCoinAmount, errors.New(\"Not enough coin\")\n\t} else {\n\t\treturn resultOutputCoins, remainOutputCoins, totalResultOutputCoinAmount, nil\n\t}\n}", "func ChooseBestOutCoinsToSpent(utxos []*crypto.InputCoin, amount uint64) (\n\tresultOutputCoins []*crypto.InputCoin,\n\tremainOutputCoins []*crypto.InputCoin,\n\ttotalResultOutputCoinAmount uint64, err error) {\n\n\tresultOutputCoins = make([]*crypto.InputCoin, 0)\n\tremainOutputCoins = make([]*crypto.InputCoin, 0)\n\ttotalResultOutputCoinAmount = uint64(0)\n\n\t// either take the smallest coins, or a single largest one\n\tvar outCoinOverLimit *crypto.InputCoin\n\toutCoinsUnderLimit := make([]*crypto.InputCoin, 0)\n\tfor _, outCoin := range utxos {\n\t\tif outCoin.CoinDetails.GetValue() < amount {\n\t\t\toutCoinsUnderLimit = append(outCoinsUnderLimit, outCoin)\n\t\t} else if outCoinOverLimit == nil {\n\t\t\toutCoinOverLimit = outCoin\n\t\t} else if outCoinOverLimit.CoinDetails.GetValue() > outCoin.CoinDetails.GetValue() {\n\t\t\tremainOutputCoins = append(remainOutputCoins, outCoin)\n\t\t} else {\n\t\t\tremainOutputCoins = append(remainOutputCoins, outCoinOverLimit)\n\t\t\toutCoinOverLimit = outCoin\n\t\t}\n\t}\n\tsort.Slice(outCoinsUnderLimit, func(i, j int) bool {\n\t\treturn outCoinsUnderLimit[i].CoinDetails.GetValue() < outCoinsUnderLimit[j].CoinDetails.GetValue()\n\t})\n\tfor _, outCoin := range outCoinsUnderLimit {\n\t\tif totalResultOutputCoinAmount < amount {\n\t\t\ttotalResultOutputCoinAmount += outCoin.CoinDetails.GetValue()\n\t\t\tresultOutputCoins = append(resultOutputCoins, outCoin)\n\t\t} else {\n\t\t\tremainOutputCoins = append(remainOutputCoins, outCoin)\n\t\t}\n\t}\n\tif outCoinOverLimit != nil && (outCoinOverLimit.CoinDetails.GetValue() > 2*amount || totalResultOutputCoinAmount < amount) {\n\t\tremainOutputCoins = append(remainOutputCoins, resultOutputCoins...)\n\t\tresultOutputCoins = []*crypto.InputCoin{outCoinOverLimit}\n\t\ttotalResultOutputCoinAmount = outCoinOverLimit.CoinDetails.GetValue()\n\t} else if outCoinOverLimit != nil {\n\t\tremainOutputCoins = append(remainOutputCoins, outCoinOverLimit)\n\t}\n\tif totalResultOutputCoinAmount < amount {\n\t\treturn resultOutputCoins, remainOutputCoins, totalResultOutputCoinAmount, errors.New(\"Not enough coin\")\n\t} else {\n\t\treturn resultOutputCoins, remainOutputCoins, totalResultOutputCoinAmount, nil\n\t}\n}", "func (_Vault *VaultCallerSession) GetDecimals(token common.Address) (uint8, error) {\n\treturn _Vault.Contract.GetDecimals(&_Vault.CallOpts, token)\n}", "func (_Gatekeeper *GatekeeperCaller) GetTransactionCount(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _Gatekeeper.contract.Call(opts, out, \"GetTransactionCount\")\n\treturn *ret0, err\n}", "func (_ChpRegistry *ChpRegistryCaller) CORESTAKINGAMOUNT(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _ChpRegistry.contract.Call(opts, out, \"CORE_STAKING_AMOUNT\")\n\treturn *ret0, err\n}", "func (_ReserveSpenderMultiSig *ReserveSpenderMultiSigCaller) GetTransactionCount(opts *bind.CallOpts, pending bool, executed bool) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _ReserveSpenderMultiSig.contract.Call(opts, out, \"getTransactionCount\", pending, executed)\n\treturn *ret0, err\n}", "func (_ChpRegistry *ChpRegistrySession) CORESTAKINGAMOUNT() (*big.Int, error) {\n\treturn _ChpRegistry.Contract.CORESTAKINGAMOUNT(&_ChpRegistry.CallOpts)\n}", "func (server *OpencxServer) WithdrawCoins(address string, pubkey *koblitz.PublicKey, amount uint64, params *coinparam.Params) (txid string, err error) {\n\n\t// TODO: change everything to int64 and just deal with the negatives in error handling. Casting is probably more dangerous\n\t// if you try to withdraw an overflow amount then get out\n\tif int64(amount) < 0 {\n\t\terr = fmt.Errorf(\"That amount would have caused an overflow, enter something lower\")\n\t\treturn\n\t}\n\n\t// Create the function, basically make sure the wallet stuff is alright\n\tvar withdrawFunction func(string, *koblitz.PublicKey, uint64) (string, error)\n\tif withdrawFunction, err = server.withdrawFromChain(params); err != nil {\n\t\terr = fmt.Errorf(\"Error creating withdraw function: \\n%s\", err)\n\t\treturn\n\t}\n\t// Actually try to withdraw\n\tif txid, err = withdrawFunction(address, pubkey, amount); err != nil {\n\t\terr = fmt.Errorf(\"Error withdrawing coins: \\n%s\", err)\n\t\treturn\n\t}\n\treturn\n}", "func (_DayLimit *DayLimitCaller) SpentToday(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _DayLimit.contract.Call(opts, out, \"spentToday\")\n\treturn *ret0, err\n}", "func GiveGoTotal(total C.int) {\n\tfmt.Printf(\"Go: got total from C %d\\n\", total)\n}", "func (_Bindings *BindingsCallerSession) TotalReserves() (*big.Int, error) {\n\treturn _Bindings.Contract.TotalReserves(&_Bindings.CallOpts)\n}", "func (a API) GetNetTotalsWait(cmd *None) (out *btcjson.GetNetTotalsResult, e error) {\n\tRPCHandlers[\"getnettotals\"].Call <-API{a.Ch, cmd, nil}\n\tselect {\n\tcase <-time.After(time.Second*5):\n\t\tbreak\n\tcase o := <-a.Ch.(chan GetNetTotalsRes):\n\t\tout, e = o.Res, o.Err\n\t}\n\treturn\n}", "func (p *Player) MoneyInBettingRound() int {\n\tvar m int = 0\n\tfor _, bet := range p.Game.CurrentQuestionRound().CurrentBettingRound().Bets {\n\t\tif bet.PlayerID == p.ID {\n\t\t\tm += bet.Amount\n\t\t}\n\t}\n\treturn m\n}", "func (serv *ExchangeServer) GetSupportCoins() []string {\n\tsymbols := make([]string, len(serv.coins))\n\ti := 0\n\tfor _, coin := range serv.coins {\n\t\tsymbols[i] = coin.Symbol()\n\t\ti++\n\t}\n\treturn symbols\n}" ]
[ "0.7921594", "0.7911669", "0.78747386", "0.78404725", "0.76656306", "0.7427295", "0.72755915", "0.71889263", "0.7015906", "0.67641604", "0.6664618", "0.6327653", "0.62292004", "0.6187303", "0.61255044", "0.6114289", "0.60764766", "0.57490504", "0.54574955", "0.5431898", "0.53833985", "0.5382415", "0.53307056", "0.5291161", "0.5195747", "0.51691806", "0.51419824", "0.5108959", "0.5098124", "0.4944426", "0.49443358", "0.48440605", "0.48257506", "0.4810476", "0.48093697", "0.47964352", "0.47738373", "0.4768149", "0.4744076", "0.4605146", "0.45770732", "0.45533004", "0.44963938", "0.448277", "0.44527665", "0.44466186", "0.44422176", "0.44119555", "0.44113418", "0.4402798", "0.4374181", "0.43735567", "0.43587705", "0.4352336", "0.4351995", "0.4350805", "0.43443123", "0.43423304", "0.4324632", "0.43116683", "0.42927146", "0.42841297", "0.4272556", "0.42683554", "0.42623532", "0.42230773", "0.42223588", "0.4219692", "0.4215873", "0.4207779", "0.41960746", "0.41711965", "0.41582435", "0.415467", "0.41533682", "0.4147086", "0.41401577", "0.41108352", "0.4106546", "0.40999746", "0.4095013", "0.40921634", "0.40917295", "0.40798664", "0.40773028", "0.40721434", "0.40679935", "0.40659568", "0.4062198", "0.40616712", "0.4061253", "0.40608525", "0.4057911", "0.4044189", "0.40418783", "0.40375873", "0.40352857", "0.40350467", "0.40310484", "0.40199837" ]
0.82551724
0
LockedCoins returns the set of coins that are not spendable (i.e. locked), defined as the vesting coins that are not delegated.
func (dva DelayedVestingAccount) LockedCoins(ctx sdk.Context) sdk.Coins { return dva.BaseVestingAccount.LockedCoinsFromVesting(dva.GetVestingCoins(ctx.BlockTime())) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (pva PeriodicVestingAccount) LockedCoins(ctx sdk.Context) sdk.Coins {\n\treturn pva.BaseVestingAccount.LockedCoinsFromVesting(pva.GetVestingCoins(ctx.BlockTime()))\n}", "func (cva ContinuousVestingAccount) LockedCoins(ctx sdk.Context) sdk.Coins {\n\treturn cva.BaseVestingAccount.LockedCoinsFromVesting(cva.GetVestingCoins(ctx.BlockTime()))\n}", "func (va ClawbackVestingAccount) LockedCoins(ctx sdk.Context) sdk.Coins {\n\treturn va.BaseVestingAccount.LockedCoinsFromVesting(va.GetVestingCoins(ctx.BlockTime()))\n}", "func (plva PermanentLockedAccount) LockedCoins(_ sdk.Context) sdk.Coins {\n\treturn plva.BaseVestingAccount.LockedCoinsFromVesting(plva.OriginalVesting)\n}", "func (bva BaseVestingAccount) LockedCoinsFromVesting(vestingCoins sdk.Coins) sdk.Coins {\n\tlockedCoins := vestingCoins.Sub(vestingCoins.Min(bva.DelegatedVesting))\n\tif lockedCoins == nil {\n\t\treturn sdk.Coins{}\n\t}\n\treturn lockedCoins\n}", "func (plva PermanentLockedAccount) GetVestingCoins(_ time.Time) sdk.Coins {\n\treturn plva.OriginalVesting\n}", "func (plva PermanentLockedAccount) GetVestedCoins(_ time.Time) sdk.Coins {\n\treturn nil\n}", "func (dcr *ExchangeWallet) lockedOutputs() ([]chainjson.TransactionInput, error) {\n\tvar locked []chainjson.TransactionInput\n\terr := dcr.nodeRawRequest(methodListLockUnspent, anylist{dcr.acct}, &locked)\n\treturn locked, err\n}", "func (w *rpcWallet) LockedOutputs(ctx context.Context, acctName string) ([]chainjson.TransactionInput, error) {\n\tvar locked []chainjson.TransactionInput\n\terr := w.rpcClientRawRequest(ctx, methodListLockUnspent, anylist{acctName}, &locked)\n\treturn locked, translateRPCCancelErr(err)\n}", "func (w *Wallet) LockedOutpoints() []btcjson.TransactionInput {\n\tlocked := make([]btcjson.TransactionInput, len(w.lockedOutpoints))\n\ti := 0\n\tfor op := range w.lockedOutpoints {\n\t\tlocked[i] = btcjson.TransactionInput{\n\t\t\tTxid: op.Hash.String(),\n\t\t\tVout: op.Index,\n\t\t}\n\t\ti++\n\t}\n\treturn locked\n}", "func (a *Account) LockedOutpoints() []btcjson.TransactionInput {\n\tlocked := make([]btcjson.TransactionInput, len(a.lockedOutpoints))\n\ti := 0\n\tfor op := range a.lockedOutpoints {\n\t\tlocked[i] = btcjson.TransactionInput{\n\t\t\tTxid: op.Hash.String(),\n\t\t\tVout: op.Index,\n\t\t}\n\t\ti++\n\t}\n\treturn locked\n}", "func (b *Bitcoind) ListLockUnspent() (unspendableOutputs []UnspendableOutput, err error) {\n\tr, err := b.client.call(\"listlockunspent\", nil)\n\tif err = handleError(err, &r); err != nil {\n\t\treturn\n\t}\n\n\terr = json.Unmarshal(r.Result, &unspendableOutputs)\n\treturn\n}", "func (btc *ExchangeWallet) lockedSats() (uint64, error) {\n\tlockedOutpoints, err := btc.wallet.ListLockUnspent()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tvar sum uint64\n\tbtc.fundingMtx.Lock()\n\tdefer btc.fundingMtx.Unlock()\n\tfor _, outPoint := range lockedOutpoints {\n\t\topID := outpointID(outPoint.TxID, outPoint.Vout)\n\t\tutxo, found := btc.fundingCoins[opID]\n\t\tif found {\n\t\t\tsum += utxo.amount\n\t\t\tcontinue\n\t\t}\n\t\ttxHash, err := chainhash.NewHashFromStr(outPoint.TxID)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\ttxOut, err := btc.node.GetTxOut(txHash, outPoint.Vout, true)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\tif txOut == nil {\n\t\t\t// Must be spent now?\n\t\t\tbtc.log.Debugf(\"ignoring output from listlockunspent that wasn't found with gettxout. %s\", opID)\n\t\t\tcontinue\n\t\t}\n\t\tsum += toSatoshi(txOut.Value)\n\t}\n\treturn sum, nil\n}", "func (dva DelayedVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn dva.OriginalVesting.Sub(dva.GetVestedCoins(blockTime))\n}", "func (dcr *ExchangeWallet) FundingCoins(ids []dex.Bytes) (asset.Coins, error) {\n\t// First check if we have the coins in cache.\n\tcoins := make(asset.Coins, 0, len(ids))\n\tnotFound := make(map[outPoint]bool)\n\tdcr.fundingMtx.Lock()\n\tdefer dcr.fundingMtx.Unlock() // stay locked until we update the map and lock them in the wallet\n\tfor _, id := range ids {\n\t\ttxHash, vout, err := decodeCoinID(id)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tpt := newOutPoint(txHash, vout)\n\t\tfundingCoin, found := dcr.fundingCoins[pt]\n\t\tif found {\n\t\t\tcoins = append(coins, fundingCoin.op)\n\t\t\tcontinue\n\t\t}\n\t\tnotFound[pt] = true\n\t}\n\tif len(notFound) == 0 {\n\t\treturn coins, nil\n\t}\n\n\t// Check locked outputs for not found coins.\n\tlockedOutputs, err := dcr.lockedOutputs()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor _, output := range lockedOutputs {\n\t\ttxHash, err := chainhash.NewHashFromStr(output.Txid)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error decoding txid from rpc server %s: %w\", output.Txid, err)\n\t\t}\n\t\tpt := newOutPoint(txHash, output.Vout)\n\t\tif !notFound[pt] {\n\t\t\tcontinue\n\t\t}\n\t\ttxOut, err := dcr.node.GetTxOut(dcr.ctx, txHash, output.Vout, true)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"gettxout error for locked output %v: %w\", pt.String(), translateRPCCancelErr(err))\n\t\t}\n\t\tvar address string\n\t\tif len(txOut.ScriptPubKey.Addresses) > 0 {\n\t\t\taddress = txOut.ScriptPubKey.Addresses[0]\n\t\t}\n\t\tcoin := newOutput(txHash, output.Vout, toAtoms(output.Amount), output.Tree)\n\t\tcoins = append(coins, coin)\n\t\tdcr.fundingCoins[pt] = &fundingCoin{\n\t\t\top: coin,\n\t\t\taddr: address,\n\t\t}\n\t\tdelete(notFound, pt)\n\t\tif len(notFound) == 0 {\n\t\t\treturn coins, nil\n\t\t}\n\t}\n\n\t// Some funding coins still not found after checking locked outputs.\n\t// Check wallet unspent outputs as last resort. Lock the coins if found.\n\tunspents, err := dcr.unspents()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcoinsToLock := make([]*wire.OutPoint, 0, len(notFound))\n\tfor _, txout := range unspents {\n\t\ttxHash, err := chainhash.NewHashFromStr(txout.TxID)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error decoding txid from rpc server %s: %w\", txout.TxID, err)\n\t\t}\n\t\tpt := newOutPoint(txHash, txout.Vout)\n\t\tif !notFound[pt] {\n\t\t\tcontinue\n\t\t}\n\t\tcoinsToLock = append(coinsToLock, wire.NewOutPoint(txHash, txout.Vout, txout.Tree))\n\t\tcoin := newOutput(txHash, txout.Vout, toAtoms(txout.Amount), txout.Tree)\n\t\tcoins = append(coins, coin)\n\t\tdcr.fundingCoins[pt] = &fundingCoin{\n\t\t\top: coin,\n\t\t\taddr: txout.Address,\n\t\t}\n\t\tdelete(notFound, pt)\n\t\tif len(notFound) == 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\tif len(notFound) != 0 {\n\t\tids := make([]string, 0, len(notFound))\n\t\tfor pt := range notFound {\n\t\t\tids = append(ids, pt.String())\n\t\t}\n\t\treturn nil, fmt.Errorf(\"funding coins not found: %s\", strings.Join(ids, \", \"))\n\t}\n\tdcr.log.Debugf(\"Locking funding coins that were unlocked %v\", coinsToLock)\n\terr = dcr.node.LockUnspent(dcr.ctx, false, coinsToLock)\n\tif err != nil {\n\t\treturn nil, translateRPCCancelErr(err)\n\t}\n\n\treturn coins, nil\n}", "func (bc *BlockChain) FindUnspentTransactions(addr string) []Transaction {\n\tvar unspentTXs []Transaction\n\tspentTXOutputs := make(map[string][]int)\n\titerator := bc.Iterator()\n\n\tfor {\n\t\t_block := iterator.Next()\n\n\t\tfor _, tx := range _block.Transactions {\n\t\t\ttxID := hex.EncodeToString(tx.ID)\n\n\t\tOutputs:\n\t\t\tfor outIdx, out := range tx.VOut {\n\t\t\t\tif spentTXOutputs[txID] != nil {\n\t\t\t\t\tfor _, spentOut := range spentTXOutputs[txID] {\n\t\t\t\t\t\tif spentOut == outIdx {\n\t\t\t\t\t\t\tcontinue Outputs\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif out.CanBeUnlockedWith(addr) {\n\t\t\t\t\tunspentTXs = append(unspentTXs, *tx)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif !tx.isCoinBaseTx() {\n\t\t\t\tfor _, in := range tx.VIn {\n\t\t\t\t\tif in.CanUnlockOutputWith(addr) {\n\t\t\t\t\t\tinTxID := hex.EncodeToString(in.TxID)\n\t\t\t\t\t\tspentTXOutputs[inTxID] = append(spentTXOutputs[inTxID], in.VOut)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif len(_block.Prev) == 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn unspentTXs\n}", "func (va ClawbackVestingAccount) GetVestedCoins(blockTime time.Time) sdk.Coins {\n\t// It's likely that one or the other schedule will be nearly trivial,\n\t// so there should be little overhead in recomputing the conjunction each time.\n\tcoins := coinsMin(va.GetUnlockedOnly(blockTime), va.GetVestedOnly(blockTime))\n\tif coins.IsZero() {\n\t\treturn nil\n\t}\n\treturn coins\n}", "func (dcr *ExchangeWallet) FundingCoins(ids []dex.Bytes) (asset.Coins, error) {\n\t// First check if we have the coins in cache.\n\tcoins := make(asset.Coins, 0, len(ids))\n\tnotFound := make(map[outPoint]bool)\n\tdcr.fundingMtx.Lock()\n\tdefer dcr.fundingMtx.Unlock() // stay locked until we update the map and lock them in the wallet\n\tfor _, id := range ids {\n\t\ttxHash, vout, err := decodeCoinID(id)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tpt := newOutPoint(txHash, vout)\n\t\tfundingCoin, found := dcr.fundingCoins[pt]\n\t\tif found {\n\t\t\tcoins = append(coins, fundingCoin.op)\n\t\t\tcontinue\n\t\t}\n\t\tnotFound[pt] = true\n\t}\n\tif len(notFound) == 0 {\n\t\treturn coins, nil\n\t}\n\n\t// Check locked outputs for not found coins.\n\tfor _, acct := range dcr.fundingAccounts() {\n\t\tlockedOutputs, err := dcr.wallet.LockedOutputs(dcr.ctx, acct)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfor _, output := range lockedOutputs {\n\t\t\ttxHash, err := chainhash.NewHashFromStr(output.Txid)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"error decoding txid from rpc server %s: %w\", output.Txid, err)\n\t\t\t}\n\t\t\tpt := newOutPoint(txHash, output.Vout)\n\t\t\tif !notFound[pt] {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ttxOut, err := dcr.wallet.UnspentOutput(dcr.ctx, txHash, output.Vout, output.Tree)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"gettxout error for locked output %v: %w\", pt.String(), err)\n\t\t\t}\n\t\t\tvar address string\n\t\t\tif len(txOut.Addresses) > 0 {\n\t\t\t\taddress = txOut.Addresses[0]\n\t\t\t}\n\t\t\tcoin := newOutput(txHash, output.Vout, toAtoms(output.Amount), output.Tree)\n\t\t\tcoins = append(coins, coin)\n\t\t\tdcr.fundingCoins[pt] = &fundingCoin{\n\t\t\t\top: coin,\n\t\t\t\taddr: address,\n\t\t\t}\n\t\t\tdelete(notFound, pt)\n\t\t\tif len(notFound) == 0 {\n\t\t\t\treturn coins, nil\n\t\t\t}\n\t\t}\n\t}\n\n\t// Some funding coins still not found after checking locked outputs.\n\t// Check wallet unspent outputs as last resort. Lock the coins if found.\n\tcoinsToLock := make([]*wire.OutPoint, 0, len(notFound))\n\tfor _, acct := range dcr.fundingAccounts() {\n\t\tunspents, err := dcr.wallet.Unspents(dcr.ctx, acct)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfor _, txout := range unspents {\n\t\t\ttxHash, err := chainhash.NewHashFromStr(txout.TxID)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"error decoding txid from rpc server %s: %w\", txout.TxID, err)\n\t\t\t}\n\t\t\tpt := newOutPoint(txHash, txout.Vout)\n\t\t\tif !notFound[pt] {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tcoinsToLock = append(coinsToLock, wire.NewOutPoint(txHash, txout.Vout, txout.Tree))\n\t\t\tcoin := newOutput(txHash, txout.Vout, toAtoms(txout.Amount), txout.Tree)\n\t\t\tcoins = append(coins, coin)\n\t\t\tdcr.fundingCoins[pt] = &fundingCoin{\n\t\t\t\top: coin,\n\t\t\t\taddr: txout.Address,\n\t\t\t}\n\t\t\tdelete(notFound, pt)\n\t\t\tif len(notFound) == 0 {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\t// Return an error if some coins are still not found.\n\tif len(notFound) != 0 {\n\t\tids := make([]string, 0, len(notFound))\n\t\tfor pt := range notFound {\n\t\t\tids = append(ids, pt.String())\n\t\t}\n\t\treturn nil, fmt.Errorf(\"funding coins not found: %s\", strings.Join(ids, \", \"))\n\t}\n\n\tdcr.log.Debugf(\"Locking funding coins that were unlocked %v\", coinsToLock)\n\terr := dcr.wallet.LockUnspent(dcr.ctx, false, coinsToLock)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn coins, nil\n}", "func (vva ValidatorVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn vva.OriginalVesting.Sub(vva.GetVestedCoins(blockTime))\n}", "func (va ClawbackVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn va.OriginalVesting.Sub(va.GetVestedCoins(blockTime))\n}", "func (dva DelayedVestingAccount) GetVestedCoins(blockTime time.Time) sdk.Coins {\n\tif blockTime.Unix() >= dva.EndTime {\n\t\treturn dva.OriginalVesting\n\t}\n\n\treturn nil\n}", "func (vva ValidatorVestingAccount) SpendableCoins(blockTime time.Time) sdk.Coins {\n\treturn vva.BaseVestingAccount.SpendableCoinsVestingAccount(vva.GetVestingCoins(blockTime))\n}", "func (vva ValidatorVestingAccount) GetVestedCoins(blockTime time.Time) sdk.Coins {\n\tvar vestedCoins sdk.Coins\n\tif blockTime.Unix() <= vva.StartTime {\n\t\treturn vestedCoins\n\t}\n\tcurrentPeriodStartTime := vva.StartTime\n\tnumberPeriods := len(vva.VestingPeriods)\n\tfor i := 0; i < numberPeriods; i++ {\n\t\tx := blockTime.Unix() - currentPeriodStartTime\n\t\tif x >= vva.VestingPeriods[i].Length {\n\t\t\tif vva.VestingPeriodProgress[i].PeriodComplete {\n\t\t\t\tvestedCoins = vestedCoins.Add(vva.VestingPeriods[i].Amount)\n\t\t\t}\n\t\t\tcurrentPeriodStartTime += vva.VestingPeriods[i].Length\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn vestedCoins\n\n}", "func (chain *BlockChain) FindUnspentTransactions(address string) []Transaction {\n\tvar unspentTxs []Transaction\n\n\tspentTxOs := make(map[string][]int)\n\n\titer := chain.Iterator()\n\n\tfor {\n\t\tblock := iter.Next()\n\n\t\tfor _, tx := range block.Transactions {\n\t\t\ttxID := hex.EncodeToString(tx.ID)\n\n\t\tOutputs:\n\t\t\tfor outIdx, out := range tx.Outputs {\n\t\t\t\tif spentTxOs[txID] != nil {\n\t\t\t\t\tfor _, spentOut := range spentTxOs[txID] {\n\t\t\t\t\t\tif spentOut == outIdx {\n\t\t\t\t\t\t\tcontinue Outputs\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif out.CanBeUnlocked(address) {\n\t\t\t\t\tunspentTxs = append(unspentTxs, *tx)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif tx.IsCoinbase() == false {\n\t\t\t\tfor _, in := range tx.Inputs {\n\t\t\t\t\tif in.CanUnlock(address) {\n\t\t\t\t\t\tinTxID := hex.EncodeToString(in.ID)\n\n\t\t\t\t\t\tspentTxOs[inTxID] = append(spentTxOs[inTxID], in.Out)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif len(block.PrevHash) == 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn unspentTxs\n}", "func (cva ContinuousVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn cva.OriginalVesting.Sub(cva.GetVestedCoins(blockTime))\n}", "func (pva PeriodicVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn pva.OriginalVesting.Sub(pva.GetVestedCoins(blockTime))\n}", "func (dcr *ExchangeWallet) lockFundingCoins(fCoins []*fundingCoin) error {\n\twireOPs := make([]*wire.OutPoint, 0, len(fCoins))\n\tfor _, c := range fCoins {\n\t\twireOPs = append(wireOPs, wire.NewOutPoint(c.op.txHash(), c.op.vout(), c.op.tree))\n\t}\n\terr := dcr.wallet.LockUnspent(dcr.ctx, false, wireOPs)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, c := range fCoins {\n\t\tdcr.fundingCoins[c.op.pt] = c\n\t}\n\treturn nil\n}", "func (b *Bitcoind) LockUnspent(lock bool, outputs []UnspendableOutput) (success bool, err error) {\n\tr, err := b.client.call(\"lockunspent\", []interface{}{lock, outputs})\n\tif err = handleError(err, &r); err != nil {\n\t\treturn\n\t}\n\n\terr = json.Unmarshal(r.Result, &success)\n\treturn\n}", "func (va ClawbackVestingAccount) GetUnlockedOnly(blockTime time.Time) sdk.Coins {\n\treturn ReadSchedule(va.StartTime, va.EndTime, va.LockupPeriods, va.OriginalVesting, blockTime.Unix())\n}", "func (dcr *ExchangeWallet) returnCoins(unspents asset.Coins) ([]*fundingCoin, error) {\n\tif len(unspents) == 0 {\n\t\treturn nil, fmt.Errorf(\"cannot return zero coins\")\n\t}\n\n\tops := make([]*wire.OutPoint, 0, len(unspents))\n\tfundingCoins := make([]*fundingCoin, 0, len(unspents))\n\n\tdcr.log.Debugf(\"returning coins %s\", unspents)\n\tfor _, unspent := range unspents {\n\t\top, err := dcr.convertCoin(unspent)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error converting coin: %w\", err)\n\t\t}\n\t\tops = append(ops, op.wireOutPoint()) // op.tree may be wire.TxTreeUnknown, but that's fine since wallet.LockUnspent doesn't rely on it\n\t\tif fCoin, ok := dcr.fundingCoins[op.pt]; ok {\n\t\t\tfundingCoins = append(fundingCoins, fCoin)\n\t\t\tdelete(dcr.fundingCoins, op.pt)\n\t\t} else {\n\t\t\tdcr.log.Warnf(\"returning coin %s that is not cached as a funding coin\", op)\n\t\t\tfundingCoins = append(fundingCoins, &fundingCoin{op: op})\n\t\t}\n\t}\n\n\treturn fundingCoins, dcr.wallet.LockUnspent(dcr.ctx, true, ops)\n}", "func (w *Wallet) Locked() bool {\n\treturn <-w.lockState\n}", "func (dcr *ExchangeWallet) lockFundingCoins(fCoins []*fundingCoin) error {\n\twireOPs := make([]*wire.OutPoint, 0, len(fCoins))\n\tfor _, c := range fCoins {\n\t\twireOPs = append(wireOPs, wire.NewOutPoint(c.op.txHash(), c.op.vout(), c.op.tree))\n\t}\n\terr := dcr.node.LockUnspent(dcr.ctx, false, wireOPs)\n\tif err != nil {\n\t\treturn translateRPCCancelErr(err)\n\t}\n\tfor _, c := range fCoins {\n\t\tdcr.fundingCoins[c.op.pt] = c\n\t}\n\treturn nil\n}", "func (cva ContinuousVestingAccount) GetVestedCoins(blockTime time.Time) sdk.Coins {\n\tvar vestedCoins sdk.Coins\n\n\t// We must handle the case where the start time for a vesting account has\n\t// been set into the future or when the start of the chain is not exactly\n\t// known.\n\tif blockTime.Unix() <= cva.StartTime {\n\t\treturn vestedCoins\n\t} else if blockTime.Unix() >= cva.EndTime {\n\t\treturn cva.OriginalVesting\n\t}\n\n\t// calculate the vesting scalar\n\tx := blockTime.Unix() - cva.StartTime\n\ty := cva.EndTime - cva.StartTime\n\ts := sdk.NewDec(x).Quo(sdk.NewDec(y))\n\n\tfor _, ovc := range cva.OriginalVesting {\n\t\tvestedAmt := ovc.Amount.ToDec().Mul(s).RoundInt()\n\t\tvestedCoins = append(vestedCoins, sdk.NewCoin(ovc.Denom, vestedAmt))\n\t}\n\n\treturn vestedCoins\n}", "func (dcr *ExchangeWallet) returnCoins(unspents asset.Coins) error {\n\tif len(unspents) == 0 {\n\t\treturn fmt.Errorf(\"cannot return zero coins\")\n\t}\n\tops := make([]*wire.OutPoint, 0, len(unspents))\n\n\tdcr.log.Debugf(\"returning coins %s\", unspents)\n\tfor _, unspent := range unspents {\n\t\top, err := dcr.convertCoin(unspent)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error converting coin: %w\", err)\n\t\t}\n\t\tops = append(ops, wire.NewOutPoint(op.txHash(), op.vout(), op.tree))\n\t\tdelete(dcr.fundingCoins, op.pt)\n\t}\n\treturn translateRPCCancelErr(dcr.node.LockUnspent(dcr.ctx, true, ops))\n}", "func (dcr *ExchangeWallet) Locked() bool {\n\tfor _, acct := range dcr.fundingAccounts() {\n\t\tunlocked, err := dcr.wallet.AccountUnlocked(dcr.ctx, acct)\n\t\tif err != nil {\n\t\t\tdcr.log.Errorf(\"error checking account lock status %v\", err)\n\t\t\tunlocked = false // assume wallet is unlocked?\n\t\t}\n\t\tif !unlocked {\n\t\t\treturn true // Locked is true if any of the funding accounts is locked.\n\t\t}\n\t}\n\treturn false\n}", "func (w *Wallet) ListUnspent(minconf, maxconf int32,\n\taddresses map[string]struct{}) ([]*btcjson.ListUnspentResult, er.R) {\n\n\tvar results []*btcjson.ListUnspentResult\n\terr := walletdb.View(w.db, func(tx walletdb.ReadTx) er.R {\n\t\taddrmgrNs := tx.ReadBucket(waddrmgrNamespaceKey)\n\t\ttxmgrNs := tx.ReadBucket(wtxmgrNamespaceKey)\n\n\t\tsyncBlock := w.Manager.SyncedTo()\n\n\t\tfilter := len(addresses) != 0\n\t\tunspent, err := w.TxStore.GetUnspentOutputs(txmgrNs)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tsort.Sort(sort.Reverse(creditSlice(unspent)))\n\n\t\tdefaultAccountName := \"default\"\n\n\t\tresults = make([]*btcjson.ListUnspentResult, 0, len(unspent))\n\t\tfor i := range unspent {\n\t\t\toutput := unspent[i]\n\n\t\t\t// Outputs with fewer confirmations than the minimum or more\n\t\t\t// confs than the maximum are excluded.\n\t\t\tconfs := confirms(output.Height, syncBlock.Height)\n\t\t\tif confs < minconf || confs > maxconf {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// Only mature coinbase outputs are included.\n\t\t\tif output.FromCoinBase {\n\t\t\t\ttarget := int32(w.ChainParams().CoinbaseMaturity)\n\t\t\t\tif !confirmed(target, output.Height, syncBlock.Height) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Exclude locked outputs from the result set.\n\t\t\tif w.LockedOutpoint(output.OutPoint) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// Lookup the associated account for the output. Use the\n\t\t\t// default account name in case there is no associated account\n\t\t\t// for some reason, although this should never happen.\n\t\t\t//\n\t\t\t// This will be unnecessary once transactions and outputs are\n\t\t\t// grouped under the associated account in the db.\n\t\t\tacctName := defaultAccountName\n\t\t\tsc, addrs, _, err := txscript.ExtractPkScriptAddrs(\n\t\t\t\toutput.PkScript, w.chainParams)\n\t\t\tif err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif len(addrs) > 0 {\n\t\t\t\tsmgr, acct, err := w.Manager.AddrAccount(addrmgrNs, addrs[0])\n\t\t\t\tif err == nil {\n\t\t\t\t\ts, err := smgr.AccountName(addrmgrNs, acct)\n\t\t\t\t\tif err == nil {\n\t\t\t\t\t\tacctName = s\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif filter {\n\t\t\t\tfor _, addr := range addrs {\n\t\t\t\t\t_, ok := addresses[addr.EncodeAddress()]\n\t\t\t\t\tif ok {\n\t\t\t\t\t\tgoto include\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\tinclude:\n\t\t\t// At the moment watch-only addresses are not supported, so all\n\t\t\t// recorded outputs that are not multisig are \"spendable\".\n\t\t\t// Multisig outputs are only \"spendable\" if all keys are\n\t\t\t// controlled by this wallet.\n\t\t\t//\n\t\t\t// TODO: Each case will need updates when watch-only addrs\n\t\t\t// is added. For P2PK, P2PKH, and P2SH, the address must be\n\t\t\t// looked up and not be watching-only. For multisig, all\n\t\t\t// pubkeys must belong to the manager with the associated\n\t\t\t// private key (currently it only checks whether the pubkey\n\t\t\t// exists, since the private key is required at the moment).\n\t\t\tvar spendable bool\n\t\tscSwitch:\n\t\t\tswitch sc {\n\t\t\tcase txscript.PubKeyHashTy:\n\t\t\t\tspendable = true\n\t\t\tcase txscript.PubKeyTy:\n\t\t\t\tspendable = true\n\t\t\tcase txscript.WitnessV0ScriptHashTy:\n\t\t\t\tspendable = true\n\t\t\tcase txscript.WitnessV0PubKeyHashTy:\n\t\t\t\tspendable = true\n\t\t\tcase txscript.MultiSigTy:\n\t\t\t\tfor _, a := range addrs {\n\t\t\t\t\t_, err := w.Manager.Address(addrmgrNs, a)\n\t\t\t\t\tif err == nil {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tif waddrmgr.ErrAddressNotFound.Is(err) {\n\t\t\t\t\t\tbreak scSwitch\n\t\t\t\t\t}\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tspendable = true\n\t\t\t}\n\n\t\t\tresult := &btcjson.ListUnspentResult{\n\t\t\t\tTxID: output.OutPoint.Hash.String(),\n\t\t\t\tVout: output.OutPoint.Index,\n\t\t\t\tAccount: acctName,\n\t\t\t\tScriptPubKey: hex.EncodeToString(output.PkScript),\n\t\t\t\tAmount: output.Amount.ToBTC(),\n\t\t\t\tConfirmations: int64(confs),\n\t\t\t\tSpendable: spendable,\n\t\t\t}\n\n\t\t\t// BUG: this should be a JSON array so that all\n\t\t\t// addresses can be included, or removed (and the\n\t\t\t// caller extracts addresses from the pkScript).\n\t\t\tif len(addrs) > 0 {\n\t\t\t\tresult.Address = addrs[0].EncodeAddress()\n\t\t\t}\n\n\t\t\tresults = append(results, result)\n\t\t}\n\t\treturn nil\n\t})\n\treturn results, err\n}", "func (wt *Wallet) Locked() bool {\n\treturn <-wt.lockState\n}", "func NewQueryLockedCoinsParams(accountID types.AccountID) QueryLockedCoinsParams {\n\treturn QueryLockedCoinsParams{\n\t\tAccountID: accountID,\n\t}\n}", "func (pva PeriodicVestingAccount) GetVestedCoins(blockTime time.Time) sdk.Coins {\n\tcoins := ReadSchedule(pva.StartTime, pva.EndTime, pva.VestingPeriods, pva.OriginalVesting, blockTime.Unix())\n\tif coins.IsZero() {\n\t\treturn nil\n\t}\n\treturn coins\n}", "func GetLockedDistributionAddresses() []string {\n\t// TODO -- once we reach 30% distribution, we can hardcode the\n\t// initial timestamp for releasing more coins\n\taddrs := make([]string, DistributionAddressesTotal-InitialUnlockedCount)\n\tfor i := range distributionAddresses[InitialUnlockedCount:] {\n\t\taddrs[i] = distributionAddresses[InitialUnlockedCount+uint64(i)]\n\t}\n\n\treturn addrs\n}", "func (btc *ExchangeWallet) ReturnCoins(unspents asset.Coins) error {\n\tif len(unspents) == 0 {\n\t\treturn fmt.Errorf(\"cannot return zero coins\")\n\t}\n\tops := make([]*output, 0, len(unspents))\n\tbtc.fundingMtx.Lock()\n\tdefer btc.fundingMtx.Unlock()\n\tfor _, unspent := range unspents {\n\t\top, err := btc.convertCoin(unspent)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error converting coin: %v\", err)\n\t\t}\n\t\tops = append(ops, op)\n\t\tdelete(btc.fundingCoins, outpointID(op.txHash.String(), op.vout))\n\t}\n\treturn btc.wallet.LockUnspent(true, ops)\n}", "func (r *Ring) InPot() []Box {\n\treturn r.Where(func(s *Seat) bool {\n\t\treturn s.State == seat.Play || s.State == seat.Bet || s.State == seat.AllIn\n\t})\n}", "func (dcr *ExchangeWallet) ReturnCoins(unspents asset.Coins) error {\n\tdcr.fundingMtx.Lock()\n\tdefer dcr.fundingMtx.Unlock()\n\treturn dcr.returnCoins(unspents)\n}", "func (keeper SendKeeper) GetCoins(ctx sdk.Context, addr sdk.Address) sdk.Coins {\n\treturn getCoins(ctx, keeper.am, addr)\n}", "func (txn TxnProbe) CollectLockedKeys() [][]byte {\n\treturn txn.collectLockedKeys()\n}", "func (keeper ViewKeeper) GetCoins(ctx sdk.Context, addr sdk.Address) sdk.Coins {\n\treturn getCoins(ctx, keeper.am, addr)\n}", "func GetUnspentOutputCoinsExceptSpendingUTXO(rpcClient *rpcclient.HttpClient, keyWallet *wallet.KeyWallet) ([]*crypto.InputCoin, error) {\n\tpublicKey := keyWallet.KeySet.PaymentAddress.Pk\n\n\t// check and remove utxo cache (these utxos in txs that were confirmed)\n\t//CheckAndRemoveUTXOFromCache(keyWallet.KeySet.PaymentAddress.Pk, inputCoins)\n\tCheckAndRemoveUTXOFromCacheV2(keyWallet.KeySet.PaymentAddress.Pk, rpcClient)\n\n\t// get unspent output coins from network\n\tutxos, err := GetUnspentOutputCoins(rpcClient, keyWallet)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tinputCoins := ConvertOutputCoinToInputCoin(utxos)\n\n\t// except spending utxos from unspent output coins\n\tutxosInCache := GetUTXOCacheByPublicKey(publicKey)\n\tfor serialNumberStr, _ := range utxosInCache {\n\t\tfor i, inputCoin := range inputCoins {\n\t\t\tsnStrTmp := base58.Base58Check{}.Encode(inputCoin.CoinDetails.GetSerialNumber().ToBytesS(), common.ZeroByte)\n\t\t\tif snStrTmp == serialNumberStr {\n\t\t\t\tinputCoins = removeElementFromSlice(inputCoins, i)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\treturn inputCoins, nil\n}", "func (btc *ExchangeWallet) FundingCoins(ids []dex.Bytes) (asset.Coins, error) {\n\t// First check if we have the coins in cache.\n\tcoins := make(asset.Coins, 0, len(ids))\n\tnotFound := make(map[string]struct{})\n\tbtc.fundingMtx.RLock()\n\tfor _, id := range ids {\n\t\ttxHash, vout, err := decodeCoinID(id)\n\t\tif err != nil {\n\t\t\tbtc.fundingMtx.RUnlock()\n\t\t\treturn nil, err\n\t\t}\n\t\topID := outpointID(txHash.String(), vout)\n\t\tfundingCoin, found := btc.fundingCoins[opID]\n\t\tif found {\n\t\t\tcoins = append(coins, newOutput(btc.node, txHash, vout, fundingCoin.amount, fundingCoin.redeemScript))\n\t\t\tcontinue\n\t\t}\n\t\tnotFound[opID] = struct{}{}\n\t}\n\tbtc.fundingMtx.RUnlock()\n\tif len(notFound) == 0 {\n\t\treturn coins, nil\n\t}\n\t_, utxoMap, _, err := btc.spendableUTXOs(0)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlockers := make([]*output, 0, len(ids))\n\tbtc.fundingMtx.Lock()\n\tdefer btc.fundingMtx.Unlock()\n\tfor _, id := range ids {\n\t\ttxHash, vout, err := decodeCoinID(id)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\topID := outpointID(txHash.String(), vout)\n\t\tutxo, found := utxoMap[opID]\n\t\tif !found {\n\t\t\treturn nil, fmt.Errorf(\"funding coin %s not found\", opID)\n\t\t}\n\t\tbtc.fundingCoins[opID] = utxo\n\t\tcoin := newOutput(btc.node, utxo.txHash, utxo.vout, utxo.amount, utxo.redeemScript)\n\t\tcoins = append(coins, coin)\n\t\tlockers = append(lockers, coin)\n\t\tdelete(notFound, opID)\n\t\tif len(notFound) == 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\tif len(notFound) != 0 {\n\t\tids := make([]string, 0, len(notFound))\n\t\tfor opID := range notFound {\n\t\t\tids = append(ids, opID)\n\t\t}\n\t\treturn nil, fmt.Errorf(\"coins not found: %s\", strings.Join(ids, \", \"))\n\t}\n\terr = btc.wallet.LockUnspent(false, lockers)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn coins, nil\n}", "func (vva ValidatorVestingAccount) GetFailedVestedCoins() sdk.Coins {\n\tvar failedVestedCoins sdk.Coins\n\tnumberPeriods := len(vva.VestingPeriods)\n\tfor i := 0; i < numberPeriods; i++ {\n\t\tif vva.VestingPeriodProgress[i].PeriodComplete {\n\t\t\tif !vva.VestingPeriodProgress[i].VestingSuccessful {\n\t\t\t\tfailedVestedCoins = failedVestedCoins.Add(vva.VestingPeriods[i].Amount)\n\t\t\t}\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn failedVestedCoins\n}", "func (o *AccountCollectionGetParams) SetLocked(locked *bool) {\n\to.Locked = locked\n}", "func (c *CoordinatorHelper) Coins(\n\tctx context.Context,\n\tdbTx storage.DatabaseTransaction,\n\taccountIdentifier *types.AccountIdentifier,\n\tcurrency *types.Currency,\n) ([]*types.Coin, error) {\n\tcoins, _, err := c.coinStorage.GetCoinsTransactional(\n\t\tctx,\n\t\tdbTx,\n\t\taccountIdentifier,\n\t)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"%w: unable to get coins\", err)\n\t}\n\n\tcoinsToReturn := []*types.Coin{}\n\tfor _, coin := range coins {\n\t\tif types.Hash(coin.Amount.Currency) != types.Hash(currency) {\n\t\t\tcontinue\n\t\t}\n\n\t\tcoinsToReturn = append(coinsToReturn, coin)\n\t}\n\n\treturn coinsToReturn, nil\n}", "func (dcr *ExchangeWallet) ReturnCoins(unspents asset.Coins) error {\n\tdcr.fundingMtx.Lock()\n\treturnedCoins, err := dcr.returnCoins(unspents)\n\tdcr.fundingMtx.Unlock()\n\tif err != nil || dcr.unmixedAccount == \"\" {\n\t\treturn err\n\t}\n\n\t// If any of these coins belong to the trading account, transfer them to the\n\t// unmixed account to be re-mixed into the primary account before being\n\t// re-selected for funding future orders. This doesn't apply to unspent\n\t// split tx outputs, which should remain in the trading account and be\n\t// selected from there for funding future orders.\n\tvar coinsToTransfer []asset.Coin\n\tfor _, coin := range returnedCoins {\n\t\tif coin.addr == \"\" {\n\t\t\ttxOut, err := dcr.wallet.UnspentOutput(dcr.ctx, coin.op.txHash(), coin.op.vout(), coin.op.tree)\n\t\t\tif err != nil {\n\t\t\t\tdcr.log.Errorf(\"wallet.UnspentOutput error for returned coin %s: %v\", coin.op, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif len(txOut.Addresses) == 0 {\n\t\t\t\tdcr.log.Errorf(\"no address in gettxout response for returned coin %s\", coin.op)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tcoin.addr = txOut.Addresses[0]\n\t\t}\n\t\taddrInfo, err := dcr.wallet.AddressInfo(dcr.ctx, coin.addr)\n\t\tif err != nil {\n\t\t\tdcr.log.Errorf(\"wallet.AddressInfo error for returned coin %s: %v\", coin.op, err)\n\t\t\tcontinue\n\t\t}\n\t\t// Move this coin to the unmixed account if it was sent to the internal\n\t\t// branch of the trading account. This excludes unspent split tx outputs\n\t\t// which are sent to the external branch of the trading account.\n\t\tif addrInfo.Branch == acctInternalBranch && addrInfo.Account == dcr.tradingAccount {\n\t\t\tcoinsToTransfer = append(coinsToTransfer, coin.op)\n\t\t}\n\t}\n\n\tif len(coinsToTransfer) > 0 {\n\t\ttx, totalSent, err := dcr.sendAll(coinsToTransfer, dcr.unmixedAccount)\n\t\tif err != nil {\n\t\t\tdcr.log.Errorf(\"unable to transfer unlocked swapped change from temp trading \"+\n\t\t\t\t\"account to unmixed account: %v\", err)\n\t\t} else {\n\t\t\tdcr.log.Infof(\"Transferred %s from temp trading account to unmixed account in tx %s.\",\n\t\t\t\tdcrutil.Amount(totalSent), tx.TxHash())\n\t\t}\n\t}\n\n\treturn nil\n}", "func GetCoins(accCoins []types.Coin) AccountCoins {\n\tcoins := make(AccountCoins, 0)\n\tfor _, coin := range accCoins {\n\t\tcoins = append(coins, AccountCoin{Amount: uint64(coin.Amount), Denom: coin.Denom})\n\t}\n\treturn coins\n}", "func (keeper BaseViewKeeper) GetCoins(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins {\n\treturn getCoins(ctx, keeper.am, addr)\n}", "func (b *BlockChain) GetUnspentTxns(address string) []Transaction {\n\tvar unspentTxns []Transaction\n\tvar spentTxnMap = make(map[string][]int) // map txnID -> output index\n\n\t// go over blocks one by one\n\titer := b.GetIterator()\n\tfor {\n\t\tblck := iter.Next()\n\n\t\t// go over all Transactions in this block\n\t\tfor _, txn := range blck.Transactions {\n\t\t\t// get string identifying this transaction\n\t\t\ttxID := hex.EncodeToString(txn.ID)\n\n\t\tOutputLoop:\n\t\t\t// go over all outputs in this Txn\n\t\t\tfor outIndex, output := range txn.Out {\n\n\t\t\t\t// check if this output is spent.\n\t\t\t\tif spentTxnMap[txID] != nil {\n\t\t\t\t\tfor _, indx := range spentTxnMap[txID] {\n\t\t\t\t\t\tif indx == outIndex {\n\t\t\t\t\t\t\tcontinue OutputLoop\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// check if this output belongs to this address\n\t\t\t\tif output.CheckOutputUnlock(address) {\n\t\t\t\t\tunspentTxns = append(unspentTxns, *txn)\n\t\t\t\t}\n\n\t\t\t\t// if this is not genesis block, go over all inputs\n\t\t\t\t// that refers to output that belongs to this address\n\t\t\t\t// and mark them as unspent\n\t\t\t\tif txn.IsCoinbase() == false {\n\t\t\t\t\tfor _, inp := range txn.In {\n\t\t\t\t\t\tif inp.CheckInputUnlock(address) {\n\t\t\t\t\t\t\tspentTxnMap[txID] = append(spentTxnMap[txID], inp.Out)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif len(blck.PrevBlockHash) == 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn unspentTxns\n}", "func (keeper Keeper) GetCoins(ctx sdk.Context, addr sdk.Address) sdk.Coins {\n\treturn getCoins(ctx, keeper.am, addr)\n}", "func (dcr *ExchangeWallet) Locked() bool {\n\twalletInfo, err := dcr.node.WalletInfo(dcr.ctx)\n\tif err != nil {\n\t\tdcr.log.Errorf(\"walletinfo error: %v\", err)\n\t\treturn false\n\t}\n\treturn !walletInfo.Unlocked\n}", "func GetUnspentOutputCoins(rpcClient *rpcclient.HttpClient, keyWallet *wallet.KeyWallet) ([]*crypto.OutputCoin, error) {\n\tprivateKey := &keyWallet.KeySet.PrivateKey\n\tpaymentAddressStr := keyWallet.Base58CheckSerialize(wallet.PaymentAddressType)\n\tviewingKeyStr := keyWallet.Base58CheckSerialize(wallet.ReadonlyKeyType)\n\n\toutputCoins, err := GetListOutputCoins(rpcClient, paymentAddressStr, viewingKeyStr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tserialNumbers, err := DeriveSerialNumbers(privateKey, outputCoins)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tisExisted, err := CheckExistenceSerialNumber(rpcClient, paymentAddressStr, serialNumbers)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tutxos := make([]*crypto.OutputCoin, 0)\n\tfor i, out := range outputCoins {\n\t\tif !isExisted[i] {\n\t\t\tutxos = append(utxos, out)\n\t\t}\n\t}\n\n\treturn utxos, nil\n}", "func (dcr *ExchangeWallet) lockedAtoms() (uint64, error) {\n\tlockedOutpoints, err := dcr.lockedOutputs()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tvar sum uint64\n\tfor _, op := range lockedOutpoints {\n\t\tsum += toAtoms(op.Amount)\n\t}\n\treturn sum, nil\n}", "func (u UTXOSet) FindUnspentTransactions(pubKeyHash []byte) []TxOutput {\n\tvar UTXOs []TxOutput\n\n\tdb := u.Blockchain.Database\n\n\terr := db.View(func(txn *badger.Txn) error {\n\t\topts := badger.DefaultIteratorOptions\n\n\t\tit := txn.NewIterator(opts)\n\t\tdefer it.Close()\n\n\t\t// iterate through UTXOS prefixes\n\t\tfor it.Seek(utxoPrefix); it.ValidForPrefix(utxoPrefix); it.Next() {\n\t\t\t// get the value of each utxo prefixed item\n\t\t\tv := valueHash(it.Item())\n\t\t\touts := DeserializeOutputs(v)\n\n\t\t\t// iterate through each output, check to see if it is locked by the provided hash address\n\t\t\tfor _, out := range outs.Outputs {\n\t\t\t\tif out.IsLockedWithKey(pubKeyHash) {\n\t\t\t\t\tUTXOs = append(UTXOs, out)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn nil\n\t})\n\thandle(err)\n\n\treturn UTXOs\n}", "func distributeLockedAmount(ctx coretypes.Sandbox, bets []*BetInfo, totalLockedAmount int64) bool {\n\tsumsByPlayers := make(map[coretypes.AgentID]int64)\n\ttotalWinningAmount := int64(0)\n\tfor _, bet := range bets {\n\t\tif _, ok := sumsByPlayers[bet.Player]; !ok {\n\t\t\tsumsByPlayers[bet.Player] = 0\n\t\t}\n\t\tsumsByPlayers[bet.Player] += bet.Sum\n\t\ttotalWinningAmount += bet.Sum\n\t}\n\n\t// NOTE 1: float64 was avoided for determinism reasons\n\t// NOTE 2: beware overflows\n\n\tfor player, sum := range sumsByPlayers {\n\t\tsumsByPlayers[player] = (totalLockedAmount * sum) / totalWinningAmount\n\t}\n\n\t// make deterministic sequence by sorting. Eliminate possible rounding effects\n\tseqPlayers := make([]coretypes.AgentID, 0, len(sumsByPlayers))\n\tresultSum := int64(0)\n\tfor player, sum := range sumsByPlayers {\n\t\tseqPlayers = append(seqPlayers, player)\n\t\tresultSum += sum\n\t}\n\tsort.Slice(seqPlayers, func(i, j int) bool {\n\t\treturn bytes.Compare(seqPlayers[i][:], seqPlayers[j][:]) < 0\n\t})\n\n\t// ensure we distribute not more than totalLockedAmount iotas\n\tif resultSum > totalLockedAmount {\n\t\tsumsByPlayers[seqPlayers[0]] -= resultSum - totalLockedAmount\n\t}\n\n\t// filter out those who proportionally got 0\n\tfinalWinners := seqPlayers[:0]\n\tfor _, player := range seqPlayers {\n\t\tif sumsByPlayers[player] <= 0 {\n\t\t\tcontinue\n\t\t}\n\t\tfinalWinners = append(finalWinners, player)\n\t}\n\t// distribute iotas\n\tfor i := range finalWinners {\n\n\t\tavailable := ctx.Balance(balance.ColorIOTA)\n\t\tctx.Event(fmt.Sprintf(\"sending reward iotas %d to the winner %s. Available iotas: %d\",\n\t\t\tsumsByPlayers[finalWinners[i]], finalWinners[i].String(), available))\n\n\t\t//if !ctx.MoveTokens(finalWinners[i], balance.ColorIOTA, sumsByPlayers[finalWinners[i]]) {\n\t\t//\treturn false\n\t\t//}\n\t}\n\treturn true\n}", "func (w *rpcWallet) LockUnspent(ctx context.Context, unlock bool, ops []*wire.OutPoint) error {\n\treturn translateRPCCancelErr(w.client().LockUnspent(ctx, unlock, ops))\n}", "func GetUnlockedDistributionAddresses() []string {\n\t// The first InitialUnlockedCount (25) addresses are unlocked by default.\n\t// Subsequent addresses will be unlocked at a rate of UnlockAddressRate (5) per year,\n\t// after the InitialUnlockedCount (25) addresses have no remaining balance.\n\t// The unlock timer will be enabled manually once the\n\t// InitialUnlockedCount (25) addresses are distributed.\n\n\t// NOTE: To have automatic unlocking, transaction verification would have\n\t// to be handled in visor rather than in coin.Transactions.Visor(), because\n\t// the coin package is agnostic to the state of the blockchain and cannot reference it.\n\t// Instead of automatic unlocking, we can hardcode the timestamp at which the first 30%\n\t// is distributed, then compute the unlocked addresses easily here.\n\n\taddrs := make([]string, InitialUnlockedCount)\n\tfor i := range distributionAddresses[:InitialUnlockedCount] {\n\t\taddrs[i] = distributionAddresses[i]\n\t}\n\treturn addrs\n}", "func (ck CoinKeeper) GetCoins(ctx sdk.Context, addr sdk.Address, amt sdk.Coins) sdk.Coins {\n\tacc := ck.am.GetAccount(ctx, addr)\n\treturn acc.GetCoins()\n}", "func WithoutBlocking(ctx context.Context) context.Context {\n\treturn context.WithValue(ctx, nonBlockingTxnCtxKey, &nonBlockingTxnOpt{})\n}", "func (b *Bitcoind) ListUnspent(minconf, maxconf uint32) (transactions []Transaction, err error) {\n\tif maxconf > 999999 {\n\t\tmaxconf = 999999\n\t}\n\n\tr, err := b.client.call(\"listunspent\", []interface{}{minconf, maxconf})\n\tif err = handleError(err, &r); err != nil {\n\t\treturn\n\t}\n\n\terr = json.Unmarshal(r.Result, &transactions)\n\treturn\n}", "func (am *AccountManager) ListUnspent(minconf, maxconf int,\n\taddresses map[string]bool) ([]*btcjson.ListUnspentResult, error) {\n\n\tbs, err := GetCurBlock()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfilter := len(addresses) != 0\n\n\tvar results []*btcjson.ListUnspentResult\n\tfor _, a := range am.AllAccounts() {\n\t\tunspent, err := a.TxStore.UnspentOutputs()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfor _, credit := range unspent {\n\t\t\tconfs := credit.Confirmations(bs.Height)\n\t\t\tif int(confs) < minconf || int(confs) > maxconf {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t_, addrs, _, _ := credit.Addresses(cfg.Net())\n\t\t\tif filter {\n\t\t\t\tfor _, addr := range addrs {\n\t\t\t\t\t_, ok := addresses[addr.EncodeAddress()]\n\t\t\t\t\tif ok {\n\t\t\t\t\t\tgoto include\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\t\tinclude:\n\t\t\tresult := &btcjson.ListUnspentResult{\n\t\t\t\tTxId: credit.Tx().Sha().String(),\n\t\t\t\tVout: credit.OutputIndex,\n\t\t\t\tAccount: a.Name(),\n\t\t\t\tScriptPubKey: hex.EncodeToString(credit.TxOut().PkScript),\n\t\t\t\tAmount: credit.Amount().ToUnit(btcutil.AmountBTC),\n\t\t\t\tConfirmations: int64(confs),\n\t\t\t}\n\n\t\t\t// BUG: this should be a JSON array so that all\n\t\t\t// addresses can be included, or removed (and the\n\t\t\t// caller extracts addresses from the pkScript).\n\t\t\tif len(addrs) > 0 {\n\t\t\t\tresult.Address = addrs[0].EncodeAddress()\n\t\t\t}\n\n\t\t\tresults = append(results, result)\n\t\t}\n\t}\n\n\treturn results, nil\n}", "func (w *Wallet) ResetLockedOutpoints() {\n\tw.lockedOutpoints = map[wire.OutPoint]struct{}{}\n}", "func (c *Channel) Locked() *big.Int {\n\treturn c.OurState.AmountLocked()\n}", "func (va ClawbackVestingAccount) GetVestedOnly(blockTime time.Time) sdk.Coins {\n\treturn ReadSchedule(va.StartTime, va.EndTime, va.VestingPeriods, va.OriginalVesting, blockTime.Unix())\n}", "func (c *Channel) Locked() *big.Int {\n\treturn c.OurState.amountLocked()\n}", "func (s *Store) ListLockedOutputs(ns walletdb.ReadBucket) ([]*LockedOutput,\n\terror) {\n\n\tvar outputs []*LockedOutput\n\terr := forEachLockedOutput(\n\t\tns, func(op wire.OutPoint, id LockID, expiration time.Time) {\n\t\t\t// Skip expired leases. They will be cleaned up with the\n\t\t\t// next call to DeleteExpiredLockedOutputs.\n\t\t\tif !s.clock.Now().Before(expiration) {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\toutputs = append(outputs, &LockedOutput{\n\t\t\t\tOutpoint: op,\n\t\t\t\tLockID: id,\n\t\t\t\tExpiration: expiration,\n\t\t\t})\n\t\t},\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn outputs, nil\n}", "func coinSupplyHandler(gateway Gatewayer) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tif r.Method != http.MethodGet {\n\t\t\twh.Error405(w)\n\t\t\treturn\n\t\t}\n\n\t\tallUnspents, err := gateway.GetUnspentOutputsSummary(nil)\n\t\tif err != nil {\n\t\t\terr = fmt.Errorf(\"gateway.GetUnspentOutputsSummary failed: %v\", err)\n\t\t\twh.Error500(w, err.Error())\n\t\t\treturn\n\t\t}\n\n\t\tunlockedAddrs := params.GetUnlockedDistributionAddressesDecoded()\n\t\t// Search map of unlocked addresses, used to filter unspents\n\t\tunlockedAddrSet := newAddrSet(unlockedAddrs)\n\n\t\tvar unlockedSupply uint64\n\t\t// check confirmed unspents only\n\t\tfor _, u := range allUnspents.Confirmed {\n\t\t\t// check if address is an unlocked distribution address\n\t\t\tif _, ok := unlockedAddrSet[u.Body.Address]; ok {\n\t\t\t\tvar err error\n\t\t\t\tunlockedSupply, err = mathutil.AddUint64(unlockedSupply, u.Body.Coins)\n\t\t\t\tif err != nil {\n\t\t\t\t\terr = fmt.Errorf(\"uint64 overflow while adding up unlocked supply coins: %v\", err)\n\t\t\t\t\twh.Error500(w, err.Error())\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// \"total supply\" is the number of coins unlocked.\n\t\t// Each distribution address was allocated params.DistributionAddressInitialBalance coins.\n\t\ttotalSupply := uint64(len(unlockedAddrs)) * params.DistributionAddressInitialBalance\n\t\ttotalSupply *= droplet.Multiplier\n\n\t\t// \"current supply\" is the number of coins distributed from the unlocked pool\n\t\tcurrentSupply := totalSupply - unlockedSupply\n\n\t\tcurrentSupplyStr, err := droplet.ToString(currentSupply)\n\t\tif err != nil {\n\t\t\terr = fmt.Errorf(\"Failed to convert coins to string: %v\", err)\n\t\t\twh.Error500(w, err.Error())\n\t\t\treturn\n\t\t}\n\n\t\ttotalSupplyStr, err := droplet.ToString(totalSupply)\n\t\tif err != nil {\n\t\t\terr = fmt.Errorf(\"Failed to convert coins to string: %v\", err)\n\t\t\twh.Error500(w, err.Error())\n\t\t\treturn\n\t\t}\n\n\t\tmaxSupplyStr, err := droplet.ToString(params.MaxCoinSupply * droplet.Multiplier)\n\t\tif err != nil {\n\t\t\terr = fmt.Errorf(\"Failed to convert coins to string: %v\", err)\n\t\t\twh.Error500(w, err.Error())\n\t\t\treturn\n\t\t}\n\n\t\t// locked distribution addresses\n\t\tlockedAddrs := params.GetLockedDistributionAddressesDecoded()\n\t\tlockedAddrSet := newAddrSet(lockedAddrs)\n\n\t\t// get total coins hours which excludes locked distribution addresses\n\t\tvar totalCoinHours uint64\n\t\tfor _, out := range allUnspents.Confirmed {\n\t\t\tif _, ok := lockedAddrSet[out.Body.Address]; !ok {\n\t\t\t\tvar err error\n\t\t\t\ttotalCoinHours, err = mathutil.AddUint64(totalCoinHours, out.CalculatedHours)\n\t\t\t\tif err != nil {\n\t\t\t\t\terr = fmt.Errorf(\"uint64 overflow while adding up total coin hours: %v\", err)\n\t\t\t\t\twh.Error500(w, err.Error())\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// get current coin hours which excludes all distribution addresses\n\t\tvar currentCoinHours uint64\n\t\tfor _, out := range allUnspents.Confirmed {\n\t\t\t// check if address not in locked distribution addresses\n\t\t\tif _, ok := lockedAddrSet[out.Body.Address]; !ok {\n\t\t\t\t// check if address not in unlocked distribution addresses\n\t\t\t\tif _, ok := unlockedAddrSet[out.Body.Address]; !ok {\n\t\t\t\t\tcurrentCoinHours += out.CalculatedHours\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif err != nil {\n\t\t\terr = fmt.Errorf(\"Failed to get total coinhours: %v\", err)\n\t\t\twh.Error500(w, err.Error())\n\t\t\treturn\n\t\t}\n\n\t\tcs := CoinSupply{\n\t\t\tCurrentSupply: currentSupplyStr,\n\t\t\tTotalSupply: totalSupplyStr,\n\t\t\tMaxSupply: maxSupplyStr,\n\t\t\tCurrentCoinHourSupply: strconv.FormatUint(currentCoinHours, 10),\n\t\t\tTotalCoinHourSupply: strconv.FormatUint(totalCoinHours, 10),\n\t\t\tUnlockedAddresses: params.GetUnlockedDistributionAddresses(),\n\t\t\tLockedAddresses: params.GetLockedDistributionAddresses(),\n\t\t}\n\n\t\twh.SendJSONOr500(logger, w, cs)\n\t}\n}", "func (dcr *ExchangeWallet) spendableUTXOs() ([]*compositeUTXO, error) {\n\tunspents, err := dcr.unspents()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(unspents) == 0 {\n\t\treturn nil, fmt.Errorf(\"insufficient funds. 0 DCR available to spend in %q account\", dcr.acct)\n\t}\n\n\t// Parse utxos to include script size for spending input.\n\t// Returned utxos will be sorted in ascending order by amount (smallest first).\n\tutxos, err := dcr.parseUTXOs(unspents)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error parsing unspent outputs: %w\", err)\n\t}\n\tif len(utxos) == 0 {\n\t\treturn nil, fmt.Errorf(\"no funds available\")\n\t}\n\treturn utxos, nil\n}", "func (s *Store) UnspentOutputs(ns walletdb.ReadBucket) ([]Credit, error) {\n\tvar unspent []Credit\n\n\tvar op wire.OutPoint\n\tvar block Block\n\terr := ns.NestedReadBucket(bucketUnspent).ForEach(func(k, v []byte) error {\n\t\terr := readCanonicalOutPoint(k, &op)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Skip the output if it's locked.\n\t\t_, _, isLocked := isLockedOutput(ns, op, s.clock.Now())\n\t\tif isLocked {\n\t\t\treturn nil\n\t\t}\n\n\t\tif existsRawUnminedInput(ns, k) != nil {\n\t\t\t// Output is spent by an unmined transaction.\n\t\t\t// Skip this k/v pair.\n\t\t\treturn nil\n\t\t}\n\n\t\terr = readUnspentBlock(v, &block)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tblockTime, err := fetchBlockTime(ns, block.Height)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// TODO(jrick): reading the entire transaction should\n\t\t// be avoidable. Creating the credit only requires the\n\t\t// output amount and pkScript.\n\t\trec, err := fetchTxRecord(ns, &op.Hash, &block)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unable to retrieve transaction %v: \"+\n\t\t\t\t\"%v\", op.Hash, err)\n\t\t}\n\t\ttxOut := rec.MsgTx.TxOut[op.Index]\n\t\tcred := Credit{\n\t\t\tOutPoint: op,\n\t\t\tBlockMeta: BlockMeta{\n\t\t\t\tBlock: block,\n\t\t\t\tTime: blockTime,\n\t\t\t},\n\t\t\tAmount: btcutil.Amount(txOut.Value),\n\t\t\tPkScript: txOut.PkScript,\n\t\t\tReceived: rec.Received,\n\t\t\tFromCoinBase: blockchain.IsCoinBaseTx(&rec.MsgTx),\n\t\t}\n\t\tunspent = append(unspent, cred)\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\tif _, ok := err.(Error); ok {\n\t\t\treturn nil, err\n\t\t}\n\t\tstr := \"failed iterating unspent bucket\"\n\t\treturn nil, storeError(ErrDatabase, str, err)\n\t}\n\n\terr = ns.NestedReadBucket(bucketUnminedCredits).ForEach(func(k, v []byte) error {\n\t\tif err := readCanonicalOutPoint(k, &op); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Skip the output if it's locked.\n\t\t_, _, isLocked := isLockedOutput(ns, op, s.clock.Now())\n\t\tif isLocked {\n\t\t\treturn nil\n\t\t}\n\n\t\tif existsRawUnminedInput(ns, k) != nil {\n\t\t\t// Output is spent by an unmined transaction.\n\t\t\t// Skip to next unmined credit.\n\t\t\treturn nil\n\t\t}\n\n\t\t// TODO(jrick): Reading/parsing the entire transaction record\n\t\t// just for the output amount and script can be avoided.\n\t\trecVal := existsRawUnmined(ns, op.Hash[:])\n\t\tvar rec TxRecord\n\t\terr = readRawTxRecord(&op.Hash, recVal, &rec)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unable to retrieve raw transaction \"+\n\t\t\t\t\"%v: %v\", op.Hash, err)\n\t\t}\n\n\t\ttxOut := rec.MsgTx.TxOut[op.Index]\n\t\tcred := Credit{\n\t\t\tOutPoint: op,\n\t\t\tBlockMeta: BlockMeta{\n\t\t\t\tBlock: Block{Height: -1},\n\t\t\t},\n\t\t\tAmount: btcutil.Amount(txOut.Value),\n\t\t\tPkScript: txOut.PkScript,\n\t\t\tReceived: rec.Received,\n\t\t\tFromCoinBase: blockchain.IsCoinBaseTx(&rec.MsgTx),\n\t\t}\n\t\tunspent = append(unspent, cred)\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\tif _, ok := err.(Error); ok {\n\t\t\treturn nil, err\n\t\t}\n\t\tstr := \"failed iterating unmined credits bucket\"\n\t\treturn nil, storeError(ErrDatabase, str, err)\n\t}\n\n\treturn unspent, nil\n}", "func (tx *Transaction) GetNewFromCoins() []FromCoin {\n\tnfcs := make([]FromCoin, 0)\n\tfor index, c := range tx.To.Coins {\n\t\tticket := Ticket{}\n\t\tticket.SetTxid(*tx.GetTxID())\n\t\tticket.SetIndex(uint32(index))\n\n\t\tnfc := FromCoin{}\n\t\tnfc.SetId(c.Id)\n\t\tnfc.AddTicket(&ticket)\n\n\t\tnfcs = append(nfcs, nfc)\n\t}\n\n\treturn nfcs\n}", "func (b *BlockChain) GetUnspentOutputs(address string) []TxOutput {\n\tvar unspentOuts []TxOutput\n\ttxns := b.GetUnspentTxns(address)\n\n\t// go over each txn and each output in it and collect ones which belongs to this address\n\tfor _, txn := range txns {\n\t\t// iterate over all outputs\n\t\tfor _, output := range txn.Out {\n\t\t\tif output.CheckOutputUnlock(address) {\n\t\t\t\tunspentOuts = append(unspentOuts, output)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn unspentOuts\n}", "func (serv *ExchangeServer) GetSupportCoins() []string {\n\tsymbols := make([]string, len(serv.coins))\n\ti := 0\n\tfor _, coin := range serv.coins {\n\t\tsymbols[i] = coin.Symbol()\n\t\ti++\n\t}\n\treturn symbols\n}", "func (o RunnerOutput) Locked() pulumi.BoolOutput {\n\treturn o.ApplyT(func(v *Runner) pulumi.BoolOutput { return v.Locked }).(pulumi.BoolOutput)\n}", "func (cb CommitteeBits) FilterNonParticipants(committee []ValidatorIndex) []ValidatorIndex {\n\tbitLen := cb.BitLen()\n\tout := committee[:0]\n\tif bitLen != uint64(len(committee)) {\n\t\tpanic(\"committee mismatch, bitfield length does not match\")\n\t}\n\tfor i := uint64(0); i < bitLen; i++ {\n\t\tif !cb.GetBit(i) {\n\t\t\tout = append(out, committee[i])\n\t\t}\n\t}\n\treturn out\n}", "func (cm *coinsMempool) Get(maxTransactions uint64, s state.State) ([]*primitives.Tx, state.State) {\n\tcm.lock.RLock()\n\tdefer cm.lock.RUnlock()\n\tallTransactions := make([]*primitives.Tx, 0, maxTransactions)\n\nouter:\n\tfor _, addr := range cm.mempool {\n\t\tfor _, tx := range addr.transactions {\n\t\t\tif err := s.ApplyTransactionSingle(tx, [20]byte{}, cm.params); err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tallTransactions = append(allTransactions, tx)\n\t\t\tif uint64(len(allTransactions)) >= maxTransactions {\n\t\t\t\tbreak outer\n\t\t\t}\n\t\t}\n\t}\n\n\t// we can prioritize here, but we aren't to keep it simple\n\treturn allTransactions, s\n}", "func (k Keeper) MintCoins(ctx sdk.Context, newCoins sdk.Coins) error {\n\tif newCoins.Empty() {\n\t\t// skip as no coins need to be minted\n\t\treturn nil\n\t}\n\treturn k.supplyKeeper.MintCoins(ctx, types.ModuleName, newCoins)\n}", "func (u UTXOSet) FindUnspentTransactionOutputs(pubKeyHash []byte) []TxOutput {\n\tvar UTXOs []TxOutput\n\n\tdb := u.BlockChain.Database\n\n\terr := db.View(func(txn *badger.Txn) error {\n\t\topts := badger.DefaultIteratorOptions\n\n\t\tit := txn.NewIterator(opts)\n\t\tdefer it.Close()\n\n\t\t// iterate through all transactions with UTXOs\n\t\tfor it.Seek(utxoPrefix); it.ValidForPrefix(utxoPrefix); it.Next() {\n\t\t\titem := it.Item()\n\t\t\tv, err := item.Value()\n\t\t\tHandle(err)\n\t\t\touts := DeserializeOutputs(v)\n\t\t\t// go through all outputs of that transaction\n\t\t\tfor _, out := range outs.Outputs {\n\t\t\t\t// check the output was locked with this address (belongs to this receiver and can be unlocked by this address to use as new input)\n\t\t\t\tif out.IsLockedWithKey(pubKeyHash) {\n\t\t\t\t\tUTXOs = append(UTXOs, out)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t})\n\tHandle(err)\n\treturn UTXOs\n}", "func (_TokensNetwork *TokensNetworkCaller) QueryUnlockedLocks(opts *bind.CallOpts, token common.Address, participant common.Address, partner common.Address, lockhash [32]byte) (bool, error) {\n\tvar (\n\t\tret0 = new(bool)\n\t)\n\tout := ret0\n\terr := _TokensNetwork.contract.Call(opts, out, \"queryUnlockedLocks\", token, participant, partner, lockhash)\n\treturn *ret0, err\n}", "func (rt *recvTxOut) SetLocked(locked bool) {\n\trt.locked = locked\n}", "func (rt *recvTxOut) Locked() bool {\n\treturn rt.locked\n}", "func (_TokensNetwork *TokensNetworkCallerSession) QueryUnlockedLocks(token common.Address, participant common.Address, partner common.Address, lockhash [32]byte) (bool, error) {\n\treturn _TokensNetwork.Contract.QueryUnlockedLocks(&_TokensNetwork.CallOpts, token, participant, partner, lockhash)\n}", "func (tp *TXPool) GetUnverifiedTxs(txs []*types.Transaction,\n\theight uint32) *CheckBlkResult {\n\ttp.Lock()\n\tdefer tp.Unlock()\n\tres := &CheckBlkResult{\n\t\tVerifiedTxs: make([]*VerifyTxResult, 0, len(txs)),\n\t\tUnverifiedTxs: make([]*types.Transaction, 0),\n\t\tOldTxs: make([]*types.Transaction, 0),\n\t}\n\tfor _, tx := range txs {\n\t\ttxEntry := tp.txList[tx.Hash()]\n\t\tif txEntry == nil {\n\t\t\tres.UnverifiedTxs = append(res.UnverifiedTxs,\n\t\t\t\ttx)\n\t\t\tcontinue\n\t\t}\n\n\t\tif !tp.compareTxHeight(txEntry, height) {\n\t\t\tdelete(tp.txList, tx.Hash())\n\t\t\tres.OldTxs = append(res.OldTxs, txEntry.Tx)\n\t\t\tcontinue\n\t\t}\n\n\t\tfor _, v := range txEntry.Attrs {\n\t\t\tif v.Type == vt.Stateful {\n\t\t\t\tentry := &VerifyTxResult{\n\t\t\t\t\tTx: tx,\n\t\t\t\t\tHeight: v.Height,\n\t\t\t\t\tErrCode: v.ErrCode,\n\t\t\t\t}\n\t\t\t\tres.VerifiedTxs = append(res.VerifiedTxs,\n\t\t\t\t\tentry)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\treturn res\n}", "func (_TokensNetwork *TokensNetworkSession) QueryUnlockedLocks(token common.Address, participant common.Address, partner common.Address, lockhash [32]byte) (bool, error) {\n\treturn _TokensNetwork.Contract.QueryUnlockedLocks(&_TokensNetwork.CallOpts, token, participant, partner, lockhash)\n}", "func (tb *transactionBuilder) FundCoins(amount types.Currency, refundAddress *types.UnlockHash, reuseRefundAddress bool) error {\n\ttb.wallet.mu.Lock()\n\tdefer tb.wallet.mu.Unlock()\n\n\tif !tb.wallet.unlocked {\n\t\treturn modules.ErrLockedWallet\n\t}\n\n\t// prepare fulfillable context\n\tctx := tb.wallet.getFulfillableContextForLatestBlock()\n\n\t// Collect a value-sorted set of fulfillable coin outputs.\n\tvar so sortedOutputs\n\tfor scoid, sco := range tb.wallet.coinOutputs {\n\t\tif !sco.Condition.Fulfillable(ctx) {\n\t\t\tcontinue\n\t\t}\n\t\tso.ids = append(so.ids, scoid)\n\t\tso.outputs = append(so.outputs, sco)\n\t}\n\t// Add all of the unconfirmed outputs as well.\n\tfor _, upt := range tb.wallet.unconfirmedProcessedTransactions {\n\t\tfor i, sco := range upt.Transaction.CoinOutputs {\n\t\t\tuh := sco.Condition.UnlockHash()\n\t\t\t// Determine if the output belongs to the wallet.\n\t\t\texists, err := tb.wallet.keyExists(uh)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif !exists || !sco.Condition.Fulfillable(ctx) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tso.ids = append(so.ids, upt.Transaction.CoinOutputID(uint64(i)))\n\t\t\tso.outputs = append(so.outputs, sco)\n\t\t}\n\t}\n\tsort.Sort(sort.Reverse(so))\n\n\t// Create a transaction that will add the correct amount of coins to the\n\t// transaction.\n\tvar fund types.Currency\n\t// potentialFund tracks the balance of the wallet including outputs that\n\t// have been spent in other unconfirmed transactions recently. This is to\n\t// provide the user with a more useful error message in the event that they\n\t// are overspending.\n\tvar potentialFund types.Currency\n\tvar spentScoids []types.CoinOutputID\n\tfor i := range so.ids {\n\t\tscoid := so.ids[i]\n\t\tsco := so.outputs[i]\n\t\t// Check that this output has not recently been spent by the wallet.\n\t\tspendHeight := tb.wallet.spentOutputs[types.OutputID(scoid)]\n\t\t// Prevent an underflow error.\n\t\tallowedHeight := tb.wallet.consensusSetHeight - RespendTimeout\n\t\tif tb.wallet.consensusSetHeight < RespendTimeout {\n\t\t\tallowedHeight = 0\n\t\t}\n\t\tif spendHeight > allowedHeight {\n\t\t\tpotentialFund = potentialFund.Add(sco.Value)\n\t\t\tcontinue\n\t\t}\n\n\t\t// prepare fulfillment, matching the output\n\t\tuh := sco.Condition.UnlockHash()\n\t\tvar ff types.MarshalableUnlockFulfillment\n\t\tswitch sco.Condition.ConditionType() {\n\t\tcase types.ConditionTypeUnlockHash, types.ConditionTypeTimeLock:\n\t\t\t// ConditionTypeTimeLock is fine, as we know it's fulfillable,\n\t\t\t// and that can only mean for now that it is using an internal unlockHashCondition or nilCondition\n\t\t\tpk, _, err := tb.wallet.getKey(uh)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tff = types.NewSingleSignatureFulfillment(pk)\n\t\tdefault:\n\t\t\tbuild.Severe(fmt.Errorf(\"unexpected condition type: %[1]v (%[1]T)\", sco.Condition))\n\t\t\treturn types.ErrUnexpectedUnlockCondition\n\t\t}\n\t\t// Add a coin input for this output.\n\t\tsci := types.CoinInput{\n\t\t\tParentID: scoid,\n\t\t\tFulfillment: types.NewFulfillment(ff),\n\t\t}\n\t\ttb.coinInputs = append(tb.coinInputs, inputSignContext{\n\t\t\tInputIndex: len(tb.transaction.CoinInputs),\n\t\t\tUnlockHash: uh,\n\t\t})\n\t\ttb.transaction.CoinInputs = append(tb.transaction.CoinInputs, sci)\n\n\t\tspentScoids = append(spentScoids, scoid)\n\n\t\t// Add the output to the total fund\n\t\tfund = fund.Add(sco.Value)\n\t\tpotentialFund = potentialFund.Add(sco.Value)\n\t\tif fund.Cmp(amount) >= 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\tif potentialFund.Cmp(amount) >= 0 && fund.Cmp(amount) < 0 {\n\t\treturn modules.ErrIncompleteTransactions\n\t}\n\tif fund.Cmp(amount) < 0 {\n\t\treturn modules.ErrLowBalance\n\t}\n\n\t// Create a refund output if needed.\n\tif !amount.Equals(fund) {\n\t\tvar refundUnlockHash types.UnlockHash\n\t\tif refundAddress != nil {\n\t\t\t// use specified refund address\n\t\t\trefundUnlockHash = *refundAddress\n\t\t} else if reuseRefundAddress {\n\t\t\t// use the fist coin input of this tx as refund address\n\t\t\tvar maxCoinAmount types.Currency\n\t\t\tfor _, ci := range tb.transaction.CoinInputs {\n\t\t\t\tco, exists := tb.wallet.coinOutputs[ci.ParentID]\n\t\t\t\tif !exists {\n\t\t\t\t\tco = tb.getCoFromUnconfirmedProcessedTransactions(ci.ParentID)\n\t\t\t\t}\n\t\t\t\tif maxCoinAmount.Cmp(co.Value) < 0 {\n\t\t\t\t\tmaxCoinAmount = co.Value\n\t\t\t\t\trefundUnlockHash = co.Condition.UnlockHash()\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\t// generate a new address\n\t\t\tvar err error\n\t\t\trefundUnlockHash, err = tb.wallet.nextPrimarySeedAddress()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\trefundOutput := types.CoinOutput{\n\t\t\tValue: fund.Sub(amount),\n\t\t\tCondition: types.NewCondition(types.NewUnlockHashCondition(refundUnlockHash)),\n\t\t}\n\t\ttb.transaction.CoinOutputs = append(tb.transaction.CoinOutputs, refundOutput)\n\t}\n\n\t// Mark all outputs that were spent as spent.\n\tfor _, scoid := range spentScoids {\n\t\ttb.wallet.spentOutputs[types.OutputID(scoid)] = tb.wallet.consensusSetHeight\n\t}\n\treturn nil\n}", "func (o AttachedDiskResponseOutput) Locked() pulumi.BoolOutput {\n\treturn o.ApplyT(func(v AttachedDiskResponse) bool { return v.Locked }).(pulumi.BoolOutput)\n}", "func (b *rpcVestingBalance) unbonding() (sdk.Coins, sdk.Coins, error) {\n\tunbondingCoins, err := b.totalUnbondingDelegations()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tunbonding := unbondingCoins.AmountOf(stakingDenom)\n\tdelegatedFree := b.vacc.GetDelegatedFree().AmountOf(stakingDenom)\n\n\tunbondingFree := sdk.MinInt(delegatedFree, unbonding)\n\tunbondingVesting := unbonding.Sub(unbondingFree)\n\n\tliquidCoins := sdk.NewCoins(newKavaCoin(unbondingFree))\n\tvestingCoins := sdk.NewCoins(newKavaCoin(unbondingVesting))\n\treturn liquidCoins, vestingCoins, nil\n}", "func (s *StakingKeeperMock) GetBondedValidatorsByPower(ctx sdk.Context) []stakingtypes.Validator {\n\treturn s.BondedValidators\n}", "func (s *Store) GetUnspentOutputs(ns walletdb.ReadBucket) ([]Credit, er.R) {\n\tvar unspent []Credit\n\terr := s.ForEachUnspentOutput(ns, nil, func(_ []byte, c *Credit) er.R {\n\t\tunspent = append(unspent, *c)\n\t\treturn nil\n\t})\n\treturn unspent, err\n}", "func (btc *ExchangeWallet) spendableUTXOs(confs uint32) ([]*compositeUTXO, map[string]*compositeUTXO, uint64, error) {\n\tunspents, err := btc.wallet.ListUnspent()\n\tif err != nil {\n\t\treturn nil, nil, 0, err\n\t}\n\tsort.Slice(unspents, func(i, j int) bool { return unspents[i].Amount < unspents[j].Amount })\n\tvar sum uint64\n\tutxos := make([]*compositeUTXO, 0, len(unspents))\n\tutxoMap := make(map[string]*compositeUTXO, len(unspents))\n\tfor _, txout := range unspents {\n\t\tif txout.Confirmations >= confs && txout.Safe {\n\t\t\tnfo, err := dexbtc.InputInfo(txout.ScriptPubKey, txout.RedeemScript, btc.chainParams)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, nil, 0, fmt.Errorf(\"error reading asset info: %v\", err)\n\t\t\t}\n\t\t\ttxHash, err := chainhash.NewHashFromStr(txout.TxID)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, nil, 0, fmt.Errorf(\"error decoding txid in ListUnspentResult: %v\", err)\n\t\t\t}\n\t\t\tutxo := &compositeUTXO{\n\t\t\t\ttxHash: txHash,\n\t\t\t\tvout: txout.Vout,\n\t\t\t\taddress: txout.Address,\n\t\t\t\tredeemScript: txout.RedeemScript,\n\t\t\t\tamount: toSatoshi(txout.Amount),\n\t\t\t\tinput: nfo,\n\t\t\t}\n\t\t\tutxos = append(utxos, utxo)\n\t\t\tutxoMap[outpointID(txout.TxID, txout.Vout)] = utxo\n\t\t\tsum += toSatoshi(txout.Amount)\n\t\t}\n\t}\n\treturn utxos, utxoMap, sum, nil\n}", "func newCoins() sdk.Coins {\n\treturn sdk.Coins{\n\t\tsdk.NewInt64Coin(\"atom\", 10000000),\n\t}\n}", "func (w *Wallet) GetUnspentBlockStakeOutputs() (unspent []types.UnspentBlockStakeOutput, err error) {\n\tw.mu.RLock()\n\tdefer w.mu.RUnlock()\n\n\tif !w.unlocked {\n\t\terr = modules.ErrLockedWallet\n\t\treturn\n\t}\n\n\tunspent = make([]types.UnspentBlockStakeOutput, 0)\n\n\t// prepare fulfillable context\n\tctx := w.getFulfillableContextForLatestBlock()\n\n\t// collect all fulfillable block stake outputs\n\tfor usbsoid, output := range w.blockstakeOutputs {\n\t\tif output.Condition.Fulfillable(ctx) {\n\t\t\tunspent = append(unspent, w.unspentblockstakeoutputs[usbsoid])\n\t\t}\n\t}\n\treturn\n}", "func (dcr *ExchangeWallet) spendableUTXOs() ([]*compositeUTXO, error) {\n\tunspents, err := dcr.wallet.Unspents(dcr.ctx, dcr.primaryAcct)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif dcr.tradingAccount != \"\" {\n\t\t// Trading account may contain spendable utxos such as unspent split tx\n\t\t// outputs that are unlocked/returned. TODO: Care should probably be\n\t\t// taken to ensure only unspent split tx outputs are selected and other\n\t\t// unmixed outputs in the trading account are ignored.\n\t\ttradingAcctSpendables, err := dcr.wallet.Unspents(dcr.ctx, dcr.tradingAccount)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tunspents = append(unspents, tradingAcctSpendables...)\n\t}\n\tif len(unspents) == 0 {\n\t\treturn nil, fmt.Errorf(\"insufficient funds. 0 DCR available to spend in account %q\", dcr.primaryAcct)\n\t}\n\n\t// Parse utxos to include script size for spending input. Returned utxos\n\t// will be sorted in ascending order by amount (smallest first).\n\tutxos, err := dcr.parseUTXOs(unspents)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error parsing unspent outputs: %w\", err)\n\t}\n\tif len(utxos) == 0 {\n\t\treturn nil, fmt.Errorf(\"no funds available\")\n\t}\n\treturn utxos, nil\n}", "func (m *Machine) ReturnCoins() {\n\tcoins := m.cashEngine.DropCoins()\n\n\ts := fmt.Sprintf(\"-> \")\n\tfor i, c := range coins {\n\t\tif i == len(coins)-1 {\n\t\t\ts += fmt.Sprintf(\"%s\", c.value.String())\n\t\t\tcontinue\n\t\t}\n\t\ts += fmt.Sprintf(\"%s, \", c.value.String())\n\t}\n\n\tm.logger.Println(s)\n}", "func (_DelegationController *DelegationControllerCaller) GetLockedInPendingDelegations(opts *bind.CallOpts, holder common.Address) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _DelegationController.contract.Call(opts, out, \"getLockedInPendingDelegations\", holder)\n\treturn *ret0, err\n}" ]
[ "0.7511586", "0.7426521", "0.7413611", "0.7314529", "0.6837458", "0.63913995", "0.6190784", "0.6113658", "0.5887874", "0.58083475", "0.56820905", "0.5653764", "0.56137216", "0.5558164", "0.5549295", "0.54992867", "0.5479662", "0.54710203", "0.54137", "0.5398946", "0.5390875", "0.537964", "0.53657687", "0.53312", "0.5280878", "0.52758205", "0.5267908", "0.5255792", "0.52520764", "0.522687", "0.52015865", "0.5188483", "0.5175178", "0.5144665", "0.5144427", "0.5107513", "0.509879", "0.50886923", "0.50751036", "0.5050334", "0.50262237", "0.49953252", "0.49610573", "0.49299344", "0.48908412", "0.48789907", "0.48705155", "0.4869485", "0.4847028", "0.48372054", "0.48167995", "0.4811132", "0.4808342", "0.4800838", "0.47947377", "0.47925186", "0.47915825", "0.47542986", "0.4741802", "0.47142497", "0.47122768", "0.47003815", "0.46986505", "0.46975315", "0.46959382", "0.4690516", "0.4679099", "0.46756017", "0.46594617", "0.46586516", "0.4654842", "0.46405822", "0.46119425", "0.45873702", "0.45708454", "0.45659402", "0.45521998", "0.45490927", "0.45398957", "0.4525667", "0.45233285", "0.45183712", "0.45141983", "0.45058998", "0.4504195", "0.44934013", "0.44892028", "0.44833848", "0.44814962", "0.44685918", "0.44536418", "0.44452357", "0.44340432", "0.44311908", "0.44247618", "0.44243246", "0.442431", "0.44228593", "0.44206217", "0.44143552" ]
0.7436818
1
TrackDelegation tracks a desired delegation amount by setting the appropriate values for the amount of delegated vesting, delegated free, and reducing the overall amount of base coins.
func (dva *DelayedVestingAccount) TrackDelegation(blockTime time.Time, balance, amount sdk.Coins) { dva.BaseVestingAccount.TrackDelegation(balance, dva.GetVestingCoins(blockTime), amount) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (bva *BaseVestingAccount) TrackDelegation(balance, vestingCoins, amount sdk.Coins) {\n\tfor _, coin := range amount {\n\t\tbaseAmt := balance.AmountOf(coin.Denom)\n\t\tvestingAmt := vestingCoins.AmountOf(coin.Denom)\n\t\tdelVestingAmt := bva.DelegatedVesting.AmountOf(coin.Denom)\n\n\t\t// Panic if the delegation amount is zero or if the base coins does not\n\t\t// exceed the desired delegation amount.\n\t\tif coin.Amount.IsZero() || baseAmt.LT(coin.Amount) {\n\t\t\tpanic(\"delegation attempt with zero coins or insufficient funds\")\n\t\t}\n\n\t\t// compute x and y per the specification, where:\n\t\t// X := min(max(V - DV, 0), D)\n\t\t// Y := D - X\n\t\tx := sdk.MinInt(sdk.MaxInt(vestingAmt.Sub(delVestingAmt), sdk.ZeroInt()), coin.Amount)\n\t\ty := coin.Amount.Sub(x)\n\n\t\tif !x.IsZero() {\n\t\t\txCoin := sdk.NewCoin(coin.Denom, x)\n\t\t\tbva.DelegatedVesting = bva.DelegatedVesting.Add(xCoin)\n\t\t}\n\n\t\tif !y.IsZero() {\n\t\t\tyCoin := sdk.NewCoin(coin.Denom, y)\n\t\t\tbva.DelegatedFree = bva.DelegatedFree.Add(yCoin)\n\t\t}\n\t}\n}", "func (pva *PeriodicVestingAccount) TrackDelegation(blockTime time.Time, balance, amount sdk.Coins) {\n\tpva.BaseVestingAccount.TrackDelegation(balance, pva.GetVestingCoins(blockTime), amount)\n}", "func (vva *ValidatorVestingAccount) TrackDelegation(blockTime time.Time, amount sdk.Coins) {\n\tvva.BaseVestingAccount.TrackDelegation(vva.GetVestingCoins(blockTime), amount)\n}", "func (cva *ContinuousVestingAccount) TrackDelegation(blockTime time.Time, balance, amount sdk.Coins) {\n\tcva.BaseVestingAccount.TrackDelegation(balance, cva.GetVestingCoins(blockTime), amount)\n}", "func (va *ClawbackVestingAccount) TrackDelegation(blockTime time.Time, balance, amount sdk.Coins) {\n\tva.BaseVestingAccount.TrackDelegation(balance, va.GetVestingCoins(blockTime), amount)\n}", "func (plva *PermanentLockedAccount) TrackDelegation(blockTime time.Time, balance, amount sdk.Coins) {\n\tplva.BaseVestingAccount.TrackDelegation(balance, plva.OriginalVesting, amount)\n}", "func (bva *BaseVestingAccount) TrackUndelegation(amount sdk.Coins) {\n\tfor _, coin := range amount {\n\t\t// panic if the undelegation amount is zero\n\t\tif coin.Amount.IsZero() {\n\t\t\tpanic(\"undelegation attempt with zero coins\")\n\t\t}\n\t\tdelegatedFree := bva.DelegatedFree.AmountOf(coin.Denom)\n\t\tdelegatedVesting := bva.DelegatedVesting.AmountOf(coin.Denom)\n\n\t\t// compute x and y per the specification, where:\n\t\t// X := min(DF, D)\n\t\t// Y := min(DV, D - X)\n\t\tx := sdk.MinInt(delegatedFree, coin.Amount)\n\t\ty := sdk.MinInt(delegatedVesting, coin.Amount.Sub(x))\n\n\t\tif !x.IsZero() {\n\t\t\txCoin := sdk.NewCoin(coin.Denom, x)\n\t\t\tbva.DelegatedFree = bva.DelegatedFree.Sub(sdk.Coins{xCoin})\n\t\t}\n\n\t\tif !y.IsZero() {\n\t\t\tyCoin := sdk.NewCoin(coin.Denom, y)\n\t\t\tbva.DelegatedVesting = bva.DelegatedVesting.Sub(sdk.Coins{yCoin})\n\t\t}\n\t}\n}", "func (va *ClawbackVestingAccount) updateDelegation(encumbered, toClawBack, bonded, unbonding, unbonded sdk.Coins) sdk.Coins {\n\tdelegated := bonded.Add(unbonding...)\n\toldDelegated := va.DelegatedVesting.Add(va.DelegatedFree...)\n\tslashed := oldDelegated.Sub(coinsMin(delegated, oldDelegated))\n\ttotal := delegated.Add(unbonded...)\n\ttoClawBack = coinsMin(toClawBack, total) // might have been slashed\n\tnewDelegated := coinsMin(delegated, total.Sub(toClawBack)).Add(slashed...)\n\tva.DelegatedVesting = coinsMin(encumbered, newDelegated)\n\tva.DelegatedFree = newDelegated.Sub(va.DelegatedVesting)\n\treturn toClawBack\n}", "func (k msgServer) Delegate(goCtx context.Context, msg *types.MsgDelegate) (*types.MsgDelegateResponse, error) {\n\tctx := sdk.UnwrapSDKContext(goCtx)\n\tvalAddr, valErr := sdk.ValAddressFromBech32(msg.ValidatorAddress)\n\tif valErr != nil {\n\t\treturn nil, valErr\n\t}\n\n\tvalidator, found := k.GetValidator(ctx, valAddr)\n\tif !found {\n\t\treturn nil, types.ErrNoValidatorFound\n\t}\n\n\tdelegatorAddress, err := sdk.AccAddressFromBech32(msg.DelegatorAddress)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbondDenom := k.BondDenom(ctx)\n\tif msg.Amount.Denom != bondDenom {\n\t\treturn nil, sdkerrors.Wrapf(\n\t\t\tsdkerrors.ErrInvalidRequest, \"invalid coin denomination: got %s, expected %s\", msg.Amount.Denom, bondDenom,\n\t\t)\n\t}\n\n\ttokens := msg.Amount.Amount\n\n\t// if this delegation is from a liquid staking provider (identified if the delegator\n\t// is an ICA account), it cannot exceed the global or validator bond cap\n\tif k.DelegatorIsLiquidStaker(delegatorAddress) {\n\t\tshares, err := validator.SharesFromTokens(tokens)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif err := k.SafelyIncreaseTotalLiquidStakedTokens(ctx, tokens, false); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif err := k.SafelyIncreaseValidatorLiquidShares(ctx, &validator, shares); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// NOTE: source funds are always unbonded\n\tnewShares, err := k.Keeper.Delegate(ctx, delegatorAddress, tokens, types.Unbonded, validator, true)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif tokens.IsInt64() {\n\t\tdefer func() {\n\t\t\ttelemetry.IncrCounter(1, types.ModuleName, \"delegate\")\n\t\t\ttelemetry.SetGaugeWithLabels(\n\t\t\t\t[]string{\"tx\", \"msg\", msg.Type()},\n\t\t\t\tfloat32(tokens.Int64()),\n\t\t\t\t[]metrics.Label{telemetry.NewLabel(\"denom\", msg.Amount.Denom)},\n\t\t\t)\n\t\t}()\n\t}\n\n\tctx.EventManager().EmitEvents(sdk.Events{\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeDelegate,\n\t\t\tsdk.NewAttribute(types.AttributeKeyValidator, msg.ValidatorAddress),\n\t\t\tsdk.NewAttribute(sdk.AttributeKeyAmount, msg.Amount.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyNewShares, newShares.String()),\n\t\t),\n\t})\n\n\treturn &types.MsgDelegateResponse{}, nil\n}", "func (k Keeper) TransferDelegation(ctx sdk.Context, valAddr sdk.ValAddress, fromDelegator, toDelegator sdk.AccAddress, shares sdk.Dec) (sdk.Dec, error) {\n\t// Redelegations link a delegation to it's previous validator so slashes are propagated to the new validator.\n\t// If the delegation is transferred to a new owner, the redelegation object must be updated.\n\t// For expediency all transfers with redelegations are blocked.\n\tif k.stakingKeeper.HasReceivingRedelegation(ctx, fromDelegator, valAddr) {\n\t\treturn sdk.Dec{}, types.ErrRedelegationsNotCompleted\n\t}\n\n\tif shares.IsNil() || shares.LT(sdk.ZeroDec()) {\n\t\treturn sdk.Dec{}, errorsmod.Wrap(types.ErrUntransferableShares, \"nil or negative shares\")\n\t}\n\tif shares.Equal(sdk.ZeroDec()) {\n\t\t// Block 0 transfers to reduce edge cases.\n\t\treturn sdk.Dec{}, errorsmod.Wrap(types.ErrUntransferableShares, \"zero shares\")\n\t}\n\n\tfromDelegation, found := k.stakingKeeper.GetDelegation(ctx, fromDelegator, valAddr)\n\tif !found {\n\t\treturn sdk.Dec{}, types.ErrNoDelegatorForAddress\n\t}\n\tvalidator, found := k.stakingKeeper.GetValidator(ctx, valAddr)\n\tif !found {\n\t\treturn sdk.Dec{}, types.ErrNoValidatorFound\n\t}\n\t// Prevent validators from reducing their self delegation below the min.\n\tisValidatorOperator := fromDelegator.Equals(valAddr)\n\tif isValidatorOperator {\n\t\tif isBelowMinSelfDelegation(validator, fromDelegation.Shares.Sub(shares)) {\n\t\t\treturn sdk.Dec{}, types.ErrSelfDelegationBelowMinimum\n\t\t}\n\t}\n\n\treturnAmount, err := k.fastUndelegate(ctx, valAddr, fromDelegator, shares)\n\tif err != nil {\n\t\treturn sdk.Dec{}, err\n\t}\n\treturnCoins := sdk.NewCoins(sdk.NewCoin(k.stakingKeeper.BondDenom(ctx), returnAmount))\n\n\tif err := k.bankKeeper.SendCoins(ctx, fromDelegator, toDelegator, returnCoins); err != nil {\n\t\treturn sdk.Dec{}, err\n\t}\n\treceivedShares, err := k.delegateFromAccount(ctx, valAddr, toDelegator, returnAmount)\n\tif err != nil {\n\t\treturn sdk.Dec{}, err\n\t}\n\n\treturn receivedShares, nil\n}", "func (_DelegationController *DelegationControllerTransactor) Delegate(opts *bind.TransactOpts, validatorId *big.Int, amount *big.Int, delegationPeriod *big.Int, info string) (*types.Transaction, error) {\n\treturn _DelegationController.contract.Transact(opts, \"delegate\", validatorId, amount, delegationPeriod, info)\n}", "func (_DelegationController *DelegationControllerSession) Delegate(validatorId *big.Int, amount *big.Int, delegationPeriod *big.Int, info string) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.Delegate(&_DelegationController.TransactOpts, validatorId, amount, delegationPeriod, info)\n}", "func (_DelegationController *DelegationControllerTransactorSession) Delegate(validatorId *big.Int, amount *big.Int, delegationPeriod *big.Int, info string) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.Delegate(&_DelegationController.TransactOpts, validatorId, amount, delegationPeriod, info)\n}", "func (broadcast *Broadcast) Delegate(ctx context.Context, delegator, voter, amount,\n\tprivKeyHex string, seq int64) (*model.BroadcastResponse, error) {\n\tmsg := model.DelegateMsg{\n\t\tDelegator: delegator,\n\t\tVoter: voter,\n\t\tAmount: amount,\n\t}\n\treturn broadcast.broadcastTransaction(ctx, msg, privKeyHex, seq, \"\", false)\n}", "func (o OfflineNotaryRepository) AddDelegation(data.RoleName, []data.PublicKey, []string) error {\n\treturn nil\n}", "func Delegate(stub shim.ChaincodeStubInterface, args []string) error {\n\tvar vote entities.Vote\n\terr := json.Unmarshal([]byte(args[0]), &vote)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tpoll, err := validateDelegate(stub, vote)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = addVoteToPoll(stub, poll, vote)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Println(\"saving delegate vote\")\n\tutil.UpdateObjectInChain(stub, vote.ID(), util.VotesIndexName, []byte(args[0]))\n\n\tfmt.Println(\"successfully delegated vote to \" + vote.Delegate + \"!\")\n\treturn nil\n}", "func (b *rpcVestingBalance) delegated() (sdk.Coins, sdk.Coins, error) {\n\tdelegatedCoins, err := b.totalDelegated()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tunbondingCoins, err := b.totalUnbondingDelegations()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tdelegated := delegatedCoins.AmountOf(stakingDenom)\n\tunbonding := unbondingCoins.AmountOf(stakingDenom)\n\ttotalStaked := delegated.Add(unbonding)\n\tdelegatedFree := b.vacc.GetDelegatedFree().AmountOf(stakingDenom)\n\n\t// total number of staked and unbonding tokens considered to be liquid\n\ttotalFree := sdk.MinInt(totalStaked, delegatedFree)\n\t// any coins that are not considered liquid, are vesting up to a maximum of delegated\n\tstakedVesting := sdk.MinInt(totalStaked.Sub(totalFree), delegated)\n\t// staked free coins are left over\n\tstakedFree := delegated.Sub(stakedVesting)\n\n\tliquidCoins := sdk.NewCoins(newKavaCoin(stakedFree))\n\tvestingCoins := sdk.NewCoins(newKavaCoin(stakedVesting))\n\treturn liquidCoins, vestingCoins, nil\n}", "func (k Keeper) Delegation(ctx sdk.Context, addrDel sdk.AccAddress, addrVal sdk.ValAddress) exported.DelegationI {\n\treturn nil\n}", "func (del Delegation) AmountDelegated() hexutil.Big {\n\tif del.Delegation.AmountDelegated == nil {\n\t\treturn hexutil.Big{}\n\t}\n\treturn *del.Delegation.AmountDelegated\n}", "func TestCallSimDelegate(t *testing.T) {\n\t// Roll up our sleeves and swear fealty to the witch-king\n\tctx, cancel := context.WithCancel(context.Background())\n\tdefer cancel()\n\tg, ctx := errgroup.WithContext(ctx)\n\n\tdb := dbm.NewMemDB()\n\tst, err := state.MakeGenesisState(db, genesisDoc)\n\trequire.NoError(t, err)\n\n\tfrom := crypto.PrivateKeyFromSecret(\"raaah\", crypto.CurveTypeEd25519)\n\tcontractAddress := crypto.Address{1, 2, 3, 4, 5}\n\tblockchain := &bcm.Blockchain{}\n\tsink := exec.NewNoopEventSink()\n\n\t// Function to set storage value for later\n\tsetDelegate := func(up state.Updatable, value crypto.Address) error {\n\t\tcall, _, err := abi.EncodeFunctionCall(string(solidity.Abi_DelegateProxy), \"setDelegate\", logger, value)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tcache := acmstate.NewCache(st)\n\t\t_, err = evm.Default().Execute(cache, blockchain, sink,\n\t\t\tengine.CallParams{\n\t\t\t\tCallType: exec.CallTypeCall,\n\t\t\t\tOrigin: from.GetAddress(),\n\t\t\t\tCaller: from.GetAddress(),\n\t\t\t\tCallee: contractAddress,\n\t\t\t\tInput: call,\n\t\t\t\tGas: big.NewInt(9999999),\n\t\t\t}, solidity.DeployedBytecode_DelegateProxy)\n\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn cache.Sync(up)\n\t}\n\n\t// Initialise sender smart contract state\n\t_, _, err = st.Update(func(up state.Updatable) error {\n\t\terr = up.UpdateAccount(&acm.Account{\n\t\t\tAddress: from.GetAddress(),\n\t\t\tPublicKey: from.GetPublicKey(),\n\t\t\tBalance: 9999999,\n\t\t\tPermissions: permission.DefaultAccountPermissions,\n\t\t})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn up.UpdateAccount(&acm.Account{\n\t\t\tAddress: contractAddress,\n\t\t\tEVMCode: solidity.DeployedBytecode_DelegateProxy,\n\t\t})\n\t})\n\trequire.NoError(t, err)\n\n\t// Set a series of values of storage slot so we get a deep version tree (which we need to trigger the bug)\n\tdelegate := crypto.Address{0xBE, 0xEF, 0, 0xFA, 0xCE, 0, 0xBA, 0}\n\tfor i := 0; i < 0xBF; i++ {\n\t\tdelegate[7] = byte(i)\n\t\t_, _, err = st.Update(func(up state.Updatable) error {\n\t\t\treturn setDelegate(up, delegate)\n\t\t})\n\t\trequire.NoError(t, err)\n\t}\n\n\t// This is important in order to illicit the former bug - we need a cold LRU tree cache in MutableForest\n\tst, err = state.LoadState(db, st.Version())\n\trequire.NoError(t, err)\n\n\tgetIntCall, _, err := abi.EncodeFunctionCall(string(solidity.Abi_DelegateProxy), \"getDelegate\", logger)\n\trequire.NoError(t, err)\n\tn := 1000\n\n\tfor i := 0; i < n; i++ {\n\t\tg.Go(func() error {\n\t\t\ttxe, err := CallSim(st, blockchain, from.GetAddress(), contractAddress, getIntCall, logger)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\terr = txe.GetException().AsError()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\taddress, err := crypto.AddressFromBytes(txe.GetResult().Return[12:])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif address != delegate {\n\t\t\t\t// The bug for which this test was written will return the zero address here since it is accessing\n\t\t\t\t// an uninitialised tree\n\t\t\t\treturn fmt.Errorf(\"getDelegate returned %v but expected %v\", address, delegate)\n\t\t\t}\n\t\t\treturn nil\n\t\t})\n\t}\n\n\trequire.NoError(t, g.Wait())\n}", "func CalculateDelegateNetPayout(delegatedContracts []DelegatedContract) []DelegatedContract{\n var delegateIndex int\n\n for index, delegate := range delegatedContracts{\n if (delegate.Delegate){\n delegateIndex = index\n }\n }\n\n for _, delegate := range delegatedContracts{\n if (!delegate.Delegate){\n delegatedContracts[delegateIndex].TotalPayout = delegatedContracts[delegateIndex].TotalPayout + delegate.Fee\n }\n }\n return delegatedContracts\n}", "func consolidateDelegations(ctx contract.Context, validator, delegator *types.Address) (*Delegation, []*Delegation, int, error) {\n\t// cycle through all delegations and delete those which are BONDED and\n\t// unlocked while accumulating their amounts\n\tdelegations, err := returnMatchingDelegations(ctx, validator, delegator)\n\tif err != nil {\n\t\treturn nil, nil, -1, err\n\t}\n\n\tunconsolidatedDelegationsCount := 0\n\ttotalDelegationAmount := common.BigZero()\n\tvar consolidatedDelegations []*Delegation\n\tfor _, delegation := range delegations {\n\t\tif delegation.LockTime > uint64(ctx.Now().Unix()) || delegation.State != BONDED {\n\t\t\tunconsolidatedDelegationsCount++\n\t\t\tcontinue\n\t\t}\n\n\t\ttotalDelegationAmount.Add(totalDelegationAmount, &delegation.Amount.Value)\n\t\tconsolidatedDelegations = append(consolidatedDelegations, delegation)\n\n\t\tif err = DeleteDelegation(ctx, delegation); err != nil {\n\t\t\treturn nil, nil, -1, err\n\t\t}\n\t}\n\n\tindex, err := GetNextDelegationIndex(ctx, *validator, *delegator)\n\tif err != nil {\n\t\treturn nil, nil, -1, err\n\t}\n\n\t// create new conolidated delegation\n\tdelegation := &Delegation{\n\t\tValidator: validator,\n\t\tDelegator: delegator,\n\t\tAmount: &types.BigUInt{Value: *totalDelegationAmount},\n\t\tUpdateAmount: loom.BigZeroPB(),\n\t\tLocktimeTier: 0,\n\t\tLockTime: 0,\n\t\tState: BONDED,\n\t\tIndex: index,\n\t}\n\tif err := SetDelegation(ctx, delegation); err != nil {\n\t\treturn nil, nil, -1, err\n\t}\n\treturn delegation, consolidatedDelegations, unconsolidatedDelegationsCount, nil\n}", "func (_TokensNetwork *TokensNetworkTransactor) UpdateBalanceProofDelegate(opts *bind.TransactOpts, token common.Address, partner common.Address, participant common.Address, transferred_amount *big.Int, locksroot [32]byte, nonce uint64, additional_hash [32]byte, partner_signature []byte, participant_signature []byte) (*types.Transaction, error) {\n\treturn _TokensNetwork.contract.Transact(opts, \"updateBalanceProofDelegate\", token, partner, participant, transferred_amount, locksroot, nonce, additional_hash, partner_signature, participant_signature)\n}", "func (k msgServer) CancelUnbondingDelegation(goCtx context.Context, msg *types.MsgCancelUnbondingDelegation) (*types.MsgCancelUnbondingDelegationResponse, error) {\n\tctx := sdk.UnwrapSDKContext(goCtx)\n\n\tvalAddr, err := sdk.ValAddressFromBech32(msg.ValidatorAddress)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdelegatorAddress, err := sdk.AccAddressFromBech32(msg.DelegatorAddress)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbondDenom := k.BondDenom(ctx)\n\tif msg.Amount.Denom != bondDenom {\n\t\treturn nil, sdkerrors.Wrapf(\n\t\t\tsdkerrors.ErrInvalidRequest, \"invalid coin denomination: got %s, expected %s\", msg.Amount.Denom, bondDenom,\n\t\t)\n\t}\n\n\tvalidator, found := k.GetValidator(ctx, valAddr)\n\tif !found {\n\t\treturn nil, types.ErrNoValidatorFound\n\t}\n\n\t// In some situations, the exchange rate becomes invalid, e.g. if\n\t// Validator loses all tokens due to slashing. In this case,\n\t// make all future delegations invalid.\n\tif validator.InvalidExRate() {\n\t\treturn nil, types.ErrDelegatorShareExRateInvalid\n\t}\n\n\tif validator.IsJailed() {\n\t\treturn nil, types.ErrValidatorJailed\n\t}\n\n\tubd, found := k.GetUnbondingDelegation(ctx, delegatorAddress, valAddr)\n\tif !found {\n\t\treturn nil, status.Errorf(\n\t\t\tcodes.NotFound,\n\t\t\t\"unbonding delegation with delegator %s not found for validator %s\",\n\t\t\tmsg.DelegatorAddress, msg.ValidatorAddress,\n\t\t)\n\t}\n\n\t// if this undelegation was from a liquid staking provider (identified if the delegator\n\t// is an ICA account), the global and validator liquid totals should be incremented\n\ttokens := msg.Amount.Amount\n\tshares, err := validator.SharesFromTokens(tokens)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif k.DelegatorIsLiquidStaker(delegatorAddress) {\n\t\tif err := k.SafelyIncreaseTotalLiquidStakedTokens(ctx, tokens, false); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif err := k.SafelyIncreaseValidatorLiquidShares(ctx, &validator, shares); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tvar (\n\t\tunbondEntry types.UnbondingDelegationEntry\n\t\tunbondEntryIndex int64 = -1\n\t)\n\n\tfor i, entry := range ubd.Entries {\n\t\tif entry.CreationHeight == msg.CreationHeight {\n\t\t\tunbondEntry = entry\n\t\t\tunbondEntryIndex = int64(i)\n\t\t\tbreak\n\t\t}\n\t}\n\tif unbondEntryIndex == -1 {\n\t\treturn nil, sdkerrors.ErrNotFound.Wrapf(\"unbonding delegation entry is not found at block height %d\", msg.CreationHeight)\n\t}\n\n\tif unbondEntry.Balance.LT(msg.Amount.Amount) {\n\t\treturn nil, sdkerrors.ErrInvalidRequest.Wrap(\"amount is greater than the unbonding delegation entry balance\")\n\t}\n\n\tif unbondEntry.CompletionTime.Before(ctx.BlockTime()) {\n\t\treturn nil, sdkerrors.ErrInvalidRequest.Wrap(\"unbonding delegation is already processed\")\n\t}\n\n\t// delegate back the unbonding delegation amount to the validator\n\t_, err = k.Keeper.Delegate(ctx, delegatorAddress, msg.Amount.Amount, types.Unbonding, validator, false)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tamount := unbondEntry.Balance.Sub(msg.Amount.Amount)\n\tif amount.IsZero() {\n\t\tubd.RemoveEntry(unbondEntryIndex)\n\t} else {\n\t\t// update the unbondingDelegationEntryBalance and InitialBalance for ubd entry\n\t\tunbondEntry.Balance = amount\n\t\tunbondEntry.InitialBalance = unbondEntry.InitialBalance.Sub(msg.Amount.Amount)\n\t\tubd.Entries[unbondEntryIndex] = unbondEntry\n\t}\n\n\t// set the unbonding delegation or remove it if there are no more entries\n\tif len(ubd.Entries) == 0 {\n\t\tk.RemoveUnbondingDelegation(ctx, ubd)\n\t} else {\n\t\tk.SetUnbondingDelegation(ctx, ubd)\n\t}\n\n\tctx.EventManager().EmitEvent(\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeCancelUnbondingDelegation,\n\t\t\tsdk.NewAttribute(sdk.AttributeKeyAmount, msg.Amount.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyValidator, msg.ValidatorAddress),\n\t\t\tsdk.NewAttribute(types.AttributeKeyDelegator, msg.DelegatorAddress),\n\t\t\tsdk.NewAttribute(types.AttributeKeyCreationHeight, strconv.FormatInt(msg.CreationHeight, 10)),\n\t\t),\n\t)\n\n\treturn &types.MsgCancelUnbondingDelegationResponse{}, nil\n}", "func CalculatePayoutForContract(contract Contract, rate float64, delegate bool) Contract{\n ////-------------JUST FOR TESTING -------------////\n totalNodeRewards := 378 //Amount of rewards for my delegation in cycle 11\n ////--------------END TESTING ------------------////\n\n grossRewards := contract.SharePercentage * float64(totalNodeRewards)\n contract.GrossPayout = grossRewards\n fee := rate * grossRewards\n contract.Fee = fee\n var netRewards float64\n if (delegate){\n netRewards = grossRewards\n contract.NetPayout = netRewards\n contract.Fee = 0\n } else {\n netRewards = grossRewards - fee\n contract.NetPayout = contract.NetPayout + netRewards\n }\n\n return contract\n}", "func (us *DelegationService) AddDelegation(delegation *models.Delegation) (*models.Delegation, error) {\n\t// TODO(tho) add CSR validation against template\n\treturn us.storeInterface.AddDelegation(delegation)\n}", "func (_TokensNetwork *TokensNetworkSession) UpdateBalanceProofDelegate(token common.Address, partner common.Address, participant common.Address, transferred_amount *big.Int, locksroot [32]byte, nonce uint64, additional_hash [32]byte, partner_signature []byte, participant_signature []byte) (*types.Transaction, error) {\n\treturn _TokensNetwork.Contract.UpdateBalanceProofDelegate(&_TokensNetwork.TransactOpts, token, partner, participant, transferred_amount, locksroot, nonce, additional_hash, partner_signature, participant_signature)\n}", "func NewDelegation(d *types.Delegation) *Delegation {\n\treturn &Delegation{Delegation: *d, cg: new(singleflight.Group)}\n}", "func (_TokensNetwork *TokensNetworkTransactorSession) UpdateBalanceProofDelegate(token common.Address, partner common.Address, participant common.Address, transferred_amount *big.Int, locksroot [32]byte, nonce uint64, additional_hash [32]byte, partner_signature []byte, participant_signature []byte) (*types.Transaction, error) {\n\treturn _TokensNetwork.Contract.UpdateBalanceProofDelegate(&_TokensNetwork.TransactOpts, token, partner, participant, transferred_amount, locksroot, nonce, additional_hash, partner_signature, participant_signature)\n}", "func (k Keeper) Delegation(ctx context.Context, addrDel sdk.AccAddress, addrVal sdk.ValAddress) (types.DelegationI, error) {\n\tbond, err := k.Delegations.Get(ctx, collections.Join(addrDel, addrVal))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn bond, nil\n}", "func (_TokensNetwork *TokensNetworkTransactor) UnlockDelegate(opts *bind.TransactOpts, token common.Address, partner common.Address, participant common.Address, transferred_amount *big.Int, expiration *big.Int, amount *big.Int, secret_hash [32]byte, merkle_proof []byte, participant_signature []byte) (*types.Transaction, error) {\n\treturn _TokensNetwork.contract.Transact(opts, \"unlockDelegate\", token, partner, participant, transferred_amount, expiration, amount, secret_hash, merkle_proof, participant_signature)\n}", "func TestDelegatorProxyValidatorConstraints4Steps(t *testing.T) {\n\tcommon.InitConfig()\n\tparams := DefaultParams()\n\n\toriginVaSet := addrVals[1:]\n\tparams.MaxValidators = uint16(len(originVaSet))\n\tparams.Epoch = 2\n\tparams.UnbondingTime = time.Millisecond * 300\n\tstartUpValidator := NewValidator(StartUpValidatorAddr, StartUpValidatorPubkey, Description{}, types.DefaultMinSelfDelegation)\n\tstartUpStatus := baseValidatorStatus{startUpValidator}\n\torgValsLen := len(originVaSet)\n\tfullVaSet := make([]sdk.ValAddress, orgValsLen+1)\n\tcopy(fullVaSet, originVaSet)\n\tcopy(fullVaSet[orgValsLen:], []sdk.ValAddress{startUpStatus.getValidator().GetOperator()})\n\n\tbAction := baseAction{}\n\n\tstep1Actions := IActions{\n\t\tdelegatorRegProxyAction{bAction, ProxiedDelegator, true},\n\t\tdelegatorsAddSharesAction{bAction, false, true, 0, []sdk.AccAddress{ProxiedDelegator}},\n\t\tdelegatorWithdrawAction{bAction, ProxiedDelegator, sdk.OneDec(), sdk.DefaultBondDenom},\n\t\tproxyBindAction{bAction, ProxiedDelegator, ProxiedDelegator},\n\t\tproxyUnBindAction{bAction, ProxiedDelegator},\n\t}\n\n\tstep2Actions := IActions{\n\t\tdelegatorDepositAction{bAction, ValidDelegator1, DelegatedToken1, sdk.DefaultBondDenom},\n\t\tproxyBindAction{bAction, ValidDelegator1, ProxiedDelegator},\n\t\tdelegatorsAddSharesAction{bAction, false, true, 0, []sdk.AccAddress{ValidDelegator1}},\n\t\tproxyUnBindAction{bAction, ValidDelegator1},\n\t\tdelegatorWithdrawAction{bAction, ValidDelegator1, sdk.OneDec(), sdk.DefaultBondDenom},\n\t}\n\n\tstep3Actions := IActions{\n\t\tdelegatorDepositAction{bAction, ValidDelegator1, DelegatedToken1, sdk.DefaultBondDenom},\n\t\tproxyBindAction{bAction, ValidDelegator1, ProxiedDelegator},\n\t\tproxyUnBindAction{bAction, ValidDelegator1},\n\t\tdelegatorWithdrawAction{bAction, ValidDelegator1, sdk.OneDec(), sdk.DefaultBondDenom},\n\t}\n\n\tstep4Actions := IActions{\n\t\tdelegatorRegProxyAction{bAction, ProxiedDelegator, true},\n\t\tdelegatorsAddSharesAction{bAction, false, true, 0, []sdk.AccAddress{ProxiedDelegator}},\n\t\tproxyBindAction{bAction, ProxiedDelegator, ProxiedDelegator},\n\t\tproxyUnBindAction{bAction, ProxiedDelegator},\n\t\tdelegatorWithdrawAction{bAction, ProxiedDelegator, sdk.OneDec(), sdk.DefaultBondDenom},\n\t}\n\n\tfor s1 := 0; s1 < len(step1Actions); s1++ {\n\t\tfor s2 := 0; s2 < len(step2Actions); s2++ {\n\t\t\tfor s3 := 0; s3 < len(step3Actions); s3++ {\n\t\t\t\tfor s4 := 0; s4 < len(step4Actions); s4++ {\n\t\t\t\t\tinputActions := []IAction{\n\t\t\t\t\t\tcreateValidatorAction{bAction, nil},\n\t\t\t\t\t\tdelegatorsAddSharesAction{bAction, false, true, 0, []sdk.AccAddress{ValidDelegator2}},\n\t\t\t\t\t\tdelegatorDepositAction{bAction, ProxiedDelegator, MaxDelegatedToken, sdk.DefaultBondDenom},\n\t\t\t\t\t\tstep1Actions[s1],\n\t\t\t\t\t\tstep2Actions[s2],\n\t\t\t\t\t\tstep3Actions[s3],\n\t\t\t\t\t\tstep4Actions[s4],\n\t\t\t\t\t\tdelegatorRegProxyAction{bAction, ProxiedDelegator, false},\n\t\t\t\t\t\tdestroyValidatorAction{bAction},\n\t\t\t\t\t}\n\n\t\t\t\t\tactionsAndChecker, caseName := generateActionsAndCheckers(inputActions, 3)\n\n\t\t\t\t\tt.Logf(\"============================================== indexes:[%d,%d,%d,%d] %s ==============================================\", s1, s2, s3, s4, caseName)\n\t\t\t\t\t_, _, mk := CreateTestInput(t, false, SufficientInitPower)\n\t\t\t\t\tsmTestCase := newValidatorSMTestCase(mk, params, startUpStatus, inputActions, actionsAndChecker, t)\n\t\t\t\t\tsmTestCase.SetupValidatorSetAndDelegatorSet(int(params.MaxValidators))\n\t\t\t\t\tsmTestCase.printParticipantSnapshot(t)\n\t\t\t\t\tsmTestCase.Run(t)\n\t\t\t\t\tt.Log(\"============================================================================================\")\n\t\t\t\t}\n\n\t\t\t}\n\t\t}\n\t}\n}", "func (k Keeper) fastUndelegate(ctx sdk.Context, valAddr sdk.ValAddress, delegator sdk.AccAddress, shares sdk.Dec) (sdkmath.Int, error) {\n\tvalidator, found := k.stakingKeeper.GetValidator(ctx, valAddr)\n\tif !found {\n\t\treturn sdkmath.Int{}, types.ErrNoDelegatorForAddress\n\t}\n\n\treturnAmount, err := k.stakingKeeper.Unbond(ctx, delegator, valAddr, shares)\n\tif err != nil {\n\t\treturn sdkmath.Int{}, err\n\t}\n\treturnCoins := sdk.NewCoins(sdk.NewCoin(k.stakingKeeper.BondDenom(ctx), returnAmount))\n\n\t// transfer the validator tokens to the not bonded pool\n\tif validator.IsBonded() {\n\t\tif err := k.bankKeeper.SendCoinsFromModuleToModule(ctx, stakingtypes.BondedPoolName, stakingtypes.NotBondedPoolName, returnCoins); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\n\tif err := k.bankKeeper.UndelegateCoinsFromModuleToAccount(ctx, stakingtypes.NotBondedPoolName, delegator, returnCoins); err != nil {\n\t\treturn sdkmath.Int{}, err\n\t}\n\treturn returnAmount, nil\n}", "func (pva *PeriodicVestingAccount) addGrant(ctx sdk.Context, sk StakingKeeper, grantStartTime int64, grantVestingPeriods []Period, grantCoins sdk.Coins) {\n\t// how much is really delegated?\n\tbondedAmt := sk.GetDelegatorBonded(ctx, pva.GetAddress())\n\tunbondingAmt := sk.GetDelegatorUnbonding(ctx, pva.GetAddress())\n\tdelegatedAmt := bondedAmt.Add(unbondingAmt)\n\tdelegated := sdk.NewCoins(sdk.NewCoin(sk.BondDenom(ctx), delegatedAmt))\n\n\t// discover what has been slashed\n\toldDelegated := pva.DelegatedVesting.Add(pva.DelegatedFree...)\n\tslashed := oldDelegated.Sub(coinsMin(oldDelegated, delegated))\n\n\t// rebase the DV+DF by capping slashed at the current unvested amount\n\tunvested := pva.GetVestingCoins(ctx.BlockTime())\n\tnewSlashed := coinsMin(unvested, slashed)\n\tnewTotalDelegated := delegated.Add(newSlashed...)\n\n\t// modify vesting schedule for the new grant\n\tnewStart, newEnd, newPeriods := DisjunctPeriods(pva.StartTime, grantStartTime,\n\t\tpva.GetVestingPeriods(), grantVestingPeriods)\n\tpva.StartTime = newStart\n\tpva.EndTime = newEnd\n\tpva.VestingPeriods = newPeriods\n\tpva.OriginalVesting = pva.OriginalVesting.Add(grantCoins...)\n\n\t// cap DV at the current unvested amount, DF rounds out to newTotalDelegated\n\tunvested2 := pva.GetVestingCoins(ctx.BlockTime())\n\tpva.DelegatedVesting = coinsMin(newTotalDelegated, unvested2)\n\tpva.DelegatedFree = newTotalDelegated.Sub(pva.DelegatedVesting)\n}", "func (k msgServer) Undelegate(goCtx context.Context, msg *types.MsgUndelegate) (*types.MsgUndelegateResponse, error) {\n\tctx := sdk.UnwrapSDKContext(goCtx)\n\n\taddr, err := sdk.ValAddressFromBech32(msg.ValidatorAddress)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdelegatorAddress, err := sdk.AccAddressFromBech32(msg.DelegatorAddress)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttokens := msg.Amount.Amount\n\tshares, err := k.ValidateUnbondAmount(\n\t\tctx, delegatorAddress, addr, tokens,\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvalidator, found := k.GetValidator(ctx, addr)\n\tif !found {\n\t\treturn nil, types.ErrNoValidatorFound\n\t}\n\n\tdelegation, found := k.GetDelegation(ctx, delegatorAddress, addr)\n\tif !found {\n\t\treturn nil, status.Errorf(\n\t\t\tcodes.NotFound,\n\t\t\t\"delegation with delegator %s not found for validator %s\",\n\t\t\tmsg.DelegatorAddress, msg.ValidatorAddress,\n\t\t)\n\t}\n\n\t// if this is a validator self-bond, the new liquid delegation cannot fall below the self-bond * bond factor\n\tif delegation.ValidatorBond {\n\t\tif err := k.SafelyDecreaseValidatorBond(ctx, &validator, shares); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// if this delegation is from a liquid staking provider (identified if the delegator\n\t// is an ICA account), the global and validator liquid totals should be decremented\n\tif k.DelegatorIsLiquidStaker(delegatorAddress) {\n\t\tif err := k.DecreaseTotalLiquidStakedTokens(ctx, tokens); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif err := k.DecreaseValidatorLiquidShares(ctx, &validator, shares); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tbondDenom := k.BondDenom(ctx)\n\tif msg.Amount.Denom != bondDenom {\n\t\treturn nil, sdkerrors.Wrapf(\n\t\t\tsdkerrors.ErrInvalidRequest, \"invalid coin denomination: got %s, expected %s\", msg.Amount.Denom, bondDenom,\n\t\t)\n\t}\n\n\tcompletionTime, err := k.Keeper.Undelegate(ctx, delegatorAddress, addr, shares)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif tokens.IsInt64() {\n\t\tdefer func() {\n\t\t\ttelemetry.IncrCounter(1, types.ModuleName, \"undelegate\")\n\t\t\ttelemetry.SetGaugeWithLabels(\n\t\t\t\t[]string{\"tx\", \"msg\", msg.Type()},\n\t\t\t\tfloat32(tokens.Int64()),\n\t\t\t\t[]metrics.Label{telemetry.NewLabel(\"denom\", msg.Amount.Denom)},\n\t\t\t)\n\t\t}()\n\t}\n\n\tctx.EventManager().EmitEvents(sdk.Events{\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeUnbond,\n\t\t\tsdk.NewAttribute(types.AttributeKeyValidator, msg.ValidatorAddress),\n\t\t\tsdk.NewAttribute(sdk.AttributeKeyAmount, msg.Amount.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyCompletionTime, completionTime.Format(time.RFC3339)),\n\t\t),\n\t})\n\n\treturn &types.MsgUndelegateResponse{\n\t\tCompletionTime: completionTime,\n\t}, nil\n}", "func (p *Ledger) RecordPayment(destination types.NodeAddress, amount int64, confirmed chan bool) {\n\tok := <-confirmed\n\tif ok {\n\t\tp.l.Lock()\n\t\tp.incoming_debt[p.id] -= amount\n\t\tp.outgoing_debt[destination] -= amount\n\t\tp.l.Unlock()\n\t}\n}", "func (a *account) managedTrackDeposit(amount types.Currency) {\n\ta.mu.Lock()\n\tdefer a.mu.Unlock()\n\ta.pendingDeposits = a.pendingDeposits.Add(amount)\n}", "func NewDelegation(d *types.Delegation, repo repository.Repository) *Delegation {\n\treturn &Delegation{\n\t\tDelegation: *d,\n\t\trepo: repo,\n\t}\n}", "func (p *Protocol) NumDelegates() uint64 {\n\treturn p.numDelegates\n}", "func (rs *rootResolver) Delegation(args *struct {\n\tAddress common.Address\n\tStaker hexutil.Big\n}) (*Delegation, error) {\n\t// get the delegator detail from backend\n\td, err := repository.R().Delegation(&args.Address, &args.Staker)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn NewDelegation(d), nil\n}", "func (_TokensNetwork *TokensNetworkSession) UnlockDelegate(token common.Address, partner common.Address, participant common.Address, transferred_amount *big.Int, expiration *big.Int, amount *big.Int, secret_hash [32]byte, merkle_proof []byte, participant_signature []byte) (*types.Transaction, error) {\n\treturn _TokensNetwork.Contract.UnlockDelegate(&_TokensNetwork.TransactOpts, token, partner, participant, transferred_amount, expiration, amount, secret_hash, merkle_proof, participant_signature)\n}", "func (o OfflineNotaryRepository) AddDelegationPaths(data.RoleName, []string) error {\n\treturn nil\n}", "func (tracker *PeerTracker) Track(ci *types.ChainInfo) {\n\ttracker.mu.Lock()\n\tdefer tracker.mu.Unlock()\n\n\t_, tracking := tracker.peers[ci.Peer]\n\t_, trusted := tracker.trusted[ci.Peer]\n\ttracker.peers[ci.Peer] = ci\n\tlogPeerTracker.Infof(\"Tracking %s, new=%t, count=%d trusted=%t\", ci, !tracking, len(tracker.peers), trusted)\n}", "func TestSlashWithRedelegation(t *testing.T) {\n\tapp, ctx, addrDels, addrVals := bootstrapSlashTest(t, 10)\n\tconsAddr := sdk.ConsAddress(PKs[0].Address())\n\tfraction := sdk.NewDecWithPrec(5, 1)\n\tbondDenom := app.StakingKeeper.BondDenom(ctx)\n\n\t// set a redelegation\n\trdTokens := app.StakingKeeper.TokensFromConsensusPower(ctx, 6)\n\trd := types.NewRedelegation(addrDels[0], addrVals[0], addrVals[1], 11,\n\t\ttime.Unix(0, 0), rdTokens, rdTokens.ToDec())\n\tapp.StakingKeeper.SetRedelegation(ctx, rd)\n\n\t// set the associated delegation\n\tdel := types.NewDelegation(addrDels[0], addrVals[1], rdTokens.ToDec())\n\tapp.StakingKeeper.SetDelegation(ctx, del)\n\n\t// update bonded tokens\n\tbondedPool := app.StakingKeeper.GetBondedPool(ctx)\n\tnotBondedPool := app.StakingKeeper.GetNotBondedPool(ctx)\n\trdCoins := sdk.NewCoins(sdk.NewCoin(bondDenom, rdTokens.MulRaw(2)))\n\n\trequire.NoError(t, simapp.FundModuleAccount(app.BankKeeper, ctx, bondedPool.GetName(), rdCoins))\n\n\tapp.AccountKeeper.SetModuleAccount(ctx, bondedPool)\n\n\toldBonded := app.BankKeeper.GetBalance(ctx, bondedPool.GetAddress(), bondDenom).Amount\n\toldNotBonded := app.BankKeeper.GetBalance(ctx, notBondedPool.GetAddress(), bondDenom).Amount\n\n\t// slash validator\n\tctx = ctx.WithBlockHeight(12)\n\tvalidator, found := app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)\n\trequire.True(t, found)\n\n\trequire.NotPanics(t, func() { app.StakingKeeper.Slash(ctx, consAddr, 10, 10, fraction) })\n\tburnAmount := app.StakingKeeper.TokensFromConsensusPower(ctx, 10).ToDec().Mul(fraction).TruncateInt()\n\n\tbondedPool = app.StakingKeeper.GetBondedPool(ctx)\n\tnotBondedPool = app.StakingKeeper.GetNotBondedPool(ctx)\n\n\t// burn bonded tokens from only from delegations\n\tbondedPoolBalance := app.BankKeeper.GetBalance(ctx, bondedPool.GetAddress(), bondDenom).Amount\n\trequire.True(sdk.IntEq(t, oldBonded.Sub(burnAmount), bondedPoolBalance))\n\n\tnotBondedPoolBalance := app.BankKeeper.GetBalance(ctx, notBondedPool.GetAddress(), bondDenom).Amount\n\trequire.True(sdk.IntEq(t, oldNotBonded, notBondedPoolBalance))\n\toldBonded = app.BankKeeper.GetBalance(ctx, bondedPool.GetAddress(), bondDenom).Amount\n\n\t// read updating redelegation\n\trd, found = app.StakingKeeper.GetRedelegation(ctx, addrDels[0], addrVals[0], addrVals[1])\n\trequire.True(t, found)\n\trequire.Len(t, rd.Entries, 1)\n\t// read updated validator\n\tvalidator, found = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)\n\trequire.True(t, found)\n\t// power decreased by 2 - 4 stake originally bonded at the time of infraction\n\t// was still bonded at the time of discovery and was slashed by half, 4 stake\n\t// bonded at the time of discovery hadn't been bonded at the time of infraction\n\t// and wasn't slashed\n\trequire.Equal(t, int64(8), validator.GetConsensusPower(app.StakingKeeper.PowerReduction(ctx)))\n\n\t// slash the validator again\n\tvalidator, found = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)\n\trequire.True(t, found)\n\n\trequire.NotPanics(t, func() { app.StakingKeeper.Slash(ctx, consAddr, 10, 10, sdk.OneDec()) })\n\tburnAmount = app.StakingKeeper.TokensFromConsensusPower(ctx, 7)\n\n\t// read updated pool\n\tbondedPool = app.StakingKeeper.GetBondedPool(ctx)\n\tnotBondedPool = app.StakingKeeper.GetNotBondedPool(ctx)\n\n\t// seven bonded tokens burned\n\tbondedPoolBalance = app.BankKeeper.GetBalance(ctx, bondedPool.GetAddress(), bondDenom).Amount\n\trequire.True(sdk.IntEq(t, oldBonded.Sub(burnAmount), bondedPoolBalance))\n\trequire.True(sdk.IntEq(t, oldNotBonded, notBondedPoolBalance))\n\n\tbondedPoolBalance = app.BankKeeper.GetBalance(ctx, bondedPool.GetAddress(), bondDenom).Amount\n\trequire.True(sdk.IntEq(t, oldBonded.Sub(burnAmount), bondedPoolBalance))\n\n\tnotBondedPoolBalance = app.BankKeeper.GetBalance(ctx, notBondedPool.GetAddress(), bondDenom).Amount\n\trequire.True(sdk.IntEq(t, oldNotBonded, notBondedPoolBalance))\n\toldBonded = app.BankKeeper.GetBalance(ctx, bondedPool.GetAddress(), bondDenom).Amount\n\n\t// read updating redelegation\n\trd, found = app.StakingKeeper.GetRedelegation(ctx, addrDels[0], addrVals[0], addrVals[1])\n\trequire.True(t, found)\n\trequire.Len(t, rd.Entries, 1)\n\t// read updated validator\n\tvalidator, found = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)\n\trequire.True(t, found)\n\t// power decreased by 4\n\trequire.Equal(t, int64(4), validator.GetConsensusPower(app.StakingKeeper.PowerReduction(ctx)))\n\n\t// slash the validator again, by 100%\n\tctx = ctx.WithBlockHeight(12)\n\tvalidator, found = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)\n\trequire.True(t, found)\n\n\trequire.NotPanics(t, func() { app.StakingKeeper.Slash(ctx, consAddr, 10, 10, sdk.OneDec()) })\n\n\tburnAmount = app.StakingKeeper.TokensFromConsensusPower(ctx, 10).ToDec().Mul(sdk.OneDec()).TruncateInt()\n\tburnAmount = burnAmount.Sub(sdk.OneDec().MulInt(rdTokens).TruncateInt())\n\n\t// read updated pool\n\tbondedPool = app.StakingKeeper.GetBondedPool(ctx)\n\tnotBondedPool = app.StakingKeeper.GetNotBondedPool(ctx)\n\n\tbondedPoolBalance = app.BankKeeper.GetBalance(ctx, bondedPool.GetAddress(), bondDenom).Amount\n\trequire.True(sdk.IntEq(t, oldBonded.Sub(burnAmount), bondedPoolBalance))\n\tnotBondedPoolBalance = app.BankKeeper.GetBalance(ctx, notBondedPool.GetAddress(), bondDenom).Amount\n\trequire.True(sdk.IntEq(t, oldNotBonded, notBondedPoolBalance))\n\toldBonded = app.BankKeeper.GetBalance(ctx, bondedPool.GetAddress(), bondDenom).Amount\n\n\t// read updating redelegation\n\trd, found = app.StakingKeeper.GetRedelegation(ctx, addrDels[0], addrVals[0], addrVals[1])\n\trequire.True(t, found)\n\trequire.Len(t, rd.Entries, 1)\n\t// apply TM updates\n\tapplyValidatorSetUpdates(t, ctx, app.StakingKeeper, -1)\n\t// read updated validator\n\t// validator decreased to zero power, should be in unbonding period\n\tvalidator, _ = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)\n\trequire.Equal(t, validator.GetStatus(), types.Unbonding)\n\n\t// slash the validator again, by 100%\n\t// no stake remains to be slashed\n\tctx = ctx.WithBlockHeight(12)\n\t// validator still in unbonding period\n\tvalidator, _ = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)\n\trequire.Equal(t, validator.GetStatus(), types.Unbonding)\n\n\trequire.NotPanics(t, func() { app.StakingKeeper.Slash(ctx, consAddr, 10, 10, sdk.OneDec()) })\n\n\t// read updated pool\n\tbondedPool = app.StakingKeeper.GetBondedPool(ctx)\n\tnotBondedPool = app.StakingKeeper.GetNotBondedPool(ctx)\n\n\tbondedPoolBalance = app.BankKeeper.GetBalance(ctx, bondedPool.GetAddress(), bondDenom).Amount\n\trequire.True(sdk.IntEq(t, oldBonded, bondedPoolBalance))\n\tnotBondedPoolBalance = app.BankKeeper.GetBalance(ctx, notBondedPool.GetAddress(), bondDenom).Amount\n\trequire.True(sdk.IntEq(t, oldNotBonded, notBondedPoolBalance))\n\n\t// read updating redelegation\n\trd, found = app.StakingKeeper.GetRedelegation(ctx, addrDels[0], addrVals[0], addrVals[1])\n\trequire.True(t, found)\n\trequire.Len(t, rd.Entries, 1)\n\t// read updated validator\n\t// power still zero, still in unbonding period\n\tvalidator, _ = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)\n\trequire.Equal(t, validator.GetStatus(), types.Unbonding)\n}", "func (m *MetricsProvider) SignerAddLinkedDataProof(value time.Duration) {\n}", "func (*CardanoSignTransactionRequest_Certificate_StakeDelegation) Descriptor() ([]byte, []int) {\n\treturn file_cardano_proto_rawDescGZIP(), []int{4, 3, 0}\n}", "func (_TokensNetwork *TokensNetworkTransactorSession) UnlockDelegate(token common.Address, partner common.Address, participant common.Address, transferred_amount *big.Int, expiration *big.Int, amount *big.Int, secret_hash [32]byte, merkle_proof []byte, participant_signature []byte) (*types.Transaction, error) {\n\treturn _TokensNetwork.Contract.UnlockDelegate(&_TokensNetwork.TransactOpts, token, partner, participant, transferred_amount, expiration, amount, secret_hash, merkle_proof, participant_signature)\n}", "func (_Bep20 *Bep20Transactor) DelegateBySig(opts *bind.TransactOpts, delegatee common.Address, nonce *big.Int, expiry *big.Int, v uint8, r [32]byte, s [32]byte) (*types.Transaction, error) {\n\treturn _Bep20.contract.Transact(opts, \"delegateBySig\", delegatee, nonce, expiry, v, r, s)\n}", "func (va *ClawbackVestingAccount) addGrant(ctx sdk.Context, sk StakingKeeper, grantStartTime int64, grantLockupPeriods, grantVestingPeriods []Period, grantCoins sdk.Coins) {\n\t// how much is really delegated?\n\tbondedAmt := sk.GetDelegatorBonded(ctx, va.GetAddress())\n\tunbondingAmt := sk.GetDelegatorUnbonding(ctx, va.GetAddress())\n\tdelegatedAmt := bondedAmt.Add(unbondingAmt)\n\tdelegated := sdk.NewCoins(sdk.NewCoin(sk.BondDenom(ctx), delegatedAmt))\n\n\t// discover what has been slashed\n\toldDelegated := va.DelegatedVesting.Add(va.DelegatedFree...)\n\tslashed := oldDelegated.Sub(coinsMin(oldDelegated, delegated))\n\n\t// rebase the DV + DF by capping slashed at the current unvested amount\n\tunvested := va.OriginalVesting.Sub(va.GetVestedOnly(ctx.BlockTime()))\n\tnewSlashed := coinsMin(slashed, unvested)\n\tnewDelegated := delegated.Add(newSlashed...)\n\n\t// modify schedules for the new grant\n\tnewLockupStart, newLockupEnd, newLockupPeriods := DisjunctPeriods(va.StartTime, grantStartTime, va.LockupPeriods, grantLockupPeriods)\n\tnewVestingStart, newVestingEnd, newVestingPeriods := DisjunctPeriods(va.StartTime, grantStartTime,\n\t\tva.GetVestingPeriods(), grantVestingPeriods)\n\tif newLockupStart != newVestingStart {\n\t\tpanic(\"bad start time calculation\")\n\t}\n\tva.StartTime = newLockupStart\n\tva.EndTime = max64(newLockupEnd, newVestingEnd)\n\tva.LockupPeriods = newLockupPeriods\n\tva.VestingPeriods = newVestingPeriods\n\tva.OriginalVesting = va.OriginalVesting.Add(grantCoins...)\n\n\t// cap DV at the current unvested amount, DF rounds out to newDelegated\n\tunvested2 := va.GetVestingCoins(ctx.BlockTime())\n\tva.DelegatedVesting = coinsMin(newDelegated, unvested2)\n\tva.DelegatedFree = newDelegated.Sub(va.DelegatedVesting)\n}", "func CalculatePercentageSharesForCycle(delegatedContracts []DelegatedContract, cycle int, rate float64, spillage bool, delegateAddr string) ([]DelegatedContract, error){\n var stakingBalance float64\n //var balance float64\n var err error\n\n spillAlert := false\n\n stakingBalance, err = GetDelegateStakingBalance(delegateAddr, cycle)\n if (err != nil){\n return delegatedContracts, errors.New(\"func CalculateRollSpillage(delegatedContracts []DelegatedContract, delegateAddr string) failed: \" + err.Error())\n }\n\n mod := math.Mod(stakingBalance, 10000)\n sum := stakingBalance - mod\n balanceCheck := stakingBalance - mod\n\n for index, delegation := range delegatedContracts{\n counter := 0\n for i, _ := range delegation.Contracts {\n if (delegatedContracts[index].Contracts[i].Cycle == cycle){\n break\n }\n counter = counter + 1\n }\n balanceCheck = balanceCheck - delegatedContracts[index].Contracts[counter].Amount\n //fmt.Println(stakingBalance)\n if (spillAlert){\n delegatedContracts[index].Contracts[counter].SharePercentage = 0\n delegatedContracts[index].Contracts[counter].RollInclusion = 0\n } else if (balanceCheck < 0 && spillage){\n spillAlert = true\n delegatedContracts[index].Contracts[counter].SharePercentage = (delegatedContracts[index].Contracts[counter].Amount + stakingBalance) / sum\n delegatedContracts[index].Contracts[counter].RollInclusion = delegatedContracts[index].Contracts[counter].Amount + stakingBalance\n } else{\n delegatedContracts[index].Contracts[counter].SharePercentage = delegatedContracts[index].Contracts[counter].Amount / stakingBalance\n delegatedContracts[index].Contracts[counter].RollInclusion = delegatedContracts[index].Contracts[counter].Amount\n }\n delegatedContracts[index].Contracts[counter] = CalculatePayoutForContract(delegatedContracts[index].Contracts[counter], rate, delegatedContracts[index].Delegate)\n delegatedContracts[index].Fee = delegatedContracts[index].Fee + delegatedContracts[index].Contracts[counter].Fee\n }\n\n return delegatedContracts, nil\n}", "func (a *account) managedTrackWithdrawal(amount types.Currency) {\n\ta.mu.Lock()\n\tdefer a.mu.Unlock()\n\ta.pendingWithdrawals = a.pendingWithdrawals.Add(amount)\n}", "func (_OwnerProxyRegistry *OwnerProxyRegistryCaller) CountDelegates(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _OwnerProxyRegistry.contract.Call(opts, &out, \"countDelegates\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (_OwnerProxyRegistry *OwnerProxyRegistryTransactor) AddDelegate(opts *bind.TransactOpts, from common.Address) (*types.Transaction, error) {\n\treturn _OwnerProxyRegistry.contract.Transact(opts, \"addDelegate\", from)\n}", "func TestSlashWithUnbondingDelegation(t *testing.T) {\n\tapp, ctx, addrDels, addrVals := bootstrapSlashTest(t, 10)\n\n\tconsAddr := sdk.ConsAddress(PKs[0].Address())\n\tfraction := sdk.NewDecWithPrec(5, 1)\n\n\t// set an unbonding delegation with expiration timestamp beyond which the\n\t// unbonding delegation shouldn't be slashed\n\tubdTokens := app.StakingKeeper.TokensFromConsensusPower(ctx, 4)\n\tubd := types.NewUnbondingDelegation(addrDels[0], addrVals[0], 11, time.Unix(0, 0), ubdTokens)\n\tapp.StakingKeeper.SetUnbondingDelegation(ctx, ubd)\n\n\t// slash validator for the first time\n\tctx = ctx.WithBlockHeight(12)\n\tbondedPool := app.StakingKeeper.GetBondedPool(ctx)\n\toldBondedPoolBalances := app.BankKeeper.GetAllBalances(ctx, bondedPool.GetAddress())\n\n\tvalidator, found := app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)\n\trequire.True(t, found)\n\tapp.StakingKeeper.Slash(ctx, consAddr, 10, 10, fraction)\n\n\t// end block\n\tapplyValidatorSetUpdates(t, ctx, app.StakingKeeper, 1)\n\n\t// read updating unbonding delegation\n\tubd, found = app.StakingKeeper.GetUnbondingDelegation(ctx, addrDels[0], addrVals[0])\n\trequire.True(t, found)\n\trequire.Len(t, ubd.Entries, 1)\n\n\t// balance decreased\n\trequire.Equal(t, app.StakingKeeper.TokensFromConsensusPower(ctx, 2), ubd.Entries[0].Balance)\n\n\t// bonded tokens burned\n\tnewBondedPoolBalances := app.BankKeeper.GetAllBalances(ctx, bondedPool.GetAddress())\n\tdiffTokens := oldBondedPoolBalances.Sub(newBondedPoolBalances).AmountOf(app.StakingKeeper.BondDenom(ctx))\n\trequire.Equal(t, app.StakingKeeper.TokensFromConsensusPower(ctx, 3), diffTokens)\n\n\t// read updated validator\n\tvalidator, found = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)\n\trequire.True(t, found)\n\n\t// power decreased by 3 - 6 stake originally bonded at the time of infraction\n\t// was still bonded at the time of discovery and was slashed by half, 4 stake\n\t// bonded at the time of discovery hadn't been bonded at the time of infraction\n\t// and wasn't slashed\n\trequire.Equal(t, int64(7), validator.GetConsensusPower(app.StakingKeeper.PowerReduction(ctx)))\n\n\t// slash validator again\n\tctx = ctx.WithBlockHeight(13)\n\tapp.StakingKeeper.Slash(ctx, consAddr, 9, 10, fraction)\n\n\tubd, found = app.StakingKeeper.GetUnbondingDelegation(ctx, addrDels[0], addrVals[0])\n\trequire.True(t, found)\n\trequire.Len(t, ubd.Entries, 1)\n\n\t// balance decreased again\n\trequire.Equal(t, sdk.NewInt(0), ubd.Entries[0].Balance)\n\n\t// bonded tokens burned again\n\tnewBondedPoolBalances = app.BankKeeper.GetAllBalances(ctx, bondedPool.GetAddress())\n\tdiffTokens = oldBondedPoolBalances.Sub(newBondedPoolBalances).AmountOf(app.StakingKeeper.BondDenom(ctx))\n\trequire.Equal(t, app.StakingKeeper.TokensFromConsensusPower(ctx, 6), diffTokens)\n\n\t// read updated validator\n\tvalidator, found = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)\n\trequire.True(t, found)\n\n\t// power decreased by 3 again\n\trequire.Equal(t, int64(4), validator.GetConsensusPower(app.StakingKeeper.PowerReduction(ctx)))\n\n\t// slash validator again\n\t// all originally bonded stake has been slashed, so this will have no effect\n\t// on the unbonding delegation, but it will slash stake bonded since the infraction\n\t// this may not be the desirable behaviour, ref https://github.com/cosmos/cosmos-sdk/issues/1440\n\tctx = ctx.WithBlockHeight(13)\n\tapp.StakingKeeper.Slash(ctx, consAddr, 9, 10, fraction)\n\n\tubd, found = app.StakingKeeper.GetUnbondingDelegation(ctx, addrDels[0], addrVals[0])\n\trequire.True(t, found)\n\trequire.Len(t, ubd.Entries, 1)\n\n\t// balance unchanged\n\trequire.Equal(t, sdk.NewInt(0), ubd.Entries[0].Balance)\n\n\t// bonded tokens burned again\n\tnewBondedPoolBalances = app.BankKeeper.GetAllBalances(ctx, bondedPool.GetAddress())\n\tdiffTokens = oldBondedPoolBalances.Sub(newBondedPoolBalances).AmountOf(app.StakingKeeper.BondDenom(ctx))\n\trequire.Equal(t, app.StakingKeeper.TokensFromConsensusPower(ctx, 9), diffTokens)\n\n\t// read updated validator\n\tvalidator, found = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)\n\trequire.True(t, found)\n\n\t// power decreased by 3 again\n\trequire.Equal(t, int64(1), validator.GetConsensusPower(app.StakingKeeper.PowerReduction(ctx)))\n\n\t// slash validator again\n\t// all originally bonded stake has been slashed, so this will have no effect\n\t// on the unbonding delegation, but it will slash stake bonded since the infraction\n\t// this may not be the desirable behaviour, ref https://github.com/cosmos/cosmos-sdk/issues/1440\n\tctx = ctx.WithBlockHeight(13)\n\tapp.StakingKeeper.Slash(ctx, consAddr, 9, 10, fraction)\n\n\tubd, found = app.StakingKeeper.GetUnbondingDelegation(ctx, addrDels[0], addrVals[0])\n\trequire.True(t, found)\n\trequire.Len(t, ubd.Entries, 1)\n\n\t// balance unchanged\n\trequire.Equal(t, sdk.NewInt(0), ubd.Entries[0].Balance)\n\n\t// just 1 bonded token burned again since that's all the validator now has\n\tnewBondedPoolBalances = app.BankKeeper.GetAllBalances(ctx, bondedPool.GetAddress())\n\tdiffTokens = oldBondedPoolBalances.Sub(newBondedPoolBalances).AmountOf(app.StakingKeeper.BondDenom(ctx))\n\trequire.Equal(t, app.StakingKeeper.TokensFromConsensusPower(ctx, 10), diffTokens)\n\n\t// apply TM updates\n\tapplyValidatorSetUpdates(t, ctx, app.StakingKeeper, -1)\n\n\t// read updated validator\n\t// power decreased by 1 again, validator is out of stake\n\t// validator should be in unbonding period\n\tvalidator, _ = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)\n\trequire.Equal(t, validator.GetStatus(), types.Unbonding)\n}", "func (_DelegationController *DelegationControllerTransactor) AcceptPendingDelegation(opts *bind.TransactOpts, delegationId *big.Int) (*types.Transaction, error) {\n\treturn _DelegationController.contract.Transact(opts, \"acceptPendingDelegation\", delegationId)\n}", "func (rs *rootResolver) Delegation(args *struct {\n\tAddress common.Address\n\tStaker hexutil.Uint64\n}) (*Delegation, error) {\n\t// get the delegator detail from backend\n\td, err := rs.repo.Delegation(args.Address, args.Staker)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn NewDelegation(d, rs.repo), nil\n}", "func (acc *Account) delegationsTotal() (amount *big.Int, inWithdraw *big.Int, rewards *big.Int, err error) {\n\t// pull all the delegations of the account\n\tlist, err := repository.R().DelegationsByAddressAll(&acc.Address)\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\n\t// prep containers for calculation and loop all delegations found\n\tamount = new(big.Int)\n\trewards = new(big.Int)\n\tinWithdraw = new(big.Int)\n\tfor _, dlg := range list {\n\t\t// any active delegated amount?\n\t\tif 0 < dlg.AmountDelegated.ToInt().Uint64() {\n\t\t\tamount = new(big.Int).Add(amount, dlg.AmountDelegated.ToInt())\n\t\t}\n\n\t\t// get pending rewards for this delegation (can be stashed)\n\t\trw, err := repository.R().PendingRewards(&acc.Address, dlg.ToStakerId)\n\t\tif err != nil {\n\t\t\treturn nil, nil, nil, err\n\t\t}\n\n\t\t// any rewards?\n\t\tif 0 < rw.Amount.ToInt().Uint64() {\n\t\t\trewards = new(big.Int).Add(rewards, rw.Amount.ToInt())\n\t\t}\n\n\t\t// get pending withdrawals\n\t\twd, err := repository.R().WithdrawRequestsPendingTotal(&acc.Address, dlg.ToStakerId)\n\t\tif err != nil {\n\t\t\treturn nil, nil, nil, err\n\t\t}\n\n\t\t// add pending withdrawals value\n\t\tif 0 < wd.Uint64() {\n\t\t\tinWithdraw = new(big.Int).Add(inWithdraw, wd)\n\t\t}\n\t}\n\n\treturn amount, rewards, inWithdraw, nil\n}", "func (_DelegationController *DelegationControllerTransactor) GetAndUpdateDelegatedAmount(opts *bind.TransactOpts, holder common.Address) (*types.Transaction, error) {\n\treturn _DelegationController.contract.Transact(opts, \"getAndUpdateDelegatedAmount\", holder)\n}", "func (del Delegation) Amount() (hexutil.Big, error) {\n\t// get the base amount delegated\n\tbase, err := repository.R().DelegationAmountStaked(&del.Address, del.Delegation.ToStakerId)\n\tif err != nil {\n\t\treturn hexutil.Big{}, err\n\t}\n\n\t// get the sum of all pending withdrawals\n\twd, err := del.pendingWithdrawalsValue()\n\tif err != nil {\n\t\treturn hexutil.Big{}, err\n\t}\n\tval := new(big.Int).Add(base, wd)\n\treturn (hexutil.Big)(*val), nil\n}", "func distributeDelegatorRewards(ctx contract.Context, cachedDelegations *CachedDposStorage, formerValidatorTotals map[string]loom.BigUInt, delegatorRewards map[string]*loom.BigUInt, distributedRewards *loom.BigUInt) (map[string]*loom.BigUInt, error) {\n\tnewDelegationTotals := make(map[string]*loom.BigUInt)\n\n\tcandidates, err := LoadCandidateList(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Initialize delegation totals with whitelist amounts\n\tfor _, candidate := range candidates {\n\t\tstatistic, _ := GetStatistic(ctx, loom.UnmarshalAddressPB(candidate.Address))\n\n\t\tif statistic != nil && statistic.WhitelistAmount != nil && !common.IsZero(statistic.WhitelistAmount.Value) {\n\t\t\tvalidatorKey := loom.UnmarshalAddressPB(statistic.Address).String()\n\t\t\tamount := calculateWeightedWhitelistAmount(*statistic)\n\t\t\tnewDelegationTotals[validatorKey] = &amount\n\t\t}\n\t}\n\n\tdelegations, err := cachedDelegations.loadDelegationList(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar currentDelegations = make(DelegationList, len(delegations))\n\tcopy(currentDelegations, delegations)\n\tfor _, d := range currentDelegations {\n\t\tdelegation, err := GetDelegation(ctx, d.Index, *d.Validator, *d.Delegator)\n\t\tif err == contract.ErrNotFound {\n\t\t\tcontinue\n\t\t} else if err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tvalidatorKey := loom.UnmarshalAddressPB(delegation.Validator).String()\n\n\t\t// Do not distribute rewards to delegators of the Limbo validator\n\t\t// NOTE: because all delegations are sorted in reverse index order, the\n\t\t// 0-index delegation (for rewards) is handled last. Therefore, all\n\t\t// increases to reward delegations will be reflected in newDelegation\n\t\t// totals that are computed at the end of this for loop. (We do this to\n\t\t// avoid looping over all delegations twice)\n\t\tif loom.UnmarshalAddressPB(delegation.Validator).Compare(LimboValidatorAddress(ctx)) != 0 {\n\t\t\t// allocating validator distributions to delegators\n\t\t\t// based on former validator delegation totals\n\t\t\tdelegationTotal := formerValidatorTotals[validatorKey]\n\t\t\trewardsTotal := delegatorRewards[validatorKey]\n\t\t\tif rewardsTotal != nil {\n\t\t\t\tweightedDelegation := calculateWeightedDelegationAmount(*delegation)\n\t\t\t\tdelegatorDistribution := calculateShare(weightedDelegation, delegationTotal, *rewardsTotal)\n\t\t\t\t// increase a delegator's distribution\n\t\t\t\tdistributedRewards.Add(distributedRewards, &delegatorDistribution)\n\t\t\t\tcachedDelegations.IncreaseRewardDelegation(ctx, delegation.Validator, delegation.Delegator, delegatorDistribution)\n\n\t\t\t\t// If the reward delegation is updated by the\n\t\t\t\t// IncreaseRewardDelegation command, we must be sure to use this\n\t\t\t\t// updated version in the rest of the loop. No other delegations\n\t\t\t\t// (non-rewards) have the possibility of being updated outside\n\t\t\t\t// of this loop.\n\t\t\t\tif ctx.FeatureEnabled(features.DPOSVersion3_1, false) && d.Index == REWARD_DELEGATION_INDEX {\n\t\t\t\t\tdelegation, err = GetDelegation(ctx, d.Index, *d.Validator, *d.Delegator)\n\t\t\t\t\tif err == contract.ErrNotFound {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t} else if err != nil {\n\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tupdatedAmount := common.BigZero()\n\t\tif delegation.State == BONDING {\n\t\t\tupdatedAmount.Add(&delegation.Amount.Value, &delegation.UpdateAmount.Value)\n\t\t\tdelegation.Amount = &types.BigUInt{Value: *updatedAmount}\n\t\t} else if delegation.State == UNBONDING {\n\t\t\tupdatedAmount.Sub(&delegation.Amount.Value, &delegation.UpdateAmount.Value)\n\t\t\tdelegation.Amount = &types.BigUInt{Value: *updatedAmount}\n\t\t\tcoin, err := loadCoin(ctx)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\terr = coin.Transfer(loom.UnmarshalAddressPB(delegation.Delegator), &delegation.UpdateAmount.Value)\n\t\t\tif err != nil {\n\t\t\t\ttransferFromErr := fmt.Sprintf(\"Failed coin Transfer - distributeDelegatorRewards, %v, %s\", delegation.Delegator.String(), delegation.UpdateAmount.Value.String())\n\t\t\t\treturn nil, logDposError(ctx, err, transferFromErr)\n\t\t\t}\n\t\t} else if delegation.State == REDELEGATING {\n\t\t\tif err = cachedDelegations.DeleteDelegation(ctx, delegation); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tdelegation.Validator = delegation.UpdateValidator\n\t\t\tdelegation.Amount = delegation.UpdateAmount\n\t\t\tdelegation.LocktimeTier = delegation.UpdateLocktimeTier\n\n\t\t\tindex, err := GetNextDelegationIndex(ctx, *delegation.Validator, *delegation.Delegator)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tdelegation.Index = index\n\n\t\t\tvalidatorKey = loom.UnmarshalAddressPB(delegation.Validator).String()\n\t\t}\n\n\t\t// Delete any delegation whose full amount has been unbonded. In all\n\t\t// other cases, update the delegation state to BONDED and reset its\n\t\t// UpdateAmount\n\t\tif common.IsZero(delegation.Amount.Value) && delegation.State == UNBONDING {\n\t\t\tif err := cachedDelegations.DeleteDelegation(ctx, delegation); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t} else {\n\t\t\t// After a delegation update, zero out UpdateAmount\n\t\t\tdelegation.UpdateAmount = loom.BigZeroPB()\n\t\t\tdelegation.State = BONDED\n\n\t\t\tresetDelegationIfExpired(ctx, delegation)\n\t\t\tif err := cachedDelegations.SetDelegation(ctx, delegation); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\n\t\t// Calculate delegation totals for all validators except the Limbo\n\t\t// validator\n\t\tif loom.UnmarshalAddressPB(delegation.Validator).Compare(LimboValidatorAddress(ctx)) != 0 {\n\t\t\tnewTotal := common.BigZero()\n\t\t\tweightedDelegation := calculateWeightedDelegationAmount(*delegation)\n\t\t\tnewTotal.Add(newTotal, &weightedDelegation)\n\t\t\tif newDelegationTotals[validatorKey] != nil {\n\t\t\t\tnewTotal.Add(newTotal, newDelegationTotals[validatorKey])\n\t\t\t}\n\t\t\tnewDelegationTotals[validatorKey] = newTotal\n\t\t}\n\t}\n\n\treturn newDelegationTotals, nil\n}", "func (a *Account) Track() {\n\t// Request notifications for transactions sending to all wallet\n\t// addresses.\n\taddrs := a.ActiveAddresses()\n\taddrstrs := make([]string, len(addrs))\n\ti := 0\n\tfor addr := range addrs {\n\t\taddrstrs[i] = addr.EncodeAddress()\n\t\ti++\n\t}\n\n\terr := NotifyNewTXs(CurrentServerConn(), addrstrs)\n\tif err != nil {\n\t\tlog.Error(\"Unable to request transaction updates for address.\")\n\t}\n\n\tfor _, txout := range a.TxStore.UnspentOutputs() {\n\t\tReqSpentUtxoNtfn(txout)\n\t}\n}", "func (m *mParcelMockDelegationToken) Set(f func() (r insolar.DelegationToken)) *ParcelMock {\n\tm.mainExpectation = nil\n\tm.expectationSeries = nil\n\n\tm.mock.DelegationTokenFunc = f\n\treturn m.mock\n}", "func (bva BaseVestingAccount) GetDelegatedVesting() sdk.Coins {\n\treturn bva.DelegatedVesting\n}", "func (n *Node) BecomeDelegator(genesisAmount uint64, seedAmount uint64, delegatorAmount uint64, txFee uint64, stakerNodeID string) *Node {\n\n\t// exports AVAX from the X Chain\n\texportTxID, err := n.client.XChainAPI().ExportAVAX(\n\t\tn.UserPass,\n\t\tnil, // from addrs\n\t\t\"\", // change addr\n\t\tseedAmount+txFee,\n\t\tn.PAddress,\n\t)\n\tif err != nil {\n\t\tpanic(stacktrace.Propagate(err, \"Failed to export AVAX to pchainAddress %s\", n.PAddress))\n\t\treturn n\n\t}\n\n\t// waits Tx acceptance in the XChain\n\terr = chainhelper.XChain().AwaitTransactionAcceptance(n.client, exportTxID, constants.TimeoutDuration)\n\tif err != nil {\n\t\tpanic(err)\n\t\treturn n\n\t}\n\n\t// imports the amount to the P Chain\n\timportTxID, err := n.client.PChainAPI().ImportAVAX(\n\t\tn.UserPass,\n\t\tnil, // from addrs\n\t\t\"\", // change addr\n\t\tn.PAddress,\n\t\tconstants.XChainID.String(),\n\t)\n\tif err != nil {\n\t\tpanic(stacktrace.Propagate(err, \"Failed import AVAX to pchainAddress %s\", n.PAddress))\n\t\treturn n\n\t}\n\n\t// waits Tx acceptance in the PChain\n\terr = chainhelper.PChain().AwaitTransactionAcceptance(n.client, importTxID, constants.TimeoutDuration)\n\tif err != nil {\n\t\tpanic(err)\n\t\treturn n\n\t}\n\n\t// verify the PChain balance (seedAmount+txFee-txFee)\n\terr = chainhelper.PChain().CheckBalance(n.client, n.PAddress, seedAmount)\n\tif err != nil {\n\t\tpanic(stacktrace.Propagate(err, \"expected balance of seedAmount exists in the PChain\"))\n\t\treturn n\n\t}\n\n\t// verify the XChain balance of genesisAmount - seedAmount - txFee - txFee (import PChain)\n\terr = chainhelper.XChain().CheckBalance(n.client, n.XAddress, \"AVAX\", genesisAmount-seedAmount-2*txFee)\n\tif err != nil {\n\t\tpanic(stacktrace.Propagate(err, \"expected balance XChain balance of genesisAmount-seedAmount-txFee\"))\n\t\treturn n\n\t}\n\n\tdelegatorStartTime := time.Now().Add(20 * time.Second)\n\tstartTime := uint64(delegatorStartTime.Unix())\n\tendTime := uint64(delegatorStartTime.Add(36 * time.Hour).Unix())\n\taddDelegatorTxID, err := n.client.PChainAPI().AddDelegator(\n\t\tn.UserPass,\n\t\tnil, // from addrs\n\t\t\"\", // change addr\n\t\tn.PAddress,\n\t\tstakerNodeID,\n\t\tdelegatorAmount,\n\t\tstartTime,\n\t\tendTime,\n\t)\n\tif err != nil {\n\t\tpanic(stacktrace.Propagate(err, \"Failed to add delegator %s\", n.PAddress))\n\t\treturn n\n\t}\n\n\terr = chainhelper.PChain().AwaitTransactionAcceptance(n.client, addDelegatorTxID, constants.TimeoutDuration)\n\tif err != nil {\n\t\tpanic(stacktrace.Propagate(err, \"Failed to accept AddDelegator tx: %s\", addDelegatorTxID))\n\t\treturn n\n\t}\n\n\t// Sleep until delegator starts validating\n\ttime.Sleep(time.Until(delegatorStartTime) + 3*time.Second)\n\n\texpectedDelegatorBalance := seedAmount - delegatorAmount\n\terr = chainhelper.PChain().CheckBalance(n.client, n.PAddress, expectedDelegatorBalance)\n\tif err != nil {\n\t\tpanic(stacktrace.Propagate(err, \"Unexpected P Chain Balance after adding a new delegator to the network.\"))\n\t\treturn n\n\t}\n\tlogrus.Infof(\"Added delegator to subnet and verified the expected P Chain balance.\")\n\n\treturn n\n}", "func (_DelegationController *DelegationControllerSession) Delegations(arg0 *big.Int) (struct {\n\tHolder common.Address\n\tValidatorId *big.Int\n\tAmount *big.Int\n\tDelegationPeriod *big.Int\n\tCreated *big.Int\n\tStarted *big.Int\n\tFinished *big.Int\n\tInfo string\n}, error) {\n\treturn _DelegationController.Contract.Delegations(&_DelegationController.CallOpts, arg0)\n}", "func (_TransferProxyRegistry *TransferProxyRegistryCaller) CountDelegates(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _TransferProxyRegistry.contract.Call(opts, &out, \"countDelegates\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (a *Account) Track() {\n\trpcc, err := accessClient()\n\tif err != nil {\n\t\tlog.Errorf(\"No chain server client to track addresses.\")\n\t\treturn\n\t}\n\n\t// Request notifications for transactions sending to all wallet\n\t// addresses.\n\t//\n\t// TODO: return as slice? (doesn't have to be ordered, or\n\t// SortedActiveAddresses would be fine.)\n\taddrMap := a.KeyStore.ActiveAddresses()\n\taddrs := make([]btcutil.Address, 0, len(addrMap))\n\tfor addr := range addrMap {\n\t\taddrs = append(addrs, addr)\n\t}\n\n\tif err := rpcc.NotifyReceived(addrs); err != nil {\n\t\tlog.Error(\"Unable to request transaction updates for address.\")\n\t}\n\n\tunspent, err := a.TxStore.UnspentOutputs()\n\tif err != nil {\n\t\tlog.Errorf(\"Unable to access unspent outputs: %v\", err)\n\t\treturn\n\t}\n\tReqSpentUtxoNtfns(unspent)\n}", "func (_DelegationController *DelegationControllerCallerSession) Delegations(arg0 *big.Int) (struct {\n\tHolder common.Address\n\tValidatorId *big.Int\n\tAmount *big.Int\n\tDelegationPeriod *big.Int\n\tCreated *big.Int\n\tStarted *big.Int\n\tFinished *big.Int\n\tInfo string\n}, error) {\n\treturn _DelegationController.Contract.Delegations(&_DelegationController.CallOpts, arg0)\n}", "func (pm *DPoSProtocolManager) syncDelegatedNodeSafely() {\n\tif !pm.isDelegatedNode() {\n\t\t// only candidate node is able to participant to this process.\n\t\treturn;\n\t}\n\tpm.lock.Lock()\n\tdefer pm.lock.Unlock()\n\tlog.Info(\"Preparing for next big period...\");\n\t// pull the newest delegators from voting contract.\n\ta, b, err0 := VotingAccessor.Refresh()\n\tif err0 != nil {\n\t\tlog.Error(err0.Error())\n\t\treturn;\n\t}\n\tDelegatorsTable = a\n\tDelegatorNodeInfo = b\n\tif uint8(len(GigPeriodHistory)) >= BigPeriodHistorySize {\n\t\tGigPeriodHistory = GigPeriodHistory[1:] //remove the first old one.\n\t}\n\tif len(DelegatorsTable) == 0 || pm.ethManager.peers.Len() == 0 {\n\t\tlog.Info(\"Sorry, could not detect any delegator!\");\n\t\treturn;\n\t}\n\tround := uint64(1)\n\tactiveTime := uint64(time.Now().Unix() + int64(GigPeriodInterval))\n\tif NextGigPeriodInstance != nil {\n\t\tif !TestMode {\n\t\t\tgap := int64(NextGigPeriodInstance.activeTime) - time.Now().Unix()\n\t\t\tif gap > 2 || gap < -2 {\n\t\t\t\tlog.Warn(fmt.Sprintf(\"Scheduling of the new electing round is improper! current gap: %v seconds\", gap))\n\t\t\t\t//restart the scheduler\n\t\t\t\tNextElectionInfo = nil;\n\t\t\t\tgo pm.syncDelegatedNodeSafely();\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\tround = NextGigPeriodInstance.round + 1\n\t\tactiveTime = GigPeriodInstance.activeTime + uint64(GigPeriodInterval)\n\t\t// keep the big period history for block validation.\n\t\tGigPeriodHistory[len(GigPeriodHistory)-1] = *NextGigPeriodInstance;\n\n\t\tGigPeriodInstance = &GigPeriodTable{\n\t\t\tNextGigPeriodInstance.round,\n\t\t\tNextGigPeriodInstance.state,\n\t\t\tNextGigPeriodInstance.delegatedNodes,\n\t\t\tNextGigPeriodInstance.delegatedNodesSign,\n\t\t\tNextGigPeriodInstance.confirmedTickets,\n\t\t\tNextGigPeriodInstance.confirmedBestNode,\n\t\t\tNextGigPeriodInstance.activeTime,\n\t\t};\n\t\tlog.Info(fmt.Sprintf(\"Switched the new big period round. %d \", GigPeriodInstance.round));\n\t}\n\n\t// make sure all delegators are synced at this round.\n\tNextGigPeriodInstance = &GigPeriodTable{\n\t\tround,\n\t\tSTATE_LOOKING,\n\t\tDelegatorsTable,\n\t\tSignCandidates(DelegatorsTable),\n\t\tmake(map[string]uint32),\n\t\tmake(map[string]*GigPeriodTable),\n\t\tactiveTime,\n\t};\n\tpm.trySyncAllDelegators()\n}", "func (_DelegationController *DelegationControllerCaller) Delegations(opts *bind.CallOpts, arg0 *big.Int) (struct {\n\tHolder common.Address\n\tValidatorId *big.Int\n\tAmount *big.Int\n\tDelegationPeriod *big.Int\n\tCreated *big.Int\n\tStarted *big.Int\n\tFinished *big.Int\n\tInfo string\n}, error) {\n\tret := new(struct {\n\t\tHolder common.Address\n\t\tValidatorId *big.Int\n\t\tAmount *big.Int\n\t\tDelegationPeriod *big.Int\n\t\tCreated *big.Int\n\t\tStarted *big.Int\n\t\tFinished *big.Int\n\t\tInfo string\n\t})\n\tout := ret\n\terr := _DelegationController.contract.Call(opts, out, \"delegations\", arg0)\n\treturn *ret, err\n}", "func (ac *Accumulator) WithTracking(max int) telegraf.TrackingAccumulator {\n\treturn &TrackingAccumulator{\n\t\tAccumulator: ac,\n\t\tdone: make(chan telegraf.DeliveryInfo, max),\n\t}\n}", "func (k Querier) Delegation(ctx context.Context, req *types.QueryDelegationRequest) (*types.QueryDelegationResponse, error) {\n\tif req == nil {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"empty request\")\n\t}\n\n\tif req.DelegatorAddr == \"\" {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"delegator address cannot be empty\")\n\t}\n\tif req.ValidatorAddr == \"\" {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"validator address cannot be empty\")\n\t}\n\n\tdelAddr, err := k.authKeeper.AddressCodec().StringToBytes(req.DelegatorAddr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvalAddr, err := k.validatorAddressCodec.StringToBytes(req.ValidatorAddr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdelegation, err := k.Delegations.Get(ctx, collections.Join(sdk.AccAddress(delAddr), sdk.ValAddress(valAddr)))\n\tif err != nil {\n\t\tif errors.Is(err, collections.ErrNotFound) {\n\t\t\treturn nil, status.Errorf(\n\t\t\t\tcodes.NotFound,\n\t\t\t\t\"delegation with delegator %s not found for validator %s\",\n\t\t\t\treq.DelegatorAddr, req.ValidatorAddr)\n\t\t}\n\t\treturn nil, status.Error(codes.Internal, err.Error())\n\t}\n\n\tdelResponse, err := delegationToDelegationResponse(ctx, k.Keeper, delegation)\n\tif err != nil {\n\t\treturn nil, status.Error(codes.Internal, err.Error())\n\t}\n\n\treturn &types.QueryDelegationResponse{DelegationResponse: &delResponse}, nil\n}", "func (_DelegationController *DelegationControllerCaller) DelegationsByHolder(opts *bind.CallOpts, arg0 common.Address, arg1 *big.Int) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _DelegationController.contract.Call(opts, out, \"delegationsByHolder\", arg0, arg1)\n\treturn *ret0, err\n}", "func (_DelegationController *DelegationControllerTransactorSession) AcceptPendingDelegation(delegationId *big.Int) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.AcceptPendingDelegation(&_DelegationController.TransactOpts, delegationId)\n}", "func TestApplyChangelistCreatesDelegation(t *testing.T) {\n\trepo, cs, err := testutils.EmptyRepo(\"docker.com/notary\")\n\trequire.NoError(t, err)\n\n\tnewKey, err := cs.Create(\"targets/level1\", \"docker.com/notary\", data.ED25519Key)\n\trequire.NoError(t, err)\n\n\terr = repo.UpdateDelegationKeys(\"targets/level1\", []data.PublicKey{newKey}, []string{}, 1)\n\trequire.NoError(t, err)\n\terr = repo.UpdateDelegationPaths(\"targets/level1\", []string{\"\"}, []string{}, false)\n\trequire.NoError(t, err)\n\tdelete(repo.Targets, \"targets/level1\")\n\n\thash := sha256.Sum256([]byte{})\n\tf := &data.FileMeta{\n\t\tLength: 1,\n\t\tHashes: map[string][]byte{\n\t\t\t\"sha256\": hash[:],\n\t\t},\n\t}\n\tfjson, err := json.Marshal(f)\n\trequire.NoError(t, err)\n\n\tcl := changelist.NewMemChangelist()\n\trequire.NoError(t, cl.Add(&changelist.TUFChange{\n\t\tActn: changelist.ActionCreate,\n\t\tRole: \"targets/level1\",\n\t\tChangeType: \"target\",\n\t\tChangePath: \"latest\",\n\t\tData: fjson,\n\t}))\n\n\trequire.NoError(t, applyChangelist(repo, nil, cl))\n\t_, ok := repo.Targets[\"targets/level1\"]\n\trequire.True(t, ok, \"Failed to create the delegation target\")\n\t_, ok = repo.Targets[\"targets/level1\"].Signed.Targets[\"latest\"]\n\trequire.True(t, ok, \"Failed to write change to delegation target\")\n}", "func CalculateRollSpillage(delegatedContracts []DelegatedContract, delegateAddr string, cycle int) ([]DelegatedContract, error) {\n stakingBalance, err := GetDelegateStakingBalance(delegateAddr, cycle)\n if (err != nil){\n return delegatedContracts, errors.New(\"func CalculateRollSpillage(delegatedContracts []DelegatedContract, delegateAddr string) failed: \" + err.Error())\n }\n\n mod := math.Mod(stakingBalance, 10000)\n sum := mod * 10000\n\n for index, delegatedContract := range delegatedContracts{\n for i, contract := range delegatedContract.Contracts{\n if (contract.Cycle == cycle){\n stakingBalance = stakingBalance - contract.Amount\n if (stakingBalance < 0){\n delegatedContracts[index].Contracts[i].SharePercentage = (contract.Amount - stakingBalance) / sum\n }\n }\n }\n }\n\n return delegatedContracts, nil\n}", "func (_Bep20 *Bep20Transactor) Delegate(opts *bind.TransactOpts, delegatee common.Address) (*types.Transaction, error) {\n\treturn _Bep20.contract.Transact(opts, \"delegate\", delegatee)\n}", "func (_Bep20 *Bep20Session) DelegateBySig(delegatee common.Address, nonce *big.Int, expiry *big.Int, v uint8, r [32]byte, s [32]byte) (*types.Transaction, error) {\n\treturn _Bep20.Contract.DelegateBySig(&_Bep20.TransactOpts, delegatee, nonce, expiry, v, r, s)\n}", "func (_DelegationController *DelegationControllerSession) AcceptPendingDelegation(delegationId *big.Int) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.AcceptPendingDelegation(&_DelegationController.TransactOpts, delegationId)\n}", "func UnmarshalDelegation(cdc *codec.Codec, key, value []byte) (delegation Delegation, err error) {\n\tvar storeValue delegationValue\n\terr = cdc.UnmarshalBinaryLengthPrefixed(value, &storeValue)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"%v: %v\", ErrNoDelegation(DefaultCodespace).Data(), err)\n\t\treturn\n\t}\n\n\taddrs := key[1:] // remove prefix bytes\n\tif len(addrs) != 2*sdk.AddrLen {\n\t\terr = fmt.Errorf(\"%v\", ErrBadDelegationAddr(DefaultCodespace).Data())\n\t\treturn\n\t}\n\n\tdelAddr := sdk.AccAddress(addrs[:sdk.AddrLen])\n\tvalAddr := sdk.ValAddress(addrs[sdk.AddrLen:])\n\n\treturn Delegation{\n\t\tDelegatorAddr: delAddr,\n\t\tValidatorAddr: valAddr,\n\t\tShares: storeValue.Shares,\n\t}, nil\n}", "func (_DelegationController *DelegationControllerSession) DelegationsByHolder(arg0 common.Address, arg1 *big.Int) (*big.Int, error) {\n\treturn _DelegationController.Contract.DelegationsByHolder(&_DelegationController.CallOpts, arg0, arg1)\n}", "func SendPayments() {\n\tif !checkConfigSharingRatio() {\n\t\tlogger.Fatal(\"Unable to calculcate.\")\n\t}\n\n\tpubKey := viper.GetString(\"delegate.pubkey\")\n\tif core.EnvironmentParams.Network.Type == core.DEVNET {\n\t\tpubKey = viper.GetString(\"delegate.Dpubkey\")\n\t}\n\n\tparams := core.DelegateQueryParams{PublicKey: pubKey}\n\tvar payload core.TransactionPayload\n\n\tvotersEarnings := arkclient.CalculateVotersProfit(params, viper.GetFloat64(\"voters.shareratio\"))\n\n\tsumEarned := 0.0\n\tsumRatio := 0.0\n\tsumShareEarned := 0.0\n\n\tp1, p2 := \"\", \"\"\n\tif _, err := os.Stat(\"/path/to/whatever\"); err == nil {\n\t\t// path/to/whatever exists\n\t} else {\n\t\tp1, p2 = readAccountData()\n\t}\n\n\tclearScreen()\n\n\tfor _, element := range votersEarnings {\n\t\tsumEarned += element.EarnedAmount100\n\t\tsumShareEarned += element.EarnedAmountXX\n\t\tsumRatio += element.VoteWeightShare\n\n\t\t//transaction parameters\n\t\ttxAmount2Send := int64(element.EarnedAmountXX*core.SATOSHI) - core.EnvironmentParams.Fees.Send\n\t\ttx := core.CreateTransaction(element.Address, txAmount2Send, viper.GetString(\"voters.txdescription\"), p1, p2)\n\n\t\tpayload.Transactions = append(payload.Transactions, tx)\n\t}\n\n\t//Cost & reserve fund calculation\n\tcostAmount := sumEarned * viper.GetFloat64(\"costs.shareratio\")\n\treserveAmount := sumEarned * viper.GetFloat64(\"reserve.shareratio\")\n\n\t//summary and conversion checks\n\tif (costAmount + reserveAmount + sumShareEarned) != sumEarned {\n\t\tcolor.Set(color.FgHiRed)\n\t\tlog.Println(\"Calculation of ratios NOT OK - overall summary failing\")\n\t\tlogger.Println(\"Calculation of ratios NOT OK - overall summary failing\")\n\t}\n\n\tcostAmount2Send := int64(costAmount*core.SATOSHI) - core.EnvironmentParams.Fees.Send\n\tcostAddress := viper.GetString(\"costs.address\")\n\tif core.EnvironmentParams.Network.Type == core.DEVNET {\n\t\tcostAddress = viper.GetString(\"costs.Daddress\")\n\t}\n\ttxCosts := core.CreateTransaction(costAddress, costAmount2Send, viper.GetString(\"costs.txdescription\"), p1, p2)\n\tpayload.Transactions = append(payload.Transactions, txCosts)\n\n\treserveAddress := viper.GetString(\"reserve.address\")\n\tif core.EnvironmentParams.Network.Type == core.DEVNET {\n\t\treserveAddress = viper.GetString(\"reserve.Daddress\")\n\t}\n\treserveAmount2Send := int64(reserveAmount*core.SATOSHI) - core.EnvironmentParams.Fees.Send\n\n\ttxReserve := core.CreateTransaction(reserveAddress, reserveAmount2Send, viper.GetString(\"reserve.txdescription\"), p1, p2)\n\tpayload.Transactions = append(payload.Transactions, txReserve)\n\n\tcolor.Set(color.FgHiGreen)\n\tfmt.Println(\"--------------------------------------------------------------------------------------------------------------\")\n\tfmt.Println(\"Transactions to be sent:\")\n\tfmt.Println(\"--------------------------------------------------------------------------------------------------------------\")\n\tcolor.Set(color.FgHiCyan)\n\tfor _, el := range payload.Transactions {\n\t\ts := fmt.Sprintf(\"|%s|%15d| %-40s|\", el.RecipientID, el.Amount, el.VendorField)\n\t\tfmt.Println(s)\n\t\tlogger.Println(s)\n\t}\n\n\tcolor.Set(color.FgHiYellow)\n\tfmt.Println(\"\")\n\tfmt.Println(\"--------------------------------------------------------------------------------------------------------------\")\n\tfmt.Print(\"Send transactions and complete reward payments [Y/N]: \")\n\n\tc, _ := reader.ReadByte()\n\n\tif c == []byte(\"Y\")[0] || c == []byte(\"y\")[0] {\n\t\tfmt.Println(\"Sending rewards to voters and sharing accounts.............\")\n\n\t\tres, httpresponse, err := arkclient.PostTransaction(payload)\n\t\tif res.Success {\n\t\t\tcolor.Set(color.FgHiGreen)\n\t\t\tlogger.Println(\"Transactions sent with Success,\", httpresponse.Status, res.TransactionIDs)\n\t\t\tlog.Println(\"Transactions sent with Success,\", httpresponse.Status)\n\t\t\tlog.Println(\"Audit log of sent transactions is in file paymentLog.csv!\")\n\t\t\tlog2csv(payload, res.TransactionIDs, votersEarnings)\n\t\t} else {\n\t\t\tcolor.Set(color.FgHiRed)\n\t\t\tlogger.Println(res.Message, res.Error, httpresponse.Status, err.Error())\n\t\t\tfmt.Println()\n\t\t\tfmt.Println(\"Failed\", res.Error)\n\t\t}\n\t\treader.ReadString('\\n')\n\t\tpause()\n\t}\n}", "func (_DelegationController *DelegationControllerRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.DelegationControllerTransactor.contract.Transfer(opts)\n}", "func (p *Protocol) NumCandidateDelegates() uint64 {\n\treturn p.numCandidateDelegates\n}", "func MustMarshalDelegation(cdc *codec.Codec, delegation Delegation) []byte {\n\tval := delegationValue{\n\t\tdelegation.Shares,\n\t}\n\treturn cdc.MustMarshalBinaryLengthPrefixed(val)\n}", "func StoreDelegationFromMessage(\n\theight int64, msg *stakingtypes.MsgDelegate, stakingClient stakingtypes.QueryClient, db *database.Db,\n) error {\n\theader := client.GetHeightRequestHeader(height)\n\tres, err := stakingClient.Delegation(\n\t\tcontext.Background(),\n\t\t&stakingtypes.QueryDelegationRequest{\n\t\t\tDelegatorAddr: msg.DelegatorAddress,\n\t\t\tValidatorAddr: msg.ValidatorAddress,\n\t\t},\n\t\theader,\n\t)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdelegation := ConvertDelegationResponse(height, *res.DelegationResponse)\n\treturn db.SaveDelegations([]types.Delegation{delegation})\n}", "func (_DelegationController *DelegationControllerTransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.contract.Transfer(opts)\n}", "func (s *ArkClient) GetDelegateVoteWeight(params DelegateQueryParams) (int, *http.Response, error) {\n\trespData := new(DelegateVoters)\n\trespError := new(ArkApiResponseError)\n\tresp, err := s.sling.New().Get(\"api/delegates/voters\").QueryStruct(&params).Receive(respData, respError)\n\tif err == nil {\n\t\terr = respError\n\t}\n\n\t//calculating vote weight\n\tbalance := 0\n\tif respData.Success {\n\t\tfor _, element := range respData.Accounts {\n\t\t\tintBalance, _ := strconv.Atoi(element.Balance)\n\t\t\tbalance += intBalance\n\t\t}\n\t}\n\n\treturn balance, resp, err\n}", "func (m *ParcelMock) DelegationTokenMinimockCounter() uint64 {\n\treturn atomic.LoadUint64(&m.DelegationTokenCounter)\n}", "func (_DelegationController *DelegationControllerTransactor) Confiscate(opts *bind.TransactOpts, validatorId *big.Int, amount *big.Int) (*types.Transaction, error) {\n\treturn _DelegationController.contract.Transact(opts, \"confiscate\", validatorId, amount)\n}", "func (_Bep20 *Bep20TransactorSession) DelegateBySig(delegatee common.Address, nonce *big.Int, expiry *big.Int, v uint8, r [32]byte, s [32]byte) (*types.Transaction, error) {\n\treturn _Bep20.Contract.DelegateBySig(&_Bep20.TransactOpts, delegatee, nonce, expiry, v, r, s)\n}", "func Transfer(\n\tctx *vm.Context, db vm.StateDB, sender, recipient types.AddressHash, amount *big.Int,\n) {\n\t// NOTE: amount is a re-used pointer varaible\n\tdb.SubBalance(sender, amount)\n\tdb.AddBalance(recipient, amount)\n\tif db.IsContractAddr(sender) && amount.Uint64() > 0 {\n\t\ttransferInfo := vm.NewTransferInfo(sender, recipient, amount.Uint64())\n\t\tlogger.Debugf(\"new transfer info: sender: %x, recipient: %x, amount: %d\",\n\t\t\tsender[:], recipient[:], amount)\n\t\tif v, ok := ctx.Transfers[sender]; ok {\n\t\t\t// if sender and recipient already exists in Transfers, update it instead\n\t\t\t// of append to it\n\t\t\tfor _, w := range v {\n\t\t\t\tif w.To == recipient {\n\t\t\t\t\t// NOTE: cannot miss 'w.value = '\n\t\t\t\t\tw.Value += amount.Uint64()\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tctx.Transfers[sender] = append(ctx.Transfers[sender], transferInfo)\n\t}\n}", "func (o *Member) SetDelegateCur(v int32) {\n\to.DelegateCur = &v\n}", "func (_DelegationController *DelegationControllerCallerSession) DelegationsByHolder(arg0 common.Address, arg1 *big.Int) (*big.Int, error) {\n\treturn _DelegationController.Contract.DelegationsByHolder(&_DelegationController.CallOpts, arg0, arg1)\n}", "func (vi *votedInfo) CalculateReward(multiplier, divider *big.Int, period int) {\n\tif multiplier.Sign() == 0 || period == 0 {\n\t\treturn\n\t}\n\tif divider.Sign() == 0 || vi.totalBondedDelegation.Sign() == 0 {\n\t\treturn\n\t}\n\t// reward = multiplier * period * bondedDelegation / (divider * totalBondedDelegation)\n\tbase := new(big.Int).Mul(multiplier, big.NewInt(int64(period)))\n\treward := new(big.Int)\n\tfor i, addrKey := range vi.rank {\n\t\tif i == vi.maxRankForReward {\n\t\t\tbreak\n\t\t}\n\t\tprep := vi.preps[addrKey]\n\t\tif prep.Enable() == false {\n\t\t\tcontinue\n\t\t}\n\n\t\treward.Mul(base, prep.GetBondedDelegation())\n\t\treward.Div(reward, divider)\n\t\treward.Div(reward, vi.totalBondedDelegation)\n\n\t\tlog.Tracef(\"VOTED REWARD %d = %d * %d * %d / (%d * %d)\",\n\t\t\treward, multiplier, period, prep.GetBondedDelegation(), divider, vi.totalBondedDelegation)\n\n\t\tprep.SetIScore(new(big.Int).Add(prep.IScore(), reward))\n\t}\n}", "func TestDonationCase1(t *testing.T) {\n\tassert := assert.New(t)\n\tstore := newReputationStoreOnMock()\n\trep := NewTestReputationImpl(store)\n\tt1 := time.Date(1995, time.February, 5, 11, 11, 0, 0, time.UTC)\n\tt3 := time.Date(1995, time.February, 6, 12, 11, 0, 0, time.UTC)\n\tt4 := time.Date(1995, time.February, 7, 13, 11, 1, 0, time.UTC)\n\tuser1 := \"user1\"\n\tpost1 := \"post1\"\n\tpost2 := \"post2\"\n\n\t// round 2\n\trep.Update(t1.Unix())\n\trep.DonateAt(user1, post1, big.NewInt(100*OneLinoCoin))\n\tassert.Equal(big.NewInt(100*OneLinoCoin), rep.store.GetRoundPostSumStake(2, post1))\n\tassert.Equal(rep.GetReputation(user1), big.NewInt(InitialCustomerScore))\n\tassert.Equal(big.NewInt(OneLinoCoin), rep.store.GetRoundSumDp(2)) // bounded by this user's dp\n\n\t// round 3\n\trep.Update(t3.Unix())\n\t// (1 * 9 + 100) / 10\n\tassert.Equal(big.NewInt(1090000), rep.GetReputation(user1))\n\tassert.Equal(big.NewInt(OneLinoCoin), rep.GetSumRep(post1))\n\trep.DonateAt(user1, post1, big.NewInt(1*OneLinoCoin)) // does not count\n\trep.DonateAt(user1, post2, big.NewInt(900*OneLinoCoin))\n\trep.Update(t4.Unix())\n\t// (10.9 * 9 + 900) / 10\n\tassert.Equal(big.NewInt(9981000), rep.GetReputation(user1))\n\tassert.Equal([]Pid{post2}, rep.store.GetRoundResult(3))\n\t// round 4\n}", "func (s *Streams) Delegate(data interface{}) {\n\tlisteners := s.Size()\n\n\tif listeners <= 0 {\n\t\treturn\n\t}\n\n\tif s.reverse {\n\t\ts.RevMunch(data)\n\t} else {\n\t\ts.Munch(data)\n\t}\n\n}", "func bindDelegationController(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) {\n\tparsed, err := abi.JSON(strings.NewReader(DelegationControllerABI))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn bind.NewBoundContract(address, parsed, caller, transactor, filterer), nil\n}", "func (_DelegationController *DelegationControllerSession) GetAndUpdateDelegatedAmount(holder common.Address) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.GetAndUpdateDelegatedAmount(&_DelegationController.TransactOpts, holder)\n}", "func CheckPercentageSumForCycle(cycle int, delegatedContracts []DelegatedContract) float64{\n var sum float64\n sum = 0\n for x := 0; x < len(delegatedContracts); x++{\n counter := 0\n for y := 0; y < len(delegatedContracts[x].Contracts); y++{\n if (delegatedContracts[x].Contracts[y].Cycle == cycle){\n break\n }\n counter = counter + 1\n }\n\n sum = sum + delegatedContracts[x].Contracts[counter].SharePercentage\n }\n return sum\n}" ]
[ "0.8186638", "0.78269565", "0.77586985", "0.77205014", "0.77158755", "0.765882", "0.6832526", "0.6124114", "0.5759102", "0.5743524", "0.55394906", "0.54927427", "0.5372109", "0.5255176", "0.51808655", "0.5126337", "0.5003338", "0.4969066", "0.48711935", "0.47619656", "0.47565082", "0.47423035", "0.47419503", "0.47156972", "0.4713995", "0.46757418", "0.46662575", "0.464224", "0.46361196", "0.4626242", "0.46208608", "0.46149158", "0.45703837", "0.4552948", "0.4539356", "0.4504784", "0.44947723", "0.44746554", "0.4446406", "0.4440518", "0.44160286", "0.44151652", "0.44142532", "0.44077742", "0.43870252", "0.4386496", "0.4385185", "0.43836138", "0.4369003", "0.43554905", "0.43516308", "0.4345447", "0.4342704", "0.43321013", "0.43252823", "0.43123925", "0.43054244", "0.43023154", "0.42974293", "0.42821792", "0.42672935", "0.4262207", "0.42567664", "0.42536753", "0.42323923", "0.42259842", "0.42140234", "0.42104757", "0.42011476", "0.4200735", "0.41951585", "0.41939312", "0.41914093", "0.41837692", "0.4168791", "0.4161268", "0.41429934", "0.4131476", "0.41207102", "0.41165742", "0.41090724", "0.40976712", "0.40954417", "0.40950072", "0.4082267", "0.4080457", "0.4074488", "0.40673217", "0.4067066", "0.40664452", "0.40586093", "0.40585405", "0.40520585", "0.4047957", "0.40449592", "0.40440315", "0.40412122", "0.40305102", "0.40282542", "0.40242052" ]
0.7899151
1
GetStartTime returns zero since a delayed vesting account has no start time.
func (dva DelayedVestingAccount) GetStartTime() int64 { return 0 }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (va ClawbackVestingAccount) GetStartTime() int64 {\n\treturn va.StartTime\n}", "func (cva ContinuousVestingAccount) GetStartTime() int64 {\n\treturn cva.StartTime\n}", "func (plva PermanentLockedAccount) GetStartTime() int64 {\n\treturn 0\n}", "func (pva PeriodicVestingAccount) GetStartTime() int64 {\n\treturn pva.StartTime\n}", "func GetStartTime() time.Time {\n\treturn startAtTime\n}", "func (txn TxnProbe) GetStartTime() time.Time {\n\treturn txn.startTime\n}", "func (o *ApplianceSetupInfoAllOf) GetStartTime() time.Time {\n\tif o == nil || o.StartTime == nil {\n\t\tvar ret time.Time\n\t\treturn ret\n\t}\n\treturn *o.StartTime\n}", "func (req *StartWFSRequest) GetStartTime() time.Time {\n\treturn req.StartTime\n}", "func (this *SyncFlightInfo) GetStartTime() time.Time {\n\tthis.lock.RLock()\n\tdefer this.lock.RUnlock()\n\treturn this.startTime\n}", "func (o *UcsdBackupInfoAllOf) GetStartTime() time.Time {\n\tif o == nil || o.StartTime == nil {\n\t\tvar ret time.Time\n\t\treturn ret\n\t}\n\treturn *o.StartTime\n}", "func (o *ApplianceClusterInstallPhase) GetStartTime() time.Time {\n\tif o == nil || o.StartTime == nil {\n\t\tvar ret time.Time\n\t\treturn ret\n\t}\n\treturn *o.StartTime\n}", "func (o *VirtualizationIweVirtualMachine) GetStartTime() string {\n\tif o == nil || o.StartTime == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.StartTime\n}", "func (o *WorkflowServiceItemActionInstance) GetStartTime() time.Time {\n\tif o == nil || o.StartTime == nil {\n\t\tvar ret time.Time\n\t\treturn ret\n\t}\n\treturn *o.StartTime\n}", "func (o *OnpremUpgradePhase) GetStartTime() time.Time {\n\tif o == nil || o.StartTime == nil {\n\t\tvar ret time.Time\n\t\treturn ret\n\t}\n\treturn *o.StartTime\n}", "func (v *Validator) StartTime() time.Time {\n\treturn time.Unix(int64(v.Start), 0)\n}", "func (f *Filler) StartTime() time.Time {\n\treturn f.tp\n}", "func (o *Job) GetStartTime(ctx context.Context) (startTime uint64, err error) {\n\terr = o.object.CallWithContext(ctx, \"org.freedesktop.DBus.Properties.Get\", 0, InterfaceJob, \"StartTime\").Store(&startTime)\n\treturn\n}", "func (c *Container) GetStartTime() time.Time {\n\treturn c.start\n}", "func (c *Context) StartTime() *time.Time {\n\treturn &c.startTime\n}", "func StartTime() time.Time {\n\treturn processStartTime\n}", "func (s *Session) GetStartTime() time.Time {\n\treturn s.started\n}", "func (gm GlobalManager) GetChainStartTime(ctx sdk.Context) (int64, sdk.Error) {\n\tglobalTime, err := gm.storage.GetGlobalTime(ctx)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn globalTime.ChainStartTime, nil\n}", "func (p *SASQueryParameters) StartTime() time.Time {\n\treturn p.startTime\n}", "func (o ElastigroupScheduledTaskOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ElastigroupScheduledTask) *string { return v.StartTime }).(pulumi.StringPtrOutput)\n}", "func (r *ScheduledAction) StartTime() pulumi.StringOutput {\n\treturn (pulumi.StringOutput)(r.s.State[\"startTime\"])\n}", "func (mgr *Manager) StartTime() time.Time {\n\treturn mgr.startTime\n}", "func (o GoogleCloudRetailV2alphaConditionTimeRangeOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v GoogleCloudRetailV2alphaConditionTimeRange) *string { return v.StartTime }).(pulumi.StringPtrOutput)\n}", "func (o BeanstalkScheduledTaskOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v BeanstalkScheduledTask) *string { return v.StartTime }).(pulumi.StringPtrOutput)\n}", "func (s *Storage) StartTime() (int64, error) {\n\treturn int64(model.Latest), nil\n}", "func (m *UserExperienceAnalyticsDeviceStartupHistory) GetStartTime()(*i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time) {\n val, err := m.GetBackingStore().Get(\"startTime\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time)\n }\n return nil\n}", "func (_LvRecording *LvRecordingCaller) StartTime(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _LvRecording.contract.Call(opts, &out, \"startTime\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (a *Auction) StartTime() time.Time {\n\treturn a.startTime\n}", "func (o *ProjectDeploymentRuleResponse) GetStartTime() time.Time {\n\tif o == nil || o.StartTime.Get() == nil {\n\t\tvar ret time.Time\n\t\treturn ret\n\t}\n\treturn *o.StartTime.Get()\n}", "func (req *ServerHTTPRequest) StartTime() time.Time {\n\treturn req.startTime\n}", "func (o ReservedInstanceOutput) StartTime() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *ReservedInstance) pulumi.StringOutput { return v.StartTime }).(pulumi.StringOutput)\n}", "func (instance *Instance) StartTime() time.Time {\n\tuptimeDuration := time.Duration(instance.Uptime) * time.Second\n\n\treturn time.Now().Add(-uptimeDuration)\n}", "func (b *fixedResolutionValues) StartTime() xtime.UnixNano {\n\treturn b.startTime\n}", "func (m *SimulationAutomationRun) GetStartDateTime()(*i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time) {\n val, err := m.GetBackingStore().Get(\"startDateTime\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time)\n }\n return nil\n}", "func (m *RequestSchedule) GetStartDateTime()(*i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time) {\n val, err := m.GetBackingStore().Get(\"startDateTime\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time)\n }\n return nil\n}", "func (m *GetSchedulePostRequestBody) GetStartTime()(iadcd81124412c61e647227ecfc4449d8bba17de0380ddda76f641a29edf2b242.DateTimeTimeZoneable) {\n return m.startTime\n}", "func (o GoogleCloudRetailV2alphaConditionTimeRangeResponseOutput) StartTime() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GoogleCloudRetailV2alphaConditionTimeRangeResponse) string { return v.StartTime }).(pulumi.StringOutput)\n}", "func (o DataTransferConfigScheduleOptionsPtrOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *DataTransferConfigScheduleOptions) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.StartTime\n\t}).(pulumi.StringPtrOutput)\n}", "func (o *ModelsBackupJobStatusResponse) GetStartTime() string {\n\tif o == nil || o.StartTime == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.StartTime\n}", "func (o TimelineOutput) StartTime() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v *Timeline) pulumi.IntPtrOutput { return v.StartTime }).(pulumi.IntPtrOutput)\n}", "func (m *ExternalActivity) GetStartDateTime()(*i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time) {\n val, err := m.GetBackingStore().Get(\"startDateTime\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time)\n }\n return nil\n}", "func (o InstanceMaintenanceWindowOutput) StartTime() InstanceMaintenanceWindowStartTimeOutput {\n\treturn o.ApplyT(func(v InstanceMaintenanceWindow) InstanceMaintenanceWindowStartTime { return v.StartTime }).(InstanceMaintenanceWindowStartTimeOutput)\n}", "func (o *WorkflowServiceItemActionInstance) GetStartTimeOk() (*time.Time, bool) {\n\tif o == nil || o.StartTime == nil {\n\t\treturn nil, false\n\t}\n\treturn o.StartTime, true\n}", "func (o InstanceMaintenanceScheduleOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v InstanceMaintenanceSchedule) *string { return v.StartTime }).(pulumi.StringPtrOutput)\n}", "func (o InstanceMaintenanceScheduleOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v InstanceMaintenanceSchedule) *string { return v.StartTime }).(pulumi.StringPtrOutput)\n}", "func (o DataTransferConfigScheduleOptionsOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v DataTransferConfigScheduleOptions) *string { return v.StartTime }).(pulumi.StringPtrOutput)\n}", "func (o *KubernetesPodStatus) GetStartTime() string {\n\tif o == nil || o.StartTime == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.StartTime\n}", "func StartTime() {\n\tstart = time.Now()\n}", "func (o LookupJobResultOutput) StartTime() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupJobResult) string { return v.StartTime }).(pulumi.StringOutput)\n}", "func (m *BookingWorkTimeSlot) GetStart()(*i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.TimeOnly) {\n val, err := m.GetBackingStore().Get(\"start\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.TimeOnly)\n }\n return nil\n}", "func (o ScanRunPtrOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ScanRun) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.StartTime\n\t}).(pulumi.StringPtrOutput)\n}", "func (o ScanRunPtrOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ScanRun) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.StartTime\n\t}).(pulumi.StringPtrOutput)\n}", "func (e *Event) StartTime() Time {\n\treturn e.start\n}", "func (o ResourcePolicyWeeklyCycleDayOfWeekOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ResourcePolicyWeeklyCycleDayOfWeek) *string { return v.StartTime }).(pulumi.StringPtrOutput)\n}", "func (o ScanRunOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ScanRun) *string { return v.StartTime }).(pulumi.StringPtrOutput)\n}", "func (o ScanRunOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ScanRun) *string { return v.StartTime }).(pulumi.StringPtrOutput)\n}", "func (o NodeGroupMaintenanceWindowPtrOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *NodeGroupMaintenanceWindow) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.StartTime\n\t}).(pulumi.StringPtrOutput)\n}", "func (o TriggerBuildArtifactsObjectsTimingOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v TriggerBuildArtifactsObjectsTiming) *string { return v.StartTime }).(pulumi.StringPtrOutput)\n}", "func (o ScanRunResponsePtrOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ScanRunResponse) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.StartTime\n\t}).(pulumi.StringPtrOutput)\n}", "func (m *MobileAppInstallTimeSettings) GetStartDateTime()(*i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time) {\n return m.startDateTime\n}", "func (o InstanceMaintenancePolicyWeeklyMaintenanceWindowOutput) StartTime() InstanceMaintenancePolicyWeeklyMaintenanceWindowStartTimeOutput {\n\treturn o.ApplyT(func(v InstanceMaintenancePolicyWeeklyMaintenanceWindow) InstanceMaintenancePolicyWeeklyMaintenanceWindowStartTime {\n\t\treturn v.StartTime\n\t}).(InstanceMaintenancePolicyWeeklyMaintenanceWindowStartTimeOutput)\n}", "func (o InstanceMaintenancePolicyWeeklyMaintenanceWindowOutput) StartTime() InstanceMaintenancePolicyWeeklyMaintenanceWindowStartTimeOutput {\n\treturn o.ApplyT(func(v InstanceMaintenancePolicyWeeklyMaintenanceWindow) InstanceMaintenancePolicyWeeklyMaintenanceWindowStartTime {\n\t\treturn v.StartTime\n\t}).(InstanceMaintenancePolicyWeeklyMaintenanceWindowStartTimeOutput)\n}", "func (o NodeGroupMaintenanceWindowOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v NodeGroupMaintenanceWindow) *string { return v.StartTime }).(pulumi.StringPtrOutput)\n}", "func (o ResourcePolicyDailyCycleOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ResourcePolicyDailyCycle) *string { return v.StartTime }).(pulumi.StringPtrOutput)\n}", "func (_LvRecordableStream *LvRecordableStreamCaller) StartTime(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _LvRecordableStream.contract.Call(opts, &out, \"startTime\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (o TriggerBuildArtifactsObjectsTimingPtrOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *TriggerBuildArtifactsObjectsTiming) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.StartTime\n\t}).(pulumi.StringPtrOutput)\n}", "func (o NodeGroupMaintenanceWindowResponseOutput) StartTime() pulumi.StringOutput {\n\treturn o.ApplyT(func(v NodeGroupMaintenanceWindowResponse) string { return v.StartTime }).(pulumi.StringOutput)\n}", "func determineStepStartTime(index int, running *corev1.ContainerStateRunning, terminated *corev1.ContainerStateTerminated, stageSteps []v1.CoreActivityStep) metav1.Time {\n\tvar startedAt metav1.Time\n\tif len(stageSteps) > 0 {\n\t\tpreviousStep := stageSteps[index-1]\n\t\tif previousStep.CompletedTimestamp != nil {\n\t\t\tstartedAt = *previousStep.CompletedTimestamp\n\t\t}\n\t} else {\n\t\tif running != nil {\n\t\t\tstartedAt = running.StartedAt\n\t\t} else if terminated != nil {\n\t\t\tstartedAt = terminated.StartedAt\n\t\t}\n\t}\n\treturn startedAt\n}", "func (o ResourcePolicyInstanceSchedulePolicyOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ResourcePolicyInstanceSchedulePolicy) *string { return v.StartTime }).(pulumi.StringPtrOutput)\n}", "func (o ScanRunResponseOutput) StartTime() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ScanRunResponse) string { return v.StartTime }).(pulumi.StringOutput)\n}", "func (o ScanRunResponseOutput) StartTime() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ScanRunResponse) string { return v.StartTime }).(pulumi.StringOutput)\n}", "func (o InstanceMaintenanceSchedulePtrOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *InstanceMaintenanceSchedule) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.StartTime\n\t}).(pulumi.StringPtrOutput)\n}", "func (m *MarketHoursMutation) StartTime() (r time.Time, exists bool) {\n\tv := m.start_time\n\tif v == nil {\n\t\treturn\n\t}\n\treturn *v, true\n}", "func (o NodeGroupMaintenanceWindowResponsePtrOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *NodeGroupMaintenanceWindowResponse) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.StartTime\n\t}).(pulumi.StringPtrOutput)\n}", "func (o *ApplianceSetupInfoAllOf) GetStartTimeOk() (*time.Time, bool) {\n\tif o == nil || o.StartTime == nil {\n\t\treturn nil, false\n\t}\n\treturn o.StartTime, true\n}", "func (n *ssvNode) getSlotStartTime(slot uint64) time.Time {\n\ttimeSinceGenesisStart := slot * uint64(n.ethNetwork.SlotDurationSec().Seconds())\n\tstart := time.Unix(int64(n.ethNetwork.MinGenesisTime()+timeSinceGenesisStart), 0)\n\treturn start\n}", "func (s JobStr) StartTime() (time.Time, error) {\n\tvar (\n\t\terr error\n\t\tres time.Time\n\t)\n\n\tif !strings.Contains(string(s), \"expect_cost:\") {\n\t\treturn res, nil\n\t}\n\n\titems := strings.Split(string(s), \" \")\n\tres, err = time.Parse(\"2006-01-02 15:04:05.999\", items[0]+\" \"+items[1])\n\tif err != nil {\n\t\tlogrus.Errorf(\"time.Parse err:%v\", err)\n\t\treturn res, err\n\t}\n\n\treturn res, err\n}", "func (f FakeContainerImpl) GetContainerStartTime(containerID string) (int64, error) {\n\tpanic(\"implement me\")\n}", "func (o *Run) GetStartedAt() time.Time {\n\tif o == nil || o.StartedAt == nil {\n\t\tvar ret time.Time\n\t\treturn ret\n\t}\n\treturn *o.StartedAt\n}", "func (o LicenseOutput) StartTime() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *License) pulumi.StringOutput { return v.StartTime }).(pulumi.StringOutput)\n}", "func (o *VirtualizationIweVirtualMachine) GetStartTimeOk() (*string, bool) {\n\tif o == nil || o.StartTime == nil {\n\t\treturn nil, false\n\t}\n\treturn o.StartTime, true\n}", "func (o RestoreResponseOutput) StartTime() pulumi.StringOutput {\n\treturn o.ApplyT(func(v RestoreResponse) string { return v.StartTime }).(pulumi.StringOutput)\n}", "func (o *ApplianceClusterInstallPhase) GetStartTimeOk() (*time.Time, bool) {\n\tif o == nil || o.StartTime == nil {\n\t\treturn nil, false\n\t}\n\treturn o.StartTime, true\n}", "func (q *Queries) EventStartTime(ctx context.Context, id models.EventID) (time.Time, error) {\n\tdefer daoSpan(&ctx)()\n\treturn q.dbc.EventStartTime(ctx, id)\n}", "func (o JobStatusPtrOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v JobStatus) *string { return v.StartTime }).(pulumi.StringPtrOutput)\n}", "func (o ResourcePolicyInstanceSchedulePolicyResponseOutput) StartTime() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ResourcePolicyInstanceSchedulePolicyResponse) string { return v.StartTime }).(pulumi.StringOutput)\n}", "func (o ResourcePolicyInstanceSchedulePolicyPtrOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ResourcePolicyInstanceSchedulePolicy) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.StartTime\n\t}).(pulumi.StringPtrOutput)\n}", "func (c *PurchasesVoidedpurchasesListCall) StartTime(startTime int64) *PurchasesVoidedpurchasesListCall {\n\tc.urlParams_.Set(\"startTime\", fmt.Sprint(startTime))\n\treturn c\n}", "func (o ResourcePolicyWeeklyCycleDayOfWeekResponseOutput) StartTime() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ResourcePolicyWeeklyCycleDayOfWeekResponse) string { return v.StartTime }).(pulumi.StringOutput)\n}", "func (o ResourcePolicyDailyCyclePtrOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ResourcePolicyDailyCycle) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.StartTime\n\t}).(pulumi.StringPtrOutput)\n}", "func (o StorageCapacityUnitOutput) StartTime() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *StorageCapacityUnit) pulumi.StringOutput { return v.StartTime }).(pulumi.StringOutput)\n}", "func (m TradingSessionStatus) GetTradSesStartTime() (v time.Time, err quickfix.MessageRejectError) {\n\tvar f field.TradSesStartTimeField\n\tif err = m.Get(&f); err == nil {\n\t\tv = f.Value()\n\t}\n\treturn\n}", "func (o JobStatusOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v JobStatus) *string { return v.StartTime }).(pulumi.StringPtrOutput)\n}", "func (m *Reminder) GetEventStartTime()(DateTimeTimeZoneable) {\n val, err := m.GetBackingStore().Get(\"eventStartTime\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(DateTimeTimeZoneable)\n }\n return nil\n}", "func (o BaselineStrategyOutput) StartTime() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *BaselineStrategy) pulumi.StringOutput { return v.StartTime }).(pulumi.StringOutput)\n}", "func (c *ClockVal) SetStartTime() {\n\tc.StartTime = NowTime()\n}" ]
[ "0.7676309", "0.75976443", "0.7532421", "0.75001425", "0.7361028", "0.725803", "0.72427595", "0.72406596", "0.7240466", "0.7142592", "0.7111448", "0.71034706", "0.7032013", "0.69124645", "0.6803729", "0.676755", "0.6750249", "0.673714", "0.6735365", "0.66810524", "0.6627456", "0.6623518", "0.661764", "0.6616669", "0.66084987", "0.65921056", "0.65798545", "0.65766674", "0.65366364", "0.6514673", "0.6498517", "0.6486444", "0.6486331", "0.6482464", "0.64746535", "0.6467476", "0.6467023", "0.643111", "0.6391722", "0.6346618", "0.6328201", "0.6314074", "0.6303125", "0.6300475", "0.6289709", "0.6268087", "0.6245478", "0.62251675", "0.62251675", "0.62184614", "0.62125194", "0.6199988", "0.6198418", "0.619083", "0.6190431", "0.6190431", "0.61902285", "0.6188928", "0.6188092", "0.6188092", "0.6185823", "0.6181068", "0.61711985", "0.6167747", "0.6165318", "0.6165318", "0.6161737", "0.61578035", "0.6156358", "0.61553764", "0.61531526", "0.61518294", "0.61506", "0.6143946", "0.6143946", "0.61425513", "0.61392117", "0.6134951", "0.612858", "0.61193174", "0.61175424", "0.6117436", "0.6104652", "0.6103719", "0.60948473", "0.6092323", "0.60905164", "0.6086741", "0.60821855", "0.60775286", "0.60721177", "0.60654944", "0.6042302", "0.6038304", "0.6017232", "0.60117686", "0.60107005", "0.6009796", "0.59994066", "0.5989888" ]
0.8550508
0
Validate checks for errors on the account fields
func (dva DelayedVestingAccount) Validate() error { return dva.BaseVestingAccount.Validate() }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (account *Account) Validate() (map[string]interface{}, bool) {\n\n\tif !strings.Contains(account.Phone, \"+\") {\n\t\treturn u.Message(false, \"Phone Number address is required\"), false\n\t}\n\n\tif len(account.UserName) < 3 {\n\t\treturn u.Message(false, \"Username is required\"), false\n\t}\n\n\t//PhoneNumber must be unique\n\ttemp := &Account{}\n\n\t//check for errors and duplicate phones\n\terr := GetDB().Table(\"accounts\").Where(\"phone = ?\", account.Phone).First(temp).Error\n\tif err != nil && err != gorm.ErrRecordNotFound {\n\t\treturn u.Message(false, \"Connection error. Please retry\"+err.Error()), false\n\t}\n\tif temp.Phone != \"\" {\n\t\treturn u.Message(false, \"Phone Number address already in use by another user.\"), false\n\t}\n\n\t//check for errors and duplicate username\n\terr = GetDB().Table(\"accounts\").Where(\"user_name = ?\", account.UserName).First(temp).Error\n\tif err != nil && err != gorm.ErrRecordNotFound {\n\t\treturn u.Message(false, \"Connection error. Please retry\"+err.Error()), false\n\t}\n\tif temp.UserName != \"\" {\n\t\tresponse := fmt.Sprintf(\"Username: %d is already in use by another user.\", account.UserName)\n\t\treturn u.Message(false, response), false\n\t}\n\n\treturn u.Message(false, \"Requirement passed\"), true\n}", "func (account Account) Validate() (map[string]interface{}, bool) {\n\n\tif !strings.Contains(account.Email, \"@\") {\n\t\treturn u.Message(false, ERROR_EMAIL), false\n\t}\n\n\tif len(account.Password) < 6 {\n\t\treturn u.Message(false, ERROR_PASSWORD_LENTH), false\n\t}\n\n\t// Email must be unique\n\ttemp := &Account{}\n\n\t// 数据类型合法时,查询数据表,GetDB return the configed db\n\terr := GetDB().Table(\"accounts\").Where(\"email = ?\", account.Email).First(temp).Error\n\tif err != nil && err != gorm.ErrRecordNotFound {\n\t\treturn u.Message(false, ERROR_CONNECTION), false\n\t}\n\t// 存在该email\n\tif temp.Email != \"\" {\n\t\treturn u.Message(false, ERROR_EMAIL_USED), false\n\t}\n\n\treturn u.Message(false, GET_SUCCESS), true\n}", "func (a Account) Validate() error {\n\treturn validation.ValidateStruct(&a,\n\t\tvalidation.Field(&a.Name, validation.Required, validation.Length(3, 75)),\n\t)\n}", "func (m *Account) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateAccountID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateAuditLogs(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateCurrency(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateParentAccountID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validatePaymentMethodID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateReferenceTime(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (account *Account) Validate() (map[string]interface{}, bool) {\n\n\tif !strings.Contains(account.Email, \"@\") {\n\t\treturn u.Message(false, \"Email address is required\"), false\n\t}\n\n\tif len(account.Password) < 6 {\n\t\treturn u.Message(false, \"Password is required\"), false\n\t}\n\n\t//Email must be unique\n\ttemp := &Account{}\n\t//check for errors and duplicate emails\n\terr := GetDB().Table(\"accounts\").Where(\"email = ?\", account.Email).First(temp).Error\n\tif err != nil && err != gorm.ErrRecordNotFound {\n\t\treturn u.Message(false, \"Connection error. Please retry\"), false\n\t}\n\tif temp.Email != \"\" {\n\t\treturn u.Message(false, \"Email address already in use by another user.\"), false\n\t}\n\treturn u.Message(false, \"Requirement passed\"), true\n}", "func (a *Account) Validate() error {\n\treturn nil\n}", "func (mt *Account) Validate() (err error) {\n\tif mt.ID == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`response`, \"id\"))\n\t}\n\tif mt.Password == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`response`, \"password\"))\n\t}\n\n\treturn\n}", "func (accountInfo *AccountInfo) Validate() error {\n\taccountSchema, _ := GetAccountSchema(accountInfo.Domain)\n\tif accountSchema == nil {\n\t\treturn errors.New(\"schema undefined for domain \" + accountInfo.Domain)\n\t}\n\n\t// Group\n\tif !accountSchema.IsGroupExist(accountInfo.Group) {\n\t\treturn errors.New(\"unknown group \" + accountInfo.Group)\n\t}\n\n\t// UserID\n\tif accountInfo.Uid == \"\" {\n\t\treturn errors.New(\"uid can not be empty\")\n\t}\n\n\t// LoginIDs\n\tif len(accountInfo.LoginIDs) == 0 {\n\t\treturn errors.New(\"should have at least one login id\")\n\t}\n\trequiredIDs := accountSchema.getRequiredLogIDs()\n\tfor _, requiredID := range requiredIDs {\n\t\tif _, ok := accountInfo.LoginIDs[requiredID]; !ok {\n\t\t\treturn errors.New(\"login id:\" + requiredID + \" is required but not specified\")\n\t\t}\n\t}\n\tfor k, v := range accountInfo.LoginIDs {\n\t\tloginIDSchema, _ := accountSchema.GetLoginIDSchema(k)\n\t\tif loginIDSchema == nil {\n\t\t\treturn errors.New(\"login id schema for \" + k + \" is not defined\")\n\t\t} else {\n\t\t\tif !loginIDSchema.NeedVerified {\n\t\t\t\tv.Verified = true\n\t\t\t\t// accountInfo.LoginIDs[k] = v\n\t\t\t}\n\t\t\tif !loginIDSchema.Validator.Validate(v.ID) {\n\t\t\t\treturn errors.New(\"invalid format of login id \" + k + \":\" + v.ID)\n\t\t\t}\n\t\t}\n\t}\n\n\t// options\n\toptionsMap := mergeMaps(accountInfo.Profiles, accountInfo.Others)\n\trequiredOptions := accountSchema.getRequiredOptions()\n\tfor _, requiredOption := range requiredOptions {\n\t\tif _, ok := optionsMap[requiredOption]; !ok {\n\t\t\treturn errors.New(\"option:\" + requiredOption + \" is required but not specified\")\n\t\t}\n\t}\n\n\tfor k, v := range optionsMap {\n\t\toptionSchema, _ := accountSchema.GetOptionSchema(k)\n\t\tif optionSchema == nil {\n\t\t\treturn errors.New(\"option schema for \" + k + \" is not defined\")\n\t\t} else {\n\t\t\tif !optionSchema.Validator.Validate(v) {\n\t\t\t\treturn errors.New(\"invalid format of option \" + k)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func (mt *Account) Validate() (err error) {\n\n\tif mt.Href == \"\" {\n\t\terr = goa.MissingAttributeError(`response`, \"href\", err)\n\t}\n\tif mt.Name == \"\" {\n\t\terr = goa.MissingAttributeError(`response`, \"name\", err)\n\t}\n\n\tif mt.CreatedAt != nil {\n\t\tif err2 := goa.ValidateFormat(goa.FormatDateTime, *mt.CreatedAt); err2 != nil {\n\t\t\terr = goa.InvalidFormatError(`response.created_at`, *mt.CreatedAt, goa.FormatDateTime, err2, err)\n\t\t}\n\t}\n\tif mt.CreatedBy != nil {\n\t\tif err2 := goa.ValidateFormat(goa.FormatEmail, *mt.CreatedBy); err2 != nil {\n\t\t\terr = goa.InvalidFormatError(`response.created_by`, *mt.CreatedBy, goa.FormatEmail, err2, err)\n\t\t}\n\t}\n\treturn\n}", "func (c *modAccountRun) validate(args []string) error {\n\tif len(args) < 2 {\n\t\treturn errors.New(\"not enough arguments\")\n\t}\n\n\tif len(args) > 2 {\n\t\treturn errors.New(\"too many arguments\")\n\t}\n\n\treturn nil\n}", "func (m *LedgerAccount) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateAccount(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateCurrency(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validatePostings(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (b *OGame) ValidateAccount(code string) error {\n\treturn b.validateAccount(code)\n}", "func (ut *accountInputPayload) Validate() (err error) {\n\tif ut.Email != nil {\n\t\tif err2 := goa.ValidateFormat(goa.FormatEmail, *ut.Email); err2 != nil {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidFormatError(`response.email`, *ut.Email, goa.FormatEmail, err2))\n\t\t}\n\t}\n\tif ut.Name != nil {\n\t\tif utf8.RuneCountInString(*ut.Name) < 1 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`response.name`, *ut.Name, utf8.RuneCountInString(*ut.Name), 1, true))\n\t\t}\n\t}\n\tif ut.Name != nil {\n\t\tif utf8.RuneCountInString(*ut.Name) > 30 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`response.name`, *ut.Name, utf8.RuneCountInString(*ut.Name), 30, false))\n\t\t}\n\t}\n\tif ut.Surname != nil {\n\t\tif utf8.RuneCountInString(*ut.Surname) < 1 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`response.surname`, *ut.Surname, utf8.RuneCountInString(*ut.Surname), 1, true))\n\t\t}\n\t}\n\tif ut.Surname != nil {\n\t\tif utf8.RuneCountInString(*ut.Surname) > 30 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`response.surname`, *ut.Surname, utf8.RuneCountInString(*ut.Surname), 30, false))\n\t\t}\n\t}\n\treturn\n}", "func (account *Account) ValidateUpdate() (map[string]interface{}, bool) {\n\n\tif !strings.Contains(account.Email, \"@\") {\n\t\treturn u.Message(false, \"Email address is required\"), false\n\t}\n\n\tif len(account.Password) < 6 {\n\t\treturn u.Message(false, \"Password is required\"), false\n\t}\n\n\t//Email must be unique\n\ttemp := &Account{}\n\t//check for errors and duplicate emails\n\terr := GetDB().Table(\"accounts\").Where(\"email = ?\", account.Email).First(temp).Error\n\tif err != nil && err != gorm.ErrRecordNotFound {\n\t\treturn u.Message(false, \"Connection error. Please retry\"), false\n\t}\n\tif temp.Email == \"\" {\n\t\treturn u.Message(false, \"Email address not found in database.\"), false\n\t}\n\treturn u.Message(true, \"Requirement passed\"), true\n}", "func (ut *AccountInputPayload) Validate() (err error) {\n\tif ut.Email != nil {\n\t\tif err2 := goa.ValidateFormat(goa.FormatEmail, *ut.Email); err2 != nil {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidFormatError(`response.email`, *ut.Email, goa.FormatEmail, err2))\n\t\t}\n\t}\n\tif ut.Name != nil {\n\t\tif utf8.RuneCountInString(*ut.Name) < 1 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`response.name`, *ut.Name, utf8.RuneCountInString(*ut.Name), 1, true))\n\t\t}\n\t}\n\tif ut.Name != nil {\n\t\tif utf8.RuneCountInString(*ut.Name) > 30 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`response.name`, *ut.Name, utf8.RuneCountInString(*ut.Name), 30, false))\n\t\t}\n\t}\n\tif ut.Surname != nil {\n\t\tif utf8.RuneCountInString(*ut.Surname) < 1 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`response.surname`, *ut.Surname, utf8.RuneCountInString(*ut.Surname), 1, true))\n\t\t}\n\t}\n\tif ut.Surname != nil {\n\t\tif utf8.RuneCountInString(*ut.Surname) > 30 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`response.surname`, *ut.Surname, utf8.RuneCountInString(*ut.Surname), 30, false))\n\t\t}\n\t}\n\treturn\n}", "func ValidateAccount(client httpclient.IHttpClient, ctx context.Context, lobby, code string) error {\n\tif len(code) != 36 {\n\t\treturn errors.New(\"invalid validation code\")\n\t}\n\treq, err := http.NewRequest(http.MethodPut, \"https://\"+lobby+\".ogame.gameforge.com/api/users/validate/\"+code, strings.NewReader(`{\"language\":\"en\"}`))\n\tif err != nil {\n\t\treturn err\n\t}\n\treq.WithContext(ctx)\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\treturn nil\n}", "func (b *Builder) Validate() (*Account, error) {\n\tb.validate.SetTagName(b.essential.Country)\n\tif err := validateStruct(b.validate, b.essential); err != nil {\n\t\treturn nil, err\n\t}\n\tb.validate.SetTagName(\"validate\")\n\tif err := validateStruct(b.validate, b.essential); err != nil {\n\t\treturn nil, err\n\t}\n\tif err := validateStruct(b.validate, b.optional); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Account{\n\t\tid: b.essential.ID,\n\t\torganizationID: b.essential.OrganizationID,\n\t\tversionIndex: b.optional.VersionIndex,\n\t\tcountry: b.essential.Country,\n\t\tbankIDCode: b.essential.BankIDCode,\n\t\tbankID: b.essential.BankID,\n\t\tbic: b.essential.Bic,\n\t\tiban: b.essential.Iban,\n\t\tbaseCurrency: b.optional.BaseCurrency,\n\t\taccountNumber: b.optional.AccountNumber,\n\t\tcustomerID: b.optional.CustomerID,\n\t\ttitle: b.optional.Title,\n\t\tfirstName: b.optional.FirstName,\n\t\tbankAccountName: b.optional.BankAccountName,\n\t\taltBankAccountNames: b.optional.AltBankAccountNames,\n\t\taccountClassification: b.optional.AccountClassification,\n\t\tjointAccount: b.optional.JointAccount,\n\t\taccountMatchingOptOut: b.optional.AccountMatchingOptOut,\n\t\tsecondaryIdentification: b.optional.SecondaryIdentification,\n\t}, nil\n}", "func (a *Account) Validate() error {\n\tvalidate := validator.New()\n\treturn validate.Struct(a)\n}", "func (ga GenesisAccount) Validate() error {\n\tif ethermint.IsZeroAddress(ga.Address) {\n\t\treturn fmt.Errorf(\"address cannot be the zero address %s\", ga.Address)\n\t}\n\tif len(ethcmn.Hex2Bytes(ga.Code)) == 0 {\n\t\treturn errors.New(\"code cannot be empty\")\n\t}\n\n\treturn ga.Storage.Validate()\n}", "func validate(user *customer_api.DbUser, allowEmpty bool) error {\n\tconst minNameLength, maxNameLength = 3, 20\n\tconst emailRegexString = \"^[a-zA-Z0-9+_.-]+@[a-zA-Z0-9.-]+$\"\n\tvar emailRegex = regexp.MustCompile(emailRegexString)\n\n\tif !(allowEmpty && user.Email == \"\") {\n\t\tif len(user.Email) < 5 || !emailRegex.MatchString(user.Email) {\n\t\t\treturn errors.New(\"invalid email\")\n\t\t}\n\t}\n\n\tif !(allowEmpty && user.FirstName == \"\") {\n\t\tif len(user.FirstName) < minNameLength || len(user.FirstName) > maxNameLength {\n\t\t\treturn errors.New(\"first_name should be between 3 and 20 characters\")\n\t\t}\n\t}\n\n\tif !(allowEmpty && user.LastName == \"\") {\n\t\tif len(user.LastName) < minNameLength || len(user.LastName) > maxNameLength {\n\t\t\treturn errors.New(\"last_name should be between 3 and 20 characters\")\n\t\t}\n\t}\n\n\tif !(allowEmpty && user.Phone == 0) {\n\t\tif user.Phone < 1000000000 || user.Phone > 9999999999 {\n\t\t\treturn errors.New(\"invalid phone no\")\n\t\t}\n\t}\n\n\tif !(allowEmpty && user.Id == \"\") {\n\t\tif user.Id == \"\" {\n\t\t\treturn errors.New(\"id cannot be empty\")\n\t\t}\n\t}\n\treturn nil\n}", "func (server *Server) checkValidAccount(ctx *gin.Context, id int64, curr string) (bool, db.Account) {\n\tacc, err := server.repository.GetAccount(ctx, id)\n\tif err != nil {\n\t\tctx.JSON(http.StatusNotFound, errorResponse(err))\n\t\treturn false, db.Account{}\n\t}\n\tif acc.Currency != curr {\n\t\terr = fmt.Errorf(\"invalid currency for account [%d]: expected %s received %s\", acc.ID, acc.Currency, curr)\n\t\tctx.JSON(http.StatusBadRequest, errorResponse(err))\n\t\treturn false, db.Account{}\n\t}\n\n\treturn true, acc\n}", "func (mt *EasypostCarrierAccounts) Validate() (err error) {\n\tif mt.ID == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`response`, \"id\"))\n\t}\n\tif mt.Object == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`response`, \"object\"))\n\t}\n\n\tif ok := goa.ValidatePattern(`^CarrierAccount$`, mt.Object); !ok {\n\t\terr = goa.MergeErrors(err, goa.InvalidPatternError(`response.object`, mt.Object, `^CarrierAccount$`))\n\t}\n\treturn\n}", "func (m *InfrastructureAccount) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateCostCenter(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateCriticalityLevel(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateEnvironment(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateExternalID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateLifecycleStatus(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateName(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateOwner(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateType(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (m *CloudAccountExtended) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\t// validation for a type composition with CloudAccount\n\tif err := m.CloudAccount.Validate(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateState(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateType(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (a *Account) Validate() error {\n\terr := validation.ValidateStruct(a,\n\t\tvalidation.Field(&a.AdminRoleArn, validateAdminRoleArn...),\n\t\tvalidation.Field(&a.ID, validateID...),\n\t\tvalidation.Field(&a.LastModifiedOn, validateInt64...),\n\t\tvalidation.Field(&a.Status, validateStatus...),\n\t\tvalidation.Field(&a.CreatedOn, validateInt64...),\n\t\tvalidation.Field(&a.PrincipalRoleArn, validatePrincipalRoleArn...),\n\t\tvalidation.Field(&a.PrincipalPolicyHash, validatePrincipalPolicyHash...),\n\t)\n\tif err != nil {\n\t\treturn errors.NewValidation(\"account\", err)\n\t}\n\treturn nil\n}", "func validRawAccount(accountName string) error {\n\t// param absence check\n\tif accountName == \"\" {\n\t\treturn fmt.Errorf(\"invoke NewAccount failed, account name is empty\")\n\t}\n\n\t// account naming rule check\n\tif len(accountName) != accountSize {\n\t\treturn fmt.Errorf(\"invoke NewAccount failed, account name length expect %d, actual: %d\", accountSize, len(accountName))\n\t}\n\n\tfor i := 0; i < accountSize; i++ {\n\t\tif accountName[i] >= '0' && accountName[i] <= '9' {\n\t\t\tcontinue\n\t\t} else {\n\t\t\treturn fmt.Errorf(\"invoke NewAccount failed, account name expect continuous %d number\", accountSize)\n\t\t}\n\t}\n\n\treturn nil\n}", "func (o *CloudSnapshotAccount) Validate() error {\n\n\terrors := elemental.Errors{}\n\trequiredErrors := elemental.Errors{}\n\n\tif err := ValidateTagsWithoutReservedPrefixes(\"associatedTags\", o.AssociatedTags); err != nil {\n\t\terrors = errors.Append(err)\n\t}\n\n\tif err := elemental.ValidateStringInList(\"cloudType\", string(o.CloudType), []string{\"AWS\", \"GCP\"}, false); err != nil {\n\t\terrors = errors.Append(err)\n\t}\n\n\tif len(requiredErrors) > 0 {\n\t\treturn requiredErrors\n\t}\n\n\tif len(errors) > 0 {\n\t\treturn errors\n\t}\n\n\treturn nil\n}", "func (m *ProviderAccountRequest) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateDataset(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateDatasetName(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateField(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validatePreferences(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (uu *UserUpdate) check() error {\n\tif v, ok := uu.mutation.AccountName(); ok {\n\t\tif err := user.AccountNameValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"account_name\", err: fmt.Errorf(\"ent: validator failed for field \\\"account_name\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.StaffType(); ok {\n\t\tif err := user.StaffTypeValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"staff_type\", err: fmt.Errorf(\"ent: validator failed for field \\\"staff_type\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.FamilyName(); ok {\n\t\tif err := user.FamilyNameValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"family_name\", err: fmt.Errorf(\"ent: validator failed for field \\\"family_name\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.GivenName(); ok {\n\t\tif err := user.GivenNameValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"given_name\", err: fmt.Errorf(\"ent: validator failed for field \\\"given_name\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.DisplayName(); ok {\n\t\tif err := user.DisplayNameValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"display_name\", err: fmt.Errorf(\"ent: validator failed for field \\\"display_name\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.IDNumber(); ok {\n\t\tif err := user.IDNumberValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"id_number\", err: fmt.Errorf(\"ent: validator failed for field \\\"id_number\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.Sex(); ok {\n\t\tif err := user.SexValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"sex\", err: fmt.Errorf(\"ent: validator failed for field \\\"sex\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.PhoneNumber(); ok {\n\t\tif err := user.PhoneNumberValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"phone_number\", err: fmt.Errorf(\"ent: validator failed for field \\\"phone_number\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.Address(); ok {\n\t\tif err := user.AddressValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"address\", err: fmt.Errorf(\"ent: validator failed for field \\\"address\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.StaffID(); ok {\n\t\tif err := user.StaffIDValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"staff_id\", err: fmt.Errorf(\"ent: validator failed for field \\\"staff_id\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.PersonalEmail(); ok {\n\t\tif err := user.PersonalEmailValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"personal_email\", err: fmt.Errorf(\"ent: validator failed for field \\\"personal_email\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.IntranetWorkEmail(); ok {\n\t\tif err := user.IntranetWorkEmailValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"intranet_work_email\", err: fmt.Errorf(\"ent: validator failed for field \\\"intranet_work_email\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.ExtranetWorkEmail(); ok {\n\t\tif err := user.ExtranetWorkEmailValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"extranet_work_email\", err: fmt.Errorf(\"ent: validator failed for field \\\"extranet_work_email\\\": %w\", err)}\n\t\t}\n\t}\n\treturn nil\n}", "func (profileImport *ProfileImportRequest) Validate(tx *sql.Tx) error {\n\n\tprofile := profileImport.Profile\n\n\t// Profile fields are valid\n\terrs := tovalidate.ToErrors(validation.Errors{\n\t\t\"name\": validation.Validate(profile.Name, validation.By(\n\t\t\tfunc(value interface{}) error {\n\t\t\t\tname, ok := value.(*string)\n\t\t\t\tif !ok {\n\t\t\t\t\treturn fmt.Errorf(\"wrong type, need: string, got: %T\", value)\n\t\t\t\t}\n\t\t\t\tif name == nil || *name == \"\" {\n\t\t\t\t\treturn errors.New(\"required and cannot be blank\")\n\t\t\t\t}\n\t\t\t\tif strings.Contains(*name, \" \") {\n\t\t\t\t\treturn errors.New(\"cannot contain spaces\")\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t},\n\t\t)),\n\t\t\"description\": validation.Validate(profile.Description, validation.Required),\n\t\t\"cdnName\": validation.Validate(profile.CDNName, validation.Required),\n\t\t\"type\": validation.Validate(profile.Type, validation.Required),\n\t})\n\n\t// Validate CDN exist\n\tif profile.CDNName != nil {\n\t\tif ok, err := CDNExistsByName(*profile.CDNName, tx); err != nil {\n\t\t\terrString := fmt.Sprintf(\"checking cdn name %v existence\", *profile.CDNName)\n\t\t\tlog.Errorf(\"%v: %v\", errString, err.Error())\n\t\t\terrs = append(errs, errors.New(errString))\n\t\t} else if !ok {\n\t\t\terrs = append(errs, fmt.Errorf(\"%v CDN does not exist\", *profile.CDNName))\n\t\t}\n\t}\n\n\t// Validate profile does not already exist\n\tif profile.Name != nil {\n\t\tif ok, err := ProfileExistsByName(*profile.Name, tx); err != nil {\n\t\t\terrString := fmt.Sprintf(\"checking profile name %v existence\", *profile.Name)\n\t\t\tlog.Errorf(\"%v: %v\", errString, err.Error())\n\t\t\terrs = append(errs, errors.New(errString))\n\t\t} else if ok {\n\t\t\terrs = append(errs, fmt.Errorf(\"a profile with the name \\\"%s\\\" already exists\", *profile.Name))\n\t\t}\n\t}\n\n\t// Validate all parameters\n\t// export/import does not include secure flag\n\t// default value to not flag on validation\n\tsecure := 1\n\tfor i, pp := range profileImport.Parameters {\n\t\tif ppErrs := validateProfileParamPostFields(pp.ConfigFile, pp.Name, pp.Value, &secure); len(ppErrs) > 0 {\n\t\t\tfor _, err := range ppErrs {\n\t\t\t\terrs = append(errs, errors.New(\"parameter \"+strconv.Itoa(i)+\": \"+err.Error()))\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(errs) > 0 {\n\t\treturn util.JoinErrs(errs)\n\t}\n\n\treturn nil\n}", "func (u *Usecase) validFields(d *Device) error {\n\tif d.Name == \"\" {\n\t\treturn &InvalidError{\"attribute `Name` must not be empty\"}\n\t}\n\n\tif d.User == 0 {\n\t\treturn &InvalidError{\"invalid user\"}\n\t}\n\n\treturn nil\n}", "func (t *TokenAccount) Validate() error {\n\tv := validator.New()\n\terr := v.RegisterValidation(\"notblank\", validators.NotBlank)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = v.RegisterValidation(\"notall\", validation.NotAll)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn v.Struct(t)\n}", "func (v *Reg) Validate(ctx context.Context, f *reg.Form) error {\n\tvar es Errors\n\n\tif err := validation.Validate(f.Email, validation.Required, is.Email); err != nil {\n\t\tes = append(es, Error{\n\t\t\tField: \"email\",\n\t\t\tMessage: err.Error(),\n\t\t})\n\t}\n\n\tif err := validation.Validate(f.AccountID, validation.Required); err != nil {\n\t\tes = append(es, Error{\n\t\t\tField: \"account_id\",\n\t\t\tMessage: err.Error(),\n\t\t})\n\t}\n\n\tif err := v.Uniquer.Unique(ctx, f.Email); err != nil {\n\t\tswitch errors.Cause(err) {\n\t\tcase reg.ErrEmailExists:\n\t\t\tes = append(es, Error{\n\t\t\t\tField: \"email\",\n\t\t\t\tMessage: err.Error(),\n\t\t\t})\n\t\tdefault:\n\t\t\treturn errors.Wrap(err, \"unique\")\n\t\t}\n\t}\n\n\tfmt.Println(f.Password, f.PasswordConfirmation)\n\n\tif err := validation.Validate(f.Password, validation.Required, validation.Length(6, 32)); err != nil {\n\t\tes = append(es, Error{\n\t\t\tField: \"password\",\n\t\t\tMessage: err.Error(),\n\t\t})\n\t}\n\n\tif err := validation.Validate(f.PasswordConfirmation, validation.Required, validation.Length(6, 32)); err != nil {\n\t\tes = append(es, Error{\n\t\t\tField: \"password_confirmation\",\n\t\t\tMessage: err.Error(),\n\t\t})\n\t}\n\n\tif f.Password != f.PasswordConfirmation {\n\t\tes = append(es, Error{\n\t\t\tField: \"password_confirmation\",\n\t\t\tMessage: \"mismatch\",\n\t\t}, Error{\n\t\t\tField: \"password\",\n\t\t\tMessage: \"mismatch\",\n\t\t})\n\t}\n\n\tif len(es) > 0 {\n\t\treturn es\n\t}\n\n\treturn nil\n}", "func validateAccountName(accountName string) (string, error) {\n\treturn accountName, nil\n}", "func (rcv *controller) validate() error {\n\n\tif err := rcv.read(); err != nil {\n\t\treturn err\n\t}\n\n\t// If account does not exists\n\tif rcv.store.Email == \"\" {\n\t\treturn errors.New(rcv.Translate(\"text11\"))\n\t}\n\n\t// If time for activating account is expired\n\tif time.Now().Unix() > rcv.store.Expired {\n\t\t// Delete registered user from neo4j\n\t\tmaccount.Delete(rcv.store.Email, rcv.Local)\n\t\treturn &expiredError{rcv.Controller}\n\t}\n\n\treturn nil\n}", "func (acc *AccessControlCreate) check() error {\n\tif _, ok := acc.mutation.ServiceID(); !ok {\n\t\treturn &ValidationError{Name: \"service_id\", err: errors.New(\"ent: missing required field \\\"service_id\\\"\")}\n\t}\n\tif _, ok := acc.mutation.OpenAuth(); !ok {\n\t\treturn &ValidationError{Name: \"open_auth\", err: errors.New(\"ent: missing required field \\\"open_auth\\\"\")}\n\t}\n\tif _, ok := acc.mutation.BlackList(); !ok {\n\t\treturn &ValidationError{Name: \"black_list\", err: errors.New(\"ent: missing required field \\\"black_list\\\"\")}\n\t}\n\tif _, ok := acc.mutation.WhiteList(); !ok {\n\t\treturn &ValidationError{Name: \"white_list\", err: errors.New(\"ent: missing required field \\\"white_list\\\"\")}\n\t}\n\tif _, ok := acc.mutation.WhiteHostName(); !ok {\n\t\treturn &ValidationError{Name: \"white_host_name\", err: errors.New(\"ent: missing required field \\\"white_host_name\\\"\")}\n\t}\n\tif _, ok := acc.mutation.ClientipFlowLimit(); !ok {\n\t\treturn &ValidationError{Name: \"clientip_flow_limit\", err: errors.New(\"ent: missing required field \\\"clientip_flow_limit\\\"\")}\n\t}\n\tif _, ok := acc.mutation.ServiceFlowLimit(); !ok {\n\t\treturn &ValidationError{Name: \"service_flow_limit\", err: errors.New(\"ent: missing required field \\\"service_flow_limit\\\"\")}\n\t}\n\treturn nil\n}", "func (u *User) Validate(tx *pop.Connection) (*validate.Errors, error) {\n\tvar err error\n\t//validate based on is agent\n\tif !u.IsAgent { //is not an agent\n\t\treturn validate.Validate(\n\t\t\t&validators.StringIsPresent{Field: u.Email, Name: \"Email\"},\n\t\t\t&validators.StringIsPresent{Field: u.PasswordHash, Name: \"PasswordHash\"},\n\t\t\t&validators.StringIsPresent{Field: u.LastName, Name: \"LastName\"},\n\t\t\t&validators.StringIsPresent{Field: u.FirstName, Name: \"FirstName\"},\n\t\t\t&validators.StringIsPresent{Field: u.Phone, Name: \"Phone\"},\n\t\t\t// check to see if the email address is already taken:\n\t\t\t&validators.FuncValidator{\n\t\t\t\tField: u.Email,\n\t\t\t\tName: \"Email\",\n\t\t\t\tMessage: \"%s is already taken\",\n\t\t\t\tFn: func() bool {\n\t\t\t\t\tvar b bool\n\t\t\t\t\tq := tx.Where(\"email = ?\", u.Email)\n\t\t\t\t\tif u.ID != uuid.Nil {\n\t\t\t\t\t\tq = q.Where(\"id != ?\", u.ID)\n\t\t\t\t\t}\n\t\t\t\t\tb, err = q.Exists(u)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn false\n\t\t\t\t\t}\n\t\t\t\t\treturn !b\n\t\t\t\t},\n\t\t\t},\n\t\t), err\n\n\t} else { // trying to save agent\n\t\treturn validate.Validate(\n\t\t\t&validators.StringIsPresent{Field: u.Email, Name: \"Email\"},\n\t\t\t&validators.StringIsPresent{Field: u.PasswordHash, Name: \"PasswordHash\"},\n\t\t\t&validators.StringIsPresent{Field: u.LastName, Name: \"LastName\"},\n\t\t\t&validators.StringIsPresent{Field: u.FirstName, Name: \"FirstName\"},\n\t\t\t&validators.StringIsPresent{Field: u.Phone, Name: \"Phone\"},\n\t\t\t&validators.StringIsPresent{Field: u.PublicEmail.String, Name: \"PublicEmail\"},\n\t\t\t&validators.StringIsPresent{Field: u.Company.String, Name: \"Company\"},\n\t\t\t&validators.StringIsPresent{Field: u.Address1.String, Name: \"Address1\"},\n\t\t\t&validators.StringIsPresent{Field: u.City.String, Name: \"City\"},\n\t\t\t&validators.StringIsPresent{Field: u.State.String, Name: \"State\"},\n\t\t\t&validators.StringIsPresent{Field: u.Zipcode.String, Name: \"Zipcode\"},\n\t\t\t// check to see if the email address is already taken:\n\t\t\t&validators.FuncValidator{\n\t\t\t\tField: u.Email,\n\t\t\t\tName: \"Email\",\n\t\t\t\tMessage: \"%s is already taken\",\n\t\t\t\tFn: func() bool {\n\t\t\t\t\tvar b bool\n\t\t\t\t\tq := tx.Where(\"email = ?\", u.Email)\n\t\t\t\t\tif u.ID != uuid.Nil {\n\t\t\t\t\t\tq = q.Where(\"id != ?\", u.ID)\n\t\t\t\t\t}\n\t\t\t\t\tb, err = q.Exists(u)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn false\n\t\t\t\t\t}\n\t\t\t\t\treturn !b\n\t\t\t\t},\n\t\t\t},\n\t\t), err\n\n\t}\n}", "func IsValidAccount(a string) bool {\n\t_, err := NewAccount(a)\n\treturn err == nil\n}", "func (u User) IsValid() []error{\n\tvar errs []error\n\tfirstname := strings.Trim(u.FirstName, \" \")\n\tlastname := strings.Trim(u.LastName, \" \")\n\n\tif firstname != \"\" {\n\t\tif strings.Contains(firstname, \" \"){\n\t\t\terrs = append(errs, errors.New(\"FirstName can't have spaces\"))\n\t\t}\n\t\tif len(firstname) < 2 {\n\t\t\terrs = append(errs, errors.New(\"FirstName must be at least 2 characters\"))\n\t\t}\n\t\tif !helper.IsLetter(firstname) {\n\t\t\terrs = append(errs, errors.New(\"Firstname contains a number\"))\n\t\t}\n\t}\n\n\tif lastname != \"\"{\n\t\tif strings.Contains(lastname, \" \"){\n\t\t\terrs = append(errs, errors.New(\"LastName can't have spaces\"))\n\t\t}\n\n\t\tif len(lastname) < 2 {\n\t\t\terrs = append(errs, errors.New(\"LastName must be at least 2 characters\"))\n\t\t}\n\n\t\tif !helper.IsLetter(lastname) {\n\t\t\terrs = append(errs, errors.New(\"Lastname contains a number\"))\n\t\t}\n\t}\n\n\tif u.Email != \"\" {\n\t\tre := regexp.MustCompile(\"^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$\")\n\n\t\tif !re.MatchString(u.Email) {\n\t\t\terrs = append(errs, errors.New(\"Email address is not valid\"))\n\t\t}\n\t}\n\n\n\tyear, _, _, _, _, _ := helper.DateDiff(u.DateOfBirth, time.Now())\n\tif year < 18 {\n\t\terrs = append(errs, errors.New(\"You must be 18 or more\"))\n\t}\n\tif len(errs) > 0 {\n\t\treturn errs\n\t}\n\treturn nil\n}", "func (m *BillingProfiles2) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateAdviceOfCharge(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateCurrency(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateFraudDailyLimit(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateFraudDailyLock(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateFraudDailyNotify(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateFraudIntervalLimit(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateFraudIntervalLock(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateFraudIntervalNotify(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateFraudUseResellerRates(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateHandle(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateIntervalCharge(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateIntervalFreeCash(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateIntervalFreeTime(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateName(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validatePeaktimeSpecial(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validatePeaktimeWeekdays(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validatePrepaid(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validatePrepaidLibrary(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateResellerID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (o *conversionOptions) validate() error {\r\n\tif o.goalID == 0 && len(o.goalName) == 0 {\r\n\t\treturn fmt.Errorf(\"missing required attribute(s): %s or %s\", fieldID, fieldName)\r\n\t} else if o.goalID == 0 && o.tonicPowUserID > 0 {\r\n\t\treturn fmt.Errorf(\"missing required attribute: %s\", fieldID)\r\n\t} else if o.tonicPowUserID == 0 && len(o.tncpwSession) == 0 {\r\n\t\treturn fmt.Errorf(\"missing required attribute(s): %s or %s\", fieldVisitorSessionGUID, fieldUserID)\r\n\t}\r\n\treturn nil\r\n}", "func (m *CustomerTripletexAccount2) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateAccountType(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateAdministrator(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateChartOfAccountsType(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateModules(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateType(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateVatStatusType(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (bva BaseVestingAccount) Validate() error {\n\tif !(bva.DelegatedVesting.IsAllLTE(bva.OriginalVesting)) {\n\t\treturn errors.New(\"delegated vesting amount cannot be greater than original vesting amount\")\n\t}\n\treturn bva.BaseAccount.Validate()\n}", "func (uuo *UserUpdateOne) check() error {\n\tif v, ok := uuo.mutation.AccountName(); ok {\n\t\tif err := user.AccountNameValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"account_name\", err: fmt.Errorf(\"ent: validator failed for field \\\"account_name\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.StaffType(); ok {\n\t\tif err := user.StaffTypeValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"staff_type\", err: fmt.Errorf(\"ent: validator failed for field \\\"staff_type\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.FamilyName(); ok {\n\t\tif err := user.FamilyNameValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"family_name\", err: fmt.Errorf(\"ent: validator failed for field \\\"family_name\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.GivenName(); ok {\n\t\tif err := user.GivenNameValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"given_name\", err: fmt.Errorf(\"ent: validator failed for field \\\"given_name\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.DisplayName(); ok {\n\t\tif err := user.DisplayNameValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"display_name\", err: fmt.Errorf(\"ent: validator failed for field \\\"display_name\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.IDNumber(); ok {\n\t\tif err := user.IDNumberValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"id_number\", err: fmt.Errorf(\"ent: validator failed for field \\\"id_number\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.Sex(); ok {\n\t\tif err := user.SexValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"sex\", err: fmt.Errorf(\"ent: validator failed for field \\\"sex\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.PhoneNumber(); ok {\n\t\tif err := user.PhoneNumberValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"phone_number\", err: fmt.Errorf(\"ent: validator failed for field \\\"phone_number\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.Address(); ok {\n\t\tif err := user.AddressValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"address\", err: fmt.Errorf(\"ent: validator failed for field \\\"address\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.StaffID(); ok {\n\t\tif err := user.StaffIDValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"staff_id\", err: fmt.Errorf(\"ent: validator failed for field \\\"staff_id\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.PersonalEmail(); ok {\n\t\tif err := user.PersonalEmailValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"personal_email\", err: fmt.Errorf(\"ent: validator failed for field \\\"personal_email\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.IntranetWorkEmail(); ok {\n\t\tif err := user.IntranetWorkEmailValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"intranet_work_email\", err: fmt.Errorf(\"ent: validator failed for field \\\"intranet_work_email\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.ExtranetWorkEmail(); ok {\n\t\tif err := user.ExtranetWorkEmailValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"extranet_work_email\", err: fmt.Errorf(\"ent: validator failed for field \\\"extranet_work_email\\\": %w\", err)}\n\t\t}\n\t}\n\treturn nil\n}", "func (m *DomainDiscoverAPIAccount) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateCid(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (msg MsgAddAdminAccount) ValidateBasic() sdk.Error {\n if msg.AdminAddress.Empty() {\n return sdk.ErrInvalidAddress(msg.AdminAddress.String())\n }\n if msg.Owner.Empty() {\n return sdk.ErrInvalidAddress(msg.Owner.String())\n }\n return nil\n}", "func init() {\n\taccountFields := schema.Account{}.Fields()\n\t_ = accountFields\n\t// accountDescProvider is the schema descriptor for provider field.\n\taccountDescProvider := accountFields[1].Descriptor()\n\t// account.ProviderValidator is a validator for the \"provider\" field. It is called by the builders before save.\n\taccount.ProviderValidator = accountDescProvider.Validators[0].(func(string) error)\n\t// accountDescEmail is the schema descriptor for email field.\n\taccountDescEmail := accountFields[2].Descriptor()\n\t// account.EmailValidator is a validator for the \"email\" field. It is called by the builders before save.\n\taccount.EmailValidator = accountDescEmail.Validators[0].(func(string) error)\n\t// accountDescPassword is the schema descriptor for password field.\n\taccountDescPassword := accountFields[3].Descriptor()\n\t// account.PasswordValidator is a validator for the \"password\" field. It is called by the builders before save.\n\taccount.PasswordValidator = func() func(string) error {\n\t\tvalidators := accountDescPassword.Validators\n\t\tfns := [...]func(string) error{\n\t\t\tvalidators[0].(func(string) error),\n\t\t\tvalidators[1].(func(string) error),\n\t\t}\n\t\treturn func(password string) error {\n\t\t\tfor _, fn := range fns {\n\t\t\t\tif err := fn(password); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\t}()\n\t// accountDescLocked is the schema descriptor for locked field.\n\taccountDescLocked := accountFields[4].Descriptor()\n\t// account.DefaultLocked holds the default value on creation for the locked field.\n\taccount.DefaultLocked = accountDescLocked.Default.(bool)\n\t// accountDescConfirmed is the schema descriptor for confirmed field.\n\taccountDescConfirmed := accountFields[5].Descriptor()\n\t// account.DefaultConfirmed holds the default value on creation for the confirmed field.\n\taccount.DefaultConfirmed = accountDescConfirmed.Default.(bool)\n\t// accountDescConfirmationToken is the schema descriptor for confirmation_token field.\n\taccountDescConfirmationToken := accountFields[7].Descriptor()\n\t// account.ConfirmationTokenValidator is a validator for the \"confirmation_token\" field. It is called by the builders before save.\n\taccount.ConfirmationTokenValidator = accountDescConfirmationToken.Validators[0].(func(string) error)\n\t// accountDescRecoveryToken is the schema descriptor for recovery_token field.\n\taccountDescRecoveryToken := accountFields[9].Descriptor()\n\t// account.RecoveryTokenValidator is a validator for the \"recovery_token\" field. It is called by the builders before save.\n\taccount.RecoveryTokenValidator = accountDescRecoveryToken.Validators[0].(func(string) error)\n\t// accountDescOtp is the schema descriptor for otp field.\n\taccountDescOtp := accountFields[11].Descriptor()\n\t// account.OtpValidator is a validator for the \"otp\" field. It is called by the builders before save.\n\taccount.OtpValidator = accountDescOtp.Validators[0].(func(string) error)\n\t// accountDescEmailChange is the schema descriptor for email_change field.\n\taccountDescEmailChange := accountFields[12].Descriptor()\n\t// account.EmailChangeValidator is a validator for the \"email_change\" field. It is called by the builders before save.\n\taccount.EmailChangeValidator = accountDescEmailChange.Validators[0].(func(string) error)\n\t// accountDescEmailChangeToken is the schema descriptor for email_change_token field.\n\taccountDescEmailChangeToken := accountFields[14].Descriptor()\n\t// account.EmailChangeTokenValidator is a validator for the \"email_change_token\" field. It is called by the builders before save.\n\taccount.EmailChangeTokenValidator = accountDescEmailChangeToken.Validators[0].(func(string) error)\n\t// accountDescCreatedAt is the schema descriptor for created_at field.\n\taccountDescCreatedAt := accountFields[18].Descriptor()\n\t// account.DefaultCreatedAt holds the default value on creation for the created_at field.\n\taccount.DefaultCreatedAt = accountDescCreatedAt.Default.(func() time.Time)\n\t// accountDescUpdatedAt is the schema descriptor for updated_at field.\n\taccountDescUpdatedAt := accountFields[19].Descriptor()\n\t// account.DefaultUpdatedAt holds the default value on creation for the updated_at field.\n\taccount.DefaultUpdatedAt = accountDescUpdatedAt.Default.(func() time.Time)\n\t// account.UpdateDefaultUpdatedAt holds the default value on update for the updated_at field.\n\taccount.UpdateDefaultUpdatedAt = accountDescUpdatedAt.UpdateDefault.(func() time.Time)\n\t// accountDescID is the schema descriptor for id field.\n\taccountDescID := accountFields[0].Descriptor()\n\t// account.DefaultID holds the default value on creation for the id field.\n\taccount.DefaultID = accountDescID.Default.(func() uuid.UUID)\n\tsessionFields := schema.Session{}.Fields()\n\t_ = sessionFields\n\t// sessionDescCreatedAt is the schema descriptor for created_at field.\n\tsessionDescCreatedAt := sessionFields[2].Descriptor()\n\t// session.DefaultCreatedAt holds the default value on creation for the created_at field.\n\tsession.DefaultCreatedAt = sessionDescCreatedAt.Default.(func() time.Time)\n\t// sessionDescUpdatedAt is the schema descriptor for updated_at field.\n\tsessionDescUpdatedAt := sessionFields[3].Descriptor()\n\t// session.DefaultUpdatedAt holds the default value on creation for the updated_at field.\n\tsession.DefaultUpdatedAt = sessionDescUpdatedAt.Default.(func() time.Time)\n\t// session.UpdateDefaultUpdatedAt holds the default value on update for the updated_at field.\n\tsession.UpdateDefaultUpdatedAt = sessionDescUpdatedAt.UpdateDefault.(func() time.Time)\n}", "func (mt AccountCollection) Validate() (err error) {\n\tfor _, e := range mt {\n\t\tif e != nil {\n\t\t\tif err2 := e.Validate(); err2 != nil {\n\t\t\t\terr = goa.MergeErrors(err, err2)\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}", "func (frm entryForm) Validate() (map[string]string, bool) {\n\terrs := map[string]string{}\n\tg1 := frm.Department != \"\"\n\tif !g1 {\n\t\terrs[\"department\"] = \"Missing department\"\n\t}\n\tg2 := frm.CheckThis\n\tif !g2 {\n\t\terrs[\"check_this\"] = \"You need to comply\"\n\t}\n\tg3 := frm.Items != \"\"\n\tif !g3 {\n\t\terrs[\"items\"] = \"No items\"\n\t}\n\treturn errs, g1 && g2 && g3\n}", "func (vva ValidatorVestingAccount) Validate() error {\n\tif vva.SigningThreshold > 100 || vva.SigningThreshold < 0 {\n\t\treturn errors.New(\"signing threshold must be between 0 and 100\")\n\t}\n\tif vva.ReturnAddress.Equals(vva.Address) {\n\t\treturn errors.New(\"return address cannot be the same as the account address\")\n\t}\n\treturn vva.PeriodicVestingAccount.Validate()\n}", "func validate(msgs []*LogMsg) {\n\tif !validatePRAMRegistration(msgs) {\n\t\tlog.Fatalf(\"validatePRAMRegistration\\n\")\n\t}\n}", "func (_PermInterface *PermInterfaceCaller) ValidateAccount(opts *bind.CallOpts, _account common.Address, _orgId string) (bool, error) {\n\tvar out []interface{}\n\terr := _PermInterface.contract.Call(opts, &out, \"validateAccount\", _account, _orgId)\n\n\tif err != nil {\n\t\treturn *new(bool), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(bool)).(*bool)\n\n\treturn out0, err\n\n}", "func (ut *RegisterPayload) Validate() (err error) {\n\tif ut.Email == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`type`, \"email\"))\n\t}\n\tif ut.Password == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`type`, \"password\"))\n\t}\n\tif ut.FirstName == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`type`, \"first_name\"))\n\t}\n\tif ut.LastName == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`type`, \"last_name\"))\n\t}\n\tif err2 := goa.ValidateFormat(goa.FormatEmail, ut.Email); err2 != nil {\n\t\terr = goa.MergeErrors(err, goa.InvalidFormatError(`type.email`, ut.Email, goa.FormatEmail, err2))\n\t}\n\tif utf8.RuneCountInString(ut.Email) < 6 {\n\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`type.email`, ut.Email, utf8.RuneCountInString(ut.Email), 6, true))\n\t}\n\tif utf8.RuneCountInString(ut.Email) > 150 {\n\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`type.email`, ut.Email, utf8.RuneCountInString(ut.Email), 150, false))\n\t}\n\tif utf8.RuneCountInString(ut.FirstName) < 1 {\n\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`type.first_name`, ut.FirstName, utf8.RuneCountInString(ut.FirstName), 1, true))\n\t}\n\tif utf8.RuneCountInString(ut.FirstName) > 200 {\n\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`type.first_name`, ut.FirstName, utf8.RuneCountInString(ut.FirstName), 200, false))\n\t}\n\tif utf8.RuneCountInString(ut.LastName) < 1 {\n\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`type.last_name`, ut.LastName, utf8.RuneCountInString(ut.LastName), 1, true))\n\t}\n\tif utf8.RuneCountInString(ut.LastName) > 200 {\n\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`type.last_name`, ut.LastName, utf8.RuneCountInString(ut.LastName), 200, false))\n\t}\n\tif utf8.RuneCountInString(ut.Password) < 5 {\n\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`type.password`, ut.Password, utf8.RuneCountInString(ut.Password), 5, true))\n\t}\n\tif utf8.RuneCountInString(ut.Password) > 100 {\n\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`type.password`, ut.Password, utf8.RuneCountInString(ut.Password), 100, false))\n\t}\n\treturn\n}", "func (a *Api) validateError() (err error) {\n\tif a.UserID == 0 {\n\t\treturn a.Errors(ErrorMissingValue, \"user_id\")\n\t}\n\n\tif a.Token == \"\" {\n\t\treturn a.Errors(ErrorMissingValue, \"token\")\n\t}\n\n\treturn\n}", "func (uc *UserCreate) check() error {\n\tif _, ok := uc.mutation.Firstname(); !ok {\n\t\treturn &ValidationError{Name: \"firstname\", err: errors.New(\"ent: missing required field \\\"firstname\\\"\")}\n\t}\n\tif _, ok := uc.mutation.Lastname(); !ok {\n\t\treturn &ValidationError{Name: \"lastname\", err: errors.New(\"ent: missing required field \\\"lastname\\\"\")}\n\t}\n\tif _, ok := uc.mutation.Username(); !ok {\n\t\treturn &ValidationError{Name: \"username\", err: errors.New(\"ent: missing required field \\\"username\\\"\")}\n\t}\n\tif _, ok := uc.mutation.Password(); !ok {\n\t\treturn &ValidationError{Name: \"password\", err: errors.New(\"ent: missing required field \\\"password\\\"\")}\n\t}\n\treturn nil\n}", "func (ac *AreahistoryCreate) check() error {\n\tif _, ok := ac.mutation.WalletID(); !ok {\n\t\treturn &ValidationError{Name: \"WalletID\", err: errors.New(\"ent: missing required field \\\"WalletID\\\"\")}\n\t}\n\tif v, ok := ac.mutation.WalletID(); ok {\n\t\tif err := areahistory.WalletIDValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"WalletID\", err: fmt.Errorf(\"ent: validator failed for field \\\"WalletID\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := ac.mutation.ProvinceNameTH(); ok {\n\t\tif err := areahistory.ProvinceNameTHValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"ProvinceNameTH\", err: fmt.Errorf(\"ent: validator failed for field \\\"ProvinceNameTH\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := ac.mutation.DistrictNameTH(); ok {\n\t\tif err := areahistory.DistrictNameTHValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"DistrictNameTH\", err: fmt.Errorf(\"ent: validator failed for field \\\"DistrictNameTH\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := ac.mutation.SubDistrict(); ok {\n\t\tif err := areahistory.SubDistrictValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"SubDistrict\", err: fmt.Errorf(\"ent: validator failed for field \\\"SubDistrict\\\": %w\", err)}\n\t\t}\n\t}\n\treturn nil\n}", "func (_PermInterface *PermInterfaceSession) ValidateAccount(_account common.Address, _orgId string) (bool, error) {\n\treturn _PermInterface.Contract.ValidateAccount(&_PermInterface.CallOpts, _account, _orgId)\n}", "func (uu *UserUpdate) check() error {\n\tif v, ok := uu.mutation.Username(); ok {\n\t\tif err := user.UsernameValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"username\", err: fmt.Errorf(\"ent: validator failed for field \\\"username\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.Fullname(); ok {\n\t\tif err := user.FullnameValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"fullname\", err: fmt.Errorf(\"ent: validator failed for field \\\"fullname\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.Password(); ok {\n\t\tif err := user.PasswordValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"password\", err: fmt.Errorf(\"ent: validator failed for field \\\"password\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.Email(); ok {\n\t\tif err := user.EmailValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"email\", err: fmt.Errorf(\"ent: validator failed for field \\\"email\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.Phone(); ok {\n\t\tif err := user.PhoneValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"phone\", err: fmt.Errorf(\"ent: validator failed for field \\\"phone\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.Bio(); ok {\n\t\tif err := user.BioValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"bio\", err: fmt.Errorf(\"ent: validator failed for field \\\"bio\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.Intro(); ok {\n\t\tif err := user.IntroValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"intro\", err: fmt.Errorf(\"ent: validator failed for field \\\"intro\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.GithubProfile(); ok {\n\t\tif err := user.GithubProfileValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"github_profile\", err: fmt.Errorf(\"ent: validator failed for field \\\"github_profile\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.ProfilePictureURL(); ok {\n\t\tif err := user.ProfilePictureURLValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"profile_picture_url\", err: fmt.Errorf(\"ent: validator failed for field \\\"profile_picture_url\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.Status(); ok {\n\t\tif err := user.StatusValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"status\", err: fmt.Errorf(\"ent: validator failed for field \\\"status\\\": %w\", err)}\n\t\t}\n\t}\n\treturn nil\n}", "func (uc *UserCreate) check() error {\n\tif _, ok := uc.mutation.Age(); !ok {\n\t\treturn &ValidationError{Name: \"age\", err: errors.New(\"ent: missing required field \\\"age\\\"\")}\n\t}\n\tif v, ok := uc.mutation.Age(); ok {\n\t\tif err := user.AgeValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"age\", err: fmt.Errorf(\"ent: validator failed for field \\\"age\\\": %w\", err)}\n\t\t}\n\t}\n\tif _, ok := uc.mutation.Name(); !ok {\n\t\treturn &ValidationError{Name: \"name\", err: errors.New(\"ent: missing required field \\\"name\\\"\")}\n\t}\n\tif v, ok := uc.mutation.ID(); ok {\n\t\tif err := user.IDValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"id\", err: fmt.Errorf(\"ent: validator failed for field \\\"id\\\": %w\", err)}\n\t\t}\n\t}\n\treturn nil\n}", "func (p *PaymentNeed) validate() error {\n\tif p.BeneficiaryID == 0 {\n\t\treturn fmt.Errorf(\"beneficiary ID nul\")\n\t}\n\tif p.Value == 0 {\n\t\treturn fmt.Errorf(\"value nul\")\n\t}\n\treturn nil\n}", "func (r *Result) validate(errMsg *[]string, parentField string) {\n\tjn := resultJsonMap\n\taddErrMessage(errMsg, len(r.Key) > 0 && hasNonEmptyKV(r.Key), \"field '%s' must be non-empty and must not have empty keys or values\", parentField+\".\"+jn[\"Key\"])\n\taddErrMessage(errMsg, hasNonEmptyKV(r.Options), \"field '%s' must not have empty keys or values\", parentField+\".\"+jn[\"Options\"])\n\taddErrMessage(errMsg, regExHexadecimal.MatchString(string(r.Digest)), \"field '%s' must be hexadecimal\", parentField+\".\"+jn[\"Digest\"])\n}", "func CheckAccountResponse(t *testing.T, resp *models.Account, expectedAccount *models.Account) {\n\tif resp.ID != expectedAccount.ID {\n\t\tt.Errorf(\"Response contains wrong ID, got %v expected %v\", resp.ID, expectedAccount.ID)\n\t}\n\tif resp.Type != expectedAccount.Type {\n\t\tt.Errorf(\"Response contains wrong Type, got %v expected %v\", resp.Type, expectedAccount.Type)\n\t}\n\tif resp.OrganisationID != expectedAccount.OrganisationID {\n\t\tt.Errorf(\"Response contains wrong OrganisationID, got %v expected %v\", resp.OrganisationID, expectedAccount.OrganisationID)\n\t}\n\tif resp.Version != expectedAccount.Version {\n\t\tt.Errorf(\"Response contains wrong Version, got %v expected %v\", resp.Version, expectedAccount.Version)\n\t}\n\tif resp.Attributes.Country != expectedAccount.Attributes.Country {\n\t\tt.Errorf(\"Response contains wrong Country, got %v expected %v\", resp.Attributes.Country, expectedAccount.Attributes.Country)\n\t}\n\tif resp.Attributes.BaseCurrency != expectedAccount.Attributes.BaseCurrency {\n\t\tt.Errorf(\"Response contains wrong BaseCurrency, got %v expected %v\", resp.Attributes.BaseCurrency, expectedAccount.Attributes.BaseCurrency)\n\t}\n\tif resp.Attributes.BankID != expectedAccount.Attributes.BankID {\n\t\tt.Errorf(\"Response contains wrong BankID, got %v expected %v\", resp.Attributes.BankID, expectedAccount.Attributes.BankID)\n\t}\n\tif resp.Attributes.BankIDCode != expectedAccount.Attributes.BankIDCode {\n\t\tt.Errorf(\"Response contains wrong BankIDCode, got %v expected %v\", resp.Attributes.BankIDCode, expectedAccount.Attributes.BankIDCode)\n\t}\n\tif resp.Attributes.Bic != expectedAccount.Attributes.Bic {\n\t\tt.Errorf(\"Response contains wrong Bic, got %v expected %v\", resp.Attributes.Bic, expectedAccount.Attributes.Bic)\n\t}\n\tif resp.Attributes.AccountNumber != expectedAccount.Attributes.AccountNumber {\n\t\tt.Errorf(\"Response contains wrong AccountNumber, got %v expected %v\", resp.Attributes.AccountNumber, expectedAccount.Attributes.AccountNumber)\n\t}\n\tif resp.Attributes.CustomerID != expectedAccount.Attributes.CustomerID {\n\t\tt.Errorf(\"Response contains wrong CustomerID, got %v expected %v\", resp.Attributes.CustomerID, expectedAccount.Attributes.CustomerID)\n\t}\n\tif resp.Attributes.FirstName != expectedAccount.Attributes.FirstName {\n\t\tt.Errorf(\"Response contains wrong FirstName, got %v expected %v\", resp.Attributes.FirstName, expectedAccount.Attributes.FirstName)\n\t}\n\tif resp.Attributes.BankAccountName != expectedAccount.Attributes.BankAccountName {\n\t\tt.Errorf(\"Response contains wrong BankAccountName, got %v expected %v\", resp.Attributes.BankAccountName, expectedAccount.Attributes.BankAccountName)\n\t}\n\n\tresponseLength := len(resp.Attributes.AlternativeBankAccountNames)\n\texpectedLength := len(expectedAccount.Attributes.AlternativeBankAccountNames)\n\n\tif responseLength != expectedLength {\n\t\tt.Errorf(\"AlternativeBankAccountNames array is wrong, got %v expected %v\", responseLength, expectedLength)\n\t} else {\n\t\ti := 0\n\t\tfor i < responseLength {\n\t\t\tif resp.Attributes.AlternativeBankAccountNames[i] != expectedAccount.Attributes.AlternativeBankAccountNames[i] {\n\t\t\t\tt.Errorf(\"Response contains wrong AlternativeBankAccountNames, got %v expected %v\", resp.Attributes.AlternativeBankAccountNames[i], expectedAccount.Attributes.AlternativeBankAccountNames[i])\n\t\t\t}\n\t\t\ti = i + 1\n\t\t}\n\t}\n\n\tif resp.Attributes.AlternativeBankAccountNames[0] != expectedAccount.Attributes.AlternativeBankAccountNames[0] {\n\t\tt.Errorf(\"Response contains wrong AlternativeBankAccountNames, got %v expected %v\", resp.Attributes.AlternativeBankAccountNames[0], expectedAccount.Attributes.AlternativeBankAccountNames[0])\n\t}\n\tif resp.Attributes.AccountClassification != expectedAccount.Attributes.AccountClassification {\n\t\tt.Errorf(\"Response contains wrong AccountClassification, got %v expected %v\", resp.Attributes.AccountClassification, expectedAccount.Attributes.AccountClassification)\n\t}\n\tif resp.Attributes.JointAccount != expectedAccount.Attributes.JointAccount {\n\t\tt.Errorf(\"Response contains wrong JointAccount, got %v expected %v\", resp.Attributes.JointAccount, expectedAccount.Attributes.JointAccount)\n\t}\n\tif resp.Attributes.Switched != expectedAccount.Attributes.Switched {\n\t\tt.Errorf(\"Response contains wrong Switched, got %v expected %v\", resp.Attributes.Switched, expectedAccount.Attributes.Switched)\n\t}\n\tif resp.Attributes.AccountMatchingOptOut != expectedAccount.Attributes.AccountMatchingOptOut {\n\t\tt.Errorf(\"Response contains wrong AccountMatchingOptOut, got %v expected %v\", resp.Attributes.AccountMatchingOptOut, expectedAccount.Attributes.AccountMatchingOptOut)\n\t}\n\tif resp.Attributes.Status != expectedAccount.Attributes.Status {\n\t\tt.Errorf(\"Response contains wrong Status, got %v expected %v\", resp.Attributes.Status, expectedAccount.Attributes.Status)\n\t}\n\tif resp.Attributes.SecondaryIdentification != expectedAccount.Attributes.SecondaryIdentification {\n\t\tt.Errorf(\"Response contains wrong SecondaryIdentification, got %v expected %v\", resp.Attributes.SecondaryIdentification, expectedAccount.Attributes.SecondaryIdentification)\n\t}\n}", "func (_PermInterface *PermInterfaceCallerSession) ValidateAccount(_account common.Address, _orgId string) (bool, error) {\n\treturn _PermInterface.Contract.ValidateAccount(&_PermInterface.CallOpts, _account, _orgId)\n}", "func (cfg fromCFN) validate() error {\n\tif cfg.isEmpty() {\n\t\treturn nil\n\t}\n\tif len(aws.StringValue(cfg.Name)) == 0 {\n\t\treturn errors.New(\"name cannot be an empty string\")\n\t}\n\treturn nil\n}", "func isAccountFlagsValid(accountId string) bool {\n\taccount := GetStellarAccount(accountId)\n\treturn account.Flags.AuthRequired && account.Flags.AuthRevocable\n}", "func validate(name, gender string) error {\n\tif name == \"\" {\n\t\treturn &inputError{message: \"name is missing\", missingField: \"name\"}\n\t}\n\tif gender == \"\" {\n\t\treturn &inputError{message: \"gender is missing\", missingField: \"gender\"}\n\t}\n\treturn nil\n}", "func (user *User) Validate() *errors.RestErr {\n\t// Delete spaces at first_name, last_name and email before saving\n\tuser.FirstName = strings.TrimSpace(user.FirstName)\n\tuser.LastName = strings.TrimSpace(user.LastName)\n\tuser.Email = strings.TrimSpace(strings.ToLower(user.Email))\n\n\tif user.Email == \"\"{\n\t\treturn errors.NewBadRequestError(\"Email addres is required\")\n\t}\n\tif !ValidateEmail(user.Email){\n\t\treturn errors.NewBadRequestError(\"Wrong email format\")\n\t}\n\tif strings.TrimSpace(user.Password)== \"\" || len(strings.TrimSpace(user.Password)) < 8{\n\t\treturn errors.NewBadRequestError(\"Password is required and password length must be higher than 8 characters\")\n\t}\n\n\n\treturn nil\n}", "func checkAccount(t *testing.T, tree *avl.Tree, id AccountID, expectedBalance, expectedReward, expectedStake *uint64) {\n\tvar balance, reward, stake uint64\n\tvar exist bool\n\n\tbalance, exist = ReadAccountBalance(tree, id)\n\tassert.Equal(t, expectedBalance != nil, exist, \"account ID: %x\", id)\n\treward, exist = ReadAccountReward(tree, id)\n\tassert.Equal(t, expectedReward != nil, exist, \"account ID: %x\", id)\n\tstake, exist = ReadAccountStake(tree, id)\n\tassert.Equal(t, expectedStake != nil, exist, \"account ID: %x\", id)\n\n\tif expectedBalance != nil {\n\t\tassert.Equal(t, balance, *expectedBalance, \"account ID: %x\", id)\n\t}\n\n\tif expectedReward != nil {\n\t\tassert.Equal(t, reward, *expectedReward, \"account ID: %x\", id)\n\t}\n\n\tif expectedStake != nil {\n\t\tassert.Equal(t, stake, *expectedStake, \"account ID: %x\", id)\n\t}\n}", "func ValidBaseInfo(ctx *gin.Context) {\n\tres := helper.Res{}\n\n\tvar baseInfo BaseInfo\n\tif err := ctx.Bind(&baseInfo); err != nil {\n\t\tres.Status(http.StatusBadRequest).Error(err).Send(ctx)\n\t\treturn\n\t}\n\n\t// user does exist\n\tif _, err := models.FindOneByUsername(baseInfo.Username); err != nil {\n\t\tres.Status(http.StatusBadRequest).Error(err).Send(ctx)\n\t\treturn\n\t}\n\n\t// the email of user does exist\n\tif _, err := models.FindOneByEmail(baseInfo.Email); err != nil {\n\t\tres.Status(http.StatusBadRequest).Error(err).Send(ctx)\n\t\treturn\n\t}\n\n\tres.Success(gin.H{\n\t\t\"isValid\": true,\n\t}).Send(ctx)\n}", "func (w Warrant) Validate() error {\n\tif len(w.FirstName) == 0 {\n\t\treturn errors.New(\"missing first name element\")\n\t}\n\tif len(w.LastName) == 0 {\n\t\treturn errors.New(\"missing last name element\")\n\t}\n\tif len(w.Civility) == 0 {\n\t\treturn errors.New(\"missing civility element\")\n\t}\n\treturn nil\n}", "func (va ClawbackVestingAccount) Validate() error {\n\tif va.GetStartTime() >= va.GetEndTime() {\n\t\treturn errors.New(\"vesting start-time must be before end-time\")\n\t}\n\n\tlockupEnd := va.StartTime\n\tlockupCoins := sdk.NewCoins()\n\tfor _, p := range va.LockupPeriods {\n\t\tlockupEnd += p.Length\n\t\tlockupCoins = lockupCoins.Add(p.Amount...)\n\t}\n\tif lockupEnd > va.EndTime {\n\t\treturn errors.New(\"lockup schedule extends beyond account end time\")\n\t}\n\tif !coinEq(lockupCoins, va.OriginalVesting) {\n\t\treturn errors.New(\"original vesting coins does not match the sum of all coins in lockup periods\")\n\t}\n\n\tvestingEnd := va.StartTime\n\tvestingCoins := sdk.NewCoins()\n\tfor _, p := range va.VestingPeriods {\n\t\tvestingEnd += p.Length\n\t\tvestingCoins = vestingCoins.Add(p.Amount...)\n\t}\n\tif vestingEnd > va.EndTime {\n\t\treturn errors.New(\"vesting schedule exteds beyond account end time\")\n\t}\n\tif !coinEq(vestingCoins, va.OriginalVesting) {\n\t\treturn errors.New(\"original vesting coins does not match the sum of all coins in vesting periods\")\n\t}\n\n\treturn va.BaseVestingAccount.Validate()\n}", "func (ut *registerPayload) Validate() (err error) {\n\tif ut.Email == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`request`, \"email\"))\n\t}\n\tif ut.Password == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`request`, \"password\"))\n\t}\n\tif ut.FirstName == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`request`, \"first_name\"))\n\t}\n\tif ut.LastName == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`request`, \"last_name\"))\n\t}\n\tif ut.Email != nil {\n\t\tif err2 := goa.ValidateFormat(goa.FormatEmail, *ut.Email); err2 != nil {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidFormatError(`request.email`, *ut.Email, goa.FormatEmail, err2))\n\t\t}\n\t}\n\tif ut.Email != nil {\n\t\tif utf8.RuneCountInString(*ut.Email) < 6 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`request.email`, *ut.Email, utf8.RuneCountInString(*ut.Email), 6, true))\n\t\t}\n\t}\n\tif ut.Email != nil {\n\t\tif utf8.RuneCountInString(*ut.Email) > 150 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`request.email`, *ut.Email, utf8.RuneCountInString(*ut.Email), 150, false))\n\t\t}\n\t}\n\tif ut.FirstName != nil {\n\t\tif utf8.RuneCountInString(*ut.FirstName) < 1 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`request.first_name`, *ut.FirstName, utf8.RuneCountInString(*ut.FirstName), 1, true))\n\t\t}\n\t}\n\tif ut.FirstName != nil {\n\t\tif utf8.RuneCountInString(*ut.FirstName) > 200 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`request.first_name`, *ut.FirstName, utf8.RuneCountInString(*ut.FirstName), 200, false))\n\t\t}\n\t}\n\tif ut.LastName != nil {\n\t\tif utf8.RuneCountInString(*ut.LastName) < 1 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`request.last_name`, *ut.LastName, utf8.RuneCountInString(*ut.LastName), 1, true))\n\t\t}\n\t}\n\tif ut.LastName != nil {\n\t\tif utf8.RuneCountInString(*ut.LastName) > 200 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`request.last_name`, *ut.LastName, utf8.RuneCountInString(*ut.LastName), 200, false))\n\t\t}\n\t}\n\tif ut.Password != nil {\n\t\tif utf8.RuneCountInString(*ut.Password) < 5 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`request.password`, *ut.Password, utf8.RuneCountInString(*ut.Password), 5, true))\n\t\t}\n\t}\n\tif ut.Password != nil {\n\t\tif utf8.RuneCountInString(*ut.Password) > 100 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`request.password`, *ut.Password, utf8.RuneCountInString(*ut.Password), 100, false))\n\t\t}\n\t}\n\treturn\n}", "func ValidateWarriorAccount(name string, email string, pwd1 string, pwd2 string) (WarriorName string, WarriorEmail string, WarriorPassword string, validateErr error) {\n\tv := validator.New()\n\ta := warriorAccount{\n\t\tName: name,\n\t\tEmail: email,\n\t\tPassword1: pwd1,\n\t\tPassword2: pwd2,\n\t}\n\terr := v.Struct(a)\n\n\treturn name, email, pwd1, err\n}", "func validateAttributes(attrs map[string]models.ValueType, allAttrs bool) error {\n\t// TBD: to finalize the attributes specifics\n\tattrsOK := false\n\tif vt, ok := attrs[AttrCred]; ok && vt.Kind == com.ValueTypeSecret {\n\t\tif !allAttrs {\n\t\t\tattrsOK = true\n\t\t} else if vt, ok := attrs[AttrZone]; ok && vt.Kind == com.ValueTypeString {\n\t\t\tattrsOK = true\n\t\t}\n\t}\n\tif !attrsOK {\n\t\tmsg := \"required domain attributes missing or invalid: need \" + AttrCred + \"[E]\"\n\t\tif allAttrs {\n\t\t\tmsg += \", \" + AttrZone + \"[S]\"\n\t\t}\n\t\treturn fmt.Errorf(msg)\n\t}\n\treturn nil\n}", "func (cc *CompanyCreate) check() error {\n\tif _, ok := cc.mutation.CreatedAt(); !ok {\n\t\treturn &ValidationError{Name: \"created_at\", err: errors.New(`ent: missing required field \"created_at\"`)}\n\t}\n\tif _, ok := cc.mutation.UpdatedAt(); !ok {\n\t\treturn &ValidationError{Name: \"updated_at\", err: errors.New(`ent: missing required field \"updated_at\"`)}\n\t}\n\tif _, ok := cc.mutation.Name(); !ok {\n\t\treturn &ValidationError{Name: \"name\", err: errors.New(`ent: missing required field \"name\"`)}\n\t}\n\tif v, ok := cc.mutation.Name(); ok {\n\t\tif err := company.NameValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"name\", err: fmt.Errorf(`ent: validator failed for field \"name\": %w`, err)}\n\t\t}\n\t}\n\tif _, ok := cc.mutation.Overview(); !ok {\n\t\treturn &ValidationError{Name: \"overview\", err: errors.New(`ent: missing required field \"overview\"`)}\n\t}\n\tif v, ok := cc.mutation.Overview(); ok {\n\t\tif err := company.OverviewValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"overview\", err: fmt.Errorf(`ent: validator failed for field \"overview\": %w`, err)}\n\t\t}\n\t}\n\tif _, ok := cc.mutation.Website(); !ok {\n\t\treturn &ValidationError{Name: \"website\", err: errors.New(`ent: missing required field \"website\"`)}\n\t}\n\tif v, ok := cc.mutation.Website(); ok {\n\t\tif err := company.WebsiteValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"website\", err: fmt.Errorf(`ent: validator failed for field \"website\": %w`, err)}\n\t\t}\n\t}\n\tif _, ok := cc.mutation.LogoURL(); !ok {\n\t\treturn &ValidationError{Name: \"logo_url\", err: errors.New(`ent: missing required field \"logo_url\"`)}\n\t}\n\tif v, ok := cc.mutation.LogoURL(); ok {\n\t\tif err := company.LogoURLValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"logo_url\", err: fmt.Errorf(`ent: validator failed for field \"logo_url\": %w`, err)}\n\t\t}\n\t}\n\tif _, ok := cc.mutation.Size(); !ok {\n\t\treturn &ValidationError{Name: \"size\", err: errors.New(`ent: missing required field \"size\"`)}\n\t}\n\tif v, ok := cc.mutation.Size(); ok {\n\t\tif err := company.SizeValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"size\", err: fmt.Errorf(`ent: validator failed for field \"size\": %w`, err)}\n\t\t}\n\t}\n\tif _, ok := cc.mutation.FoundedAt(); !ok {\n\t\treturn &ValidationError{Name: \"founded_at\", err: errors.New(`ent: missing required field \"founded_at\"`)}\n\t}\n\tif v, ok := cc.mutation.FoundedAt(); ok {\n\t\tif err := company.FoundedAtValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"founded_at\", err: fmt.Errorf(`ent: validator failed for field \"founded_at\": %w`, err)}\n\t\t}\n\t}\n\treturn nil\n}", "func (m *ProviderAccountPreferences) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func ValidateGetAccountInternalResponseBody(body *GetAccountInternalResponseBody) (err error) {\n\tif body.Name == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"name\", \"body\"))\n\t}\n\tif body.ID == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"id\", \"body\"))\n\t}\n\tif body.Message == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"message\", \"body\"))\n\t}\n\tif body.Temporary == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"temporary\", \"body\"))\n\t}\n\tif body.Timeout == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"timeout\", \"body\"))\n\t}\n\tif body.Fault == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"fault\", \"body\"))\n\t}\n\treturn\n}", "func (o *Virtualserver) validate(dbRecord *common.DbRecord) (ok bool, err error) {\n\t////////////////////////////////////////////////////////////////////////////\n\t// Marshal data interface.\n\t////////////////////////////////////////////////////////////////////////////\n\tvar data virtualserver.Data\n\terr = shared.MarshalInterface(dbRecord.Data, &data)\n\tif err != nil {\n\t\treturn\n\t}\n\t////////////////////////////////////////////////////////////////////////////\n\t// Test required fields.\n\t////////////////////////////////////////////////////////////////////////////\n\tok = true\n\trequired := make(map[string]bool)\n\trequired[\"ProductCode\"] = false\n\trequired[\"IP\"] = false\n\trequired[\"Port\"] = false\n\trequired[\"LoadBalancerIP\"] = false\n\trequired[\"Name\"] = false\n\t////////////////////////////////////////////////////////////////////////////\n\tif data.ProductCode != 0 {\n\t\trequired[\"ProductCode\"] = true\n\t}\n\tif len(dbRecord.LoadBalancerIP) > 0 {\n\t\trequired[\"LoadBalancerIP\"] = true\n\t}\n\tif len(data.Ports) != 0 {\n\t\trequired[\"Port\"] = true\n\t}\n\tif data.IP != \"\" {\n\t\trequired[\"IP\"] = true\n\t}\n\tif data.Name != \"\" {\n\t\trequired[\"Name\"] = true\n\t}\n\tfor _, val := range required {\n\t\tif val == false {\n\t\t\tok = false\n\t\t}\n\t}\n\tif !ok {\n\t\terr = fmt.Errorf(\"missing required fields - %+v\", required)\n\t}\n\treturn\n}", "func (user *User) Validate(action string) map[string]string {\n\tvar errMessages = make(map[string]string)\n\tvar err error\n\n\tswitch strings.ToLower(action) {\n\tcase \"update\":\n\t\tif user.Email == \"\" {\n\t\t\terrMessages[\"email_required\"] = \"email required\"\n\t\t}\n\n\t\tif user.Email != \"\" {\n\t\t\tif err = checkmail.ValidateFormat(user.Email); err != nil {\n\t\t\t\terrMessages[\"invalid_email\"] = \"invalid email\"\n\t\t\t}\n\t\t}\n\tcase \"login\":\n\t\tif user.Password == \"\" {\n\t\t\terrMessages[\"password_required\"] = \"password is required\"\n\t\t}\n\n\t\tif user.Email == \"\" {\n\t\t\terrMessages[\"email_required\"] = \"email required\"\n\t\t}\n\n\t\tif user.Email != \"\" {\n\t\t\tif err = checkmail.ValidateFormat(user.Email); err != nil {\n\t\t\t\terrMessages[\"invalid_email\"] = \"invalid email\"\n\t\t\t}\n\t\t}\n\tcase \"forgotpassword\":\n\t\tif user.Email == \"\" {\n\t\t\terrMessages[\"email_required\"] = \"email required\"\n\t\t}\n\t\tif user.Email != \"\" {\n\t\t\tif err = checkmail.ValidateFormat(user.Email); err != nil {\n\t\t\t\terrMessages[\"invalid_email\"] = \"please provide a valid email\"\n\t\t\t}\n\t\t}\n\tdefault:\n\t\tif user.FirstName == \"\" {\n\t\t\terrMessages[\"firstname_required\"] = \"first name is required\"\n\t\t}\n\n\t\tif user.LastName == \"\" {\n\t\t\terrMessages[\"lastname_required\"] = \"last name is required\"\n\t\t}\n\n\t\tif user.Password == \"\" {\n\t\t\terrMessages[\"password_required\"] = \"password is required\"\n\t\t}\n\n\t\tif user.Password != \"\" && len(user.Password) < 6 {\n\t\t\terrMessages[\"invalid_password\"] = \"password should be at least 6 characters\"\n\t\t}\n\n\t\tif user.Email == \"\" {\n\t\t\terrMessages[\"email_required\"] = \"email is required\"\n\t\t}\n\n\t\tif user.Email != \"\" {\n\t\t\tif err = checkmail.ValidateFormat(user.Email); err != nil {\n\t\t\t\terrMessages[\"invalid_email\"] = \"please provide a valid email\"\n\t\t\t}\n\t\t}\n\t}\n\n\treturn errMessages\n}", "func (a *Application) Validate(tx *pop.Connection) (*validate.Errors, error) {\n\treturn validate.Validate(\n\t\t&validators.StringIsPresent{Field: a.FirstName, Name: \"FirstName\"},\n\t\t&validators.StringIsPresent{Field: a.LastName, Name: \"LastName\"},\n\t), nil\n}", "func (uuo *UserUpdateOne) check() error {\n\tif v, ok := uuo.mutation.Username(); ok {\n\t\tif err := user.UsernameValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"username\", err: fmt.Errorf(\"ent: validator failed for field \\\"username\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.Fullname(); ok {\n\t\tif err := user.FullnameValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"fullname\", err: fmt.Errorf(\"ent: validator failed for field \\\"fullname\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.Password(); ok {\n\t\tif err := user.PasswordValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"password\", err: fmt.Errorf(\"ent: validator failed for field \\\"password\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.Email(); ok {\n\t\tif err := user.EmailValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"email\", err: fmt.Errorf(\"ent: validator failed for field \\\"email\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.Phone(); ok {\n\t\tif err := user.PhoneValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"phone\", err: fmt.Errorf(\"ent: validator failed for field \\\"phone\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.Bio(); ok {\n\t\tif err := user.BioValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"bio\", err: fmt.Errorf(\"ent: validator failed for field \\\"bio\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.Intro(); ok {\n\t\tif err := user.IntroValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"intro\", err: fmt.Errorf(\"ent: validator failed for field \\\"intro\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.GithubProfile(); ok {\n\t\tif err := user.GithubProfileValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"github_profile\", err: fmt.Errorf(\"ent: validator failed for field \\\"github_profile\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.ProfilePictureURL(); ok {\n\t\tif err := user.ProfilePictureURLValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"profile_picture_url\", err: fmt.Errorf(\"ent: validator failed for field \\\"profile_picture_url\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.Status(); ok {\n\t\tif err := user.StatusValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"status\", err: fmt.Errorf(\"ent: validator failed for field \\\"status\\\": %w\", err)}\n\t\t}\n\t}\n\treturn nil\n}", "func (r updateReq) Validate() error {\n\terr := r.addReq.Validate()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif r.ServiceAccountID != r.Body.ID {\n\t\treturn fmt.Errorf(\"service account ID mismatch, you requested to update ServiceAccount = %s but body contains ServiceAccount = %s\", r.ServiceAccountID, r.Body.ID)\n\t}\n\treturn nil\n}", "func (bu *BankdetailUpdate) check() error {\n\tif v, ok := bu.mutation.BankAccountNo(); ok {\n\t\tif err := bankdetail.BankAccountNoValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"Bank_AccountNo\", err: fmt.Errorf(\"ent: validator failed for field \\\"Bank_AccountNo\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := bu.mutation.BankName(); ok {\n\t\tif err := bankdetail.BankNameValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"Bank_Name\", err: fmt.Errorf(\"ent: validator failed for field \\\"Bank_Name\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := bu.mutation.BankAccountName(); ok {\n\t\tif err := bankdetail.BankAccountNameValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"Bank_AccountName\", err: fmt.Errorf(\"ent: validator failed for field \\\"Bank_AccountName\\\": %w\", err)}\n\t\t}\n\t}\n\treturn nil\n}", "func (rc *RentalCreate) check() error {\n\tif _, ok := rc.mutation.Date(); !ok {\n\t\treturn &ValidationError{Name: \"date\", err: errors.New(`ent: missing required field \"Rental.date\"`)}\n\t}\n\tif _, ok := rc.mutation.UserID(); !ok {\n\t\treturn &ValidationError{Name: \"user_id\", err: errors.New(`ent: missing required field \"Rental.user_id\"`)}\n\t}\n\tif _, ok := rc.mutation.CarID(); !ok {\n\t\treturn &ValidationError{Name: \"car_id\", err: errors.New(`ent: missing required field \"Rental.car_id\"`)}\n\t}\n\tif _, ok := rc.mutation.UserID(); !ok {\n\t\treturn &ValidationError{Name: \"user\", err: errors.New(`ent: missing required edge \"Rental.user\"`)}\n\t}\n\tif _, ok := rc.mutation.CarID(); !ok {\n\t\treturn &ValidationError{Name: \"car\", err: errors.New(`ent: missing required edge \"Rental.car\"`)}\n\t}\n\treturn nil\n}", "func (m *ContactAccountAttributesAccountWith) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (m *Customer) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateAutoCollection(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateBalances(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateBillingAddress(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateBillingDateMode(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateBillingDayOfWeek(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateBillingDayOfWeekMode(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateContacts(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateEntityCode(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateFraudFlag(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validatePaymentMethod(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateReferralUrls(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateTaxability(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (m *OBWriteInternational3DataInitiationDebtorAccount) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateIdentification(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateName(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateSchemeName(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateSecondaryIdentification(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (m *ClusterVcenterAccount) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (e *RetrieveBalance) Validate(\n\tr *http.Request,\n) error {\n\tctx := r.Context()\n\n\t// Validate id.\n\tid, owner, token, err := ValidateID(ctx, pat.Param(r, \"balance\"))\n\tif err != nil {\n\t\treturn errors.Trace(err)\n\t}\n\te.ID = *id\n\te.Token = *token\n\te.Owner = *owner\n\n\treturn nil\n}", "func (u *User) Validate() ([]app.Invalid, error) {\n\tvar inv []app.Invalid\n\n\tif u.UserType == 0 {\n\t\tinv = append(inv, app.Invalid{Fld: \"UserType\", Err: \"The value of UserType cannot be 0.\"})\n\t}\n\n\tif u.FirstName == \"\" {\n\t\tinv = append(inv, app.Invalid{Fld: \"FirstName\", Err: \"A value of FirstName cannot be empty.\"})\n\t}\n\n\tif u.LastName == \"\" {\n\t\tinv = append(inv, app.Invalid{Fld: \"LastName\", Err: \"A value of LastName cannot be empty.\"})\n\t}\n\n\tif u.Email == \"\" {\n\t\tinv = append(inv, app.Invalid{Fld: \"Email\", Err: \"A value of Email cannot be empty.\"})\n\t}\n\n\tif u.Company == \"\" {\n\t\tinv = append(inv, app.Invalid{Fld: \"Company\", Err: \"A value of Company cannot be empty.\"})\n\t}\n\n\tif len(u.Addresses) == 0 {\n\t\tinv = append(inv, app.Invalid{Fld: \"Addresses\", Err: \"There must be at least one address.\"})\n\t} else {\n\t\tfor _, ua := range u.Addresses {\n\t\t\tif va, err := ua.Validate(); err != nil {\n\t\t\t\tinv = append(inv, va...)\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(inv) > 0 {\n\t\treturn inv, errors.New(\"Validation failures identified\")\n\t}\n\n\treturn nil, nil\n}", "func ValidateGetAccountResponseBody(body *GetAccountResponseBody) (err error) {\n\tif body.Account != nil {\n\t\tif err2 := ValidateRelayerAccountResponseBody(body.Account); err2 != nil {\n\t\t\terr = goa.MergeErrors(err, err2)\n\t\t}\n\t}\n\treturn\n}", "func (p *Pass) FieldsValid() bool {\n\tfmt.Printf(\"validating: \")\n\tvalid := true\n\tfor k, v := range *p {\n\t\tfmt.Printf(\"%v...\", k)\n\t\tv := isFieldValid(k, v)\n\t\tvalid = valid && v\n\t\tif v {\n\t\t\tfmt.Printf(\"VALID \")\n\t\t} else {\n\t\t\tfmt.Printf(\"INVALID \")\n\t\t}\n\t}\n\n\tfmt.Println(\"\")\n\treturn valid\n}", "func (t AuthToken) Validate() error {\n\t// Holds names of empty fields\n\tempty := []string{}\n\n\t// Check user id\n\tif len(t.UserID) == 0 {\n\t\tempty = append(empty, \"UserID\")\n\t}\n\n\t// Check device id\n\tif len(t.DeviceID) == 0 {\n\t\tempty = append(empty, \"DeviceID\")\n\t}\n\n\t// Check if any empty fields\n\tif len(empty) != 0 {\n\t\treturn fmt.Errorf(\"the following fields were empty: %s\",\n\t\t\tStrings.join(empty))\n\t}\n\n\t// All good\n\treturn nil\n}", "func (p *Passport) ValidateStrict(input string) {\r\n\tbyr := regexp.MustCompile(`byr:(\\d*)`)\r\n\tif byr.MatchString(input) {\r\n\t\tmatches := byr.FindStringSubmatch(input)\r\n\t\tf, err := NewYearField(matches[1], byrMin, byrMax)\r\n\t\tif err == nil {\r\n\t\t\tp.byr = f\r\n\t\t}\r\n\t}\r\n\r\n\tiyr := regexp.MustCompile(`iyr:(\\d*)`)\r\n\tif iyr.MatchString(input) {\r\n\t\tmatches := iyr.FindStringSubmatch(input)\r\n\t\tf, err := NewYearField(matches[1], iyrMin, iyrMax)\r\n\t\tif err == nil {\r\n\t\t\tp.iyr = f\r\n\t\t}\r\n\t}\r\n\r\n\teyr := regexp.MustCompile(`eyr:(\\d*)`)\r\n\tif eyr.MatchString(input) {\r\n\t\tmatches := eyr.FindStringSubmatch(input)\r\n\t\tf, err := NewYearField(matches[1], eyrMin, eyrMax)\r\n\t\tif err == nil {\r\n\t\t\tp.eyr = f\r\n\t\t}\r\n\t}\r\n\r\n\thgt := regexp.MustCompile(`hgt:(\\d*)(cm|in)?`)\r\n\tif hgt.MatchString(input) {\r\n\t\tmatches := hgt.FindStringSubmatch(input)\r\n\t\tf, err := NewHeightField(matches[1], matches[2])\r\n\t\tif err == nil {\r\n\t\t\tp.hgt = f\r\n\t\t}\r\n\t}\r\n\r\n\thcl := regexp.MustCompile(`hcl:(#[a-f0-9]*)`)\r\n\tif hcl.MatchString(input) {\r\n\t\tmatches := hcl.FindStringSubmatch(input)\r\n\t\tf, err := NewTextField(matches[1], hclExp)\r\n\t\tif err == nil {\r\n\t\t\tp.hcl = f\r\n\t\t}\r\n\t}\r\n\r\n\tecl := regexp.MustCompile(`ecl:(\\w*)`)\r\n\tif ecl.MatchString(input) {\r\n\t\tmatches := ecl.FindStringSubmatch(input)\r\n\t\tf, err := NewTextField(matches[1], eclExp)\r\n\t\tif err == nil {\r\n\t\t\tp.ecl = f\r\n\t\t}\r\n\t}\r\n\r\n\tpid := regexp.MustCompile(`pid:(\\d*)`)\r\n\tif pid.MatchString(input) {\r\n\t\tmatches := pid.FindStringSubmatch(input)\r\n\t\tf, err := NewTextField(matches[1], pidExp)\r\n\t\tif err == nil {\r\n\t\t\tp.pid = f\r\n\t\t}\r\n\t}\r\n}", "func (u *User) Validate(tx *pop.Connection) (*validate.Errors, error) {\n\treturn validate.Validate(\n\t\t&validators.StringIsPresent{Field: u.Email, Name: \"Email\"},\n\t\t&validators.StringIsPresent{Field: u.FirstName, Name: \"FirstName\"},\n\t\t&validators.StringIsPresent{Field: u.LastName, Name: \"LastName\"},\n\t\t&validators.StringIsPresent{Field: u.Nickname, Name: \"Nickname\"},\n\t\t&validators.UUIDIsPresent{Field: u.UUID, Name: \"UUID\"},\n\t\t&NullsStringIsURL{Field: u.AuthPhotoURL, Name: \"AuthPhotoURL\"},\n\t\t&domain.StringIsVisible{Field: u.Nickname, Name: \"Nickname\"},\n\t), nil\n}", "func (r *registrationRequest) isValid() error {\n\n\t//check recaptcha\n\trc := recaptcha.R{Secret: config.CaptchaSecretKey}\n\tif !rc.VerifyResponse(r.Captcha) {\n\t\treturn fmt.Errorf(\"ReCaptcha error: %s\", strings.Join(rc.LastError()[1:], \", \"))\n\t}\n\n\t// check if any of this is empty\n\tif r.Email == \"\" || r.Password == \"\" || r.PasswordConfirmation == \"\" ||\n\t\tr.First == \"\" || r.Last == \"\" {\n\t\treturn fmt.Errorf(\"%s\\n\", \"You entered incomplete data. First and last name, email and \"+\n\t\t\t\"password are mandatory fields.\")\n\t}\n\n\t// check if the password match and that the length is at least 8 chars\n\treturn passwordsAreValid(r.Password, r.PasswordConfirmation)\n}", "func (i *infoOptions) validate() error {\n\t// date-field required\n\tif len(i.DateField) == 0 {\n\t\treturn errors.New(`date-field required`)\n\t}\n\n\t// date-field index value if sep is present\n\tif len(i.Sep) > 0 {\n\t\t// attempt to convert DateField to int\n\t\tvar err error\n\t\t_, err = strconv.Atoi(i.DateField)\n\t\tif err != nil {\n\t\t\treturn errors.New(`date-field must be an integer when using a csv field separator`)\n\t\t}\n\t}\n\n\t// dest-template required\n\tif i.DestTemplate == \"\" {\n\t\treturn errors.New(`dest-template required`)\n\t}\n\n\treturn nil\n}", "func (p paymentJson) Validate() error {\n\tif p.AccountId == \"\" {\n\t\treturn errors.New(\"missing customer id\")\n\t}\n\tif p.Amount == 0 {\n\t\treturn errors.New(\"missing amount\")\n\t}\n\treturn nil\n}", "func Validation(a User) error {\n\tfmt.Println(\"user :: \", a)\n\tvar rxEmail = regexp.MustCompile(\"^[a-zA-Z0-9.!#$%&'*+\\\\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$\")\n\tswitch {\n\tcase len(strings.TrimSpace(a.Password)) == 0:\n\t\treturn ErrPasswordInvalid\n\tcase len(strings.TrimSpace(a.Email)) == 0 || !rxEmail.MatchString(a.Email):\n\t\treturn ErrEmailInvalid\n\tdefault:\n\t\treturn nil\n\t}\n}", "func (account *DatabaseAccount) createValidations() []func() (admission.Warnings, error) {\n\treturn []func() (admission.Warnings, error){account.validateResourceReferences, account.validateSecretDestinations}\n}" ]
[ "0.6950377", "0.6660194", "0.6604518", "0.660115", "0.6589453", "0.6474401", "0.6469365", "0.6463922", "0.64215875", "0.63889915", "0.6362919", "0.63358384", "0.6252108", "0.62329525", "0.6229978", "0.61784095", "0.61675555", "0.61494285", "0.6107046", "0.6084981", "0.6062506", "0.6018709", "0.59835136", "0.5935781", "0.59250987", "0.5920425", "0.5918846", "0.5906061", "0.58879864", "0.5874278", "0.5862281", "0.5844713", "0.5843288", "0.58394945", "0.58318245", "0.58267343", "0.5805197", "0.5782027", "0.577867", "0.5762948", "0.57397187", "0.57109004", "0.567482", "0.5670878", "0.5664908", "0.5659827", "0.56587", "0.5648205", "0.5621579", "0.55948484", "0.55910474", "0.5587459", "0.55859625", "0.55767894", "0.5549079", "0.5528815", "0.5525437", "0.5523396", "0.551239", "0.55084354", "0.55050844", "0.54942113", "0.54916596", "0.5487635", "0.5478365", "0.54646176", "0.54524314", "0.54512787", "0.5443251", "0.54331243", "0.5430431", "0.54267573", "0.54245096", "0.5422896", "0.54207206", "0.54192007", "0.54148257", "0.540501", "0.5398671", "0.5397307", "0.5396947", "0.5394909", "0.53946984", "0.53905594", "0.53878796", "0.5384738", "0.5380616", "0.53800863", "0.53762895", "0.5367286", "0.5357383", "0.5353596", "0.5347578", "0.5342094", "0.5340789", "0.53367335", "0.5334526", "0.5331692", "0.5330748", "0.532834" ]
0.55917954
50
NewPermanentLockedAccount returns a PermanentLockedAccount
func NewPermanentLockedAccount(baseAcc *authtypes.BaseAccount, coins sdk.Coins) *PermanentLockedAccount { baseVestingAcc := &BaseVestingAccount{ BaseAccount: baseAcc, OriginalVesting: coins, EndTime: 0, // ensure EndTime is set to 0, as PermanentLockedAccount's do not have an EndTime } return &PermanentLockedAccount{baseVestingAcc} }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (msg MsgCreatePermanentLockedAccount) Type() string { return TypeMsgCreatePermanentLockedAccount }", "func newAccount() *Account {\n\treturn &Account{\n\t\tblocks: make(map[string]uint64),\n\t}\n}", "func NewMsgCreatePermanentLockedAccount(fromAddr, toAddr sdk.AccAddress, amount sdk.Coins) *MsgCreatePermanentLockedAccount {\n\treturn &MsgCreatePermanentLockedAccount{\n\t\tFromAddress: fromAddr.String(),\n\t\tToAddress: toAddr.String(),\n\t\tAmount: amount,\n\t}\n}", "func newAccountManager() *AccountManager {\r\n\taccountManager := new(AccountManager)\r\n\treturn accountManager\r\n}", "func (e Account) EntNew() ent.Ent { return &Account{} }", "func (e Account) EntNew() ent.Ent { return &Account{} }", "func newLogin() (Login, error) {\n\tp, err := hash(\"admin\")\n\tif err != nil {\n\t\treturn Login{}, err\n\t}\n\treturn Login{Username: \"admin\", Password: p}, nil\n}", "func NewAgedAccountsPayable()(*AgedAccountsPayable) {\n m := &AgedAccountsPayable{\n }\n m.backingStore = ie8677ce2c7e1b4c22e9c3827ecd078d41185424dd9eeb92b7d971ed2d49a392e.BackingStoreFactoryInstance();\n m.SetAdditionalData(make(map[string]any))\n return m\n}", "func tNewUser(lbl string) *tUser {\n\tintBytes := make([]byte, 4)\n\tbinary.BigEndian.PutUint32(intBytes, acctCounter)\n\tacctID := account.AccountID{}\n\tcopy(acctID[:], acctTemplate[:])\n\tcopy(acctID[account.HashSize-4:], intBytes)\n\taddr := strconv.Itoa(int(acctCounter))\n\tsig := []byte{0xab} // Just to differentiate from the addr.\n\tsig = append(sig, intBytes...)\n\tsigHex := hex.EncodeToString(sig)\n\tacctCounter++\n\treturn &tUser{\n\t\tsig: sig,\n\t\tsigHex: sigHex,\n\t\tacct: acctID,\n\t\taddr: addr,\n\t\tlbl: lbl,\n\t}\n}", "func newRandomAccountPersistence() accountPersistence {\n\taid, sk := modules.NewAccountID()\n\treturn accountPersistence{\n\t\tAccountID: aid,\n\t\tBalance: types.NewCurrency64(fastrand.Uint64n(1e3)),\n\t\tHostKey: types.SiaPublicKey{},\n\t\tSecretKey: sk,\n\t}\n}", "func New(dir *utils.Directory, db *database.Manager) (p *Permanent) {\n\treturn &Permanent{\n\t\tSettings: NewSettings(dir.Path(\"settings.bin\")),\n\t\tCommitments: NewCommitments(dir.Path(\"commitments.bin\")),\n\t\tUnspentOutputs: lo.PanicOnErr(db.PermanentStorage().WithExtendedRealm([]byte{unspentOutputsPrefix})),\n\n\t\tunspentOutputIDs: lo.PanicOnErr(db.PermanentStorage().WithExtendedRealm([]byte{unspentOutputIDsPrefix})),\n\t\tattestations: lo.PanicOnErr(db.PermanentStorage().WithExtendedRealm([]byte{attestationsPrefix})),\n\t\tsybilProtection: lo.PanicOnErr(db.PermanentStorage().WithExtendedRealm([]byte{consensusWeightsPrefix})),\n\t\tthroughputQuota: lo.PanicOnErr(db.PermanentStorage().WithExtendedRealm([]byte{throughputQuotaPrefix})),\n\t}\n}", "func NewLockedJob(j *Job, success func() error, error func(string) error) *LockedJob {\n\treturn &LockedJob{\n\t\tJob: j,\n\t\tsuccess: success,\n\t\terror: error,\n\t}\n}", "func (ak AccountKeeper) NewAccount(ctx sdk.Context, acc exported.Account) exported.Account {\n\t// FIXME: update account number\n\treturn acc\n}", "func (c *CoinTest) newAccount(stub shim.ChaincodeStubInterface, args []string) pb.Response {\r\n\tvar id string\r\n\tvar asset int\r\n\tvar err error\r\n\r\n\tif len(args) == 1{\r\n\t\tid = args[0]\r\n\t\tasset = 0\r\n\t}else if len(args) == 2{\r\n\t\tid = args[0]\r\n\t\t//asset, err = strconv.Atoi(args[1])\r\n\t\t//if err != nil{\r\n\t\t//\treturn shim.Error(\"Invalid asset amount, expecting a integer value\")\r\n\t\t//}\r\n\t\tasset = 0;\r\n\t}else{\r\n\t\treturn shim.Error(\"Incorrect number of arguments.\")\r\n\t}\r\n\r\n\t//deliver 0 number of TolakCoin to user\r\n\ttolakCoin.Token.Deliver(token.Address(id), int(asset))\r\n\r\n\t//write to ledger\r\n\terr = stub.PutState(id, []byte(strconv.Itoa(asset)))\r\n\tif err != nil{\r\n\t\treturn shim.Error(err.Error())\r\n\t}\r\n\r\n\treturn shim.Success(nil)\r\n}", "func (i *Inotify) newWatchLocked(d *Dentry, ws *Watches, mask uint32) *Watch {\n\tw := &Watch{\n\t\towner: i,\n\t\twd: i.nextWatchIDLocked(),\n\t\ttarget: d,\n\t\tmask: atomicbitops.FromUint32(mask),\n\t}\n\n\t// Hold the watch in this inotify instance as well as the watch set on the\n\t// target.\n\ti.watches[w.wd] = w\n\tws.Add(w)\n\treturn w\n}", "func (a *ActStatus) updateLocked(address arry.Address) types.IAccount {\n\tact := a.db.Account(address)\n\tact.UpdateLocked(a.confirmed)\n\treturn act\n}", "func (this *LockManager) NewLock(name string, expiry int) *Lock {\n\treturn &Lock{\n\t\tname: name,\n\t\texpire: time.Duration(expiry) * time.Second,\n\t\tmanager: this,\n\t}\n}", "func NewLock(period math.Duration, bonusTable eai.RateTable) *Lock {\n\treturn &Lock{\n\t\tNoticePeriod: period,\n\t\tBonus: bonusTable.RateAt(period),\n\t}\n}", "func (msg MsgCreatePermanentLockedAccount) Route() string { return RouterKey }", "func newLockBased() Interface {\n\tgate := &lockBased{}\n\tgate.mux.Lock()\n\treturn gate\n}", "func NewLock(item string, kvs KVS) *Lock {\n\treturn &Lock{\n\t\tBaseDir: baseLockDir,\n\t\tItem: item,\n\t\tKVS: kvs,\n\t}\n}", "func NewFundingLocked(op wire.OutPoint, cid ShortChannelID,\n\tnpcp *btcec.PublicKey) *FundingLocked {\n\treturn &FundingLocked{\n\t\tChannelOutpoint: op,\n\t\tChannelID: cid,\n\t\tNextPerCommitmentPoint: npcp,\n\t}\n}", "func createAccount(gm *gomatrix.Client) (accessToken, userID string, err error) {\n username := \"testing-\" + randString(5)\n // Get the session token\n req := &gomatrix.ReqRegister{\n Username: username,\n Password: testPass,\n }\n _, respInt, err := gm.Register(req)\n if err != nil {\n return\n }\n\n // Make a dummy register request\n req = &gomatrix.ReqRegister{\n Username: username,\n Password: testPass,\n Auth: struct {\n Session string\n }{\n Session: respInt.Session,\n },\n }\n resp, err := gm.RegisterDummy(req)\n if err != nil {\n return\n }\n\n // Save the access token and UserID\n accessToken = resp.AccessToken\n userID = resp.UserID\n return\n}", "func Open(initial int64) Account {\n\tif initial < 0 {\n\t\treturn nil\n\t}\n\treturn &basicAccount{balance: initial, active: true}\n}", "func newServiceAccount(cr *storagev1.CSIPowerMaxRevProxy) *v1.ServiceAccount {\n\treturn &v1.ServiceAccount{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: ReverseProxyName,\n\t\t\tNamespace: cr.Namespace,\n\t\t\tOwnerReferences: getOwnerReferences(cr),\n\t\t},\n\t}\n}", "func (r *Registry) newQueueLocked(ctx context.Context, key ipc.Key, creds *auth.Credentials, mode linux.FileMode) (*Queue, error) {\n\tq := &Queue{\n\t\tregistry: r,\n\t\tobj: ipc.NewObject(r.reg.UserNS, key, creds, creds, mode),\n\t\tsendTime: ktime.ZeroTime,\n\t\treceiveTime: ktime.ZeroTime,\n\t\tchangeTime: ktime.NowFromContext(ctx),\n\t\tmaxBytes: maxQueueBytes,\n\t}\n\n\terr := r.reg.Register(q)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn q, nil\n}", "func NewAccount(owner string) *Account {\n\treturn &Account{owner: owner, balance: 0}\n}", "func New() GoroutineLock {\n\treturn GoroutineLock(getGoroutineID())\n}", "func NewLock() Lock {\n\treturn Lock{ch: make(chan struct{}, 1)}\n}", "func NewUserSettings()(*UserSettings) {\n m := &UserSettings{\n Entity: *NewEntity(),\n }\n return m\n}", "func NewAccount() *Account {\n\n\tcreatedAccount := Account{}\n\n\tnewPrivateKey, err := generatePrivateKey(4096)\n\tif err != nil {\n\t\tlog.Fatal(\"Error generating rsa private key \", err)\n\t}\n\tnewPublicKey, err := generatePublicKey(&newPrivateKey.PublicKey)\n\tif err != nil {\n\t\tlog.Fatal(\"Error generating rsa public key \", err)\n\t}\n\tcreatedAccount.privateKey = newPrivateKey\n\tcreatedAccount.Address = string(newPublicKey)\n\tcreatedAccount.Amount = 0\n\n\treturn &createdAccount\n}", "func (plva PermanentLockedAccount) Validate() error {\n\tif plva.EndTime > 0 {\n\t\treturn errors.New(\"permanently vested accounts cannot have an end-time\")\n\t}\n\n\treturn plva.BaseVestingAccount.Validate()\n}", "func newLockMap() *lockMap {\n\treturn &lockMap{\n\t\tmutexMap: make(map[string]*sync.Mutex),\n\t}\n}", "func New(u *url.URL) (godilock.DLocker, error) {\n\thost := u.Host\n\tif err := zklock.Connect(strings.Split(host, \",\"), 20*time.Second); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &LockManager{\n\t\tprefix: u.Path,\n\t\tsession: make(map[string]*zklock.Dlocker),\n\t}, nil\n}", "func New(name string) *FileLock {\n\treturn &FileLock{\n\t\tname: name,\n\t\tpath: \"/tmp\",\n\t\tprefix: \"flock-\",\n\t\tflockType: syscall.LOCK_EX,\n\t}\n}", "func (r opResult) createMemAccountForSpillStrategy(\n\tctx context.Context, flowCtx *execinfra.FlowCtx, opName string, processorID int32,\n) (*mon.BoundAccount, string) {\n\tmonitorName := r.getMemMonitorName(opName, processorID, \"limited\" /* suffix */)\n\tbufferingOpMemMonitor := execinfra.NewLimitedMonitor(\n\t\tctx, flowCtx.EvalCtx.Mon, flowCtx.Cfg, monitorName,\n\t)\n\tr.OpMonitors = append(r.OpMonitors, bufferingOpMemMonitor)\n\tbufferingMemAccount := bufferingOpMemMonitor.MakeBoundAccount()\n\tr.OpAccounts = append(r.OpAccounts, &bufferingMemAccount)\n\treturn &bufferingMemAccount, monitorName\n}", "func MakeNewAccount(name string) (*MyAccount, error) {\n\tkeys, err := NewKeypair()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &MyAccount{\n\t\tFields: make(map[string]string),\n\t\tKeys: keys,\n\t\tName: name,\n\t}, nil\n}", "func accountCreate(ctx *cli.Context) error {\n\n\tdataDir := ctx.GlobalString(utils.DataDirFlag.Name)\n\t//get keyStoreDir from KeyStoreDirFlag, if not use the default value\n\tkeyStoreDir := ctx.GlobalString(utils.KeyStoreDirFlag.Name)\n\tif keyStoreDir == \"\" {\n\t\tkeyStoreDir = keystore.KeyStoreScheme\n\t}\n\tkeyStoreDir = filepath.Join(dataDir, keyStoreDir)\n\tpassword := getPassPhrase(\"Your new account is locked with a password. Please give a password. Do not forget this password.\", true, 0, utils.MakePasswordList(ctx))\n\t_, err := utils.NewAccount(keyStoreDir, password)\n\n\treturn err\n}", "func NewAccount(addr, amount string) *Account {\n\tam := big.NewInt(0)\n\tam.SetString(amount, 0)\n\treturn &Account{Address: addr, Amount: am}\n}", "func newLockingWriteCloser(wc io.WriteCloser) io.WriteCloser {\n\treturn &lockingWriteCloser{WriteCloser: wc}\n}", "func newLocalUserFromIdentity(identity tlsca.Identity) authz.LocalUser {\n\treturn authz.LocalUser{\n\t\tUsername: identity.Username,\n\t\tIdentity: identity,\n\t}\n}", "func unlocked(res string) Lock {\n\treturn Lock{res, res, time.Time{}}\n}", "func NewAccount(txr *repository.Transactioner) repository.Account {\n\treturn &account{txr: txr}\n}", "func newPeriodicVestingAccount(address sdk.AccAddress, periods vestingtypes.Periods, firstPeriodStartTimestamp int64) *vestingtypes.PeriodicVestingAccount {\n\tbaseAccount := authtypes.NewBaseAccount(address, nil, 0, 0)\n\n\toriginalVesting := sdk.NewCoins()\n\tfor _, p := range periods {\n\t\toriginalVesting = originalVesting.Add(p.Amount...)\n\t}\n\n\tvar totalPeriods int64\n\tfor _, p := range periods {\n\t\ttotalPeriods += p.Length\n\t}\n\tendTime := firstPeriodStartTimestamp + totalPeriods\n\n\tbaseVestingAccount := vestingtypes.NewBaseVestingAccount(baseAccount, originalVesting, endTime)\n\treturn vestingtypes.NewPeriodicVestingAccountRaw(baseVestingAccount, firstPeriodStartTimestamp, periods)\n}", "func NewPermit(cacheTime int64, now int64) *Permit {\n\tif now == 0 {\n\t\tnow = time.Now().Unix()\n\t}\n\n\treturn &Permit{\n\t\tValidUntil: now + cacheTime,\n\t}\n}", "func newLockState() *lockState {\n\treturn &lockState{\n\t\tlocks: make(map[string]string),\n\t}\n}", "func NewAccount(user, apiKey string) *Account {\n\treturn &Account{user: user, apiKey: apiKey}\n}", "func newJobID(tm Time) (Job, error) {\n\tk, err := ksuid.NewRandomWithTime(tm)\n\tif err != nil {\n\t\treturn Job{}, err\n\t}\n\treturn Job(k), nil\n}", "func (policy *ticketPolicy) OnCreateNewAccount(acc *types.Account) {\n}", "func Open(amt int) *Account {\n\tif amt < 0 {\n\t\treturn nil\n\t}\n\treturn &Account{amt, true}\n}", "func (repo *Repository) Create(ctx context.Context, claims auth.Claims, req UserAccountCreateRequest, now time.Time) (*UserAccount, error) {\n\tspan, ctx := tracer.StartSpanFromContext(ctx, \"internal.user_account.Create\")\n\tdefer span.Finish()\n\n\t// Validate the request.\n\tv := webcontext.Validator()\n\terr := v.Struct(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Ensure the claims can modify the account specified in the request.\n\terr = repo.CanModifyAccount(ctx, claims, req.AccountID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// If now empty set it to the current time.\n\tif now.IsZero() {\n\t\tnow = time.Now()\n\t}\n\n\t// Always store the time as UTC.\n\tnow = now.UTC()\n\n\t// Postgres truncates times to milliseconds when storing. We and do the same\n\t// here so the value we return is consistent with what we store.\n\tnow = now.Truncate(time.Millisecond)\n\n\t// Check to see if there is an existing user account, including archived.\n\texistQuery := selectQuery()\n\texistQuery.Where(existQuery.And(\n\t\texistQuery.Equal(\"account_id\", req.AccountID),\n\t\texistQuery.Equal(\"user_id\", req.UserID),\n\t))\n\texisting, err := find(ctx, claims, repo.DbConn, existQuery, []interface{}{}, true)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// If there is an existing entry, then update instead of insert.\n\tvar ua UserAccount\n\tif len(existing) > 0 {\n\t\tupReq := UserAccountUpdateRequest{\n\t\t\tUserID: req.UserID,\n\t\t\tAccountID: req.AccountID,\n\t\t\tRoles: &req.Roles,\n\t\t\tunArchive: true,\n\t\t}\n\t\terr = repo.Update(ctx, claims, upReq, now)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tua = *existing[0]\n\t\tua.Roles = req.Roles\n\t\tua.UpdatedAt = now\n\t\tua.ArchivedAt = nil\n\t} else {\n\t\tuaID := uuid.NewRandom().String()\n\n\t\tua = UserAccount{\n\t\t\t//ID: uaID,\n\t\t\tUserID: req.UserID,\n\t\t\tAccountID: req.AccountID,\n\t\t\tRoles: req.Roles,\n\t\t\tStatus: UserAccountStatus_Active,\n\t\t\tCreatedAt: now,\n\t\t\tUpdatedAt: now,\n\t\t}\n\n\t\tif req.Status != nil {\n\t\t\tua.Status = *req.Status\n\t\t}\n\n\t\t// Build the insert SQL statement.\n\t\tquery := sqlbuilder.NewInsertBuilder()\n\t\tquery.InsertInto(userAccountTableName)\n\t\tquery.Cols(\"id\", \"user_id\", \"account_id\", \"roles\", \"status\", \"created_at\", \"updated_at\")\n\t\tquery.Values(uaID, ua.UserID, ua.AccountID, ua.Roles, ua.Status.String(), ua.CreatedAt, ua.UpdatedAt)\n\n\t\t// Execute the query with the provided context.\n\t\tsql, args := query.Build()\n\t\tsql = repo.DbConn.Rebind(sql)\n\t\t_, err = repo.DbConn.ExecContext(ctx, sql, args...)\n\t\tif err != nil {\n\t\t\terr = errors.Wrapf(err, \"query - %s\", query.String())\n\t\t\terr = errors.WithMessagef(err, \"add account %s to user %s failed\", req.AccountID, req.UserID)\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn &ua, nil\n}", "func (as *Service) Create(name, iamRole, externalID string) (*Account, error) {\n\n\tbody := map[string]map[string]string{\n\t\t\"account\": {\"name\": name},\n\t}\n\n\tlog.Printf(\"Making request %v\\n\", body)\n\treq, err := as.httpClient.NewRequest(http.MethodPost, \"/setup/account\", &body)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar v common.Response\n\t_, err = as.httpClient.Do(req, &v)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(v.Response.Items) == 0 {\n\t\treturn nil, errors.New(\"Couldn't create account\")\n\t}\n\tvar account Account\n\n\tfmt.Println(string(v.Response.Items[0]))\n\n\terr = json.Unmarshal(v.Response.Items[0], &account)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttime.Sleep(time.Second * 5)\n\n\terr = as.setupCloudCredentials(account.ID, iamRole, externalID)\n\n\tif err != nil {\n\t\t_ = as.Delete(account.ID)\n\t\treturn nil, err\n\t}\n\n\treturn &account, nil\n}", "func (l *ChainLedger) GetOrCreateAccount(addr types.Address) *Account {\n\th := addr.Hex()\n\tvalue, ok := l.accounts[h]\n\tif ok {\n\t\treturn value\n\t}\n\n\taccount := l.GetAccount(addr)\n\tl.accounts[h] = account\n\n\treturn account\n}", "func (plva PermanentLockedAccount) LockedCoins(_ sdk.Context) sdk.Coins {\n\treturn plva.BaseVestingAccount.LockedCoinsFromVesting(plva.OriginalVesting)\n}", "func NewCustomAccounting(h modules.Host, m modules.Miner, r modules.Renter, w modules.Wallet, persistDir string, deps modules.Dependencies) (*Accounting, error) {\n\t// Check that at least the wallet is not nil\n\tif w == nil {\n\t\treturn nil, errNilWallet\n\t}\n\n\t// Check required parameters\n\tif persistDir == \"\" {\n\t\treturn nil, errNilPersistDir\n\t}\n\tif deps == nil {\n\t\treturn nil, errNilDeps\n\t}\n\n\t// Initialize the accounting\n\ta := &Accounting{\n\t\tstaticHost: h,\n\t\tstaticMiner: m,\n\t\tstaticRenter: r,\n\t\tstaticWallet: w,\n\n\t\tstaticPersistDir: persistDir,\n\n\t\tstaticDeps: deps,\n\t}\n\n\t// Initialize the persistence\n\terr := a.initPersist()\n\tif err != nil {\n\t\treturn nil, errors.AddContext(err, \"unable to initialize the persistence\")\n\t}\n\n\t// Launch background thread to persist the accounting information\n\tif !a.staticDeps.Disrupt(\"DisablePersistLoop\") {\n\t\tgo a.callThreadedPersistAccounting()\n\t}\n\treturn a, nil\n}", "func (w *Wallet) NewAccount(index *uint32) (a *Account, err error) {\n\tindex2 := w.nextIndex\n\tif index != nil {\n\t\tindex2 = *index\n\t}\n\ta = &Account{w: w, index: index2}\n\tif err = w.impl.deriveAccount(a); err != nil {\n\t\treturn\n\t}\n\tpubkeyToAddress := util.PubkeyToAddress\n\tif w.isBanano {\n\t\tpubkeyToAddress = util.PubkeyToBananoAddress\n\t}\n\tif a.address, err = pubkeyToAddress(a.pubkey); err != nil {\n\t\treturn\n\t}\n\tif index == nil {\n\t\tw.nextIndex++\n\t}\n\tif _, ok := w.accounts[a.address]; !ok {\n\t\tw.accounts[a.address] = a\n\t} else if index == nil {\n\t\treturn w.NewAccount(nil)\n\t}\n\treturn\n}", "func NewOutlookUser()(*OutlookUser) {\n m := &OutlookUser{\n Entity: *NewEntity(),\n }\n return m\n}", "func NewSynchronizationJob()(*SynchronizationJob) {\n m := &SynchronizationJob{\n Entity: *NewEntity(),\n }\n return m\n}", "func newCacheItem() *cacheItem {\n\treturn &cacheItem{atime: time.Now()}\n}", "func (ks *KeyStore) NewAccount(passphrase string) (accounts.Account, error) {\n\t_, account, err := storeNewKey(ks.storage, crand.Reader, passphrase)\n\tif err != nil {\n\t\treturn accounts.Account{}, err\n\t}\n\treturn account, nil\n}", "func generateNewAccount() string {\n\taccount := crypto.GenerateAccount()\n\tpassphrase, err := mnemonic.FromPrivateKey(account.PrivateKey)\n\tif err != nil {\n\t\tfmt.Printf(\"Error creating new account: %s\\n\", err)\n\t} else {\n\t\tfmt.Printf(\"Created new account: %s\\n\", account.Address)\n\t\tfmt.Printf(\"Generated mnemonic: \\\"%s\\\"\\n\", passphrase)\n\t}\n\treturn account.Address.String()\n}", "func NewAccount() *Account {\n\tacc := &Account{}\n\tpriv, pub := newKeyPair()\n\tacc.PriKey = priv\n\tacc.PubKey = pub\n\treturn acc\n}", "func newAtomicBased(rate int, opts ...Option) *atomicLimiter {\r\n\tconfig := buildConfig(opts)\r\n\tl := &atomicLimiter{\r\n\t\tperRequest: config.per / time.Duration(rate),\r\n\t\tmaxSlack: -1 * config.maxSlack * time.Second / time.Duration(rate),\r\n\t\tclock: config.clock,\r\n\t}\r\n\r\n\tinitialState := state{\r\n\t\tlast: time.Time{},\r\n\t\tsleepFor: 0,\r\n\t}\r\n\tatomic.StorePointer(&l.state, unsafe.Pointer(&initialState))\r\n\treturn l\r\n}", "func (account *Account) New() {\n\n\tparams, _ := pbc.NewParamsFromString(crypto.Params)\n\tpairing := params.NewPairing()\n\n\tA := pairing.NewG1()\n\tAT := pairing.NewG1()\n\ta := pairing.NewZr()\n\n\ta.Rand()\n\n\tG := pairing.NewG1()\n\tT := pairing.NewG1()\n\tG.SetString(crypto.G, 10)\n\tT.SetString(crypto.T, 10)\n\n\tA.PowZn(G, a)\n\tAT.PowZn(T, a)\n\n\taccount.a = a.String()\n\taccount.A = A.String()\n\taccount.AT = AT.String()\n}", "func Open(initialDeposit int64) *Account {\n\tif initialDeposit < 0 {\n\t\treturn nil\n\t}\n\treturn &Account{\n\t\topen: true,\n\t\tbalance: initialDeposit,\n\t\tmutex: &sync.RWMutex{},\n\t}\n}", "func NewInformationProtection()(*InformationProtection) {\n m := &InformationProtection{\n Entity: *NewEntity(),\n }\n return m\n}", "func NewLock(lockKeyPrefix string, keyParamNames []string) *Lock {\n\treturn &Lock{lockKeyPrefix, keyParamNames}\n}", "func putPatriciaNew(ptr patricia, bucket string, cb db.CachedBatch) ([]byte, error) {\n\tvalue, err := ptr.serialize()\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to encode patricia node\")\n\t}\n\tkey := ptr.hash()\n\tlogger.Debug().Hex(\"key\", key[:8]).Msg(\"putnew\")\n\treturn key[:], cb.PutIfNotExists(bucket, key[:], value, \"failed to put non-existing key = %x\", key)\n}", "func Open(initialDeposit int64) *Account {\n\tif initialDeposit < 0 { // No bank account for you if you don't put in that money\n\t\treturn nil\n\t}\n\treturn &Account{open: true, balance: initialDeposit, mutex: sync.Mutex{}} // opens the bank account and passes a lock with the account to perform operations\n}", "func NewAllocAccount(val string) AllocAccountField {\n\treturn AllocAccountField{quickfix.FIXString(val)}\n}", "func newLogin(token string) (*login, error) {\n\tif token == \"\" {\n\t\treturn nil, nil\n\t}\n\tlogin := &login{\n\t\ttoken: token,\n\t}\n\tif err := validateLogin(login); err != nil {\n\t\treturn nil, err\n\t}\n\treturn login, nil\n}", "func makeAccount(){\n\toperatorSecret, err := hedera.SecretKeyFromString(secret)\n\tif err != nil{\n\t\tpanic(err)\n\t}\n\n\tsecretKey, _ := hedera.GenerateSecretKey()\n\tpublic := secretKey.Public()\n\n\tfmt.Printf(\"secret = %v\\n\", secretKey)\n\tfmt.Printf(\"public = %v\\n\", public)\n\n\tclient, err := hedera.Dial(server)\n\tif err !=nil{\n\t\tpanic(err)\n\t}\n\tdefer client.Close()\n\n\tnodeAccountID := hedera.AccountID{Account: 3}\n\toperatorAccountID := hedera.AccountID{Account: 1001}\n\ttime.Sleep(2* time.Second)\n\tresponse, err := client.CreateAccount().Key(public).InitialBalance(0).Operator(operatorAccountID).Node(nodeAccountID).Memo(\"Test make Account\").Sign(operatorSecret).Execute()\n\tif err != nil{\n\t\tpanic(err)\n\t}\n\n\ttransactionID := response.ID\n\tfmt.Printf(\"Created account; transaction = %v\\n\", transactionID)\n\ttime.Sleep(2* time.Second)\n \n\treceipt,err := client.Transaction(*transactionID).Receipt().Get()\n\tif err != nil{\n\t\tpanic(err)\n\t}\n\tfmt.Printf(\"Account = %v\\n\", *receipt.AccountID)\n\n}", "func Open(initialDeposit int64) *Account {\n\tif initialDeposit < 0 {\n\t\treturn nil\n\t}\n\treturn &Account{\n\t\tbalance: initialDeposit,\n\t\topen: true,\n\t\tmu: sync.Mutex{},\n\t}\n}", "func (biz *BizAccountAccess) newAccountAccess(ctx context.Context, tx *sql.Tx,\n\tu coremodel.User, accType coremodel.AccountAccessType,\n) (*coremodel.AccountAccess, error) {\n\tac, err := coremodel.NewAccountAccess(u, accType)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif err = biz.dal.Insert(ctx, tx, ac); err != nil {\n\t\treturn nil, err\n\t}\n\treturn ac, nil\n}", "func newJob(job Runnable, priority int) JobEntry {\n\treturn &pt{\n\t\tpriority: priority,\n\t\tjob: job,\n\t\tlock: &sync.Mutex{},\n\t}\n}", "func NewLock(ctx context.Context, db *sql.DB, cfg Config) (*Lock, error) {\n\tp := &util.Prepare{Ctx: ctx, DB: db}\n\treturn &Lock{\n\t\tdb: db,\n\t\tcfg: cfg,\n\t\tadvLockStmt: p.P(`select pg_try_advisory_xact_lock_shared($1)`),\n\t\tlockStmt: p.P(`\n\t\t\tselect version\n\t\t\tfrom engine_processing_versions\n\t\t\twhere type_id = $1\n\t\t\tfor update nowait\n\t\t`),\n\t\tloadState: p.P(`select state from engine_processing_versions where type_id = $1 for update nowait`),\n\t\tsaveState: p.P(`update engine_processing_versions set state = $2 where type_id = $1`),\n\t}, p.Err\n}", "func CreateNewLocalSecretManager() *LocalSecretManager {\n\treturn &LocalSecretManager{}\n}", "func newUser(userID interface{}) *User {\n\treturn &User{connMap: newConnMap(), id: userID}\n}", "func (p *politeiawww) addUserToPaywallPoolLock(u *user.User, paywallType string) {\n\tif !p.paywallIsEnabled() {\n\t\treturn\n\t}\n\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tp.addUserToPaywallPool(u, paywallType)\n}", "func NewLockbasedTxMgr(db privacyenabledstate.DB, tStore transientstore.Store) *TransientHandlerTxMgr {\n\treturn &TransientHandlerTxMgr{lockbasedtxmgr.NewLockBasedTxMgr(db, tStore), tStore}\n}", "func Open(basic int64) *Account {\n\tif basic < 0 {\n\t\treturn nil\n\t}\n\treturn &Account{amt: basic}\n}", "func (r *DefaultMultiTenantManager) newManager(ctx context.Context, userID string) (RulesManager, error) {\n\t// Create a new Prometheus registry and register it within\n\t// our metrics struct for the provided user if it doesn't already exist.\n\treg := prometheus.NewRegistry()\n\tr.userManagerMetrics.AddUserRegistry(userID, reg)\n\n\tnotifier, err := r.getOrCreateNotifier(userID, reg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn r.managerFactory(ctx, userID, notifier, r.logger, reg), nil\n}", "func New(userInfo user.Info, clusterContext *config.UserContext) (Impersonator, error) {\n\timpersonator := Impersonator{\n\t\tclusterContext: clusterContext,\n\t\tuserLister: clusterContext.Management.Management.Users(\"\").Controller().Lister(),\n\t\tuserAttributeLister: clusterContext.Management.Management.UserAttributes(\"\").Controller().Lister(),\n\t}\n\tuser, err := impersonator.getUser(userInfo)\n\timpersonator.user = user\n\tif err != nil {\n\t\treturn Impersonator{}, err\n\t}\n\n\treturn impersonator, nil\n}", "func New(expire, maid int) (*Cache){\n if expire==0 {\n expire = defaultExpiringDuration\n }\n if maid==0 {\n maid = defaultMaidDuration\n }\n\n expireDuration, _ := time.ParseDuration(fmt.Sprintf(\"%dm\", expire))\n maidDuration, _ := time.ParseDuration(fmt.Sprintf(\"%dm\", maid))\n\n //Make sure that no one is calling New at the same time.\n //Lock and Unlock the same mutex and set the old cache as invalid.\n cache.cacheMutex.Lock()\n cache.isValid = false\n cache.cacheMutex.Unlock()\n\n //Create the new cache\n cache = &Cache{\n cache: map[string]value{},\n expire: expireDuration,\n maid: maidDuration,\n isValid: false}\n\n go callMaid(cache)\n\n //Set cache as valid before returning\n cache.isValid = true\n return cache\n}", "func NewLockfile(path string) (*Lockfile, error) {\n\treturn nil, fmt.Errorf(\"not implemented\")\n}", "func createTempUser(host string, adminToken string) (user ssUser, err error) {\n\t//double duty as unique name/login\n\tsuffix, err := diceware.Generate(2)\n\tif err != nil {\n\t\tsuffix = []string{string(time.Now().Nanosecond()), string(time.Now().UnixNano())}\n\t}\n\tpassword, err := diceware.Generate(3)\n\tif err != nil {\n\t\tpassword = []string{string(time.Now().Nanosecond()), os.Getenv(\"OPS_TEAM_NAME\"), string(time.Now().UnixNano())}\n\t}\n\terr = nil\n\tuser.login = os.Getenv(\"OPS_TEAM_NAME\") + \"-\" + strings.Join(suffix, \"\")\n\tuser.password = strings.Join(password, \"\")\n\n\tcreatePostForm := url.Values{}\n\tcreatePostForm.Set(\"login\", user.login)\n\tcreatePostForm.Set(\"name\", user.login)\n\tcreatePostForm.Set(\"password\", user.password)\n\n\treq, err := http.NewRequest(\"POST\", host+\"/api/users/create\", strings.NewReader(createPostForm.Encode()))\n\tif err != nil {\n\t\treturn\n\t}\n\treq.SetBasicAuth(adminToken, \"\")\n\treq.Header.Set(\"Content-Type\", \"application/x-www-form-urlencoded\")\n\n\tcreateResp, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tdefer createResp.Body.Close()\n\tif createResp.StatusCode != 200 {\n\t\terr = errors.New(\"Failed to create user, expected status code 200 got\" + string(createResp.StatusCode))\n\t}\n\treturn\n}", "func (r opResult) createMemAccountForSpillStrategyWithLimit(\n\tctx context.Context, flowCtx *execinfra.FlowCtx, limit int64, opName string, processorID int32,\n) (*mon.BoundAccount, string) {\n\tif flowCtx.Cfg.TestingKnobs.ForceDiskSpill {\n\t\tlimit = 1\n\t}\n\tmonitorName := r.getMemMonitorName(opName, processorID, \"limited\" /* suffix */)\n\tbufferingOpMemMonitor := mon.NewMonitorInheritWithLimit(monitorName, limit, flowCtx.EvalCtx.Mon)\n\tbufferingOpMemMonitor.Start(ctx, flowCtx.EvalCtx.Mon, mon.BoundAccount{})\n\tr.OpMonitors = append(r.OpMonitors, bufferingOpMemMonitor)\n\tbufferingMemAccount := bufferingOpMemMonitor.MakeBoundAccount()\n\tr.OpAccounts = append(r.OpAccounts, &bufferingMemAccount)\n\treturn &bufferingMemAccount, monitorName\n}", "func New() lock.Locker {\n\tc := make(chan struct{}, 1)\n\tc <- struct{}{}\n\treturn &trivial {\n\t\tc: c,\n\t}\n}", "func NewAccount(email string, password string) (*Account, error) {\n\taccount := &Account{Email: email}\n\tencryptedPassword, err := utils.Encrypt(password)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\taccount.ID = primitive.NewObjectID()\n\taccount.Password = string(encryptedPassword)\n\ttNow := time.Now()\n\taccount.CreatedAt = &tNow\n\taccount.repo = repoimpl.GetAccountRepo()\n\treturn account, nil\n}", "func (m *MgoUserManager) newUser(email, pwd string, app bool) (*auth.User, error) {\n\tif !m.Formater.EmailValidate(email) {\n\t\treturn nil, auth.ErrInvalidEmail\n\t}\n\n\tif !m.Formater.PasswordValidate(pwd) {\n\t\treturn nil, auth.ErrInvalidPassword\n\t}\n\n\tu := &auth.User{}\n\tu.Id = bson.NewObjectId()\n\tu.Email = email\n\tu.LastActivity = time.Now()\n\tu.Info.JoinDay = u.LastActivity\n\n\tp, err := auth.HashPwd(pwd)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tu.Pwd = p\n\n\tu.Approved = app\n\tif !app {\n\t\tu.ConfirmCodes = map[string]string{\n\t\t\t\"activate\": base64.URLEncoding.EncodeToString(securecookie.GenerateRandomKey(64)),\n\t\t}\n\t}\n\n\treturn u, nil\n}", "func newLog(jobId string) Log {\n\treturn Log{\n\t\tId: uniuri.New(),\n\t\tJobId: jobId,\n\t\tStatus: \"New\",\n\t}\n}", "func NewPlanner()(*Planner) {\n m := &Planner{\n Entity: *NewEntity(),\n }\n return m\n}", "func (account *Account) Mine() transaction.Transaction {\n\n\tparams, _ := pbc.NewParamsFromString(crypto.Params)\n\tpairing := params.NewPairing()\n\n\tvar tx transaction.Transaction\n\tRA := pairing.NewG1()\n\tRT := pairing.NewG1()\n\tV := pairing.NewG1()\n\tP := pairing.NewG1()\n\n\tr := pairing.NewZr()\n\tr.Rand()\n\n\tT := pairing.NewG1()\n\tT.SetString(crypto.T, 10)\n\n\tA := pairing.NewG1()\n\tA.SetString(account.A, 10)\n\n\ttx.Base = true\n\tRA.PowZn(A, r)\n\tRT.PowZn(T, r)\n\tP.SetString(crypto.GetP(r.String(), account.AT, account.A), 10)\n\tV.SetString(crypto.GetV(r.String(), account.AT), 10)\n\n\ttx.RA = RA.String()\n\ttx.RT = RT.String()\n\ttx.P = P.String()\n\ttx.V = V.String()\n\ttx.Setp(crypto.Getp(account.a, RT.String()))\n\n\taccount.Wallet[account.WalletIndex] = tx\n\taccount.WalletIndex++\n\n\tfmt.Println(\"\\033[1;31;40m\", \"We mined a new tx:\", tx.P, \"\\033[0m\")\n\n\treturn tx\n}", "func openSavedAccount(name string, cfg *config) (*Account, error) {\n\tnetdir := networkDir(cfg.Net())\n\tif err := checkCreateDir(netdir); err != nil {\n\t\treturn nil, &walletOpenError{\n\t\t\tErr: err.Error(),\n\t\t}\n\t}\n\n\twlt := new(wallet.Wallet)\n\ttxs := txstore.New()\n\ta := &Account{\n\t\tname: name,\n\t\tWallet: wlt,\n\t\tTxStore: txs,\n\t}\n\n\twfilepath := accountFilename(\"wallet.bin\", name, netdir)\n\ttxfilepath := accountFilename(\"tx.bin\", name, netdir)\n\tvar wfile, txfile *os.File\n\n\t// Read wallet file.\n\twfile, err := os.Open(wfilepath)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\t// Must create and save wallet first.\n\t\t\treturn nil, errNoWallet\n\t\t}\n\t\tmsg := fmt.Sprintf(\"cannot open wallet file: %s\", err)\n\t\treturn nil, &walletOpenError{msg}\n\t}\n\tdefer wfile.Close()\n\n\tif _, err = wlt.ReadFrom(wfile); err != nil {\n\t\tmsg := fmt.Sprintf(\"cannot read wallet: %s\", err)\n\t\treturn nil, &walletOpenError{msg}\n\t}\n\n\t// Read tx file. If this fails, return a errNoTxs error and let\n\t// the caller decide if a rescan is necessary.\n\tvar finalErr error\n\tif txfile, err = os.Open(txfilepath); err != nil {\n\t\tlog.Errorf(\"cannot open tx file: %s\", err)\n\t\t// This is not a error we should immediately return with,\n\t\t// but other errors can be more important, so only return\n\t\t// this if none of the others are hit.\n\t\tfinalErr = errNoTxs\n\t\ta.fullRescan = true\n\t} else {\n\t\tdefer txfile.Close()\n\t\tif _, err = txs.ReadFrom(txfile); err != nil {\n\t\t\tlog.Errorf(\"cannot read tx file: %s\", err)\n\t\t\ta.fullRescan = true\n\t\t\tfinalErr = errNoTxs\n\t\t}\n\t}\n\n\treturn a, finalErr\n}", "func NewPausableToken(address common.Address, backend bind.ContractBackend) (*PausableToken, error) {\n\tcontract, err := bindPausableToken(address, backend, backend, backend)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &PausableToken{PausableTokenCaller: PausableTokenCaller{contract: contract}, PausableTokenTransactor: PausableTokenTransactor{contract: contract}, PausableTokenFilterer: PausableTokenFilterer{contract: contract}}, nil\n}", "func newBase() *base {\n\treturn &base{shared.NewUUID(), time.Now().UTC(), time.Now().UTC(), false/*, shared.NewUUID()*/}\n}", "func New() Lock {\n\treturn &lock{sem: make(chan int, 1)}\n}", "func NewLockedRandom(r Random) Random {\n\treturn &lockedRandom{r: r}\n}", "func New() target.Locker {\n\treturn &Noop{}\n}", "func newPassCred(username, password string, secure bool) credentials.PerRPCCredentials {\n\treturn &passCred{\n\t\tusername: username,\n\t\tpassword: password,\n\t\tsecure: secure,\n\t}\n}" ]
[ "0.6613212", "0.5847004", "0.584218", "0.55508304", "0.53399056", "0.53399056", "0.52914137", "0.521402", "0.51721936", "0.5150324", "0.51409805", "0.51152074", "0.5111328", "0.5099049", "0.5050154", "0.5040955", "0.5030609", "0.49957147", "0.49862966", "0.4979736", "0.4974968", "0.4948576", "0.49292913", "0.49082008", "0.48958585", "0.48939243", "0.48899743", "0.4881603", "0.48740196", "0.48623747", "0.48425803", "0.48186094", "0.48179993", "0.48129514", "0.48083466", "0.48063377", "0.4801581", "0.48003784", "0.47818527", "0.47694272", "0.47603175", "0.476014", "0.47491115", "0.47481814", "0.47481152", "0.4746334", "0.47314057", "0.47234178", "0.4705069", "0.46990725", "0.4685633", "0.4672828", "0.466781", "0.46469507", "0.4646424", "0.46428823", "0.46423042", "0.4631317", "0.4624894", "0.46233577", "0.4619296", "0.4612729", "0.46103203", "0.46033737", "0.4603008", "0.4601136", "0.45937824", "0.45817998", "0.4580907", "0.4573351", "0.4568345", "0.45678112", "0.456412", "0.45460922", "0.4532444", "0.4521084", "0.45186996", "0.45174256", "0.4516538", "0.45101565", "0.45050377", "0.4500559", "0.4497779", "0.44922563", "0.449081", "0.4490226", "0.4488042", "0.4486617", "0.44822714", "0.4478627", "0.44747505", "0.44699883", "0.44679427", "0.44674578", "0.44650695", "0.44638115", "0.44635144", "0.44607016", "0.44564542", "0.44519418" ]
0.7643574
0
GetVestedCoins returns the total amount of vested coins for a permanent locked vesting account. All coins are only vested once the schedule has elapsed.
func (plva PermanentLockedAccount) GetVestedCoins(_ time.Time) sdk.Coins { return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (pva PeriodicVestingAccount) GetVestedCoins(blockTime time.Time) sdk.Coins {\n\tcoins := ReadSchedule(pva.StartTime, pva.EndTime, pva.VestingPeriods, pva.OriginalVesting, blockTime.Unix())\n\tif coins.IsZero() {\n\t\treturn nil\n\t}\n\treturn coins\n}", "func (va ClawbackVestingAccount) GetVestedCoins(blockTime time.Time) sdk.Coins {\n\t// It's likely that one or the other schedule will be nearly trivial,\n\t// so there should be little overhead in recomputing the conjunction each time.\n\tcoins := coinsMin(va.GetUnlockedOnly(blockTime), va.GetVestedOnly(blockTime))\n\tif coins.IsZero() {\n\t\treturn nil\n\t}\n\treturn coins\n}", "func (dva DelayedVestingAccount) GetVestedCoins(blockTime time.Time) sdk.Coins {\n\tif blockTime.Unix() >= dva.EndTime {\n\t\treturn dva.OriginalVesting\n\t}\n\n\treturn nil\n}", "func (plva PermanentLockedAccount) GetVestingCoins(_ time.Time) sdk.Coins {\n\treturn plva.OriginalVesting\n}", "func (cva ContinuousVestingAccount) GetVestedCoins(blockTime time.Time) sdk.Coins {\n\tvar vestedCoins sdk.Coins\n\n\t// We must handle the case where the start time for a vesting account has\n\t// been set into the future or when the start of the chain is not exactly\n\t// known.\n\tif blockTime.Unix() <= cva.StartTime {\n\t\treturn vestedCoins\n\t} else if blockTime.Unix() >= cva.EndTime {\n\t\treturn cva.OriginalVesting\n\t}\n\n\t// calculate the vesting scalar\n\tx := blockTime.Unix() - cva.StartTime\n\ty := cva.EndTime - cva.StartTime\n\ts := sdk.NewDec(x).Quo(sdk.NewDec(y))\n\n\tfor _, ovc := range cva.OriginalVesting {\n\t\tvestedAmt := ovc.Amount.ToDec().Mul(s).RoundInt()\n\t\tvestedCoins = append(vestedCoins, sdk.NewCoin(ovc.Denom, vestedAmt))\n\t}\n\n\treturn vestedCoins\n}", "func (vva ValidatorVestingAccount) GetVestedCoins(blockTime time.Time) sdk.Coins {\n\tvar vestedCoins sdk.Coins\n\tif blockTime.Unix() <= vva.StartTime {\n\t\treturn vestedCoins\n\t}\n\tcurrentPeriodStartTime := vva.StartTime\n\tnumberPeriods := len(vva.VestingPeriods)\n\tfor i := 0; i < numberPeriods; i++ {\n\t\tx := blockTime.Unix() - currentPeriodStartTime\n\t\tif x >= vva.VestingPeriods[i].Length {\n\t\t\tif vva.VestingPeriodProgress[i].PeriodComplete {\n\t\t\t\tvestedCoins = vestedCoins.Add(vva.VestingPeriods[i].Amount)\n\t\t\t}\n\t\t\tcurrentPeriodStartTime += vva.VestingPeriods[i].Length\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn vestedCoins\n\n}", "func (cva ContinuousVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn cva.OriginalVesting.Sub(cva.GetVestedCoins(blockTime))\n}", "func (dva DelayedVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn dva.OriginalVesting.Sub(dva.GetVestedCoins(blockTime))\n}", "func (pva PeriodicVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn pva.OriginalVesting.Sub(pva.GetVestedCoins(blockTime))\n}", "func (va ClawbackVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn va.OriginalVesting.Sub(va.GetVestedCoins(blockTime))\n}", "func (vva ValidatorVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn vva.OriginalVesting.Sub(vva.GetVestedCoins(blockTime))\n}", "func (cva ContinuousVestingAccount) LockedCoins(ctx sdk.Context) sdk.Coins {\n\treturn cva.BaseVestingAccount.LockedCoinsFromVesting(cva.GetVestingCoins(ctx.BlockTime()))\n}", "func (va ClawbackVestingAccount) GetVestedOnly(blockTime time.Time) sdk.Coins {\n\treturn ReadSchedule(va.StartTime, va.EndTime, va.VestingPeriods, va.OriginalVesting, blockTime.Unix())\n}", "func (pva PeriodicVestingAccount) LockedCoins(ctx sdk.Context) sdk.Coins {\n\treturn pva.BaseVestingAccount.LockedCoinsFromVesting(pva.GetVestingCoins(ctx.BlockTime()))\n}", "func (va ClawbackVestingAccount) LockedCoins(ctx sdk.Context) sdk.Coins {\n\treturn va.BaseVestingAccount.LockedCoinsFromVesting(va.GetVestingCoins(ctx.BlockTime()))\n}", "func (dva DelayedVestingAccount) LockedCoins(ctx sdk.Context) sdk.Coins {\n\treturn dva.BaseVestingAccount.LockedCoinsFromVesting(dva.GetVestingCoins(ctx.BlockTime()))\n}", "func (plva PermanentLockedAccount) LockedCoins(_ sdk.Context) sdk.Coins {\n\treturn plva.BaseVestingAccount.LockedCoinsFromVesting(plva.OriginalVesting)\n}", "func (vva ValidatorVestingAccount) GetFailedVestedCoins() sdk.Coins {\n\tvar failedVestedCoins sdk.Coins\n\tnumberPeriods := len(vva.VestingPeriods)\n\tfor i := 0; i < numberPeriods; i++ {\n\t\tif vva.VestingPeriodProgress[i].PeriodComplete {\n\t\t\tif !vva.VestingPeriodProgress[i].VestingSuccessful {\n\t\t\t\tfailedVestedCoins = failedVestedCoins.Add(vva.VestingPeriods[i].Amount)\n\t\t\t}\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn failedVestedCoins\n}", "func (bva BaseVestingAccount) LockedCoinsFromVesting(vestingCoins sdk.Coins) sdk.Coins {\n\tlockedCoins := vestingCoins.Sub(vestingCoins.Min(bva.DelegatedVesting))\n\tif lockedCoins == nil {\n\t\treturn sdk.Coins{}\n\t}\n\treturn lockedCoins\n}", "func (vva ValidatorVestingAccount) SpendableCoins(blockTime time.Time) sdk.Coins {\n\treturn vva.BaseVestingAccount.SpendableCoinsVestingAccount(vva.GetVestingCoins(blockTime))\n}", "func (keeper ViewKeeper) GetCoins(ctx sdk.Context, addr sdk.Address) sdk.Coins {\n\treturn getCoins(ctx, keeper.am, addr)\n}", "func (keeper BaseViewKeeper) GetCoins(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins {\n\treturn getCoins(ctx, keeper.am, addr)\n}", "func (keeper SendKeeper) GetCoins(ctx sdk.Context, addr sdk.Address) sdk.Coins {\n\treturn getCoins(ctx, keeper.am, addr)\n}", "func (ck CoinKeeper) GetCoins(ctx sdk.Context, addr sdk.Address, amt sdk.Coins) sdk.Coins {\n\tacc := ck.am.GetAccount(ctx, addr)\n\treturn acc.GetCoins()\n}", "func (keeper Keeper) GetCoins(ctx sdk.Context, addr sdk.Address) sdk.Coins {\n\treturn getCoins(ctx, keeper.am, addr)\n}", "func (_TokenVesting *TokenVestingCallerSession) VestedAmount(_token common.Address) (*big.Int, error) {\n\treturn _TokenVesting.Contract.VestedAmount(&_TokenVesting.CallOpts, _token)\n}", "func GetCoins() (coins []Coin, error error) {\n\tvar c = []Coin{}\n\tvar d struct {\n\t\tCrypto []Coin `json:\"crypto\"`\n\t}\n\tjsonData, err := doTauRequest(1, \"GET\", \"data/coins\", nil)\n\tif err != nil {\n\t\treturn c, err\n\t}\n\tif err := json.Unmarshal(jsonData, &d); err != nil {\n\t\treturn c, err\n\t}\n\treturn d.Crypto, nil\n}", "func (_TokenVesting *TokenVestingSession) VestedAmount(_token common.Address) (*big.Int, error) {\n\treturn _TokenVesting.Contract.VestedAmount(&_TokenVesting.CallOpts, _token)\n}", "func (_TokenVesting *TokenVestingCaller) VestedAmount(opts *bind.CallOpts, _token common.Address) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _TokenVesting.contract.Call(opts, out, \"vestedAmount\", _token)\n\treturn *ret0, err\n}", "func (dcr *ExchangeWallet) FundingCoins(ids []dex.Bytes) (asset.Coins, error) {\n\t// First check if we have the coins in cache.\n\tcoins := make(asset.Coins, 0, len(ids))\n\tnotFound := make(map[outPoint]bool)\n\tdcr.fundingMtx.Lock()\n\tdefer dcr.fundingMtx.Unlock() // stay locked until we update the map and lock them in the wallet\n\tfor _, id := range ids {\n\t\ttxHash, vout, err := decodeCoinID(id)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tpt := newOutPoint(txHash, vout)\n\t\tfundingCoin, found := dcr.fundingCoins[pt]\n\t\tif found {\n\t\t\tcoins = append(coins, fundingCoin.op)\n\t\t\tcontinue\n\t\t}\n\t\tnotFound[pt] = true\n\t}\n\tif len(notFound) == 0 {\n\t\treturn coins, nil\n\t}\n\n\t// Check locked outputs for not found coins.\n\tlockedOutputs, err := dcr.lockedOutputs()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor _, output := range lockedOutputs {\n\t\ttxHash, err := chainhash.NewHashFromStr(output.Txid)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error decoding txid from rpc server %s: %w\", output.Txid, err)\n\t\t}\n\t\tpt := newOutPoint(txHash, output.Vout)\n\t\tif !notFound[pt] {\n\t\t\tcontinue\n\t\t}\n\t\ttxOut, err := dcr.node.GetTxOut(dcr.ctx, txHash, output.Vout, true)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"gettxout error for locked output %v: %w\", pt.String(), translateRPCCancelErr(err))\n\t\t}\n\t\tvar address string\n\t\tif len(txOut.ScriptPubKey.Addresses) > 0 {\n\t\t\taddress = txOut.ScriptPubKey.Addresses[0]\n\t\t}\n\t\tcoin := newOutput(txHash, output.Vout, toAtoms(output.Amount), output.Tree)\n\t\tcoins = append(coins, coin)\n\t\tdcr.fundingCoins[pt] = &fundingCoin{\n\t\t\top: coin,\n\t\t\taddr: address,\n\t\t}\n\t\tdelete(notFound, pt)\n\t\tif len(notFound) == 0 {\n\t\t\treturn coins, nil\n\t\t}\n\t}\n\n\t// Some funding coins still not found after checking locked outputs.\n\t// Check wallet unspent outputs as last resort. Lock the coins if found.\n\tunspents, err := dcr.unspents()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcoinsToLock := make([]*wire.OutPoint, 0, len(notFound))\n\tfor _, txout := range unspents {\n\t\ttxHash, err := chainhash.NewHashFromStr(txout.TxID)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error decoding txid from rpc server %s: %w\", txout.TxID, err)\n\t\t}\n\t\tpt := newOutPoint(txHash, txout.Vout)\n\t\tif !notFound[pt] {\n\t\t\tcontinue\n\t\t}\n\t\tcoinsToLock = append(coinsToLock, wire.NewOutPoint(txHash, txout.Vout, txout.Tree))\n\t\tcoin := newOutput(txHash, txout.Vout, toAtoms(txout.Amount), txout.Tree)\n\t\tcoins = append(coins, coin)\n\t\tdcr.fundingCoins[pt] = &fundingCoin{\n\t\t\top: coin,\n\t\t\taddr: txout.Address,\n\t\t}\n\t\tdelete(notFound, pt)\n\t\tif len(notFound) == 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\tif len(notFound) != 0 {\n\t\tids := make([]string, 0, len(notFound))\n\t\tfor pt := range notFound {\n\t\t\tids = append(ids, pt.String())\n\t\t}\n\t\treturn nil, fmt.Errorf(\"funding coins not found: %s\", strings.Join(ids, \", \"))\n\t}\n\tdcr.log.Debugf(\"Locking funding coins that were unlocked %v\", coinsToLock)\n\terr = dcr.node.LockUnspent(dcr.ctx, false, coinsToLock)\n\tif err != nil {\n\t\treturn nil, translateRPCCancelErr(err)\n\t}\n\n\treturn coins, nil\n}", "func (dcr *ExchangeWallet) ReturnCoins(unspents asset.Coins) error {\n\tdcr.fundingMtx.Lock()\n\tdefer dcr.fundingMtx.Unlock()\n\treturn dcr.returnCoins(unspents)\n}", "func (_CrToken *CrTokenCallerSession) TotalReserves() (*big.Int, error) {\n\treturn _CrToken.Contract.TotalReserves(&_CrToken.CallOpts)\n}", "func (t *TauAPI) GetCoins() (coins []Coin, error error) {\n\tvar c = []Coin{}\n\tvar d struct {\n\t\tCrypto []Coin `json:\"cryto\"` //typo from api\n\t\tFiat []Coin `json:\"fiat\"`\n\t}\n\tjsonData, err := t.doTauRequest(&TauReq{\n\t\tVersion: 2,\n\t\tMethod: \"GET\",\n\t\tPath: \"coins\",\n\t})\n\tif err != nil {\n\t\treturn c, err\n\t}\n\tif err := json.Unmarshal(jsonData, &d); err != nil {\n\t\treturn c, err\n\t}\n\tc = append(d.Crypto, d.Fiat...)\n\treturn c, nil\n}", "func (o *AllocationList) GetInvested() float64 {\n\tif o == nil {\n\t\tvar ret float64\n\t\treturn ret\n\t}\n\n\treturn o.Invested\n}", "func (dcr *ExchangeWallet) FundingCoins(ids []dex.Bytes) (asset.Coins, error) {\n\t// First check if we have the coins in cache.\n\tcoins := make(asset.Coins, 0, len(ids))\n\tnotFound := make(map[outPoint]bool)\n\tdcr.fundingMtx.Lock()\n\tdefer dcr.fundingMtx.Unlock() // stay locked until we update the map and lock them in the wallet\n\tfor _, id := range ids {\n\t\ttxHash, vout, err := decodeCoinID(id)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tpt := newOutPoint(txHash, vout)\n\t\tfundingCoin, found := dcr.fundingCoins[pt]\n\t\tif found {\n\t\t\tcoins = append(coins, fundingCoin.op)\n\t\t\tcontinue\n\t\t}\n\t\tnotFound[pt] = true\n\t}\n\tif len(notFound) == 0 {\n\t\treturn coins, nil\n\t}\n\n\t// Check locked outputs for not found coins.\n\tfor _, acct := range dcr.fundingAccounts() {\n\t\tlockedOutputs, err := dcr.wallet.LockedOutputs(dcr.ctx, acct)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfor _, output := range lockedOutputs {\n\t\t\ttxHash, err := chainhash.NewHashFromStr(output.Txid)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"error decoding txid from rpc server %s: %w\", output.Txid, err)\n\t\t\t}\n\t\t\tpt := newOutPoint(txHash, output.Vout)\n\t\t\tif !notFound[pt] {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ttxOut, err := dcr.wallet.UnspentOutput(dcr.ctx, txHash, output.Vout, output.Tree)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"gettxout error for locked output %v: %w\", pt.String(), err)\n\t\t\t}\n\t\t\tvar address string\n\t\t\tif len(txOut.Addresses) > 0 {\n\t\t\t\taddress = txOut.Addresses[0]\n\t\t\t}\n\t\t\tcoin := newOutput(txHash, output.Vout, toAtoms(output.Amount), output.Tree)\n\t\t\tcoins = append(coins, coin)\n\t\t\tdcr.fundingCoins[pt] = &fundingCoin{\n\t\t\t\top: coin,\n\t\t\t\taddr: address,\n\t\t\t}\n\t\t\tdelete(notFound, pt)\n\t\t\tif len(notFound) == 0 {\n\t\t\t\treturn coins, nil\n\t\t\t}\n\t\t}\n\t}\n\n\t// Some funding coins still not found after checking locked outputs.\n\t// Check wallet unspent outputs as last resort. Lock the coins if found.\n\tcoinsToLock := make([]*wire.OutPoint, 0, len(notFound))\n\tfor _, acct := range dcr.fundingAccounts() {\n\t\tunspents, err := dcr.wallet.Unspents(dcr.ctx, acct)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfor _, txout := range unspents {\n\t\t\ttxHash, err := chainhash.NewHashFromStr(txout.TxID)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"error decoding txid from rpc server %s: %w\", txout.TxID, err)\n\t\t\t}\n\t\t\tpt := newOutPoint(txHash, txout.Vout)\n\t\t\tif !notFound[pt] {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tcoinsToLock = append(coinsToLock, wire.NewOutPoint(txHash, txout.Vout, txout.Tree))\n\t\t\tcoin := newOutput(txHash, txout.Vout, toAtoms(txout.Amount), txout.Tree)\n\t\t\tcoins = append(coins, coin)\n\t\t\tdcr.fundingCoins[pt] = &fundingCoin{\n\t\t\t\top: coin,\n\t\t\t\taddr: txout.Address,\n\t\t\t}\n\t\t\tdelete(notFound, pt)\n\t\t\tif len(notFound) == 0 {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\t// Return an error if some coins are still not found.\n\tif len(notFound) != 0 {\n\t\tids := make([]string, 0, len(notFound))\n\t\tfor pt := range notFound {\n\t\t\tids = append(ids, pt.String())\n\t\t}\n\t\treturn nil, fmt.Errorf(\"funding coins not found: %s\", strings.Join(ids, \", \"))\n\t}\n\n\tdcr.log.Debugf(\"Locking funding coins that were unlocked %v\", coinsToLock)\n\terr := dcr.wallet.LockUnspent(dcr.ctx, false, coinsToLock)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn coins, nil\n}", "func (_Bindings *BindingsCallerSession) TotalReserves() (*big.Int, error) {\n\treturn _Bindings.Contract.TotalReserves(&_Bindings.CallOpts)\n}", "func (o *AllocationList) SetInvested(v float64) {\n\to.Invested = v\n}", "func (_CrToken *CrTokenSession) TotalReserves() (*big.Int, error) {\n\treturn _CrToken.Contract.TotalReserves(&_CrToken.CallOpts)\n}", "func (c Cart) GetVoucherSavings() domain.Price {\n\tprice := domain.Price{}\n\tvar err error\n\n\tfor _, item := range c.Totalitems {\n\t\tif item.Type == TotalsTypeVoucher {\n\t\t\tprice, err = price.Add(item.Price)\n\t\t\tif err != nil {\n\t\t\t\treturn price\n\t\t\t}\n\t\t}\n\t}\n\n\tif price.IsNegative() {\n\t\treturn domain.Price{}\n\t}\n\n\treturn price\n}", "func (_Bindings *BindingsSession) TotalReserves() (*big.Int, error) {\n\treturn _Bindings.Contract.TotalReserves(&_Bindings.CallOpts)\n}", "func (_DelegationController *DelegationControllerTransactorSession) GetAndUpdateLockedAmount(wallet common.Address) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.GetAndUpdateLockedAmount(&_DelegationController.TransactOpts, wallet)\n}", "func (m *Client) GetCoins() ([]string, error) {\n\tresp, err := m.Service.GetCoins()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error requesting coin list: %s\", err)\n\t}\n\tdefer resp.Body.Close()\n\n\tvar response []string\n\terr = json.NewDecoder(resp.Body).Decode(&response)\n\tif err != nil {\n\t\tmsg, _ := ioutil.ReadAll(resp.Body)\n\t\treturn nil, fmt.Errorf(\"error decoding coin list: %s: %s\", msg, err)\n\t}\n\n\treturn response, nil\n}", "func (o *Transaction) GetCounterparties() []TransactionCounterparty {\n\tif o == nil || o.Counterparties == nil {\n\t\tvar ret []TransactionCounterparty\n\t\treturn ret\n\t}\n\treturn *o.Counterparties\n}", "func (_DelegationController *DelegationControllerSession) GetAndUpdateLockedAmount(wallet common.Address) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.GetAndUpdateLockedAmount(&_DelegationController.TransactOpts, wallet)\n}", "func (_DelegationController *DelegationControllerTransactor) GetAndUpdateLockedAmount(opts *bind.TransactOpts, wallet common.Address) (*types.Transaction, error) {\n\treturn _DelegationController.contract.Transact(opts, \"getAndUpdateLockedAmount\", wallet)\n}", "func (n Network) VestingAccounts(ctx context.Context, launchID uint64) (vestingAccs []networktypes.VestingAccount, err error) {\n\tn.ev.Send(events.New(events.StatusOngoing, \"Fetching genesis vesting accounts\"))\n\tres, err := n.launchQuery.\n\t\tVestingAccountAll(ctx,\n\t\t\t&launchtypes.QueryAllVestingAccountRequest{\n\t\t\t\tLaunchID: launchID,\n\t\t\t},\n\t\t)\n\tif err != nil {\n\t\treturn vestingAccs, err\n\t}\n\n\tfor i, acc := range res.VestingAccount {\n\t\tparsedAcc, err := networktypes.ToVestingAccount(acc)\n\t\tif err != nil {\n\t\t\treturn vestingAccs, errors.Wrapf(err, \"error parsing vesting account %d\", i)\n\t\t}\n\n\t\tvestingAccs = append(vestingAccs, parsedAcc)\n\t}\n\n\treturn vestingAccs, nil\n}", "func (btc *ExchangeWallet) FundingCoins(ids []dex.Bytes) (asset.Coins, error) {\n\t// First check if we have the coins in cache.\n\tcoins := make(asset.Coins, 0, len(ids))\n\tnotFound := make(map[string]struct{})\n\tbtc.fundingMtx.RLock()\n\tfor _, id := range ids {\n\t\ttxHash, vout, err := decodeCoinID(id)\n\t\tif err != nil {\n\t\t\tbtc.fundingMtx.RUnlock()\n\t\t\treturn nil, err\n\t\t}\n\t\topID := outpointID(txHash.String(), vout)\n\t\tfundingCoin, found := btc.fundingCoins[opID]\n\t\tif found {\n\t\t\tcoins = append(coins, newOutput(btc.node, txHash, vout, fundingCoin.amount, fundingCoin.redeemScript))\n\t\t\tcontinue\n\t\t}\n\t\tnotFound[opID] = struct{}{}\n\t}\n\tbtc.fundingMtx.RUnlock()\n\tif len(notFound) == 0 {\n\t\treturn coins, nil\n\t}\n\t_, utxoMap, _, err := btc.spendableUTXOs(0)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlockers := make([]*output, 0, len(ids))\n\tbtc.fundingMtx.Lock()\n\tdefer btc.fundingMtx.Unlock()\n\tfor _, id := range ids {\n\t\ttxHash, vout, err := decodeCoinID(id)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\topID := outpointID(txHash.String(), vout)\n\t\tutxo, found := utxoMap[opID]\n\t\tif !found {\n\t\t\treturn nil, fmt.Errorf(\"funding coin %s not found\", opID)\n\t\t}\n\t\tbtc.fundingCoins[opID] = utxo\n\t\tcoin := newOutput(btc.node, utxo.txHash, utxo.vout, utxo.amount, utxo.redeemScript)\n\t\tcoins = append(coins, coin)\n\t\tlockers = append(lockers, coin)\n\t\tdelete(notFound, opID)\n\t\tif len(notFound) == 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\tif len(notFound) != 0 {\n\t\tids := make([]string, 0, len(notFound))\n\t\tfor opID := range notFound {\n\t\t\tids = append(ids, opID)\n\t\t}\n\t\treturn nil, fmt.Errorf(\"coins not found: %s\", strings.Join(ids, \", \"))\n\t}\n\terr = btc.wallet.LockUnspent(false, lockers)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn coins, nil\n}", "func (p *Player) CashSpentTotal() int {\n\treturn p.AdditionalPlayerInformation.TotalCashSpent\n}", "func (_Bindings *BindingsTransactorSession) ReduceReserves(reduceAmount *big.Int) (*types.Transaction, error) {\n\treturn _Bindings.Contract.ReduceReserves(&_Bindings.TransactOpts, reduceAmount)\n}", "func (_CrToken *CrTokenCaller) TotalReserves(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _CrToken.contract.Call(opts, &out, \"totalReserves\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (_Univ2 *Univ2CallerSession) GetReserves() (struct {\n\tReserve0 *big.Int\n\tReserve1 *big.Int\n\tBlockTimestampLast uint32\n}, error) {\n\treturn _Univ2.Contract.GetReserves(&_Univ2.CallOpts)\n}", "func (candidate *Candidate) GetTotalBipStake() *big.Int {\n\tcandidate.lock.RLock()\n\tdefer candidate.lock.RUnlock()\n\n\treturn big.NewInt(0).Set(candidate.totalBipStake)\n}", "func (b *rpcVestingBalance) delegated() (sdk.Coins, sdk.Coins, error) {\n\tdelegatedCoins, err := b.totalDelegated()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tunbondingCoins, err := b.totalUnbondingDelegations()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tdelegated := delegatedCoins.AmountOf(stakingDenom)\n\tunbonding := unbondingCoins.AmountOf(stakingDenom)\n\ttotalStaked := delegated.Add(unbonding)\n\tdelegatedFree := b.vacc.GetDelegatedFree().AmountOf(stakingDenom)\n\n\t// total number of staked and unbonding tokens considered to be liquid\n\ttotalFree := sdk.MinInt(totalStaked, delegatedFree)\n\t// any coins that are not considered liquid, are vesting up to a maximum of delegated\n\tstakedVesting := sdk.MinInt(totalStaked.Sub(totalFree), delegated)\n\t// staked free coins are left over\n\tstakedFree := delegated.Sub(stakedVesting)\n\n\tliquidCoins := sdk.NewCoins(newKavaCoin(stakedFree))\n\tvestingCoins := sdk.NewCoins(newKavaCoin(stakedVesting))\n\treturn liquidCoins, vestingCoins, nil\n}", "func (_Bindings *BindingsCaller) TotalReserves(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _Bindings.contract.Call(opts, out, \"totalReserves\")\n\treturn *ret0, err\n}", "func (cm *ConnectionManager) sumDeposits() *big.Int {\n\tchs := cm.openChannels()\n\tvar sum = big.NewInt(0)\n\tfor _, c := range chs {\n\t\tsum.Add(sum, c.OurContractBalance)\n\t}\n\treturn sum\n}", "func GetCoins(accCoins []types.Coin) AccountCoins {\n\tcoins := make(AccountCoins, 0)\n\tfor _, coin := range accCoins {\n\t\tcoins = append(coins, AccountCoin{Amount: uint64(coin.Amount), Denom: coin.Denom})\n\t}\n\treturn coins\n}", "func (c *CoordinatorHelper) Coins(\n\tctx context.Context,\n\tdbTx storage.DatabaseTransaction,\n\taccountIdentifier *types.AccountIdentifier,\n\tcurrency *types.Currency,\n) ([]*types.Coin, error) {\n\tcoins, _, err := c.coinStorage.GetCoinsTransactional(\n\t\tctx,\n\t\tdbTx,\n\t\taccountIdentifier,\n\t)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"%w: unable to get coins\", err)\n\t}\n\n\tcoinsToReturn := []*types.Coin{}\n\tfor _, coin := range coins {\n\t\tif types.Hash(coin.Amount.Currency) != types.Hash(currency) {\n\t\t\tcontinue\n\t\t}\n\n\t\tcoinsToReturn = append(coinsToReturn, coin)\n\t}\n\n\treturn coinsToReturn, nil\n}", "func (btc *ExchangeWallet) ReturnCoins(unspents asset.Coins) error {\n\tif len(unspents) == 0 {\n\t\treturn fmt.Errorf(\"cannot return zero coins\")\n\t}\n\tops := make([]*output, 0, len(unspents))\n\tbtc.fundingMtx.Lock()\n\tdefer btc.fundingMtx.Unlock()\n\tfor _, unspent := range unspents {\n\t\top, err := btc.convertCoin(unspent)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error converting coin: %v\", err)\n\t\t}\n\t\tops = append(ops, op)\n\t\tdelete(btc.fundingCoins, outpointID(op.txHash.String(), op.vout))\n\t}\n\treturn btc.wallet.LockUnspent(true, ops)\n}", "func (_Bindings *BindingsSession) ReduceReserves(reduceAmount *big.Int) (*types.Transaction, error) {\n\treturn _Bindings.Contract.ReduceReserves(&_Bindings.TransactOpts, reduceAmount)\n}", "func (_CrToken *CrTokenTransactorSession) ReduceReserves(reduceAmount *big.Int) (*types.Transaction, error) {\n\treturn _CrToken.Contract.ReduceReserves(&_CrToken.TransactOpts, reduceAmount)\n}", "func (k Keeper) GetStakedTokens(ctx sdk.Ctx) sdk.BigInt {\n\tstakedPool := k.GetStakedPool(ctx)\n\treturn stakedPool.GetCoins().AmountOf(k.StakeDenom(ctx))\n}", "func (keeper Keeper) SubtractCoins(ctx sdk.Context, addr sdk.Address, amt sdk.Coins) (sdk.Coins, sdk.Error) {\n\treturn subtractCoins(ctx, keeper.am, addr, amt)\n}", "func (o *AvailableBudget) GetSpentInBudgets() []BudgetSpent {\n\tif o == nil || o.SpentInBudgets == nil {\n\t\tvar ret []BudgetSpent\n\t\treturn ret\n\t}\n\treturn *o.SpentInBudgets\n}", "func (_CrToken *CrTokenSession) ReduceReserves(reduceAmount *big.Int) (*types.Transaction, error) {\n\treturn _CrToken.Contract.ReduceReserves(&_CrToken.TransactOpts, reduceAmount)\n}", "func (btc *ExchangeWallet) lockedSats() (uint64, error) {\n\tlockedOutpoints, err := btc.wallet.ListLockUnspent()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tvar sum uint64\n\tbtc.fundingMtx.Lock()\n\tdefer btc.fundingMtx.Unlock()\n\tfor _, outPoint := range lockedOutpoints {\n\t\topID := outpointID(outPoint.TxID, outPoint.Vout)\n\t\tutxo, found := btc.fundingCoins[opID]\n\t\tif found {\n\t\t\tsum += utxo.amount\n\t\t\tcontinue\n\t\t}\n\t\ttxHash, err := chainhash.NewHashFromStr(outPoint.TxID)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\ttxOut, err := btc.node.GetTxOut(txHash, outPoint.Vout, true)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\tif txOut == nil {\n\t\t\t// Must be spent now?\n\t\t\tbtc.log.Debugf(\"ignoring output from listlockunspent that wasn't found with gettxout. %s\", opID)\n\t\t\tcontinue\n\t\t}\n\t\tsum += toSatoshi(txOut.Value)\n\t}\n\treturn sum, nil\n}", "func (_Univ2 *Univ2Session) GetReserves() (struct {\n\tReserve0 *big.Int\n\tReserve1 *big.Int\n\tBlockTimestampLast uint32\n}, error) {\n\treturn _Univ2.Contract.GetReserves(&_Univ2.CallOpts)\n}", "func (gc *GovernanceContract) TotalVotingPower() (hexutil.Big, error) {\n\treturn gc.repo.GovernanceTotalWeight(&gc.Address)\n}", "func (va ClawbackVestingAccount) GetVestingPeriods() Periods {\n\treturn va.VestingPeriods\n}", "func (pva PeriodicVestingAccount) GetVestingPeriods() Periods {\n\treturn pva.VestingPeriods\n}", "func (keeper ViewKeeper) HasCoins(ctx sdk.Context, addr sdk.Address, amt sdk.Coins) bool {\n\treturn hasCoins(ctx, keeper.am, addr, amt)\n}", "func (_Bindings *BindingsTransactor) ReduceReserves(opts *bind.TransactOpts, reduceAmount *big.Int) (*types.Transaction, error) {\n\treturn _Bindings.contract.Transact(opts, \"_reduceReserves\", reduceAmount)\n}", "func (b *BlockChain) FetchSpendJournal(targetBlock *asiutil.Block, targetvblock *asiutil.VBlock) ([]txo.SpentTxOut, error) {\n\tb.chainLock.RLock()\n\tdefer b.chainLock.RUnlock()\n\n\tvar spendEntries []txo.SpentTxOut\n\terr := b.db.View(func(dbTx database.Tx) error {\n\t\tvar err error\n\t\tspendEntries, err = dbFetchSpendJournalEntry(dbTx, targetBlock, targetvblock)\n\t\treturn err\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn spendEntries, nil\n}", "func GetBeneficiaryCmts(ctx iris.Context) {\n\tbID, err := ctx.Params().GetInt64(\"beneficiaryID\")\n\tif err != nil {\n\t\tctx.StatusCode(http.StatusBadRequest)\n\t\tctx.JSON(jsonError{\"Engagement d'un bénéficiaire, paramètre : \" + err.Error()})\n\t\treturn\n\t}\n\tvar resp models.BeneficiaryCmts\n\tdb := ctx.Values().Get(\"db\").(*sql.DB)\n\tif err = resp.GetAll(bID, db); err != nil {\n\t\tctx.StatusCode(http.StatusInternalServerError)\n\t\tctx.JSON(jsonError{\"Engagement d'un bénéficiaire, requête : \" + err.Error()})\n\t}\n\tctx.StatusCode(http.StatusOK)\n\tctx.JSON(resp)\n}", "func (keeper BaseViewKeeper) HasCoins(ctx sdk.Context, addr sdk.AccAddress, amt sdk.Coins) bool {\n\treturn hasCoins(ctx, keeper.am, addr, amt)\n}", "func (dcr *ExchangeWallet) returnCoins(unspents asset.Coins) ([]*fundingCoin, error) {\n\tif len(unspents) == 0 {\n\t\treturn nil, fmt.Errorf(\"cannot return zero coins\")\n\t}\n\n\tops := make([]*wire.OutPoint, 0, len(unspents))\n\tfundingCoins := make([]*fundingCoin, 0, len(unspents))\n\n\tdcr.log.Debugf(\"returning coins %s\", unspents)\n\tfor _, unspent := range unspents {\n\t\top, err := dcr.convertCoin(unspent)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error converting coin: %w\", err)\n\t\t}\n\t\tops = append(ops, op.wireOutPoint()) // op.tree may be wire.TxTreeUnknown, but that's fine since wallet.LockUnspent doesn't rely on it\n\t\tif fCoin, ok := dcr.fundingCoins[op.pt]; ok {\n\t\t\tfundingCoins = append(fundingCoins, fCoin)\n\t\t\tdelete(dcr.fundingCoins, op.pt)\n\t\t} else {\n\t\t\tdcr.log.Warnf(\"returning coin %s that is not cached as a funding coin\", op)\n\t\t\tfundingCoins = append(fundingCoins, &fundingCoin{op: op})\n\t\t}\n\t}\n\n\treturn fundingCoins, dcr.wallet.LockUnspent(dcr.ctx, true, ops)\n}", "func (cs *Coins) CoinSelect(amount uint64, asset string) (unspents []explorer.Utxo, change uint64, err error) {\n\tchange = 0\n\tunspents = []explorer.Utxo{}\n\tavailableSats := uint64(0)\n\n\tfor index, unspent := range cs.Utxos {\n\t\tu := unspent\n\t\tassetHash := u.Asset()\n\t\tamountSatoshis := u.Value()\n\t\tif len(u.AssetCommitment()) > 0 && len(u.ValueCommitment()) > 0 {\n\t\t\tbk := cs.BlindingKey\n\t\t\tif len(cs.BlindingKeys) > 0 {\n\t\t\t\tbk = cs.BlindingKeys[index]\n\t\t\t}\n\t\t\tav, err := unblindUxto(u, bk)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, 0, err\n\t\t\t}\n\t\t\tassetHash = av.asset\n\t\t\tamountSatoshis = av.value\n\t\t}\n\t\tif asset == assetHash {\n\t\t\tunspents = append(unspents, unspent)\n\t\t\tavailableSats += amountSatoshis\n\n\t\t\tif availableSats >= amount {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\tif availableSats < amount {\n\t\treturn nil, 0, errors.New(\"You do not have enough coins\")\n\t}\n\n\tchange = availableSats - amount\n\n\treturn unspents, change, nil\n}", "func (k Keeper) GetWinnerIncentives(ctx sdk.Context) float32 {\n\tgames := float32(k.GetGames(ctx))\n\tvotes := float32(k.GetVotes(ctx))\n\tgVR := float32(k.GetParams(ctx).GameVoteRatio) / 100\n\treturn games / (votes*gVR + games)\n}", "func (dcr *ExchangeWallet) ReturnCoins(unspents asset.Coins) error {\n\tdcr.fundingMtx.Lock()\n\treturnedCoins, err := dcr.returnCoins(unspents)\n\tdcr.fundingMtx.Unlock()\n\tif err != nil || dcr.unmixedAccount == \"\" {\n\t\treturn err\n\t}\n\n\t// If any of these coins belong to the trading account, transfer them to the\n\t// unmixed account to be re-mixed into the primary account before being\n\t// re-selected for funding future orders. This doesn't apply to unspent\n\t// split tx outputs, which should remain in the trading account and be\n\t// selected from there for funding future orders.\n\tvar coinsToTransfer []asset.Coin\n\tfor _, coin := range returnedCoins {\n\t\tif coin.addr == \"\" {\n\t\t\ttxOut, err := dcr.wallet.UnspentOutput(dcr.ctx, coin.op.txHash(), coin.op.vout(), coin.op.tree)\n\t\t\tif err != nil {\n\t\t\t\tdcr.log.Errorf(\"wallet.UnspentOutput error for returned coin %s: %v\", coin.op, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif len(txOut.Addresses) == 0 {\n\t\t\t\tdcr.log.Errorf(\"no address in gettxout response for returned coin %s\", coin.op)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tcoin.addr = txOut.Addresses[0]\n\t\t}\n\t\taddrInfo, err := dcr.wallet.AddressInfo(dcr.ctx, coin.addr)\n\t\tif err != nil {\n\t\t\tdcr.log.Errorf(\"wallet.AddressInfo error for returned coin %s: %v\", coin.op, err)\n\t\t\tcontinue\n\t\t}\n\t\t// Move this coin to the unmixed account if it was sent to the internal\n\t\t// branch of the trading account. This excludes unspent split tx outputs\n\t\t// which are sent to the external branch of the trading account.\n\t\tif addrInfo.Branch == acctInternalBranch && addrInfo.Account == dcr.tradingAccount {\n\t\t\tcoinsToTransfer = append(coinsToTransfer, coin.op)\n\t\t}\n\t}\n\n\tif len(coinsToTransfer) > 0 {\n\t\ttx, totalSent, err := dcr.sendAll(coinsToTransfer, dcr.unmixedAccount)\n\t\tif err != nil {\n\t\t\tdcr.log.Errorf(\"unable to transfer unlocked swapped change from temp trading \"+\n\t\t\t\t\"account to unmixed account: %v\", err)\n\t\t} else {\n\t\t\tdcr.log.Infof(\"Transferred %s from temp trading account to unmixed account in tx %s.\",\n\t\t\t\tdcrutil.Amount(totalSent), tx.TxHash())\n\t\t}\n\t}\n\n\treturn nil\n}", "func (dcr *ExchangeWallet) returnCoins(unspents asset.Coins) error {\n\tif len(unspents) == 0 {\n\t\treturn fmt.Errorf(\"cannot return zero coins\")\n\t}\n\tops := make([]*wire.OutPoint, 0, len(unspents))\n\n\tdcr.log.Debugf(\"returning coins %s\", unspents)\n\tfor _, unspent := range unspents {\n\t\top, err := dcr.convertCoin(unspent)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error converting coin: %w\", err)\n\t\t}\n\t\tops = append(ops, wire.NewOutPoint(op.txHash(), op.vout(), op.tree))\n\t\tdelete(dcr.fundingCoins, op.pt)\n\t}\n\treturn translateRPCCancelErr(dcr.node.LockUnspent(dcr.ctx, true, ops))\n}", "func (bva BaseVestingAccount) GetDelegatedVesting() sdk.Coins {\n\treturn bva.DelegatedVesting\n}", "func (b *Byzcoin) Watch(ctx context.Context) <-chan *ledger.TransactionResult {\n\tc := make(chan *ledger.TransactionResult, 100)\n\tb.bc.Watch(ctx, observer{ch: c})\n\n\treturn c\n}", "func (o *AllocationList) GetCashActive() float64 {\n\tif o == nil {\n\t\tvar ret float64\n\t\treturn ret\n\t}\n\n\treturn o.CashActive\n}", "func (r Virtual_Guest) GetActiveTransactions() (resp []datatypes.Provisioning_Version1_Transaction, err error) {\n\terr = r.Session.DoRequest(\"SoftLayer_Virtual_Guest\", \"getActiveTransactions\", nil, &r.Options, &resp)\n\treturn\n}", "func (_Bindings *BindingsSession) GetCash() (*big.Int, error) {\n\treturn _Bindings.Contract.GetCash(&_Bindings.CallOpts)\n}", "func coins(a int) int {\n\tif a == 0 {\n\t\treturn 0\n\t}\n\treturn doCoins(a, 25)\n}", "func (_Univ2 *Univ2Caller) GetReserves(opts *bind.CallOpts) (struct {\n\tReserve0 *big.Int\n\tReserve1 *big.Int\n\tBlockTimestampLast uint32\n}, error) {\n\tvar out []interface{}\n\terr := _Univ2.contract.Call(opts, &out, \"getReserves\")\n\n\toutstruct := new(struct {\n\t\tReserve0 *big.Int\n\t\tReserve1 *big.Int\n\t\tBlockTimestampLast uint32\n\t})\n\tif err != nil {\n\t\treturn *outstruct, err\n\t}\n\n\toutstruct.Reserve0 = *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\toutstruct.Reserve1 = *abi.ConvertType(out[1], new(*big.Int)).(**big.Int)\n\toutstruct.BlockTimestampLast = *abi.ConvertType(out[2], new(uint32)).(*uint32)\n\n\treturn *outstruct, err\n\n}", "func (o *LoyaltySubLedger) GetTotalSpentPoints() float32 {\n\tif o == nil {\n\t\tvar ret float32\n\t\treturn ret\n\t}\n\n\treturn o.TotalSpentPoints\n}", "func (va ClawbackVestingAccount) GetUnlockedOnly(blockTime time.Time) sdk.Coins {\n\treturn ReadSchedule(va.StartTime, va.EndTime, va.LockupPeriods, va.OriginalVesting, blockTime.Unix())\n}", "func (env *Env) GetPayments(w http.ResponseWriter, r *http.Request) {\n\tlog.Printf(\"GET payments\")\n\n\ttxs, err := env.db.GetAllTX()\n\n\tif err != nil {\n\t\tlog.Printf(\"Error retrieving payments: %v\\n\", err)\n\t\trender.Status(r, http.StatusNotFound)\n\t\treturn\n\t}\n\trender.JSON(w, r, txs)\n}", "func (m *Machine) ReturnCoins() {\n\tcoins := m.cashEngine.DropCoins()\n\n\ts := fmt.Sprintf(\"-> \")\n\tfor i, c := range coins {\n\t\tif i == len(coins)-1 {\n\t\t\ts += fmt.Sprintf(\"%s\", c.value.String())\n\t\t\tcontinue\n\t\t}\n\t\ts += fmt.Sprintf(\"%s, \", c.value.String())\n\t}\n\n\tm.logger.Println(s)\n}", "func (ksqMap KitchenServedQtyMap) GetServedQty(kitchen *kitchen.Kitchen) int {\n\tkey := kitchen.GetID()\n\treturn ksqMap[key]\n}", "func (dcr *ExchangeWallet) sendCoins(addr stdaddr.Address, coins asset.Coins, val, feeRate uint64, subtract bool) (*wire.MsgTx, uint64, error) {\n\tbaseTx := wire.NewMsgTx()\n\t_, err := dcr.addInputCoins(baseTx, coins)\n\tif err != nil {\n\t\treturn nil, 0, err\n\t}\n\tpayScriptVer, payScript := addr.PaymentScript()\n\ttxOut := newTxOut(int64(val), payScriptVer, payScript)\n\tbaseTx.AddTxOut(txOut)\n\n\tvar feeSource int32 // subtract from vout 0\n\tif !subtract {\n\t\tfeeSource = -1 // subtract from change\n\t}\n\n\ttx, err := dcr.sendWithReturn(baseTx, feeRate, feeSource)\n\tif err != nil {\n\t\treturn nil, 0, err\n\t}\n\treturn tx, uint64(tx.TxOut[0].Value), err\n}", "func (_Cakevault *CakevaultSession) TotalShares() (*big.Int, error) {\n\treturn _Cakevault.Contract.TotalShares(&_Cakevault.CallOpts)\n}", "func (_CrToken *CrTokenTransactor) ReduceReserves(opts *bind.TransactOpts, reduceAmount *big.Int) (*types.Transaction, error) {\n\treturn _CrToken.contract.Transact(opts, \"_reduceReserves\", reduceAmount)\n}", "func (o *AllocationList) GetInvestedOk() (*float64, bool) {\n\tif o == nil {\n\t\treturn nil, false\n\t}\n\treturn &o.Invested, true\n}", "func (_Cakevault *CakevaultCallerSession) TotalShares() (*big.Int, error) {\n\treturn _Cakevault.Contract.TotalShares(&_Cakevault.CallOpts)\n}", "func (r *Repository) GetAmountsOfManageCandidates(ctx context.Context, companyID string) (int32, int32, error) {\n\tobjCompanyID, err := primitive.ObjectIDFromHex(companyID)\n\tif err != nil {\n\t\treturn 0, 0, errors.New(`wrong_id`)\n\t}\n\n\tamount := struct {\n\t\tSaved int32 `bson:\"saved_candidates\"`\n\t\tSkipped int32 `bson:\"skipped_candidates\"`\n\t\t// Alerts int32 `bson:\"alerts\"`\n\t}{}\n\n\tcursor, err := r.companiesCollection.Aggregate(\n\t\tctx,\n\t\t[]bson.M{\n\t\t\t{\n\t\t\t\t\"$match\": bson.M{\n\t\t\t\t\t\"company_id\": objCompanyID,\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\t\"$addFields\": bson.M{\n\t\t\t\t\t\"saved_candidates\": bson.M{\n\t\t\t\t\t\t\"$size\": \"$saved_candidates\",\n\t\t\t\t\t},\n\t\t\t\t\t\"skipped_candidates\": bson.M{\n\t\t\t\t\t\t\"$size\": \"$skipped_candidates\",\n\t\t\t\t\t},\n\t\t\t\t\t// \"alerts\": bson.M{\n\t\t\t\t\t// \t\"$size\": \"$alerts\", // TODO:\n\t\t\t\t\t// },\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\t\"$project\": bson.M{\n\t\t\t\t\t\"saved_candidates\": 1,\n\t\t\t\t\t\"skipped_candidates\": 1,\n\t\t\t\t\t// \"alerts\": 1,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t)\n\tif err != nil {\n\t\tif err == mongo.ErrNoDocuments {\n\t\t\treturn 0, 0, errors.New(`not_found`)\n\t\t}\n\t\treturn 0, 0, err\n\t}\n\tdefer cursor.Close(ctx)\n\n\tif cursor.Next(ctx) {\n\t\terr = cursor.Decode(&amount)\n\t\tif err != nil {\n\t\t\treturn 0, 0, err\n\t\t}\n\t}\n\n\treturn amount.Saved, amount.Skipped, nil\n}", "func (_Bindings *BindingsCallerSession) GetCash() (*big.Int, error) {\n\treturn _Bindings.Contract.GetCash(&_Bindings.CallOpts)\n}", "func makeSpendTxWithHoursBurned(t *testing.T, uxs coin.UxArray, keys []cipher.SecKey, toAddr cipher.Address, coins, hoursBurned uint64) coin.Transaction {\n\tspendTx := coin.Transaction{}\n\tvar totalHours uint64\n\tvar totalCoins uint64\n\tfor _, ux := range uxs {\n\t\tspendTx.PushInput(ux.Hash())\n\t\ttotalHours += ux.Body.Hours\n\t\ttotalCoins += ux.Body.Coins\n\t}\n\n\trequire.True(t, coins <= totalCoins)\n\trequire.True(t, hoursBurned <= totalHours, \"hoursBurned must be <= totalHours\")\n\n\tspendHours := totalHours - hoursBurned\n\n\tspendTx.PushOutput(toAddr, coins, spendHours)\n\tif totalCoins != coins {\n\t\tspendTx.PushOutput(uxs[0].Body.Address, totalCoins-coins, 0)\n\t}\n\tspendTx.SignInputs(keys)\n\tspendTx.UpdateHeader()\n\treturn spendTx\n}", "func (cm *coinsMempool) Get(maxTransactions uint64, s state.State) ([]*primitives.Tx, state.State) {\n\tcm.lock.RLock()\n\tdefer cm.lock.RUnlock()\n\tallTransactions := make([]*primitives.Tx, 0, maxTransactions)\n\nouter:\n\tfor _, addr := range cm.mempool {\n\t\tfor _, tx := range addr.transactions {\n\t\t\tif err := s.ApplyTransactionSingle(tx, [20]byte{}, cm.params); err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tallTransactions = append(allTransactions, tx)\n\t\t\tif uint64(len(allTransactions)) >= maxTransactions {\n\t\t\t\tbreak outer\n\t\t\t}\n\t\t}\n\t}\n\n\t// we can prioritize here, but we aren't to keep it simple\n\treturn allTransactions, s\n}" ]
[ "0.79755396", "0.77310777", "0.7681168", "0.76493204", "0.76472145", "0.7523997", "0.72600824", "0.7255338", "0.7253369", "0.7164763", "0.7144354", "0.6482787", "0.6452779", "0.64464617", "0.6323308", "0.6253597", "0.61339927", "0.59371185", "0.58343196", "0.579981", "0.54029083", "0.53148025", "0.52969146", "0.51460826", "0.5110436", "0.48077112", "0.4801463", "0.47548923", "0.47510943", "0.46456882", "0.46409896", "0.46070975", "0.457379", "0.4559607", "0.45497268", "0.45199516", "0.4480975", "0.4477674", "0.4398353", "0.43711296", "0.436636", "0.4360655", "0.43553165", "0.43402606", "0.4326249", "0.4314894", "0.42698383", "0.42604214", "0.42517573", "0.42383605", "0.4236305", "0.4220945", "0.42147452", "0.42059714", "0.42057824", "0.42015034", "0.41727757", "0.4163319", "0.41626644", "0.41464984", "0.41051164", "0.41006652", "0.40981743", "0.4092534", "0.4087275", "0.40872294", "0.40801063", "0.40728733", "0.40704507", "0.40669736", "0.40448576", "0.40399605", "0.403803", "0.40325326", "0.4031776", "0.40263465", "0.40094727", "0.4006632", "0.3990231", "0.3978811", "0.39783", "0.39724427", "0.39630386", "0.39614612", "0.3954176", "0.39450026", "0.39425462", "0.39363122", "0.39349154", "0.39328486", "0.39319614", "0.39287287", "0.39145356", "0.39140454", "0.39110234", "0.39037976", "0.39032206", "0.3899639", "0.38945153", "0.38933948" ]
0.8238134
0
GetVestingCoins returns the total number of vesting coins for a permanent locked vesting account.
func (plva PermanentLockedAccount) GetVestingCoins(_ time.Time) sdk.Coins { return plva.OriginalVesting }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (vva ValidatorVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn vva.OriginalVesting.Sub(vva.GetVestedCoins(blockTime))\n}", "func (pva PeriodicVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn pva.OriginalVesting.Sub(pva.GetVestedCoins(blockTime))\n}", "func (va ClawbackVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn va.OriginalVesting.Sub(va.GetVestedCoins(blockTime))\n}", "func (dva DelayedVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn dva.OriginalVesting.Sub(dva.GetVestedCoins(blockTime))\n}", "func (cva ContinuousVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn cva.OriginalVesting.Sub(cva.GetVestedCoins(blockTime))\n}", "func (plva PermanentLockedAccount) GetVestedCoins(_ time.Time) sdk.Coins {\n\treturn nil\n}", "func (pva PeriodicVestingAccount) GetVestedCoins(blockTime time.Time) sdk.Coins {\n\tcoins := ReadSchedule(pva.StartTime, pva.EndTime, pva.VestingPeriods, pva.OriginalVesting, blockTime.Unix())\n\tif coins.IsZero() {\n\t\treturn nil\n\t}\n\treturn coins\n}", "func (vva ValidatorVestingAccount) GetVestedCoins(blockTime time.Time) sdk.Coins {\n\tvar vestedCoins sdk.Coins\n\tif blockTime.Unix() <= vva.StartTime {\n\t\treturn vestedCoins\n\t}\n\tcurrentPeriodStartTime := vva.StartTime\n\tnumberPeriods := len(vva.VestingPeriods)\n\tfor i := 0; i < numberPeriods; i++ {\n\t\tx := blockTime.Unix() - currentPeriodStartTime\n\t\tif x >= vva.VestingPeriods[i].Length {\n\t\t\tif vva.VestingPeriodProgress[i].PeriodComplete {\n\t\t\t\tvestedCoins = vestedCoins.Add(vva.VestingPeriods[i].Amount)\n\t\t\t}\n\t\t\tcurrentPeriodStartTime += vva.VestingPeriods[i].Length\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn vestedCoins\n\n}", "func (cva ContinuousVestingAccount) GetVestedCoins(blockTime time.Time) sdk.Coins {\n\tvar vestedCoins sdk.Coins\n\n\t// We must handle the case where the start time for a vesting account has\n\t// been set into the future or when the start of the chain is not exactly\n\t// known.\n\tif blockTime.Unix() <= cva.StartTime {\n\t\treturn vestedCoins\n\t} else if blockTime.Unix() >= cva.EndTime {\n\t\treturn cva.OriginalVesting\n\t}\n\n\t// calculate the vesting scalar\n\tx := blockTime.Unix() - cva.StartTime\n\ty := cva.EndTime - cva.StartTime\n\ts := sdk.NewDec(x).Quo(sdk.NewDec(y))\n\n\tfor _, ovc := range cva.OriginalVesting {\n\t\tvestedAmt := ovc.Amount.ToDec().Mul(s).RoundInt()\n\t\tvestedCoins = append(vestedCoins, sdk.NewCoin(ovc.Denom, vestedAmt))\n\t}\n\n\treturn vestedCoins\n}", "func (dva DelayedVestingAccount) GetVestedCoins(blockTime time.Time) sdk.Coins {\n\tif blockTime.Unix() >= dva.EndTime {\n\t\treturn dva.OriginalVesting\n\t}\n\n\treturn nil\n}", "func (va ClawbackVestingAccount) GetVestedCoins(blockTime time.Time) sdk.Coins {\n\t// It's likely that one or the other schedule will be nearly trivial,\n\t// so there should be little overhead in recomputing the conjunction each time.\n\tcoins := coinsMin(va.GetUnlockedOnly(blockTime), va.GetVestedOnly(blockTime))\n\tif coins.IsZero() {\n\t\treturn nil\n\t}\n\treturn coins\n}", "func (bva BaseVestingAccount) LockedCoinsFromVesting(vestingCoins sdk.Coins) sdk.Coins {\n\tlockedCoins := vestingCoins.Sub(vestingCoins.Min(bva.DelegatedVesting))\n\tif lockedCoins == nil {\n\t\treturn sdk.Coins{}\n\t}\n\treturn lockedCoins\n}", "func (pva PeriodicVestingAccount) LockedCoins(ctx sdk.Context) sdk.Coins {\n\treturn pva.BaseVestingAccount.LockedCoinsFromVesting(pva.GetVestingCoins(ctx.BlockTime()))\n}", "func (va ClawbackVestingAccount) LockedCoins(ctx sdk.Context) sdk.Coins {\n\treturn va.BaseVestingAccount.LockedCoinsFromVesting(va.GetVestingCoins(ctx.BlockTime()))\n}", "func (cva ContinuousVestingAccount) LockedCoins(ctx sdk.Context) sdk.Coins {\n\treturn cva.BaseVestingAccount.LockedCoinsFromVesting(cva.GetVestingCoins(ctx.BlockTime()))\n}", "func (dva DelayedVestingAccount) LockedCoins(ctx sdk.Context) sdk.Coins {\n\treturn dva.BaseVestingAccount.LockedCoinsFromVesting(dva.GetVestingCoins(ctx.BlockTime()))\n}", "func (plva PermanentLockedAccount) LockedCoins(_ sdk.Context) sdk.Coins {\n\treturn plva.BaseVestingAccount.LockedCoinsFromVesting(plva.OriginalVesting)\n}", "func (vva ValidatorVestingAccount) GetFailedVestedCoins() sdk.Coins {\n\tvar failedVestedCoins sdk.Coins\n\tnumberPeriods := len(vva.VestingPeriods)\n\tfor i := 0; i < numberPeriods; i++ {\n\t\tif vva.VestingPeriodProgress[i].PeriodComplete {\n\t\t\tif !vva.VestingPeriodProgress[i].VestingSuccessful {\n\t\t\t\tfailedVestedCoins = failedVestedCoins.Add(vva.VestingPeriods[i].Amount)\n\t\t\t}\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn failedVestedCoins\n}", "func (vva ValidatorVestingAccount) SpendableCoins(blockTime time.Time) sdk.Coins {\n\treturn vva.BaseVestingAccount.SpendableCoinsVestingAccount(vva.GetVestingCoins(blockTime))\n}", "func (keeper ViewKeeper) GetCoins(ctx sdk.Context, addr sdk.Address) sdk.Coins {\n\treturn getCoins(ctx, keeper.am, addr)\n}", "func (keeper BaseViewKeeper) GetCoins(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins {\n\treturn getCoins(ctx, keeper.am, addr)\n}", "func (va ClawbackVestingAccount) GetVestedOnly(blockTime time.Time) sdk.Coins {\n\treturn ReadSchedule(va.StartTime, va.EndTime, va.VestingPeriods, va.OriginalVesting, blockTime.Unix())\n}", "func (keeper SendKeeper) GetCoins(ctx sdk.Context, addr sdk.Address) sdk.Coins {\n\treturn getCoins(ctx, keeper.am, addr)\n}", "func (keeper Keeper) GetCoins(ctx sdk.Context, addr sdk.Address) sdk.Coins {\n\treturn getCoins(ctx, keeper.am, addr)\n}", "func (ck CoinKeeper) GetCoins(ctx sdk.Context, addr sdk.Address, amt sdk.Coins) sdk.Coins {\n\tacc := ck.am.GetAccount(ctx, addr)\n\treturn acc.GetCoins()\n}", "func (bva BaseVestingAccount) GetOriginalVesting() sdk.Coins {\n\treturn bva.OriginalVesting\n}", "func GetCoins() (coins []Coin, error error) {\n\tvar c = []Coin{}\n\tvar d struct {\n\t\tCrypto []Coin `json:\"crypto\"`\n\t}\n\tjsonData, err := doTauRequest(1, \"GET\", \"data/coins\", nil)\n\tif err != nil {\n\t\treturn c, err\n\t}\n\tif err := json.Unmarshal(jsonData, &d); err != nil {\n\t\treturn c, err\n\t}\n\treturn d.Crypto, nil\n}", "func (n Network) VestingAccounts(ctx context.Context, launchID uint64) (vestingAccs []networktypes.VestingAccount, err error) {\n\tn.ev.Send(events.New(events.StatusOngoing, \"Fetching genesis vesting accounts\"))\n\tres, err := n.launchQuery.\n\t\tVestingAccountAll(ctx,\n\t\t\t&launchtypes.QueryAllVestingAccountRequest{\n\t\t\t\tLaunchID: launchID,\n\t\t\t},\n\t\t)\n\tif err != nil {\n\t\treturn vestingAccs, err\n\t}\n\n\tfor i, acc := range res.VestingAccount {\n\t\tparsedAcc, err := networktypes.ToVestingAccount(acc)\n\t\tif err != nil {\n\t\t\treturn vestingAccs, errors.Wrapf(err, \"error parsing vesting account %d\", i)\n\t\t}\n\n\t\tvestingAccs = append(vestingAccs, parsedAcc)\n\t}\n\n\treturn vestingAccs, nil\n}", "func (t *TauAPI) GetCoins() (coins []Coin, error error) {\n\tvar c = []Coin{}\n\tvar d struct {\n\t\tCrypto []Coin `json:\"cryto\"` //typo from api\n\t\tFiat []Coin `json:\"fiat\"`\n\t}\n\tjsonData, err := t.doTauRequest(&TauReq{\n\t\tVersion: 2,\n\t\tMethod: \"GET\",\n\t\tPath: \"coins\",\n\t})\n\tif err != nil {\n\t\treturn c, err\n\t}\n\tif err := json.Unmarshal(jsonData, &d); err != nil {\n\t\treturn c, err\n\t}\n\tc = append(d.Crypto, d.Fiat...)\n\treturn c, nil\n}", "func (dcr *ExchangeWallet) FundingCoins(ids []dex.Bytes) (asset.Coins, error) {\n\t// First check if we have the coins in cache.\n\tcoins := make(asset.Coins, 0, len(ids))\n\tnotFound := make(map[outPoint]bool)\n\tdcr.fundingMtx.Lock()\n\tdefer dcr.fundingMtx.Unlock() // stay locked until we update the map and lock them in the wallet\n\tfor _, id := range ids {\n\t\ttxHash, vout, err := decodeCoinID(id)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tpt := newOutPoint(txHash, vout)\n\t\tfundingCoin, found := dcr.fundingCoins[pt]\n\t\tif found {\n\t\t\tcoins = append(coins, fundingCoin.op)\n\t\t\tcontinue\n\t\t}\n\t\tnotFound[pt] = true\n\t}\n\tif len(notFound) == 0 {\n\t\treturn coins, nil\n\t}\n\n\t// Check locked outputs for not found coins.\n\tlockedOutputs, err := dcr.lockedOutputs()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor _, output := range lockedOutputs {\n\t\ttxHash, err := chainhash.NewHashFromStr(output.Txid)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error decoding txid from rpc server %s: %w\", output.Txid, err)\n\t\t}\n\t\tpt := newOutPoint(txHash, output.Vout)\n\t\tif !notFound[pt] {\n\t\t\tcontinue\n\t\t}\n\t\ttxOut, err := dcr.node.GetTxOut(dcr.ctx, txHash, output.Vout, true)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"gettxout error for locked output %v: %w\", pt.String(), translateRPCCancelErr(err))\n\t\t}\n\t\tvar address string\n\t\tif len(txOut.ScriptPubKey.Addresses) > 0 {\n\t\t\taddress = txOut.ScriptPubKey.Addresses[0]\n\t\t}\n\t\tcoin := newOutput(txHash, output.Vout, toAtoms(output.Amount), output.Tree)\n\t\tcoins = append(coins, coin)\n\t\tdcr.fundingCoins[pt] = &fundingCoin{\n\t\t\top: coin,\n\t\t\taddr: address,\n\t\t}\n\t\tdelete(notFound, pt)\n\t\tif len(notFound) == 0 {\n\t\t\treturn coins, nil\n\t\t}\n\t}\n\n\t// Some funding coins still not found after checking locked outputs.\n\t// Check wallet unspent outputs as last resort. Lock the coins if found.\n\tunspents, err := dcr.unspents()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcoinsToLock := make([]*wire.OutPoint, 0, len(notFound))\n\tfor _, txout := range unspents {\n\t\ttxHash, err := chainhash.NewHashFromStr(txout.TxID)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error decoding txid from rpc server %s: %w\", txout.TxID, err)\n\t\t}\n\t\tpt := newOutPoint(txHash, txout.Vout)\n\t\tif !notFound[pt] {\n\t\t\tcontinue\n\t\t}\n\t\tcoinsToLock = append(coinsToLock, wire.NewOutPoint(txHash, txout.Vout, txout.Tree))\n\t\tcoin := newOutput(txHash, txout.Vout, toAtoms(txout.Amount), txout.Tree)\n\t\tcoins = append(coins, coin)\n\t\tdcr.fundingCoins[pt] = &fundingCoin{\n\t\t\top: coin,\n\t\t\taddr: txout.Address,\n\t\t}\n\t\tdelete(notFound, pt)\n\t\tif len(notFound) == 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\tif len(notFound) != 0 {\n\t\tids := make([]string, 0, len(notFound))\n\t\tfor pt := range notFound {\n\t\t\tids = append(ids, pt.String())\n\t\t}\n\t\treturn nil, fmt.Errorf(\"funding coins not found: %s\", strings.Join(ids, \", \"))\n\t}\n\tdcr.log.Debugf(\"Locking funding coins that were unlocked %v\", coinsToLock)\n\terr = dcr.node.LockUnspent(dcr.ctx, false, coinsToLock)\n\tif err != nil {\n\t\treturn nil, translateRPCCancelErr(err)\n\t}\n\n\treturn coins, nil\n}", "func (_TokenVesting *TokenVestingCaller) VestedAmount(opts *bind.CallOpts, _token common.Address) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _TokenVesting.contract.Call(opts, out, \"vestedAmount\", _token)\n\treturn *ret0, err\n}", "func (dcr *ExchangeWallet) FundingCoins(ids []dex.Bytes) (asset.Coins, error) {\n\t// First check if we have the coins in cache.\n\tcoins := make(asset.Coins, 0, len(ids))\n\tnotFound := make(map[outPoint]bool)\n\tdcr.fundingMtx.Lock()\n\tdefer dcr.fundingMtx.Unlock() // stay locked until we update the map and lock them in the wallet\n\tfor _, id := range ids {\n\t\ttxHash, vout, err := decodeCoinID(id)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tpt := newOutPoint(txHash, vout)\n\t\tfundingCoin, found := dcr.fundingCoins[pt]\n\t\tif found {\n\t\t\tcoins = append(coins, fundingCoin.op)\n\t\t\tcontinue\n\t\t}\n\t\tnotFound[pt] = true\n\t}\n\tif len(notFound) == 0 {\n\t\treturn coins, nil\n\t}\n\n\t// Check locked outputs for not found coins.\n\tfor _, acct := range dcr.fundingAccounts() {\n\t\tlockedOutputs, err := dcr.wallet.LockedOutputs(dcr.ctx, acct)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfor _, output := range lockedOutputs {\n\t\t\ttxHash, err := chainhash.NewHashFromStr(output.Txid)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"error decoding txid from rpc server %s: %w\", output.Txid, err)\n\t\t\t}\n\t\t\tpt := newOutPoint(txHash, output.Vout)\n\t\t\tif !notFound[pt] {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ttxOut, err := dcr.wallet.UnspentOutput(dcr.ctx, txHash, output.Vout, output.Tree)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"gettxout error for locked output %v: %w\", pt.String(), err)\n\t\t\t}\n\t\t\tvar address string\n\t\t\tif len(txOut.Addresses) > 0 {\n\t\t\t\taddress = txOut.Addresses[0]\n\t\t\t}\n\t\t\tcoin := newOutput(txHash, output.Vout, toAtoms(output.Amount), output.Tree)\n\t\t\tcoins = append(coins, coin)\n\t\t\tdcr.fundingCoins[pt] = &fundingCoin{\n\t\t\t\top: coin,\n\t\t\t\taddr: address,\n\t\t\t}\n\t\t\tdelete(notFound, pt)\n\t\t\tif len(notFound) == 0 {\n\t\t\t\treturn coins, nil\n\t\t\t}\n\t\t}\n\t}\n\n\t// Some funding coins still not found after checking locked outputs.\n\t// Check wallet unspent outputs as last resort. Lock the coins if found.\n\tcoinsToLock := make([]*wire.OutPoint, 0, len(notFound))\n\tfor _, acct := range dcr.fundingAccounts() {\n\t\tunspents, err := dcr.wallet.Unspents(dcr.ctx, acct)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfor _, txout := range unspents {\n\t\t\ttxHash, err := chainhash.NewHashFromStr(txout.TxID)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"error decoding txid from rpc server %s: %w\", txout.TxID, err)\n\t\t\t}\n\t\t\tpt := newOutPoint(txHash, txout.Vout)\n\t\t\tif !notFound[pt] {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tcoinsToLock = append(coinsToLock, wire.NewOutPoint(txHash, txout.Vout, txout.Tree))\n\t\t\tcoin := newOutput(txHash, txout.Vout, toAtoms(txout.Amount), txout.Tree)\n\t\t\tcoins = append(coins, coin)\n\t\t\tdcr.fundingCoins[pt] = &fundingCoin{\n\t\t\t\top: coin,\n\t\t\t\taddr: txout.Address,\n\t\t\t}\n\t\t\tdelete(notFound, pt)\n\t\t\tif len(notFound) == 0 {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\t// Return an error if some coins are still not found.\n\tif len(notFound) != 0 {\n\t\tids := make([]string, 0, len(notFound))\n\t\tfor pt := range notFound {\n\t\t\tids = append(ids, pt.String())\n\t\t}\n\t\treturn nil, fmt.Errorf(\"funding coins not found: %s\", strings.Join(ids, \", \"))\n\t}\n\n\tdcr.log.Debugf(\"Locking funding coins that were unlocked %v\", coinsToLock)\n\terr := dcr.wallet.LockUnspent(dcr.ctx, false, coinsToLock)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn coins, nil\n}", "func (_TokenVesting *TokenVestingCallerSession) VestedAmount(_token common.Address) (*big.Int, error) {\n\treturn _TokenVesting.Contract.VestedAmount(&_TokenVesting.CallOpts, _token)\n}", "func (_TokenVesting *TokenVestingSession) VestedAmount(_token common.Address) (*big.Int, error) {\n\treturn _TokenVesting.Contract.VestedAmount(&_TokenVesting.CallOpts, _token)\n}", "func coins(a int) int {\n\tif a == 0 {\n\t\treturn 0\n\t}\n\treturn doCoins(a, 25)\n}", "func GetCoins(accCoins []types.Coin) AccountCoins {\n\tcoins := make(AccountCoins, 0)\n\tfor _, coin := range accCoins {\n\t\tcoins = append(coins, AccountCoin{Amount: uint64(coin.Amount), Denom: coin.Denom})\n\t}\n\treturn coins\n}", "func (va ClawbackVestingAccount) GetVestingPeriods() Periods {\n\treturn va.VestingPeriods\n}", "func (gc *GovernanceContract) TotalVotingPower() (hexutil.Big, error) {\n\treturn gc.repo.GovernanceTotalWeight(&gc.Address)\n}", "func (m *Client) GetCoins() ([]string, error) {\n\tresp, err := m.Service.GetCoins()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error requesting coin list: %s\", err)\n\t}\n\tdefer resp.Body.Close()\n\n\tvar response []string\n\terr = json.NewDecoder(resp.Body).Decode(&response)\n\tif err != nil {\n\t\tmsg, _ := ioutil.ReadAll(resp.Body)\n\t\treturn nil, fmt.Errorf(\"error decoding coin list: %s: %s\", msg, err)\n\t}\n\n\treturn response, nil\n}", "func (bva BaseVestingAccount) GetDelegatedVesting() sdk.Coins {\n\treturn bva.DelegatedVesting\n}", "func (o *Transaction) GetCounterparties() []TransactionCounterparty {\n\tif o == nil || o.Counterparties == nil {\n\t\tvar ret []TransactionCounterparty\n\t\treturn ret\n\t}\n\treturn *o.Counterparties\n}", "func (c Cart) GetVoucherSavings() domain.Price {\n\tprice := domain.Price{}\n\tvar err error\n\n\tfor _, item := range c.Totalitems {\n\t\tif item.Type == TotalsTypeVoucher {\n\t\t\tprice, err = price.Add(item.Price)\n\t\t\tif err != nil {\n\t\t\t\treturn price\n\t\t\t}\n\t\t}\n\t}\n\n\tif price.IsNegative() {\n\t\treturn domain.Price{}\n\t}\n\n\treturn price\n}", "func (_ChpRegistry *ChpRegistrySession) CORESTAKINGAMOUNT() (*big.Int, error) {\n\treturn _ChpRegistry.Contract.CORESTAKINGAMOUNT(&_ChpRegistry.CallOpts)\n}", "func (candidate *Candidate) GetTotalBipStake() *big.Int {\n\tcandidate.lock.RLock()\n\tdefer candidate.lock.RUnlock()\n\n\treturn big.NewInt(0).Set(candidate.totalBipStake)\n}", "func (cs *Coins) CoinSelect(amount uint64, asset string) (unspents []explorer.Utxo, change uint64, err error) {\n\tchange = 0\n\tunspents = []explorer.Utxo{}\n\tavailableSats := uint64(0)\n\n\tfor index, unspent := range cs.Utxos {\n\t\tu := unspent\n\t\tassetHash := u.Asset()\n\t\tamountSatoshis := u.Value()\n\t\tif len(u.AssetCommitment()) > 0 && len(u.ValueCommitment()) > 0 {\n\t\t\tbk := cs.BlindingKey\n\t\t\tif len(cs.BlindingKeys) > 0 {\n\t\t\t\tbk = cs.BlindingKeys[index]\n\t\t\t}\n\t\t\tav, err := unblindUxto(u, bk)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, 0, err\n\t\t\t}\n\t\t\tassetHash = av.asset\n\t\t\tamountSatoshis = av.value\n\t\t}\n\t\tif asset == assetHash {\n\t\t\tunspents = append(unspents, unspent)\n\t\t\tavailableSats += amountSatoshis\n\n\t\t\tif availableSats >= amount {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\tif availableSats < amount {\n\t\treturn nil, 0, errors.New(\"You do not have enough coins\")\n\t}\n\n\tchange = availableSats - amount\n\n\treturn unspents, change, nil\n}", "func (btc *ExchangeWallet) FundingCoins(ids []dex.Bytes) (asset.Coins, error) {\n\t// First check if we have the coins in cache.\n\tcoins := make(asset.Coins, 0, len(ids))\n\tnotFound := make(map[string]struct{})\n\tbtc.fundingMtx.RLock()\n\tfor _, id := range ids {\n\t\ttxHash, vout, err := decodeCoinID(id)\n\t\tif err != nil {\n\t\t\tbtc.fundingMtx.RUnlock()\n\t\t\treturn nil, err\n\t\t}\n\t\topID := outpointID(txHash.String(), vout)\n\t\tfundingCoin, found := btc.fundingCoins[opID]\n\t\tif found {\n\t\t\tcoins = append(coins, newOutput(btc.node, txHash, vout, fundingCoin.amount, fundingCoin.redeemScript))\n\t\t\tcontinue\n\t\t}\n\t\tnotFound[opID] = struct{}{}\n\t}\n\tbtc.fundingMtx.RUnlock()\n\tif len(notFound) == 0 {\n\t\treturn coins, nil\n\t}\n\t_, utxoMap, _, err := btc.spendableUTXOs(0)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlockers := make([]*output, 0, len(ids))\n\tbtc.fundingMtx.Lock()\n\tdefer btc.fundingMtx.Unlock()\n\tfor _, id := range ids {\n\t\ttxHash, vout, err := decodeCoinID(id)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\topID := outpointID(txHash.String(), vout)\n\t\tutxo, found := utxoMap[opID]\n\t\tif !found {\n\t\t\treturn nil, fmt.Errorf(\"funding coin %s not found\", opID)\n\t\t}\n\t\tbtc.fundingCoins[opID] = utxo\n\t\tcoin := newOutput(btc.node, utxo.txHash, utxo.vout, utxo.amount, utxo.redeemScript)\n\t\tcoins = append(coins, coin)\n\t\tlockers = append(lockers, coin)\n\t\tdelete(notFound, opID)\n\t\tif len(notFound) == 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\tif len(notFound) != 0 {\n\t\tids := make([]string, 0, len(notFound))\n\t\tfor opID := range notFound {\n\t\t\tids = append(ids, opID)\n\t\t}\n\t\treturn nil, fmt.Errorf(\"coins not found: %s\", strings.Join(ids, \", \"))\n\t}\n\terr = btc.wallet.LockUnspent(false, lockers)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn coins, nil\n}", "func newCoins() sdk.Coins {\n\treturn sdk.Coins{\n\t\tsdk.NewInt64Coin(\"atom\", 10000000),\n\t}\n}", "func (_ChpRegistry *ChpRegistryCallerSession) CORESTAKINGAMOUNT() (*big.Int, error) {\n\treturn _ChpRegistry.Contract.CORESTAKINGAMOUNT(&_ChpRegistry.CallOpts)\n}", "func (pva PeriodicVestingAccount) GetVestingPeriods() Periods {\n\treturn pva.VestingPeriods\n}", "func (dcr *ExchangeWallet) ReturnCoins(unspents asset.Coins) error {\n\tdcr.fundingMtx.Lock()\n\tdefer dcr.fundingMtx.Unlock()\n\treturn dcr.returnCoins(unspents)\n}", "func (_CrToken *CrTokenCallerSession) TotalReserves() (*big.Int, error) {\n\treturn _CrToken.Contract.TotalReserves(&_CrToken.CallOpts)\n}", "func (b *rpcVestingBalance) delegated() (sdk.Coins, sdk.Coins, error) {\n\tdelegatedCoins, err := b.totalDelegated()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tunbondingCoins, err := b.totalUnbondingDelegations()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tdelegated := delegatedCoins.AmountOf(stakingDenom)\n\tunbonding := unbondingCoins.AmountOf(stakingDenom)\n\ttotalStaked := delegated.Add(unbonding)\n\tdelegatedFree := b.vacc.GetDelegatedFree().AmountOf(stakingDenom)\n\n\t// total number of staked and unbonding tokens considered to be liquid\n\ttotalFree := sdk.MinInt(totalStaked, delegatedFree)\n\t// any coins that are not considered liquid, are vesting up to a maximum of delegated\n\tstakedVesting := sdk.MinInt(totalStaked.Sub(totalFree), delegated)\n\t// staked free coins are left over\n\tstakedFree := delegated.Sub(stakedVesting)\n\n\tliquidCoins := sdk.NewCoins(newKavaCoin(stakedFree))\n\tvestingCoins := sdk.NewCoins(newKavaCoin(stakedVesting))\n\treturn liquidCoins, vestingCoins, nil\n}", "func (_Bindings *BindingsCallerSession) TotalReserves() (*big.Int, error) {\n\treturn _Bindings.Contract.TotalReserves(&_Bindings.CallOpts)\n}", "func (_DelegationController *DelegationControllerTransactor) GetAndUpdateLockedAmount(opts *bind.TransactOpts, wallet common.Address) (*types.Transaction, error) {\n\treturn _DelegationController.contract.Transact(opts, \"getAndUpdateLockedAmount\", wallet)\n}", "func (k Keeper) GetStakedTokens(ctx sdk.Ctx) sdk.BigInt {\n\tstakedPool := k.GetStakedPool(ctx)\n\treturn stakedPool.GetCoins().AmountOf(k.StakeDenom(ctx))\n}", "func TestGetSupportCoins(t *testing.T) {\n\tt.Parallel()\n\tif _, err := ok.GetSupportCoins(context.Background()); err != nil {\n\t\tt.Error(\"Okx GetSupportCoins() error\", err)\n\t}\n}", "func (_ChpRegistry *ChpRegistryCaller) CORESTAKINGAMOUNT(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _ChpRegistry.contract.Call(opts, out, \"CORE_STAKING_AMOUNT\")\n\treturn *ret0, err\n}", "func (_DelegationController *DelegationControllerSession) GetAndUpdateLockedAmount(wallet common.Address) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.GetAndUpdateLockedAmount(&_DelegationController.TransactOpts, wallet)\n}", "func (cm *ConnectionManager) sumDeposits() *big.Int {\n\tchs := cm.openChannels()\n\tvar sum = big.NewInt(0)\n\tfor _, c := range chs {\n\t\tsum.Add(sum, c.OurContractBalance)\n\t}\n\treturn sum\n}", "func (_DelegationController *DelegationControllerTransactorSession) GetAndUpdateLockedAmount(wallet common.Address) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.GetAndUpdateLockedAmount(&_DelegationController.TransactOpts, wallet)\n}", "func (c *CoordinatorHelper) Coins(\n\tctx context.Context,\n\tdbTx storage.DatabaseTransaction,\n\taccountIdentifier *types.AccountIdentifier,\n\tcurrency *types.Currency,\n) ([]*types.Coin, error) {\n\tcoins, _, err := c.coinStorage.GetCoinsTransactional(\n\t\tctx,\n\t\tdbTx,\n\t\taccountIdentifier,\n\t)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"%w: unable to get coins\", err)\n\t}\n\n\tcoinsToReturn := []*types.Coin{}\n\tfor _, coin := range coins {\n\t\tif types.Hash(coin.Amount.Currency) != types.Hash(currency) {\n\t\t\tcontinue\n\t\t}\n\n\t\tcoinsToReturn = append(coinsToReturn, coin)\n\t}\n\n\treturn coinsToReturn, nil\n}", "func (_Bindings *BindingsSession) TotalReserves() (*big.Int, error) {\n\treturn _Bindings.Contract.TotalReserves(&_Bindings.CallOpts)\n}", "func (_CrToken *CrTokenSession) TotalReserves() (*big.Int, error) {\n\treturn _CrToken.Contract.TotalReserves(&_CrToken.CallOpts)\n}", "func (_Vault *VaultCaller) WithdrawRequests(opts *bind.CallOpts, arg0 common.Address, arg1 common.Address) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _Vault.contract.Call(opts, out, \"withdrawRequests\", arg0, arg1)\n\treturn *ret0, err\n}", "func (_Gatekeeper *GatekeeperSession) GetCurrentTransactionAmountForBlock() (*big.Int, error) {\n\treturn _Gatekeeper.Contract.GetCurrentTransactionAmountForBlock(&_Gatekeeper.CallOpts)\n}", "func (r *Repository) GetAmountsOfManageCandidates(ctx context.Context, companyID string) (int32, int32, error) {\n\tobjCompanyID, err := primitive.ObjectIDFromHex(companyID)\n\tif err != nil {\n\t\treturn 0, 0, errors.New(`wrong_id`)\n\t}\n\n\tamount := struct {\n\t\tSaved int32 `bson:\"saved_candidates\"`\n\t\tSkipped int32 `bson:\"skipped_candidates\"`\n\t\t// Alerts int32 `bson:\"alerts\"`\n\t}{}\n\n\tcursor, err := r.companiesCollection.Aggregate(\n\t\tctx,\n\t\t[]bson.M{\n\t\t\t{\n\t\t\t\t\"$match\": bson.M{\n\t\t\t\t\t\"company_id\": objCompanyID,\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\t\"$addFields\": bson.M{\n\t\t\t\t\t\"saved_candidates\": bson.M{\n\t\t\t\t\t\t\"$size\": \"$saved_candidates\",\n\t\t\t\t\t},\n\t\t\t\t\t\"skipped_candidates\": bson.M{\n\t\t\t\t\t\t\"$size\": \"$skipped_candidates\",\n\t\t\t\t\t},\n\t\t\t\t\t// \"alerts\": bson.M{\n\t\t\t\t\t// \t\"$size\": \"$alerts\", // TODO:\n\t\t\t\t\t// },\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\t\"$project\": bson.M{\n\t\t\t\t\t\"saved_candidates\": 1,\n\t\t\t\t\t\"skipped_candidates\": 1,\n\t\t\t\t\t// \"alerts\": 1,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t)\n\tif err != nil {\n\t\tif err == mongo.ErrNoDocuments {\n\t\t\treturn 0, 0, errors.New(`not_found`)\n\t\t}\n\t\treturn 0, 0, err\n\t}\n\tdefer cursor.Close(ctx)\n\n\tif cursor.Next(ctx) {\n\t\terr = cursor.Decode(&amount)\n\t\tif err != nil {\n\t\t\treturn 0, 0, err\n\t\t}\n\t}\n\n\treturn amount.Saved, amount.Skipped, nil\n}", "func (_Bindings *BindingsSession) GetCash() (*big.Int, error) {\n\treturn _Bindings.Contract.GetCash(&_Bindings.CallOpts)\n}", "func (s *Store) kvsGetTxn(tx *memdb.Txn, ws memdb.WatchSet, key string) (uint64, *structs.DirEntry, error) {\n\t// Get the table index.\n\tidx := maxIndexTxn(tx, \"kvs\", \"tombstones\")\n\n\t// Retrieve the key.\n\twatchCh, entry, err := tx.FirstWatch(\"kvs\", \"id\", key)\n\tif err != nil {\n\t\treturn 0, nil, fmt.Errorf(\"failed kvs lookup: %s\", err)\n\t}\n\tws.Add(watchCh)\n\tif entry != nil {\n\t\treturn idx, entry.(*structs.DirEntry), nil\n\t}\n\treturn idx, nil, nil\n}", "func (txn TxnProbe) GetLockedCount() int {\n\treturn txn.lockedCnt\n}", "func (_Vault *VaultCallerSession) GetDecimals(token common.Address) (uint8, error) {\n\treturn _Vault.Contract.GetDecimals(&_Vault.CallOpts, token)\n}", "func (_Gatekeeper *GatekeeperCaller) GetCurrentTransactionAmountForBlock(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _Gatekeeper.contract.Call(opts, out, \"GetCurrentTransactionAmountForBlock\")\n\treturn *ret0, err\n}", "func (p *Player) CashSpentTotal() int {\n\treturn p.AdditionalPlayerInformation.TotalCashSpent\n}", "func (dcr *ExchangeWallet) returnCoins(unspents asset.Coins) error {\n\tif len(unspents) == 0 {\n\t\treturn fmt.Errorf(\"cannot return zero coins\")\n\t}\n\tops := make([]*wire.OutPoint, 0, len(unspents))\n\n\tdcr.log.Debugf(\"returning coins %s\", unspents)\n\tfor _, unspent := range unspents {\n\t\top, err := dcr.convertCoin(unspent)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error converting coin: %w\", err)\n\t\t}\n\t\tops = append(ops, wire.NewOutPoint(op.txHash(), op.vout(), op.tree))\n\t\tdelete(dcr.fundingCoins, op.pt)\n\t}\n\treturn translateRPCCancelErr(dcr.node.LockUnspent(dcr.ctx, true, ops))\n}", "func (tx *Transaction) GetNewFromCoins() []FromCoin {\n\tnfcs := make([]FromCoin, 0)\n\tfor index, c := range tx.To.Coins {\n\t\tticket := Ticket{}\n\t\tticket.SetTxid(*tx.GetTxID())\n\t\tticket.SetIndex(uint32(index))\n\n\t\tnfc := FromCoin{}\n\t\tnfc.SetId(c.Id)\n\t\tnfc.AddTicket(&ticket)\n\n\t\tnfcs = append(nfcs, nfc)\n\t}\n\n\treturn nfcs\n}", "func (_Bindings *BindingsCallerSession) GetCash() (*big.Int, error) {\n\treturn _Bindings.Contract.GetCash(&_Bindings.CallOpts)\n}", "func getOVMETHTotalSupply(inStateDB *state.StateDB) *big.Int {\n\tposition := common.Big2\n\tkey := common.BytesToHash(common.LeftPadBytes(position.Bytes(), 32))\n\treturn inStateDB.GetState(OVMETHAddress, key).Big()\n}", "func (_Bindings *BindingsCaller) GetCash(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _Bindings.contract.Call(opts, out, \"getCash\")\n\treturn *ret0, err\n}", "func (_Gatekeeper *GatekeeperCallerSession) GetCurrentTransactionAmountForBlock() (*big.Int, error) {\n\treturn _Gatekeeper.Contract.GetCurrentTransactionAmountForBlock(&_Gatekeeper.CallOpts)\n}", "func (dcr *ExchangeWallet) returnCoins(unspents asset.Coins) ([]*fundingCoin, error) {\n\tif len(unspents) == 0 {\n\t\treturn nil, fmt.Errorf(\"cannot return zero coins\")\n\t}\n\n\tops := make([]*wire.OutPoint, 0, len(unspents))\n\tfundingCoins := make([]*fundingCoin, 0, len(unspents))\n\n\tdcr.log.Debugf(\"returning coins %s\", unspents)\n\tfor _, unspent := range unspents {\n\t\top, err := dcr.convertCoin(unspent)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error converting coin: %w\", err)\n\t\t}\n\t\tops = append(ops, op.wireOutPoint()) // op.tree may be wire.TxTreeUnknown, but that's fine since wallet.LockUnspent doesn't rely on it\n\t\tif fCoin, ok := dcr.fundingCoins[op.pt]; ok {\n\t\t\tfundingCoins = append(fundingCoins, fCoin)\n\t\t\tdelete(dcr.fundingCoins, op.pt)\n\t\t} else {\n\t\t\tdcr.log.Warnf(\"returning coin %s that is not cached as a funding coin\", op)\n\t\t\tfundingCoins = append(fundingCoins, &fundingCoin{op: op})\n\t\t}\n\t}\n\n\treturn fundingCoins, dcr.wallet.LockUnspent(dcr.ctx, true, ops)\n}", "func (cm *coinsMempool) Get(maxTransactions uint64, s state.State) ([]*primitives.Tx, state.State) {\n\tcm.lock.RLock()\n\tdefer cm.lock.RUnlock()\n\tallTransactions := make([]*primitives.Tx, 0, maxTransactions)\n\nouter:\n\tfor _, addr := range cm.mempool {\n\t\tfor _, tx := range addr.transactions {\n\t\t\tif err := s.ApplyTransactionSingle(tx, [20]byte{}, cm.params); err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tallTransactions = append(allTransactions, tx)\n\t\t\tif uint64(len(allTransactions)) >= maxTransactions {\n\t\t\t\tbreak outer\n\t\t\t}\n\t\t}\n\t}\n\n\t// we can prioritize here, but we aren't to keep it simple\n\treturn allTransactions, s\n}", "func (_Vault *VaultSession) GetDecimals(token common.Address) (uint8, error) {\n\treturn _Vault.Contract.GetDecimals(&_Vault.CallOpts, token)\n}", "func (server *OpencxServer) WithdrawCoins(address string, pubkey *koblitz.PublicKey, amount uint64, params *coinparam.Params) (txid string, err error) {\n\n\t// TODO: change everything to int64 and just deal with the negatives in error handling. Casting is probably more dangerous\n\t// if you try to withdraw an overflow amount then get out\n\tif int64(amount) < 0 {\n\t\terr = fmt.Errorf(\"That amount would have caused an overflow, enter something lower\")\n\t\treturn\n\t}\n\n\t// Create the function, basically make sure the wallet stuff is alright\n\tvar withdrawFunction func(string, *koblitz.PublicKey, uint64) (string, error)\n\tif withdrawFunction, err = server.withdrawFromChain(params); err != nil {\n\t\terr = fmt.Errorf(\"Error creating withdraw function: \\n%s\", err)\n\t\treturn\n\t}\n\t// Actually try to withdraw\n\tif txid, err = withdrawFunction(address, pubkey, amount); err != nil {\n\t\terr = fmt.Errorf(\"Error withdrawing coins: \\n%s\", err)\n\t\treturn\n\t}\n\treturn\n}", "func listCoins(ctx sdk.Context, k Keeper) ([]byte, error) {\n\tvar coinsList types.QueryResCoins\n\n\titerator := k.GetCoinsIterator(ctx)\n\n\tfor ; iterator.Valid(); iterator.Next() {\n\t\tvar coin types.Coin\n\n\t\t_ = k.cdc.UnmarshalBinaryLengthPrefixed(iterator.Value(), &coin)\n\n\t\tcoinsList = append(coinsList, coin)\n\t}\n\n\tres, err := codec.MarshalJSONIndent(k.cdc, coinsList)\n\n\tif err != nil {\n\t\treturn res, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error())\n\t}\n\n\treturn res, nil\n}", "func (_Token *TokenCaller) CurrentTotalStake(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _Token.contract.Call(opts, out, \"currentTotalStake\")\n\treturn *ret0, err\n}", "func (btc *ExchangeWallet) ReturnCoins(unspents asset.Coins) error {\n\tif len(unspents) == 0 {\n\t\treturn fmt.Errorf(\"cannot return zero coins\")\n\t}\n\tops := make([]*output, 0, len(unspents))\n\tbtc.fundingMtx.Lock()\n\tdefer btc.fundingMtx.Unlock()\n\tfor _, unspent := range unspents {\n\t\top, err := btc.convertCoin(unspent)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error converting coin: %v\", err)\n\t\t}\n\t\tops = append(ops, op)\n\t\tdelete(btc.fundingCoins, outpointID(op.txHash.String(), op.vout))\n\t}\n\treturn btc.wallet.LockUnspent(true, ops)\n}", "func (_Cakevault *CakevaultSession) TotalShares() (*big.Int, error) {\n\treturn _Cakevault.Contract.TotalShares(&_Cakevault.CallOpts)\n}", "func (btc *ExchangeWallet) lockedSats() (uint64, error) {\n\tlockedOutpoints, err := btc.wallet.ListLockUnspent()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tvar sum uint64\n\tbtc.fundingMtx.Lock()\n\tdefer btc.fundingMtx.Unlock()\n\tfor _, outPoint := range lockedOutpoints {\n\t\topID := outpointID(outPoint.TxID, outPoint.Vout)\n\t\tutxo, found := btc.fundingCoins[opID]\n\t\tif found {\n\t\t\tsum += utxo.amount\n\t\t\tcontinue\n\t\t}\n\t\ttxHash, err := chainhash.NewHashFromStr(outPoint.TxID)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\ttxOut, err := btc.node.GetTxOut(txHash, outPoint.Vout, true)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\tif txOut == nil {\n\t\t\t// Must be spent now?\n\t\t\tbtc.log.Debugf(\"ignoring output from listlockunspent that wasn't found with gettxout. %s\", opID)\n\t\t\tcontinue\n\t\t}\n\t\tsum += toSatoshi(txOut.Value)\n\t}\n\treturn sum, nil\n}", "func (serv *ExchangeServer) GetSupportCoins() []string {\n\tsymbols := make([]string, len(serv.coins))\n\ti := 0\n\tfor _, coin := range serv.coins {\n\t\tsymbols[i] = coin.Symbol()\n\t\ti++\n\t}\n\treturn symbols\n}", "func (k Keeper) MintCoins(ctx sdk.Context, newCoins sdk.Coins) error {\n\tif newCoins.Empty() {\n\t\t// skip as no coins need to be minted\n\t\treturn nil\n\t}\n\treturn k.supplyKeeper.MintCoins(ctx, types.ModuleName, newCoins)\n}", "func drawCoins() int {\n\treturn rand.Intn(maxCoins+1-minCoins) + minCoins\n}", "func (_Lmc *LmcCallerSession) TotalStaked() (*big.Int, error) {\n\treturn _Lmc.Contract.TotalStaked(&_Lmc.CallOpts)\n}", "func (_Distributor *DistributorTransactor) GetAndUpdateEarnedBountyAmountOf(opts *bind.TransactOpts, wallet common.Address, validatorId *big.Int) (*types.Transaction, error) {\n\treturn _Distributor.contract.Transact(opts, \"getAndUpdateEarnedBountyAmountOf\", wallet, validatorId)\n}", "func GiveGoTotal(total C.int) {\n\tfmt.Printf(\"Go: got total from C %d\\n\", total)\n}", "func (_Lmc *LmcSession) TotalStaked() (*big.Int, error) {\n\treturn _Lmc.Contract.TotalStaked(&_Lmc.CallOpts)\n}", "func (k Keeper) IncrementBorrowedCoins(ctx sdk.Context, newCoins sdk.Coins) {\n\tborrowedCoins, found := k.GetBorrowedCoins(ctx)\n\tif !found {\n\t\tk.SetBorrowedCoins(ctx, newCoins)\n\t} else {\n\t\tk.SetBorrowedCoins(ctx, borrowedCoins.Add(newCoins...))\n\t}\n}", "func (m *Machine) ReturnCoins() {\n\tcoins := m.cashEngine.DropCoins()\n\n\ts := fmt.Sprintf(\"-> \")\n\tfor i, c := range coins {\n\t\tif i == len(coins)-1 {\n\t\t\ts += fmt.Sprintf(\"%s\", c.value.String())\n\t\t\tcontinue\n\t\t}\n\t\ts += fmt.Sprintf(\"%s, \", c.value.String())\n\t}\n\n\tm.logger.Println(s)\n}", "func (_Gatekeeper *GatekeeperCallerSession) GetRootsCount() (*big.Int, error) {\n\treturn _Gatekeeper.Contract.GetRootsCount(&_Gatekeeper.CallOpts)\n}", "func (_Bindings *BindingsCaller) TotalReserves(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _Bindings.contract.Call(opts, out, \"totalReserves\")\n\treturn *ret0, err\n}", "func (_Gatekeeper *GatekeeperCaller) GetRootsCount(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _Gatekeeper.contract.Call(opts, out, \"GetRootsCount\")\n\treturn *ret0, err\n}", "func (_CrToken *CrTokenCaller) TotalReserves(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _CrToken.contract.Call(opts, &out, \"totalReserves\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}" ]
[ "0.78498274", "0.7794622", "0.7768739", "0.7705399", "0.7676226", "0.72224396", "0.70726705", "0.70528924", "0.70528334", "0.6938393", "0.6639426", "0.65996796", "0.65294945", "0.6502958", "0.6489424", "0.6332244", "0.6255476", "0.572874", "0.56868994", "0.5669699", "0.559848", "0.55965006", "0.55458254", "0.5384292", "0.5278963", "0.52260673", "0.51583445", "0.5006517", "0.49461663", "0.4905195", "0.48464885", "0.48198533", "0.4818673", "0.4803773", "0.47477734", "0.47459176", "0.47358575", "0.47105417", "0.4653005", "0.4648202", "0.4637525", "0.4632883", "0.46007738", "0.45718068", "0.45620197", "0.45562413", "0.4549387", "0.4548353", "0.4486335", "0.44857976", "0.44536132", "0.4441586", "0.4422481", "0.4422286", "0.442011", "0.4410763", "0.43943068", "0.43919995", "0.43849298", "0.43687224", "0.4367378", "0.43046153", "0.43028334", "0.42890888", "0.42739797", "0.42703667", "0.4262527", "0.42585602", "0.42543328", "0.42203423", "0.42122862", "0.42041692", "0.42022836", "0.4192806", "0.41899297", "0.4189404", "0.41883627", "0.4186005", "0.41746548", "0.41738498", "0.41647542", "0.41485384", "0.41424096", "0.41386896", "0.4119769", "0.4106513", "0.4098897", "0.40969428", "0.4092855", "0.40907988", "0.40888497", "0.408883", "0.40854323", "0.40799987", "0.4079863", "0.40783933", "0.40775123", "0.40742916", "0.4073981", "0.4072628" ]
0.8247456
0